Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+44
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isHoneypotTriggered } from "./honeypot.js";
|
||||
import { HONEYPOT_FIELD_KEY } from "./schema.js";
|
||||
|
||||
/**
|
||||
* Edge-case coverage for {@link isHoneypotTriggered}: the non-primitive
|
||||
* fall-through branch and the numeric / boolean "looks empty" boundaries
|
||||
* that decide whether a request is silently dropped.
|
||||
*/
|
||||
describe("isHoneypotTriggered — non-primitive values", () => {
|
||||
it("treats an object value as a trigger (final fall-through branch)", () => {
|
||||
// Bots that POST structured JSON into the hidden field still get flagged.
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: { nested: "x" } })).toBe(true);
|
||||
});
|
||||
|
||||
it("treats an array value as a trigger", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: ["a", "b"] })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isHoneypotTriggered — numeric boundaries", () => {
|
||||
it("does not trigger on a literal zero", () => {
|
||||
// A numeric honeypot defaulting to 0 must not produce false positives.
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: 0 })).toBe(false);
|
||||
});
|
||||
|
||||
it("triggers on a negative number", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: -1 })).toBe(true);
|
||||
});
|
||||
|
||||
it("triggers on NaN (NaN !== 0)", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: Number.NaN })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isHoneypotTriggered — boolean / whitespace boundaries", () => {
|
||||
it("does not trigger on boolean false", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not trigger on whitespace beyond plain spaces (tabs / newlines)", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: "\t\n \r" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyFieldMapping,
|
||||
FieldTypeSchema,
|
||||
FormDefinitionSchema,
|
||||
FormFieldSchema,
|
||||
FormSubmissionPayloadSchema,
|
||||
FormThemeSchema,
|
||||
HONEYPOT_FIELD_KEY,
|
||||
isHoneypotTriggered,
|
||||
matchAllowedOrigin,
|
||||
normalizeOrigin,
|
||||
resolveSubmissionTarget,
|
||||
} from "./index.js";
|
||||
|
||||
/**
|
||||
* Public-API barrel smoke test. Verifies that every export is wired to the
|
||||
* correct implementation — a forgotten or renamed re-export in index.ts
|
||||
* would surface here rather than at a downstream import site.
|
||||
*/
|
||||
describe("@hivegrid/form-widget barrel", () => {
|
||||
it("re-exports the honeypot field key constant", () => {
|
||||
expect(HONEYPOT_FIELD_KEY).toBe("hp_extra_data");
|
||||
});
|
||||
|
||||
it("re-exports the field-type enum schema", () => {
|
||||
expect(FieldTypeSchema.parse("email")).toBe("email");
|
||||
expect(FieldTypeSchema.safeParse("file").success).toBe(true);
|
||||
expect(FieldTypeSchema.safeParse("radio").success).toBe(false);
|
||||
});
|
||||
|
||||
it("re-exports the origin helpers", () => {
|
||||
expect(normalizeOrigin("Example.com")).toBe("https://example.com");
|
||||
expect(matchAllowedOrigin("https://example.com", ["example.com"])).toBe(true);
|
||||
});
|
||||
|
||||
it("re-exports the honeypot helper", () => {
|
||||
expect(isHoneypotTriggered({ [HONEYPOT_FIELD_KEY]: "spam" })).toBe(true);
|
||||
});
|
||||
|
||||
it("re-exports the routing helpers", () => {
|
||||
expect(resolveSubmissionTarget({}).type).toBe("generic");
|
||||
expect(applyFieldMapping({ payload: { a: 1 } })).toEqual({ a: 1 });
|
||||
});
|
||||
|
||||
it("re-exports the Zod schemas", () => {
|
||||
expect(FormFieldSchema.safeParse({ key: "name", type: "text", label: "Name" }).success).toBe(true);
|
||||
expect(FormThemeSchema.safeParse({ primaryColor: "#fff" }).success).toBe(true);
|
||||
expect(FormDefinitionSchema.safeParse({ title: "C", fields: [{ key: "n", type: "text", label: "N" }] }).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(FormSubmissionPayloadSchema.safeParse({ values: {} }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @toolctrl/form-widget — shared types & helpers for the embeddable form
|
||||
* @hivegrid/form-widget — shared types & helpers for the embeddable form
|
||||
* widget (Task #58). Contains zero runtime dependencies on the rest of the
|
||||
* codebase so it can be imported from the web app, the api, the worker and
|
||||
* the cli without dragging in Prisma or React.
|
||||
@@ -18,16 +18,21 @@ export {
|
||||
FormThemeSchema,
|
||||
FormSubmissionPayloadSchema,
|
||||
FieldTypeSchema,
|
||||
ConditionalLogicRuleSchema,
|
||||
FieldValidationRulesSchema,
|
||||
HONEYPOT_FIELD_KEY,
|
||||
type FormDefinition,
|
||||
type FormField,
|
||||
type FormFieldType,
|
||||
type FormTheme,
|
||||
type FormSubmissionPayload,
|
||||
type ConditionalLogicRule,
|
||||
type FieldValidationRules,
|
||||
} from "./schema.js";
|
||||
|
||||
export { matchAllowedOrigin, normalizeOrigin } from "./origin.js";
|
||||
export { isHoneypotTriggered } from "./honeypot.js";
|
||||
export { evaluateConditionalLogic, isFieldVisible, filterVisibleFields, type ConditionalValues } from "./visibility.js";
|
||||
export {
|
||||
resolveSubmissionTarget,
|
||||
applyFieldMapping,
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { matchAllowedOrigin, normalizeOrigin } from "./origin.js";
|
||||
|
||||
/**
|
||||
* Edge-case coverage for the origin allowlist matcher: the invalid-URL
|
||||
* catch path, scheme / port discrimination, blank-entry skipping and the
|
||||
* wildcard subdomain anti-bypass rules.
|
||||
*/
|
||||
describe("normalizeOrigin — invalid inputs", () => {
|
||||
it("returns null when the URL constructor throws (scheme without host)", () => {
|
||||
expect(normalizeOrigin("https://")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when a host-only input is unparseable", () => {
|
||||
// No '://' → prefixed with https://, still invalid because of the space.
|
||||
expect(normalizeOrigin("exa mple.com")).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves an explicit non-default port", () => {
|
||||
expect(normalizeOrigin("https://example.com:8443")).toBe("https://example.com:8443");
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAllowedOrigin — scheme discrimination", () => {
|
||||
it("rejects a scheme mismatch when the entry pins a scheme", () => {
|
||||
expect(matchAllowedOrigin("http://example.com", ["https://example.com"])).toBe(false);
|
||||
});
|
||||
|
||||
it("matches any scheme when the entry is a bare hostname", () => {
|
||||
expect(matchAllowedOrigin("http://example.com", ["example.com"])).toBe(true);
|
||||
expect(matchAllowedOrigin("https://example.com", ["example.com"])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAllowedOrigin — port discrimination", () => {
|
||||
it("requires an explicit port match when the entry pins a port", () => {
|
||||
// Request uses the default https port (empty) → entry ':443' must not match.
|
||||
expect(matchAllowedOrigin("https://example.com", ["example.com:443"])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAllowedOrigin — entry list hygiene", () => {
|
||||
it("skips blank / whitespace-only entries and still matches a later valid one", () => {
|
||||
expect(matchAllowedOrigin("https://example.com", ["", " ", "https://example.com"])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAllowedOrigin — wildcard subdomains", () => {
|
||||
it("matches a deeply nested subdomain", () => {
|
||||
expect(matchAllowedOrigin("https://a.b.example.com", ["*.example.com"])).toBe(true);
|
||||
});
|
||||
|
||||
it("does not allow a look-alike host to bypass the wildcard", () => {
|
||||
// 'evil-example.com' must NOT match '*.example.com'.
|
||||
expect(matchAllowedOrigin("https://evil-example.com", ["*.example.com"])).toBe(false);
|
||||
});
|
||||
|
||||
it("honours the scheme constraint on a wildcard entry", () => {
|
||||
expect(matchAllowedOrigin("http://foo.example.com", ["https://*.example.com"])).toBe(false);
|
||||
expect(matchAllowedOrigin("https://foo.example.com", ["https://*.example.com"])).toBe(true);
|
||||
});
|
||||
});
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyFieldMapping, resolveSubmissionTarget } from "./routing.js";
|
||||
|
||||
/**
|
||||
* Edge-case coverage for the submission-routing resolver: descriptor
|
||||
* immutability, null/empty target handling and the mapping branches that
|
||||
* drop missing source keys, resolve duplicate targets and guard against
|
||||
* non-string target keys.
|
||||
*/
|
||||
describe("resolveSubmissionTarget — descriptor shape", () => {
|
||||
it("returns a frozen field mapping that cannot be mutated", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "crm-contact", fieldMapping: { email: "email" } });
|
||||
expect(Object.isFrozen(target.fieldMapping)).toBe(true);
|
||||
});
|
||||
|
||||
it("freezes the empty mapping on the unknown-target fallback path", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "entity-row" });
|
||||
expect(target.type).toBe("generic");
|
||||
expect(Object.isFrozen(target.fieldMapping)).toBe(true);
|
||||
expect(target.fieldMapping).toEqual({});
|
||||
});
|
||||
|
||||
it("forwards an entityId on a crm-contact target", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "crm-contact", targetEntityId: "contact_1" });
|
||||
expect(target.type).toBe("crm-contact");
|
||||
expect(target.entityId).toBe("contact_1");
|
||||
});
|
||||
|
||||
it("treats an explicit null target type as generic", () => {
|
||||
expect(resolveSubmissionTarget({ targetType: null }).type).toBe("generic");
|
||||
});
|
||||
|
||||
it("treats an empty-string target type as generic", () => {
|
||||
expect(resolveSubmissionTarget({ targetType: "" }).type).toBe("generic");
|
||||
});
|
||||
|
||||
it("copies the provided field mapping instead of aliasing it", () => {
|
||||
const mapping = { firstName: "first_name" };
|
||||
const target = resolveSubmissionTarget({ targetType: "crm-contact", fieldMapping: mapping });
|
||||
mapping.firstName = "changed";
|
||||
expect(target.fieldMapping.firstName).toBe("first_name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyFieldMapping — mapping branches", () => {
|
||||
it("drops mapping entries whose source key is absent from the payload", () => {
|
||||
const result = applyFieldMapping({
|
||||
payload: { email: "a@b.co" },
|
||||
fieldMapping: { phone: "phone_number", email: "email" },
|
||||
});
|
||||
expect(result).toEqual({ email: "a@b.co" });
|
||||
expect(Object.prototype.hasOwnProperty.call(result, "phone_number")).toBe(false);
|
||||
});
|
||||
|
||||
it("lets the later source win when two fields map to the same target", () => {
|
||||
// Object.entries preserves insertion order → 'b' overwrites 'a' on target 'x'.
|
||||
const result = applyFieldMapping({
|
||||
payload: { a: "first", b: "second" },
|
||||
fieldMapping: { a: "x", b: "x" },
|
||||
});
|
||||
expect(result).toEqual({ x: "second" });
|
||||
});
|
||||
|
||||
it("ignores mapping entries whose target key is not a string", () => {
|
||||
const result = applyFieldMapping({
|
||||
payload: { a: "1" },
|
||||
fieldMapping: { a: 123 } as unknown as Record<string, string>,
|
||||
});
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -14,15 +14,10 @@ describe("resolveSubmissionTarget", () => {
|
||||
expect(target.fieldMapping.email).toBe("email");
|
||||
});
|
||||
|
||||
it("falls back to generic when entity-row has no entityId", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "entity-row" });
|
||||
expect(target.type).toBe("generic");
|
||||
});
|
||||
|
||||
it("preserves entityId for valid entity-row config", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "entity-row", targetEntityId: "ent_123" });
|
||||
expect(target.type).toBe("entity-row");
|
||||
expect(target.entityId).toBe("ent_123");
|
||||
it("supports the typed create-lead compatibility target", () => {
|
||||
const target = resolveSubmissionTarget({ targetType: "create-lead", targetEntityId: "lead-source" });
|
||||
expect(target.type).toBe("create-lead");
|
||||
expect(target.entityId).toBe("lead-source");
|
||||
});
|
||||
|
||||
it("falls back to generic for unknown target types", () => {
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
*
|
||||
* - `generic` — store as FormSubmission row only (default)
|
||||
* - `crm-contact` — upsert a CRM contact using mapped fields
|
||||
* - `entity-row` — create a row in a tenant-defined entity
|
||||
* - `create-lead` — legacy compatibility alias for the typed action path
|
||||
*
|
||||
* The resolver here is pure: it just describes the target. The actual
|
||||
* write happens in the submission route / worker handler.
|
||||
*/
|
||||
|
||||
export type SubmissionTargetType = "generic" | "crm-contact" | "entity-row";
|
||||
export type SubmissionTargetType = "generic" | "crm-contact" | "create-lead";
|
||||
|
||||
export interface SubmissionTargetDescriptor {
|
||||
readonly type: SubmissionTargetType;
|
||||
@@ -24,7 +24,7 @@ export interface ResolveSubmissionTargetInput {
|
||||
readonly fieldMapping?: Record<string, string> | null;
|
||||
}
|
||||
|
||||
const VALID_TARGETS: ReadonlySet<SubmissionTargetType> = new Set(["generic", "crm-contact", "entity-row"]);
|
||||
const VALID_TARGETS: ReadonlySet<SubmissionTargetType> = new Set(["generic", "crm-contact", "create-lead"]);
|
||||
|
||||
function isValidTarget(value: unknown): value is SubmissionTargetType {
|
||||
return typeof value === "string" && (VALID_TARGETS as Set<string>).has(value);
|
||||
@@ -32,10 +32,6 @@ function isValidTarget(value: unknown): value is SubmissionTargetType {
|
||||
|
||||
export function resolveSubmissionTarget(input: ResolveSubmissionTargetInput): SubmissionTargetDescriptor {
|
||||
const type: SubmissionTargetType = isValidTarget(input.targetType) ? input.targetType : "generic";
|
||||
if (type === "entity-row" && !input.targetEntityId) {
|
||||
// misconfigured form — fall back to generic so submissions still land somewhere
|
||||
return { type: "generic", entityId: null, fieldMapping: Object.freeze({}) };
|
||||
}
|
||||
return {
|
||||
type,
|
||||
entityId: input.targetEntityId ?? null,
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { FormDefinitionSchema, FormFieldSchema, FormSubmissionPayloadSchema, FormThemeSchema } from "./schema.js";
|
||||
|
||||
/**
|
||||
* Edge-case coverage for the Zod contracts: option-field branches
|
||||
* superRefine branch, length / regex boundaries, theme hex acceptance,
|
||||
* definition defaults and submission-payload limits.
|
||||
*/
|
||||
describe("FormFieldSchema — option requirement branches", () => {
|
||||
it("rejects a multiselect field with an explicitly empty options array", () => {
|
||||
const result = FormFieldSchema.safeParse({ key: "color", type: "multiselect", label: "Color", options: [] });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a select field once at least one option is provided", () => {
|
||||
const result = FormFieldSchema.safeParse({
|
||||
key: "color",
|
||||
type: "select",
|
||||
label: "Color",
|
||||
options: [{ value: "r", label: "Red" }],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a multiselect field with options", () => {
|
||||
const result = FormFieldSchema.safeParse({
|
||||
key: "size",
|
||||
type: "multiselect",
|
||||
label: "Size",
|
||||
options: [{ value: "s", label: "Small" }],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FormFieldSchema — length / key boundaries", () => {
|
||||
it("accepts equal minLength and maxLength (boundary, not strictly greater)", () => {
|
||||
const result = FormFieldSchema.safeParse({ key: "pin", type: "text", label: "PIN", minLength: 5, maxLength: 5 });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects keys containing a hyphen", () => {
|
||||
expect(FormFieldSchema.safeParse({ key: "first-name", type: "text", label: "X" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a key longer than 64 chars", () => {
|
||||
const longKey = `a${"a".repeat(64)}`; // 65 chars
|
||||
expect(FormFieldSchema.safeParse({ key: longKey, type: "text", label: "X" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an option value longer than 120 chars", () => {
|
||||
const result = FormFieldSchema.safeParse({
|
||||
key: "color",
|
||||
type: "select",
|
||||
label: "Color",
|
||||
options: [{ value: "a".repeat(121), label: "L" }],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects inconsistent validation rule ranges", () => {
|
||||
expect(
|
||||
FormFieldSchema.safeParse({
|
||||
key: "name",
|
||||
type: "text",
|
||||
label: "Name",
|
||||
validationRules: { minLength: 10, maxLength: 2 },
|
||||
}).success
|
||||
).toBe(false);
|
||||
expect(
|
||||
FormFieldSchema.safeParse({
|
||||
key: "amount",
|
||||
type: "number",
|
||||
label: "Amount",
|
||||
validationRules: { min: 50, max: 10 },
|
||||
}).success
|
||||
).toBe(false);
|
||||
expect(
|
||||
FormFieldSchema.safeParse({
|
||||
key: "choices",
|
||||
type: "multiselect",
|
||||
label: "Choices",
|
||||
options: [{ value: "a", label: "A" }],
|
||||
validationRules: { minSelected: 3, maxSelected: 1 },
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts complete validation and conditional logic metadata", () => {
|
||||
const result = FormFieldSchema.safeParse({
|
||||
key: "attachment",
|
||||
type: "file",
|
||||
label: "Attachment",
|
||||
conditionalLogic: [
|
||||
{ fieldKey: "kind", operator: "in", value: ["repair", "install"] },
|
||||
{ fieldKey: "has_files", operator: "equals", value: true },
|
||||
{ fieldKey: "count", operator: "equals", value: 2 },
|
||||
{ fieldKey: "note", operator: "empty", value: null },
|
||||
],
|
||||
validationRules: {
|
||||
acceptedFileTypes: ["image/jpeg", "application/pdf"],
|
||||
maxFileSizeMb: 10,
|
||||
pattern: "^[a-z]+$",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FormThemeSchema — hex acceptance", () => {
|
||||
it("accepts 3-digit and 8-digit hex colors", () => {
|
||||
expect(FormThemeSchema.safeParse({ primaryColor: "#abc" }).success).toBe(true);
|
||||
expect(FormThemeSchema.safeParse({ backgroundColor: "#12345678" }).success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a 2-digit hex color", () => {
|
||||
expect(FormThemeSchema.safeParse({ textColor: "#12" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts the optional fontFamily and borderRadius fields", () => {
|
||||
const result = FormThemeSchema.safeParse({ fontFamily: "Inter, sans-serif", borderRadius: "8px" });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FormDefinitionSchema — defaults", () => {
|
||||
it("applies submitLabel and successMessage defaults", () => {
|
||||
const parsed = FormDefinitionSchema.parse({
|
||||
title: "Contact",
|
||||
fields: [{ key: "name", type: "text", label: "Name" }],
|
||||
});
|
||||
expect(parsed.submitLabel).toBe("Submit");
|
||||
expect(parsed.successMessage.length).toBeGreaterThan(0);
|
||||
expect(parsed.gdprConsentLabel.length).toBeGreaterThan(0);
|
||||
expect(parsed.captchaEnabled).toBe(true);
|
||||
expect(parsed.fields[0]?.conditionalLogic).toEqual([]);
|
||||
expect(parsed.fields[0]?.validationRules).toEqual({});
|
||||
});
|
||||
|
||||
it("rejects a definition with more than 50 fields", () => {
|
||||
const fields = Array.from({ length: 51 }, (_, i) => ({ key: `f${i}`, type: "text" as const, label: "X" }));
|
||||
expect(FormDefinitionSchema.safeParse({ title: "Big", fields }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects conditional rules that reference their own field", () => {
|
||||
const result = FormDefinitionSchema.safeParse({
|
||||
title: "Contact",
|
||||
fields: [
|
||||
{
|
||||
key: "details",
|
||||
type: "text",
|
||||
label: "Details",
|
||||
conditionalLogic: [{ fieldKey: "details", operator: "not_empty" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FormSubmissionPayloadSchema — limits", () => {
|
||||
it("accepts the optional origin and turnstileToken fields", () => {
|
||||
const result = FormSubmissionPayloadSchema.safeParse({
|
||||
values: { name: "Alice" },
|
||||
origin: "https://example.com",
|
||||
turnstileToken: "tok",
|
||||
captchaToken: "captcha",
|
||||
gdprAccepted: true,
|
||||
idempotencyKey: "submission-123",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a value key longer than 64 chars", () => {
|
||||
const longKey = "k".repeat(65);
|
||||
const result = FormSubmissionPayloadSchema.safeParse({ values: { [longKey]: "x" } });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an oversized turnstileToken", () => {
|
||||
const result = FormSubmissionPayloadSchema.safeParse({ values: {}, turnstileToken: "t".repeat(4097) });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects oversized arrays and short idempotency keys", () => {
|
||||
expect(
|
||||
FormSubmissionPayloadSchema.safeParse({
|
||||
values: { choices: Array.from({ length: 51 }, (_, i) => `choice-${i}`) },
|
||||
}).success
|
||||
).toBe(false);
|
||||
expect(FormSubmissionPayloadSchema.safeParse({ values: {}, idempotencyKey: "short" }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -5,22 +5,27 @@
|
||||
* The embedded renderer + submission API both parse against the same schemas
|
||||
* so the contract is enforced at every boundary.
|
||||
*
|
||||
* Field-type set is intentionally conservative for Phase-1: text, email,
|
||||
* number, textarea, select, radio, checkbox, honeypot. File-upload is
|
||||
* out-of-scope (see security notes in the detail-md).
|
||||
* AK-P16c field-type set: 12 user-facing types plus the hidden honeypot
|
||||
* system field. The public renderer and submit API parse the same schema so
|
||||
* builder changes cannot bypass server validation.
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
/** Field-types accepted by the Phase-1 form-builder. */
|
||||
/** Field-types accepted by the AK-P16c form-builder. */
|
||||
export const FieldTypeSchema = z.enum([
|
||||
"text",
|
||||
"email",
|
||||
"number",
|
||||
"textarea",
|
||||
"number",
|
||||
"date",
|
||||
"time",
|
||||
"select",
|
||||
"radio",
|
||||
"checkbox",
|
||||
"multiselect",
|
||||
"boolean",
|
||||
"email",
|
||||
"phone",
|
||||
"file",
|
||||
"photo",
|
||||
"honeypot",
|
||||
]);
|
||||
|
||||
@@ -34,6 +39,36 @@ const FieldOption = z.object({
|
||||
label: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
export const ConditionalOperatorSchema = z.enum([
|
||||
"equals",
|
||||
"not_equals",
|
||||
"contains",
|
||||
"not_empty",
|
||||
"empty",
|
||||
"in",
|
||||
]);
|
||||
|
||||
export const ConditionalLogicRuleSchema = z.object({
|
||||
fieldKey: z.string().min(1).max(64),
|
||||
operator: ConditionalOperatorSchema,
|
||||
value: z.union([z.string().max(500), z.number(), z.boolean(), z.array(z.string().max(120)).max(50), z.null()]).optional(),
|
||||
});
|
||||
|
||||
export const FieldValidationRulesSchema = z.object({
|
||||
minLength: z.number().int().min(0).max(10000).optional(),
|
||||
maxLength: z.number().int().min(1).max(10000).optional(),
|
||||
min: z.number().optional(),
|
||||
max: z.number().optional(),
|
||||
pattern: z.string().max(500).optional(),
|
||||
minSelected: z.number().int().min(0).max(50).optional(),
|
||||
maxSelected: z.number().int().min(1).max(50).optional(),
|
||||
acceptedFileTypes: z.array(z.string().min(1).max(100)).max(50).optional(),
|
||||
maxFileSizeMb: z.number().int().min(1).max(100).optional(),
|
||||
});
|
||||
|
||||
export type ConditionalLogicRule = z.infer<typeof ConditionalLogicRuleSchema>;
|
||||
export type FieldValidationRules = z.infer<typeof FieldValidationRulesSchema>;
|
||||
|
||||
export const FormFieldSchema = z
|
||||
.object({
|
||||
key: z
|
||||
@@ -47,11 +82,13 @@ export const FormFieldSchema = z
|
||||
placeholder: z.string().max(200).optional(),
|
||||
required: z.boolean().default(false),
|
||||
options: z.array(FieldOption).max(50).optional(),
|
||||
conditionalLogic: z.array(ConditionalLogicRuleSchema).max(20).default([]),
|
||||
validationRules: FieldValidationRulesSchema.default({}),
|
||||
minLength: z.number().int().min(0).max(10000).optional(),
|
||||
maxLength: z.number().int().min(1).max(10000).optional(),
|
||||
})
|
||||
.superRefine((field, ctx) => {
|
||||
if ((field.type === "select" || field.type === "radio") && (!field.options || field.options.length === 0)) {
|
||||
if ((field.type === "select" || field.type === "multiselect") && (!field.options || field.options.length === 0)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `field ${field.key}: type ${field.type} requires at least one option`,
|
||||
@@ -63,6 +100,25 @@ export const FormFieldSchema = z
|
||||
message: `field ${field.key}: minLength must be <= maxLength`,
|
||||
});
|
||||
}
|
||||
const rules = field.validationRules ?? {};
|
||||
if (rules.minLength !== undefined && rules.maxLength !== undefined && rules.minLength > rules.maxLength) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `field ${field.key}: validationRules.minLength must be <= maxLength`,
|
||||
});
|
||||
}
|
||||
if (rules.min !== undefined && rules.max !== undefined && rules.min > rules.max) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `field ${field.key}: validationRules.min must be <= max`,
|
||||
});
|
||||
}
|
||||
if (rules.minSelected !== undefined && rules.maxSelected !== undefined && rules.minSelected > rules.maxSelected) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `field ${field.key}: validationRules.minSelected must be <= maxSelected`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type FormField = z.infer<typeof FormFieldSchema>;
|
||||
@@ -92,6 +148,8 @@ export const FormDefinitionSchema = z
|
||||
description: z.string().max(2000).optional(),
|
||||
submitLabel: z.string().min(1).max(100).default("Submit"),
|
||||
successMessage: z.string().min(1).max(500).default("Thanks — we received your submission."),
|
||||
gdprConsentLabel: z.string().min(1).max(500).default("I agree to the processing of my data for this request."),
|
||||
captchaEnabled: z.boolean().default(true),
|
||||
fields: z.array(FormFieldSchema).min(1).max(50),
|
||||
})
|
||||
.superRefine((def, ctx) => {
|
||||
@@ -101,6 +159,11 @@ export const FormDefinitionSchema = z
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `duplicate field key: ${field.key}` });
|
||||
}
|
||||
seen.add(field.key);
|
||||
for (const rule of field.conditionalLogic ?? []) {
|
||||
if (rule.fieldKey === field.key) {
|
||||
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `field ${field.key}: conditional rule cannot reference itself` });
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -110,9 +173,21 @@ export type FormDefinition = z.infer<typeof FormDefinitionSchema>;
|
||||
* here because each form has a different shape; the route handler validates
|
||||
* required-ness + length against the form's stored definition. */
|
||||
export const FormSubmissionPayloadSchema = z.object({
|
||||
values: z.record(z.string().max(64), z.union([z.string().max(10000), z.boolean(), z.number(), z.null()])),
|
||||
values: z.record(
|
||||
z.string().max(64),
|
||||
z.union([
|
||||
z.string().max(10000),
|
||||
z.boolean(),
|
||||
z.number(),
|
||||
z.array(z.string().max(1000)).max(50),
|
||||
z.null(),
|
||||
]),
|
||||
),
|
||||
origin: z.string().max(500).optional(),
|
||||
turnstileToken: z.string().max(4096).optional(),
|
||||
captchaToken: z.string().max(4096).optional(),
|
||||
gdprAccepted: z.boolean().optional(),
|
||||
idempotencyKey: z.string().min(8).max(120).optional(),
|
||||
});
|
||||
|
||||
export type FormSubmissionPayload = z.infer<typeof FormSubmissionPayloadSchema>;
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { evaluateConditionalLogic, filterVisibleFields, isFieldVisible } from "./visibility.js";
|
||||
import type { FormField } from "./schema.js";
|
||||
|
||||
function field(key: string, conditionalLogic: FormField["conditionalLogic"] = []): FormField {
|
||||
return {
|
||||
key,
|
||||
type: "text",
|
||||
label: key,
|
||||
required: false,
|
||||
conditionalLogic,
|
||||
validationRules: {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("form field visibility", () => {
|
||||
it("shows fields without conditional rules", () => {
|
||||
expect(isFieldVisible(field("name"), {})).toBe(true);
|
||||
});
|
||||
|
||||
it("evaluates equality and filled operators", () => {
|
||||
const f = field("phone", [
|
||||
{ fieldKey: "contact_method", operator: "equals", value: "phone" },
|
||||
{ fieldKey: "name", operator: "not_empty" },
|
||||
]);
|
||||
|
||||
expect(isFieldVisible(f, { contact_method: "phone", name: "Ada" })).toBe(true);
|
||||
expect(isFieldVisible(f, { contact_method: "email", name: "Ada" })).toBe(false);
|
||||
});
|
||||
|
||||
it("filters a field list", () => {
|
||||
const fields = [field("name"), field("details", [{ fieldKey: "kind", operator: "in", value: ["repair", "install"] }])];
|
||||
|
||||
expect(filterVisibleFields(fields, { kind: "repair" }).map((f) => f.key)).toEqual(["name", "details"]);
|
||||
expect(filterVisibleFields(fields, { kind: "service" }).map((f) => f.key)).toEqual(["name"]);
|
||||
});
|
||||
|
||||
it("evaluates negative, contains and empty operators", () => {
|
||||
expect(evaluateConditionalLogic({ fieldKey: "status", operator: "not_equals", value: "closed" }, { status: "open" })).toBe(true);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "status", operator: "not_equals", value: "closed" }, { status: "closed" })).toBe(false);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "notes", operator: "contains", value: "urgent" }, { notes: "Very urgent issue" })).toBe(true);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "notes", operator: "contains", value: "urgent" }, { notes: "routine" })).toBe(false);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "optional", operator: "empty" }, { optional: "" })).toBe(true);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "optional", operator: "empty" }, { optional: "set" })).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes array and scalar values for membership checks", () => {
|
||||
expect(evaluateConditionalLogic({ fieldKey: "tags", operator: "equals", value: "vip,urgent" }, { tags: ["VIP", "urgent"] })).toBe(true);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "kind", operator: "in", value: "repair" }, { kind: "repair" })).toBe(true);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "kind", operator: "in", value: ["install"] }, { kind: "repair" })).toBe(false);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "emptyList", operator: "not_empty" }, { emptyList: [] })).toBe(false);
|
||||
expect(evaluateConditionalLogic({ fieldKey: "flag", operator: "not_empty" }, { flag: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ConditionalLogicRule, FormField } from "./schema.js";
|
||||
|
||||
export type ConditionalValues = Readonly<Record<string, unknown>>;
|
||||
|
||||
function normalized(value: unknown): string {
|
||||
if (value === null || value === undefined) return "";
|
||||
if (Array.isArray(value)) return value.map((item) => normalized(item)).join(",");
|
||||
return String(value).trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isFilled(value: unknown): boolean {
|
||||
if (Array.isArray(value)) return value.length > 0;
|
||||
return value !== undefined && value !== null && value !== "" && value !== false;
|
||||
}
|
||||
|
||||
export function evaluateConditionalLogic(rule: ConditionalLogicRule, values: ConditionalValues): boolean {
|
||||
const actual = values[rule.fieldKey];
|
||||
switch (rule.operator) {
|
||||
case "equals":
|
||||
return normalized(actual) === normalized(rule.value);
|
||||
case "not_equals":
|
||||
return normalized(actual) !== normalized(rule.value);
|
||||
case "contains":
|
||||
return normalized(actual).includes(normalized(rule.value));
|
||||
case "not_empty":
|
||||
return isFilled(actual);
|
||||
case "empty":
|
||||
return !isFilled(actual);
|
||||
case "in": {
|
||||
const expected = Array.isArray(rule.value) ? rule.value.map((item) => normalized(item)) : [normalized(rule.value)];
|
||||
return expected.includes(normalized(actual));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isFieldVisible(field: Pick<FormField, "conditionalLogic">, values: ConditionalValues): boolean {
|
||||
const rules = field.conditionalLogic ?? [];
|
||||
return rules.length === 0 || rules.every((rule) => evaluateConditionalLogic(rule, values));
|
||||
}
|
||||
|
||||
export function filterVisibleFields<T extends Pick<FormField, "conditionalLogic">>(fields: readonly T[], values: ConditionalValues): T[] {
|
||||
return fields.filter((field) => isFieldVisible(field, values));
|
||||
}
|
||||
Reference in new issue
Block a user