@flamingo-stack/openframe-frontend-core 0.0.596-2034.5671.1 → 0.0.596-2034.5675.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@ var MEETING_BOOKING_ERROR_CODES = [
11
11
  "TEMPORARILY_UNAVAILABLE",
12
12
  "MEETING_UNAVAILABLE"
13
13
  ];
14
- var SUPPORTED_FORM_FIELD_TYPES = ["text", "textarea", "select", "radio", "checkbox"];
14
+ var SUPPORTED_FORM_FIELD_TYPES = ["text", "textarea", "select", "radio", "checkbox", "number"];
15
15
  function isSupportedFormField(field) {
16
16
  return SUPPORTED_FORM_FIELD_TYPES.includes(field.type);
17
17
  }
@@ -50,6 +50,9 @@ function buildBookingSchema(formFields, legalConsent, slot) {
50
50
  case "textarea":
51
51
  validator = zod.z.string().max(5e3, { message: `${field.label} is too long` });
52
52
  break;
53
+ case "number":
54
+ validator = zod.z.string().max(32, { message: `${field.label} is too long` }).regex(/^-?\d+(\.\d+)?$/, { message: `${field.label} must be a number` });
55
+ break;
53
56
  case "text":
54
57
  default:
55
58
  validator = zod.z.string().max(1e3, { message: `${field.label} is too long` });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schemas/meeting-booking-schema.ts"],"names":["z"],"mappings":";;;;;AAwIO,IAAM,2BAAA,GAA8B;AAAA,EACzC,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAwBO,IAAM,6BAA6B,CAAC,MAAA,EAAQ,UAAA,EAAY,QAAA,EAAU,SAAS,UAAU;AAGrF,SAAS,qBAAqB,KAAA,EAAkC;AACrE,EAAA,OAAQ,0BAAA,CAAiD,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA;AAC9E;AAMA,IAAM,UAAA,GAAa,4CAAA;AAQZ,SAAS,oBAAoB,EAAA,EAAqB;AACvD,EAAA,IAAI,CAAC,UAA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king-schema.cjs","sourcesContent":["import { z } from 'zod';\n\n/**\n * Meeting-booking wire contracts + validation factory.\n *\n * SERVER-SAFE tsup entry (no \"use client\" banner) with its OWN per-file\n * subpath (`./schemas/meeting-booking-schema`) — same pattern and reasons as\n * `schemas/contact-schema`: used by BOTH the lib's `<HubSpotMeetingScheduler>`\n * (client-side validation) AND the host's server-side booking route, which\n * REBUILDS the schema from the link's own fetched metadata and never trusts a\n * client-shaped instance. zod is an optional peer quarantined to per-subpath\n * verticals — do NOT re-export this module through any broad barrel.\n *\n * Every cross-boundary type for the scheduling feature lives HERE (the lib\n * owns the contract; hosts import this subpath directly, type-only where\n * possible).\n */\n\n// ---------------------------------------------------------------------------\n// Wire types\n// ---------------------------------------------------------------------------\n\n/**\n * Sanitized availability payload served by the host proxy\n * (`GET {apiBaseUrl}/api/meetings/availability?meeting=<id>&monthOffset=<n>`).\n *\n * NO timezone field on purpose: slot starts are absolute epoch-ms instants\n * (verified timezone-independent against the live API), upstream fetches are\n * UTC-pinned, and ALL zone rendering happens client-side. Slots must be\n * whitelist-copied from HubSpot's `linkAvailability` ONLY — never derived\n * from busy-time data.\n */\nexport interface MeetingAvailability {\n meetingId: string;\n monthOffset: number;\n hasMore: boolean;\n /** Offered durations in ms — HubSpot's native unit for the booking POST. */\n durationsMs: number[];\n /** Bookable slot start times (epoch ms), keyed by duration in ms. */\n slotsByDurationMs: Record<string, number[]>;\n formFields: MeetingFormField[];\n /** Verbatim whitelist-copy of HubSpot's `legalConsentOptions` when consent is enabled; null when disabled. */\n legalConsent: MeetingLegalConsent | null;\n /**\n * Who the visitor is meeting — whitelisted DISPLAY projection the host DAL\n * builds from its own people data (e.g. a profiles table matched\n * server-side). NEVER carries emails or busy-time data; optional so\n * existing hosts stay wire-compatible.\n */\n hosts?: MeetingHost[];\n}\n\n/** Display-only host identity for the scheduler's context panel. */\nexport interface MeetingHost {\n name: string;\n avatarUrl: string | null;\n /** Job title / role line under the name (null → omitted). */\n title: string | null;\n}\n\n/**\n * One scheduling link on the DIRECTORY wire (`GET /api/meetings`) — the\n * host-DAL whitelist projection consumed by `MeetingSchedulerDirectory` and\n * host pages. Never carries organizer emails/busy-time data.\n */\nexport interface SchedulingLink {\n id: string;\n /** The link's public HubSpot booking URL — escape-hatch target only. */\n link: string;\n /** HubSpot slug path — the row's in-app destination is `<basePath>/<slug>`. */\n slug: string;\n /** Audience group key (slugified audience label; `\"other\"` in scope=all). */\n purpose: string;\n title: string;\n description: string | null;\n kind: 'personal' | 'team';\n /** Display-only minutes projection (booking stays ms end-to-end). */\n durationsMinutes: number[];\n hosts: MeetingHost[];\n /** Earliest bookable slot (epoch ms) from the current-month payload. */\n nextAvailableMs: number | null;\n}\n\nexport interface SchedulingLinksPayload {\n purposes: Array<{ purpose: string; label: string; links: SchedulingLink[] }>;\n fetchedAt: string;\n}\n\nexport interface MeetingFormField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n options?: string[];\n}\n\n/**\n * HubSpot's consent copy, rendered VERBATIM by the widget (GDPR surface —\n * never edited, never summarized). Responses are keyed by\n * `communicationTypeId`.\n */\nexport interface MeetingLegalConsent {\n processingConsentText: string;\n processingConsentCheckboxLabel: string | null;\n communicationConsentText: string | null;\n communicationConsentCheckboxes: Array<{\n communicationTypeId: string;\n label: string;\n required: boolean;\n }>;\n privacyPolicyText: string | null;\n isLegitimateInterest: boolean;\n}\n\n/**\n * Whitelisted booking result returned by the host proxy — the THIRD HubSpot\n * payload that reaches a browser, so it gets the same whitelist-copy\n * treatment as the two GETs. Nothing organizer-derived.\n */\nexport interface BookingConfirmation {\n meetingId: string;\n title: string;\n startTimeMs: number;\n durationMs: number;\n}\n\n/**\n * Typed domain errors the booking route emits; the widget keys its recovery\n * UI off these. `SLOT_TAKEN` → refetch-and-recover; `TEMPORARILY_UNAVAILABLE`\n * → retry affordance; `MEETING_UNAVAILABLE` → daily ceiling exhausted\n * (escape hatch, not a retry timer); `LINK_GONE` → link deleted upstream;\n * `INVALID_EMAIL` → HubSpot rejected the attendee address (its\n * MeetingsBookingCreatedError.INVALID_EMAIL class — fake/unreachable\n * mailboxes), so the widget tells the visitor to fix the email instead of\n * blaming the slot or their other details.\n */\nexport const MEETING_BOOKING_ERROR_CODES = [\n 'SLOT_TAKEN',\n 'VALIDATION',\n 'INVALID_EMAIL',\n 'LINK_GONE',\n 'TEMPORARILY_UNAVAILABLE',\n 'MEETING_UNAVAILABLE',\n] as const;\n\n/**\n * Derived from the runtime array ABOVE — the array is the single source of\n * truth. The booking hook validates server codes against it at runtime, so a\n * code added only to a hand-written type would be silently coerced to\n * TEMPORARILY_UNAVAILABLE by every deployed widget (exactly how the\n * INVALID_EMAIL rollout mis-rendered on 2026-08-27: type extended, runtime\n * allowlist stale — an array annotation is not exhaustiveness-checked).\n */\nexport type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[number];\n\n// ---------------------------------------------------------------------------\n// Field-type vocabulary — ONE set drives the renderer AND the validator\n// ---------------------------------------------------------------------------\n\n/**\n * HubSpot custom-question types the native form supports. The widget's\n * renderer switches over THIS set and `makeBookingSchema` maps over THIS set;\n * fail-closed = a field whose `type` is not in the set (the widget then\n * renders the \"Open in HubSpot\" escape hatch for that link instead of a\n * half-working native form). Exact upstream type strings are pinned against\n * the rollout fixture link — extend here (renderer + validator move together).\n */\nexport const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox'] as const;\nexport type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];\n\nexport function isSupportedFormField(field: MeetingFormField): boolean {\n return (SUPPORTED_FORM_FIELD_TYPES as readonly string[]).includes(field.type);\n}\n\n// ---------------------------------------------------------------------------\n// Validators (single home — client widget and server rebuild both use these)\n// ---------------------------------------------------------------------------\n\nconst IANA_TZ_RE = /^(?:UTC|[A-Za-z_]+(?:\\/[A-Za-z0-9_+-]+)+)$/;\n\n/**\n * IANA timezone check. Shape prefilter, then the authoritative resolution\n * test: `Intl.DateTimeFormat` throws on unknown zones. NOT\n * `Intl.supportedValuesOf('timeZone')` — that list excludes `'UTC'` itself\n * (verified in Node), which is a legitimate booking zone. Reject, never coerce.\n */\nexport function isValidIanaTimezone(tz: string): boolean {\n if (!IANA_TZ_RE.test(tz)) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/** BCP-47 locale shape check via `Intl.getCanonicalLocales`. Reject, never coerce. */\nexport function isValidBcp47Locale(locale: string): boolean {\n try {\n return Intl.getCanonicalLocales(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build the booking-form schema for ONE link's declared questions + consent.\n *\n * A factory (not a static schema) because per-link required questions cannot\n * be expressed statically. The widget builds it from the availability payload\n * it rendered; the server REBUILDS it from the link's own fetched metadata —\n * required-consent enforcement flows from this rebuild, not a parallel check.\n *\n * Deliberately NOT `.strict()`: the humanity-signal fields\n * (`HUMANITY_SIGNAL_KEYS` from `utils/humanity-signals`) ride alongside in\n * the same POST body (read raw by the host's bot gate BEFORE parsing) and are\n * stripped server-side before anything reaches HubSpot. zod's default\n * unknown-key stripping means the parsed output never contains them.\n *\n * `timezone`/`locale` are POST-only presentation fields (the invite renders\n * in the visitor's local time) — this schema is the ONLY place a\n * client-supplied zone is accepted; the availability path is UTC-pinned.\n */\nfunction buildBookingSchema<TStart extends z.ZodTypeAny, TDuration extends z.ZodTypeAny, TZone extends z.ZodTypeAny>(\n formFields: MeetingFormField[],\n legalConsent: MeetingLegalConsent | null,\n // Passed IN rather than switched on a boolean: a `deferSlot: boolean`\n // parameter cannot be narrowed at type level, so every ternary inside would\n // infer a union and widen `startTimeMs`/`durationMs` to `number | null |\n // undefined` for BOTH schemas — including the server's wire type.\n slot: { startTimeMs: TStart; durationMs: TDuration; timezone: TZone },\n) {\n const answers: Record<string, z.ZodTypeAny> = {};\n for (const field of formFields) {\n if (!isSupportedFormField(field)) continue; // unsupported types are fail-closed at render time\n let validator: z.ZodTypeAny;\n switch (field.type as SupportedFormFieldType) {\n case 'checkbox':\n validator = z.boolean();\n break;\n case 'select':\n case 'radio':\n validator = z.string().refine(v => !v || (field.options ?? []).includes(v), {\n message: `Please choose a valid option for ${field.label}`,\n });\n break;\n case 'textarea':\n validator = z.string().max(5000, { message: `${field.label} is too long` });\n break;\n case 'text':\n default:\n validator = z.string().max(1000, { message: `${field.label} is too long` });\n break;\n }\n if (field.required) {\n validator =\n field.type === 'checkbox'\n ? z.literal(true, { message: `${field.label} is required` })\n : (validator as z.ZodString).min(1, { message: `${field.label} is required` });\n } else if (field.type !== 'checkbox') {\n validator = (validator as z.ZodString).optional().or(z.literal(''));\n } else {\n validator = z.boolean().optional();\n }\n answers[field.name] = validator;\n }\n\n const requiredConsentIds = (legalConsent?.communicationConsentCheckboxes ?? [])\n .filter(c => c.required)\n .map(c => c.communicationTypeId);\n\n // A required answer cannot be enforced by an `.optional()` parent object —\n // omitting the `formFields` key entirely would skip every per-question\n // rule. When the link declares at least one required supported question,\n // the object itself is required.\n const hasRequiredAnswers = formFields.some(f => isSupportedFormField(f) && f.required);\n const answersObject = z.object(answers);\n\n return (\n z\n .object({\n meetingId: z.string().min(1),\n startTimeMs: slot.startTimeMs,\n durationMs: slot.durationMs,\n firstName: z.string().min(1, { message: 'First name is required' }).max(255),\n lastName: z.string().min(1, { message: 'Last name is required' }).max(255),\n email: z.string().email({ message: 'Please enter a valid email address' }).max(255),\n timezone: slot.timezone,\n locale: z.string().refine(isValidBcp47Locale, { message: 'Invalid locale' }).optional(),\n // Plain `.optional()` (no `.default()`) so zod's input and output types\n // match — react-hook-form's zodResolver needs them identical, and the\n // server handles `undefined` explicitly anyway. REQUIRED when the link\n // declares required questions (see `hasRequiredAnswers` above).\n formFields: hasRequiredAnswers ? answersObject : answersObject.optional(),\n legalConsentResponses: z\n .array(z.object({ communicationTypeId: z.string(), consented: z.boolean() }))\n .optional(),\n })\n // Object-level rule: `.refine` on an `.optional()` field is skipped when\n // the field is absent — required consents must reject even on a payload\n // that omits the array entirely.\n .superRefine((data, ctx) => {\n const responses = data.legalConsentResponses ?? [];\n const ok = requiredConsentIds.every(id =>\n responses.some(r => r.communicationTypeId === id && r.consented === true),\n );\n if (!ok) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['legalConsentResponses'],\n message: 'Required consent checkboxes must be accepted',\n });\n }\n })\n );\n}\n\n/**\n * The STRICT schema — the wire contract. The server rebuilds it from the link's\n * own fetched metadata and validates every booking against it; a slot and a\n * duration are not optional on anything that reaches HubSpot.\n */\nexport function makeBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive(),\n durationMs: z.number().int().positive(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }),\n });\n}\n\n/**\n * The DEFERRED schema — same fields, with the slot/duration/timezone triple\n * relaxed. `flow=\"details-first\"` collects answers BEFORE a slot exists, so the\n * form validates against this and the parent re-attaches the authoritative\n * values at POST time.\n *\n * Two named exports over one private builder rather than an overload or an\n * options flag: `MeetingBookingPayload` is `z.infer<ReturnType<...>>`, and\n * either of those alternatives would widen `startTimeMs`/`durationMs` to\n * `number | undefined` for EVERY consumer — including the server's\n * `durationsMs.includes(data.durationMs)`.\n */\nexport function makeDeferredBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n // `.nullish()`, not `.optional()`: the widget passes these straight into\n // `defaultValues`, and details-first has `timezone === null` on the server\n // render and the first client render (zone resolution is post-hydration).\n // Accepting only `undefined` would reject a field with no rendered control\n // and no FieldWrapper — the submit button silently dead, type-check clean.\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive().nullish(),\n durationMs: z.number().int().positive().nullish(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }).nullish(),\n });\n}\n\n/** The wire payload. Pinned to the STRICT builder — see above. */\nexport type MeetingBookingPayload = z.infer<ReturnType<typeof makeBookingSchema>>;\n\n/**\n * The form's value type, used as the `useForm` generic in BOTH flows: a relaxed\n * resolver is not assignable to `Resolver<MeetingBookingPayload>`, and mixing\n * the two survives only on TS's bivariant method-parameter check.\n */\nexport type BookingFormValues = z.infer<ReturnType<typeof makeDeferredBookingSchema>>;\n"]}
1
+ {"version":3,"sources":["../../src/schemas/meeting-booking-schema.ts"],"names":["z"],"mappings":";;;;;AAwIO,IAAM,2BAAA,GAA8B;AAAA,EACzC,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AA+BO,IAAM,6BAA6B,CAAC,MAAA,EAAQ,YAAY,QAAA,EAAU,OAAA,EAAS,YAAY,QAAQ;AAG/F,SAAS,qBAAqB,KAAA,EAAkC;AACrE,EAAA,OAAQ,0BAAA,CAAiD,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA;AAC9E;AAMA,IAAM,UAAA,GAAa,4CAAA;AAQZ,SAAS,oBAAoB,EAAA,EAAqB;AACvD,EAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,EAAE,GAAG,OAAO,KAAA;AACjC,EAAA,IAAI;AACF,IAAA,IAAI,KAAK,cAAA,CAAe,OAAA,EAAS,EAAE,QAAA,EAAU,IAAI,CAAA;AACjD,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,mBAAmB,MAAA,EAAyB;AAC1D,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,mBAAA,CAAoB,MAAM,CAAA,CAAE,MAAA,GAAS,CAAA;AAAA,EACnD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAwBA,SAAS,kBAAA,CACP,UAAA,EACA,YAAA,EAKA,IAAA,EACA;AACA,EAAA,MAA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AAA,QACX,IAAA,EAAMA,MAAE,YAAA,CAAa,MAAA;AAAA,QACrB,IAAA,EAAM,CAAC,uBAAuB,CAAA;AAAA,QAC9B,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AAEP;AAOO,SAAS,iBAAA,CAAkB,YAAgC,YAAA,EAA0C;AAC1G,EAAA,OAAO,kBAAA,CAAmB,YAAY,YAAA,EAAc;AAAA,IAClD,aAAaA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA,IACvC,YAAYA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA,IACtC,QAAA,EAAUA,MAAE,MAAA,EAAO,CAAE,OAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB;AAAA,GACjF,CAAA;AACH;AAcO,SAAS,yBAAA,CAA0B,YAAgC,YAAA,EAA0C;AAMlH,EAAA,OAAO,kBAAA,CAAmB,YAAY,YAAA,EAAc;AAAA,IAClD,WAAA,EAAaA,MAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IACjD,UAAA,EAAYA,MAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IAChD,QAAA,EAAUA,KAAA,CAAE,MAAA,EAAO,CAAE,MAAA,CAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB,CAAA,CAAE,OAAA;AAAQ,GAC3F,CAAA;AACH","file":"meeting-booking-schema.cjs","sourcesContent":["import { z } from 'zod';\n\n/**\n * Meeting-booking wire contracts + validation factory.\n *\n * SERVER-SAFE tsup entry (no \"use client\" banner) with its OWN per-file\n * subpath (`./schemas/meeting-booking-schema`) — same pattern and reasons as\n * `schemas/contact-schema`: used by BOTH the lib's `<HubSpotMeetingScheduler>`\n * (client-side validation) AND the host's server-side booking route, which\n * REBUILDS the schema from the link's own fetched metadata and never trusts a\n * client-shaped instance. zod is an optional peer quarantined to per-subpath\n * verticals — do NOT re-export this module through any broad barrel.\n *\n * Every cross-boundary type for the scheduling feature lives HERE (the lib\n * owns the contract; hosts import this subpath directly, type-only where\n * possible).\n */\n\n// ---------------------------------------------------------------------------\n// Wire types\n// ---------------------------------------------------------------------------\n\n/**\n * Sanitized availability payload served by the host proxy\n * (`GET {apiBaseUrl}/api/meetings/availability?meeting=<id>&monthOffset=<n>`).\n *\n * NO timezone field on purpose: slot starts are absolute epoch-ms instants\n * (verified timezone-independent against the live API), upstream fetches are\n * UTC-pinned, and ALL zone rendering happens client-side. Slots must be\n * whitelist-copied from HubSpot's `linkAvailability` ONLY — never derived\n * from busy-time data.\n */\nexport interface MeetingAvailability {\n meetingId: string;\n monthOffset: number;\n hasMore: boolean;\n /** Offered durations in ms — HubSpot's native unit for the booking POST. */\n durationsMs: number[];\n /** Bookable slot start times (epoch ms), keyed by duration in ms. */\n slotsByDurationMs: Record<string, number[]>;\n formFields: MeetingFormField[];\n /** Verbatim whitelist-copy of HubSpot's `legalConsentOptions` when consent is enabled; null when disabled. */\n legalConsent: MeetingLegalConsent | null;\n /**\n * Who the visitor is meeting — whitelisted DISPLAY projection the host DAL\n * builds from its own people data (e.g. a profiles table matched\n * server-side). NEVER carries emails or busy-time data; optional so\n * existing hosts stay wire-compatible.\n */\n hosts?: MeetingHost[];\n}\n\n/** Display-only host identity for the scheduler's context panel. */\nexport interface MeetingHost {\n name: string;\n avatarUrl: string | null;\n /** Job title / role line under the name (null → omitted). */\n title: string | null;\n}\n\n/**\n * One scheduling link on the DIRECTORY wire (`GET /api/meetings`) — the\n * host-DAL whitelist projection consumed by `MeetingSchedulerDirectory` and\n * host pages. Never carries organizer emails/busy-time data.\n */\nexport interface SchedulingLink {\n id: string;\n /** The link's public HubSpot booking URL — escape-hatch target only. */\n link: string;\n /** HubSpot slug path — the row's in-app destination is `<basePath>/<slug>`. */\n slug: string;\n /** Audience group key (slugified audience label; `\"other\"` in scope=all). */\n purpose: string;\n title: string;\n description: string | null;\n kind: 'personal' | 'team';\n /** Display-only minutes projection (booking stays ms end-to-end). */\n durationsMinutes: number[];\n hosts: MeetingHost[];\n /** Earliest bookable slot (epoch ms) from the current-month payload. */\n nextAvailableMs: number | null;\n}\n\nexport interface SchedulingLinksPayload {\n purposes: Array<{ purpose: string; label: string; links: SchedulingLink[] }>;\n fetchedAt: string;\n}\n\nexport interface MeetingFormField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n options?: string[];\n}\n\n/**\n * HubSpot's consent copy, rendered VERBATIM by the widget (GDPR surface —\n * never edited, never summarized). Responses are keyed by\n * `communicationTypeId`.\n */\nexport interface MeetingLegalConsent {\n processingConsentText: string;\n processingConsentCheckboxLabel: string | null;\n communicationConsentText: string | null;\n communicationConsentCheckboxes: Array<{\n communicationTypeId: string;\n label: string;\n required: boolean;\n }>;\n privacyPolicyText: string | null;\n isLegitimateInterest: boolean;\n}\n\n/**\n * Whitelisted booking result returned by the host proxy — the THIRD HubSpot\n * payload that reaches a browser, so it gets the same whitelist-copy\n * treatment as the two GETs. Nothing organizer-derived.\n */\nexport interface BookingConfirmation {\n meetingId: string;\n title: string;\n startTimeMs: number;\n durationMs: number;\n}\n\n/**\n * Typed domain errors the booking route emits; the widget keys its recovery\n * UI off these. `SLOT_TAKEN` → refetch-and-recover; `TEMPORARILY_UNAVAILABLE`\n * → retry affordance; `MEETING_UNAVAILABLE` → daily ceiling exhausted\n * (escape hatch, not a retry timer); `LINK_GONE` → link deleted upstream;\n * `INVALID_EMAIL` → HubSpot rejected the attendee address (its\n * MeetingsBookingCreatedError.INVALID_EMAIL class — fake/unreachable\n * mailboxes), so the widget tells the visitor to fix the email instead of\n * blaming the slot or their other details.\n */\nexport const MEETING_BOOKING_ERROR_CODES = [\n 'SLOT_TAKEN',\n 'VALIDATION',\n 'INVALID_EMAIL',\n 'LINK_GONE',\n 'TEMPORARILY_UNAVAILABLE',\n 'MEETING_UNAVAILABLE',\n] as const;\n\n/**\n * Derived from the runtime array ABOVE — the array is the single source of\n * truth. The booking hook validates server codes against it at runtime, so a\n * code added only to a hand-written type would be silently coerced to\n * TEMPORARILY_UNAVAILABLE by every deployed widget (exactly how the\n * INVALID_EMAIL rollout mis-rendered on 2026-08-27: type extended, runtime\n * allowlist stale — an array annotation is not exhaustiveness-checked).\n */\nexport type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[number];\n\n// ---------------------------------------------------------------------------\n// Field-type vocabulary — ONE set drives the renderer AND the validator\n// ---------------------------------------------------------------------------\n\n/**\n * HubSpot custom-question types the native form supports. The widget's\n * renderer switches over THIS set and `makeBookingSchema` maps over THIS set;\n * fail-closed = a field whose `type` is not in the set (the widget then\n * renders the \"Open in HubSpot\" escape hatch for that link instead of a\n * half-working native form). Exact upstream type strings are pinned against\n * the rollout fixture link — extend here (renderer + validator move together).\n */\n// HubSpot `fieldType` values the widget can render faithfully. Anything else\n// (phonenumber, date, booleancheckbox, file, …) makes the link \"not natively\n// bookable\" and the card fails closed to the HubSpot escape hatch — so adding a\n// type here means adding a control in `booking-form.tsx` AND a validator below.\n// `number` is a Number property: the wire value stays a STRING like every other\n// answer (HubSpot's book endpoint takes `{ name, value: string }`), validated as\n// a decimal literal.\nexport const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox', 'number'] as const;\nexport type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];\n\nexport function isSupportedFormField(field: MeetingFormField): boolean {\n return (SUPPORTED_FORM_FIELD_TYPES as readonly string[]).includes(field.type);\n}\n\n// ---------------------------------------------------------------------------\n// Validators (single home — client widget and server rebuild both use these)\n// ---------------------------------------------------------------------------\n\nconst IANA_TZ_RE = /^(?:UTC|[A-Za-z_]+(?:\\/[A-Za-z0-9_+-]+)+)$/;\n\n/**\n * IANA timezone check. Shape prefilter, then the authoritative resolution\n * test: `Intl.DateTimeFormat` throws on unknown zones. NOT\n * `Intl.supportedValuesOf('timeZone')` — that list excludes `'UTC'` itself\n * (verified in Node), which is a legitimate booking zone. Reject, never coerce.\n */\nexport function isValidIanaTimezone(tz: string): boolean {\n if (!IANA_TZ_RE.test(tz)) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/** BCP-47 locale shape check via `Intl.getCanonicalLocales`. Reject, never coerce. */\nexport function isValidBcp47Locale(locale: string): boolean {\n try {\n return Intl.getCanonicalLocales(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build the booking-form schema for ONE link's declared questions + consent.\n *\n * A factory (not a static schema) because per-link required questions cannot\n * be expressed statically. The widget builds it from the availability payload\n * it rendered; the server REBUILDS it from the link's own fetched metadata —\n * required-consent enforcement flows from this rebuild, not a parallel check.\n *\n * Deliberately NOT `.strict()`: the humanity-signal fields\n * (`HUMANITY_SIGNAL_KEYS` from `utils/humanity-signals`) ride alongside in\n * the same POST body (read raw by the host's bot gate BEFORE parsing) and are\n * stripped server-side before anything reaches HubSpot. zod's default\n * unknown-key stripping means the parsed output never contains them.\n *\n * `timezone`/`locale` are POST-only presentation fields (the invite renders\n * in the visitor's local time) — this schema is the ONLY place a\n * client-supplied zone is accepted; the availability path is UTC-pinned.\n */\nfunction buildBookingSchema<TStart extends z.ZodTypeAny, TDuration extends z.ZodTypeAny, TZone extends z.ZodTypeAny>(\n formFields: MeetingFormField[],\n legalConsent: MeetingLegalConsent | null,\n // Passed IN rather than switched on a boolean: a `deferSlot: boolean`\n // parameter cannot be narrowed at type level, so every ternary inside would\n // infer a union and widen `startTimeMs`/`durationMs` to `number | null |\n // undefined` for BOTH schemas — including the server's wire type.\n slot: { startTimeMs: TStart; durationMs: TDuration; timezone: TZone },\n) {\n const answers: Record<string, z.ZodTypeAny> = {};\n for (const field of formFields) {\n if (!isSupportedFormField(field)) continue; // unsupported types are fail-closed at render time\n let validator: z.ZodTypeAny;\n switch (field.type as SupportedFormFieldType) {\n case 'checkbox':\n validator = z.boolean();\n break;\n case 'select':\n case 'radio':\n validator = z.string().refine(v => !v || (field.options ?? []).includes(v), {\n message: `Please choose a valid option for ${field.label}`,\n });\n break;\n case 'textarea':\n validator = z.string().max(5000, { message: `${field.label} is too long` });\n break;\n case 'number':\n // Optional integer sign, digits, optional decimal part — what\n // `<input type=\"number\">` emits and what a Number property stores.\n validator = z\n .string()\n .max(32, { message: `${field.label} is too long` })\n .regex(/^-?\\d+(\\.\\d+)?$/, { message: `${field.label} must be a number` });\n break;\n case 'text':\n default:\n validator = z.string().max(1000, { message: `${field.label} is too long` });\n break;\n }\n if (field.required) {\n validator =\n field.type === 'checkbox'\n ? z.literal(true, { message: `${field.label} is required` })\n : (validator as z.ZodString).min(1, { message: `${field.label} is required` });\n } else if (field.type !== 'checkbox') {\n validator = (validator as z.ZodString).optional().or(z.literal(''));\n } else {\n validator = z.boolean().optional();\n }\n answers[field.name] = validator;\n }\n\n const requiredConsentIds = (legalConsent?.communicationConsentCheckboxes ?? [])\n .filter(c => c.required)\n .map(c => c.communicationTypeId);\n\n // A required answer cannot be enforced by an `.optional()` parent object —\n // omitting the `formFields` key entirely would skip every per-question\n // rule. When the link declares at least one required supported question,\n // the object itself is required.\n const hasRequiredAnswers = formFields.some(f => isSupportedFormField(f) && f.required);\n const answersObject = z.object(answers);\n\n return (\n z\n .object({\n meetingId: z.string().min(1),\n startTimeMs: slot.startTimeMs,\n durationMs: slot.durationMs,\n firstName: z.string().min(1, { message: 'First name is required' }).max(255),\n lastName: z.string().min(1, { message: 'Last name is required' }).max(255),\n email: z.string().email({ message: 'Please enter a valid email address' }).max(255),\n timezone: slot.timezone,\n locale: z.string().refine(isValidBcp47Locale, { message: 'Invalid locale' }).optional(),\n // Plain `.optional()` (no `.default()`) so zod's input and output types\n // match — react-hook-form's zodResolver needs them identical, and the\n // server handles `undefined` explicitly anyway. REQUIRED when the link\n // declares required questions (see `hasRequiredAnswers` above).\n formFields: hasRequiredAnswers ? answersObject : answersObject.optional(),\n legalConsentResponses: z\n .array(z.object({ communicationTypeId: z.string(), consented: z.boolean() }))\n .optional(),\n })\n // Object-level rule: `.refine` on an `.optional()` field is skipped when\n // the field is absent — required consents must reject even on a payload\n // that omits the array entirely.\n .superRefine((data, ctx) => {\n const responses = data.legalConsentResponses ?? [];\n const ok = requiredConsentIds.every(id =>\n responses.some(r => r.communicationTypeId === id && r.consented === true),\n );\n if (!ok) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['legalConsentResponses'],\n message: 'Required consent checkboxes must be accepted',\n });\n }\n })\n );\n}\n\n/**\n * The STRICT schema — the wire contract. The server rebuilds it from the link's\n * own fetched metadata and validates every booking against it; a slot and a\n * duration are not optional on anything that reaches HubSpot.\n */\nexport function makeBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive(),\n durationMs: z.number().int().positive(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }),\n });\n}\n\n/**\n * The DEFERRED schema — same fields, with the slot/duration/timezone triple\n * relaxed. `flow=\"details-first\"` collects answers BEFORE a slot exists, so the\n * form validates against this and the parent re-attaches the authoritative\n * values at POST time.\n *\n * Two named exports over one private builder rather than an overload or an\n * options flag: `MeetingBookingPayload` is `z.infer<ReturnType<...>>`, and\n * either of those alternatives would widen `startTimeMs`/`durationMs` to\n * `number | undefined` for EVERY consumer — including the server's\n * `durationsMs.includes(data.durationMs)`.\n */\nexport function makeDeferredBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n // `.nullish()`, not `.optional()`: the widget passes these straight into\n // `defaultValues`, and details-first has `timezone === null` on the server\n // render and the first client render (zone resolution is post-hydration).\n // Accepting only `undefined` would reject a field with no rendered control\n // and no FieldWrapper — the submit button silently dead, type-check clean.\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive().nullish(),\n durationMs: z.number().int().positive().nullish(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }).nullish(),\n });\n}\n\n/** The wire payload. Pinned to the STRICT builder — see above. */\nexport type MeetingBookingPayload = z.infer<ReturnType<typeof makeBookingSchema>>;\n\n/**\n * The form's value type, used as the `useForm` generic in BOTH flows: a relaxed\n * resolver is not assignable to `Resolver<MeetingBookingPayload>`, and mixing\n * the two survives only on TS's bivariant method-parameter check.\n */\nexport type BookingFormValues = z.infer<ReturnType<typeof makeDeferredBookingSchema>>;\n"]}
@@ -143,7 +143,7 @@ export type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[numbe
143
143
  * half-working native form). Exact upstream type strings are pinned against
144
144
  * the rollout fixture link — extend here (renderer + validator move together).
145
145
  */
146
- export declare const SUPPORTED_FORM_FIELD_TYPES: readonly ["text", "textarea", "select", "radio", "checkbox"];
146
+ export declare const SUPPORTED_FORM_FIELD_TYPES: readonly ["text", "textarea", "select", "radio", "checkbox", "number"];
147
147
  export type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];
148
148
  export declare function isSupportedFormField(field: MeetingFormField): boolean;
149
149
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"meeting-booking-schema.d.ts","sourceRoot":"","sources":["../../src/schemas/meeting-booking-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;;GAcG;AAMH;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,4EAA4E;IAC5E,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,qEAAqE;IACrE,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAC5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
11
11
  ];
12
- var SUPPORTED_FORM_FIELD_TYPES = ["text", "textarea", "select", "radio", "checkbox"];
12
+ var SUPPORTED_FORM_FIELD_TYPES = ["text", "textarea", "select", "radio", "checkbox", "number"];
13
13
  function isSupportedFormField(field) {
14
14
  return SUPPORTED_FORM_FIELD_TYPES.includes(field.type);
15
15
  }
@@ -48,6 +48,9 @@ function buildBookingSchema(formFields, legalConsent, slot) {
48
48
  case "textarea":
49
49
  validator = z.string().max(5e3, { message: `${field.label} is too long` });
50
50
  break;
51
+ case "number":
52
+ validator = z.string().max(32, { message: `${field.label} is too long` }).regex(/^-?\d+(\.\d+)?$/, { message: `${field.label} must be a number` });
53
+ break;
51
54
  case "text":
52
55
  default:
53
56
  validator = z.string().max(1e3, { message: `${field.label} is too long` });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schemas/meeting-booking-schema.ts"],"names":[],"mappings":";;;AAwIO,IAAM,2BAAA,GAA8B;AAAA,EACzC,YAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,WAAA;AAAA,EACA,yBAAA;AAAA,EACA;AACF;AAwBO,IAAM,6BAA6B,CAAC,MAAA,EAAQ,UAAA,EAAY,QAAA,EAAU,SAAS,UAAU;AAGrF,SAAS,qBAAqB,KAAA,EAAkC;AACrE,EAAA,OAAQ,0BAAA,CAAiD,QAAA,CAAS,KAAA,CAAM,IAAI,CAAA;AAC9E;AAMA,IAAM,UAAA,GAAa,4CAAA;AAQZ,SAAS,oBAAoB,EAAA,EAAqB;AACvD,EAAA,IAAI,CAAC,UAAA,CAAW,IAAA,CAAK,EAAE,GAAG,OAAO,KAAA;AACjC,EAAA,IAAI;AACF,IAAA,IAAI,KAAK,cAAA,CAAe,OAAA,EAAS,EAAE,QAAA,EAAU,IAAI,CAAA;AACjD,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,mBAAmB,MAAA,EA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,CAAa,MAAA;AAAA,QACrB,IAAA,EAAM,CAAC,uBAAuB,CAAA;AAAA,QAC9B,OAAA,EAAS;AAAA,OACV,CAAA;AAAA,IACH;AAAA,EACF,CAAC,CAAA;AAEP;AAOO,SAAS,iBAAA,CAAkB,YAAgC,YAAA,EAA0C;AAC1G,EAAA,OAAO,kBAAA,CAAmB,YAAY,YAAA,EAAc;AAAA,IAClD,aAAa,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA,IACvC,YAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA,IACtC,QAAA,EAAU,EAAE,MAAA,EAAO,CAAE,OAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB;AAAA,GACjF,CAAA;AACH;AAcO,SAAS,yBAAA,CAA0B,YAAgC,YAAA,EAA0C;AAMlH,EAAA,OAAO,kBAAA,CAAmB,YAAY,YAAA,EAAc;AAAA,IAClD,WAAA,EAAa,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IACjD,UAAA,EAAY,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IAChD,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,MAAA,CAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB,CAAA,CAAE,OAAA;AAAQ,GAC3F,CAAA;AACH","file":"meeting-booking-schema.js","sourcesContent":["import { z } from 'zod';\n\n/**\n * Meeting-booking wire contracts + validation factory.\n *\n * SERVER-SAFE tsup entry (no \"use client\" banner) with its OWN per-file\n * subpath (`./schemas/meeting-booking-schema`) — same pattern and reasons as\n * `schemas/contact-schema`: used by BOTH the lib's `<HubSpotMeetingScheduler>`\n * (client-side validation) AND the host's server-side booking route, which\n * REBUILDS the schema from the link's own fetched metadata and never trusts a\n * client-shaped instance. zod is an optional peer quarantined to per-subpath\n * verticals — do NOT re-export this module through any broad barrel.\n *\n * Every cross-boundary type for the scheduling feature lives HERE (the lib\n * owns the contract; hosts import this subpath directly, type-only where\n * possible).\n */\n\n// ---------------------------------------------------------------------------\n// Wire types\n// ---------------------------------------------------------------------------\n\n/**\n * Sanitized availability payload served by the host proxy\n * (`GET {apiBaseUrl}/api/meetings/availability?meeting=<id>&monthOffset=<n>`).\n *\n * NO timezone field on purpose: slot starts are absolute epoch-ms instants\n * (verified timezone-independent against the live API), upstream fetches are\n * UTC-pinned, and ALL zone rendering happens client-side. Slots must be\n * whitelist-copied from HubSpot's `linkAvailability` ONLY — never derived\n * from busy-time data.\n */\nexport interface MeetingAvailability {\n meetingId: string;\n monthOffset: number;\n hasMore: boolean;\n /** Offered durations in ms — HubSpot's native unit for the booking POST. */\n durationsMs: number[];\n /** Bookable slot start times (epoch ms), keyed by duration in ms. */\n slotsByDurationMs: Record<string, number[]>;\n formFields: MeetingFormField[];\n /** Verbatim whitelist-copy of HubSpot's `legalConsentOptions` when consent is enabled; null when disabled. */\n legalConsent: MeetingLegalConsent | null;\n /**\n * Who the visitor is meeting — whitelisted DISPLAY projection the host DAL\n * builds from its own people data (e.g. a profiles table matched\n * server-side). NEVER carries emails or busy-time data; optional so\n * existing hosts stay wire-compatible.\n */\n hosts?: MeetingHost[];\n}\n\n/** Display-only host identity for the scheduler's context panel. */\nexport interface MeetingHost {\n name: string;\n avatarUrl: string | null;\n /** Job title / role line under the name (null → omitted). */\n title: string | null;\n}\n\n/**\n * One scheduling link on the DIRECTORY wire (`GET /api/meetings`) — the\n * host-DAL whitelist projection consumed by `MeetingSchedulerDirectory` and\n * host pages. Never carries organizer emails/busy-time data.\n */\nexport interface SchedulingLink {\n id: string;\n /** The link's public HubSpot booking URL — escape-hatch target only. */\n link: string;\n /** HubSpot slug path — the row's in-app destination is `<basePath>/<slug>`. */\n slug: string;\n /** Audience group key (slugified audience label; `\"other\"` in scope=all). */\n purpose: string;\n title: string;\n description: string | null;\n kind: 'personal' | 'team';\n /** Display-only minutes projection (booking stays ms end-to-end). */\n durationsMinutes: number[];\n hosts: MeetingHost[];\n /** Earliest bookable slot (epoch ms) from the current-month payload. */\n nextAvailableMs: number | null;\n}\n\nexport interface SchedulingLinksPayload {\n purposes: Array<{ purpose: string; label: string; links: SchedulingLink[] }>;\n fetchedAt: string;\n}\n\nexport interface MeetingFormField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n options?: string[];\n}\n\n/**\n * HubSpot's consent copy, rendered VERBATIM by the widget (GDPR surface —\n * never edited, never summarized). Responses are keyed by\n * `communicationTypeId`.\n */\nexport interface MeetingLegalConsent {\n processingConsentText: string;\n processingConsentCheckboxLabel: string | null;\n communicationConsentText: string | null;\n communicationConsentCheckboxes: Array<{\n communicationTypeId: string;\n label: string;\n required: boolean;\n }>;\n privacyPolicyText: string | null;\n isLegitimateInterest: boolean;\n}\n\n/**\n * Whitelisted booking result returned by the host proxy — the THIRD HubSpot\n * payload that reaches a browser, so it gets the same whitelist-copy\n * treatment as the two GETs. Nothing organizer-derived.\n */\nexport interface BookingConfirmation {\n meetingId: string;\n title: string;\n startTimeMs: number;\n durationMs: number;\n}\n\n/**\n * Typed domain errors the booking route emits; the widget keys its recovery\n * UI off these. `SLOT_TAKEN` → refetch-and-recover; `TEMPORARILY_UNAVAILABLE`\n * → retry affordance; `MEETING_UNAVAILABLE` → daily ceiling exhausted\n * (escape hatch, not a retry timer); `LINK_GONE` → link deleted upstream;\n * `INVALID_EMAIL` → HubSpot rejected the attendee address (its\n * MeetingsBookingCreatedError.INVALID_EMAIL class — fake/unreachable\n * mailboxes), so the widget tells the visitor to fix the email instead of\n * blaming the slot or their other details.\n */\nexport const MEETING_BOOKING_ERROR_CODES = [\n 'SLOT_TAKEN',\n 'VALIDATION',\n 'INVALID_EMAIL',\n 'LINK_GONE',\n 'TEMPORARILY_UNAVAILABLE',\n 'MEETING_UNAVAILABLE',\n] as const;\n\n/**\n * Derived from the runtime array ABOVE — the array is the single source of\n * truth. The booking hook validates server codes against it at runtime, so a\n * code added only to a hand-written type would be silently coerced to\n * TEMPORARILY_UNAVAILABLE by every deployed widget (exactly how the\n * INVALID_EMAIL rollout mis-rendered on 2026-08-27: type extended, runtime\n * allowlist stale — an array annotation is not exhaustiveness-checked).\n */\nexport type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[number];\n\n// ---------------------------------------------------------------------------\n// Field-type vocabulary — ONE set drives the renderer AND the validator\n// ---------------------------------------------------------------------------\n\n/**\n * HubSpot custom-question types the native form supports. The widget's\n * renderer switches over THIS set and `makeBookingSchema` maps over THIS set;\n * fail-closed = a field whose `type` is not in the set (the widget then\n * renders the \"Open in HubSpot\" escape hatch for that link instead of a\n * half-working native form). Exact upstream type strings are pinned against\n * the rollout fixture link — extend here (renderer + validator move together).\n */\nexport const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox'] as const;\nexport type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];\n\nexport function isSupportedFormField(field: MeetingFormField): boolean {\n return (SUPPORTED_FORM_FIELD_TYPES as readonly string[]).includes(field.type);\n}\n\n// ---------------------------------------------------------------------------\n// Validators (single home — client widget and server rebuild both use these)\n// ---------------------------------------------------------------------------\n\nconst IANA_TZ_RE = /^(?:UTC|[A-Za-z_]+(?:\\/[A-Za-z0-9_+-]+)+)$/;\n\n/**\n * IANA timezone check. Shape prefilter, then the authoritative resolution\n * test: `Intl.DateTimeFormat` throws on unknown zones. NOT\n * `Intl.supportedValuesOf('timeZone')` — that list excludes `'UTC'` itself\n * (verified in Node), which is a legitimate booking zone. Reject, never coerce.\n */\nexport function isValidIanaTimezone(tz: string): boolean {\n if (!IANA_TZ_RE.test(tz)) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/** BCP-47 locale shape check via `Intl.getCanonicalLocales`. Reject, never coerce. */\nexport function isValidBcp47Locale(locale: string): boolean {\n try {\n return Intl.getCanonicalLocales(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build the booking-form schema for ONE link's declared questions + consent.\n *\n * A factory (not a static schema) because per-link required questions cannot\n * be expressed statically. The widget builds it from the availability payload\n * it rendered; the server REBUILDS it from the link's own fetched metadata —\n * required-consent enforcement flows from this rebuild, not a parallel check.\n *\n * Deliberately NOT `.strict()`: the humanity-signal fields\n * (`HUMANITY_SIGNAL_KEYS` from `utils/humanity-signals`) ride alongside in\n * the same POST body (read raw by the host's bot gate BEFORE parsing) and are\n * stripped server-side before anything reaches HubSpot. zod's default\n * unknown-key stripping means the parsed output never contains them.\n *\n * `timezone`/`locale` are POST-only presentation fields (the invite renders\n * in the visitor's local time) — this schema is the ONLY place a\n * client-supplied zone is accepted; the availability path is UTC-pinned.\n */\nfunction buildBookingSchema<TStart extends z.ZodTypeAny, TDuration extends z.ZodTypeAny, TZone extends z.ZodTypeAny>(\n formFields: MeetingFormField[],\n legalConsent: MeetingLegalConsent | null,\n // Passed IN rather than switched on a boolean: a `deferSlot: boolean`\n // parameter cannot be narrowed at type level, so every ternary inside would\n // infer a union and widen `startTimeMs`/`durationMs` to `number | null |\n // undefined` for BOTH schemas — including the server's wire type.\n slot: { startTimeMs: TStart; durationMs: TDuration; timezone: TZone },\n) {\n const answers: Record<string, z.ZodTypeAny> = {};\n for (const field of formFields) {\n if (!isSupportedFormField(field)) continue; // unsupported types are fail-closed at render time\n let validator: z.ZodTypeAny;\n switch (field.type as SupportedFormFieldType) {\n case 'checkbox':\n validator = z.boolean();\n break;\n case 'select':\n case 'radio':\n validator = z.string().refine(v => !v || (field.options ?? []).includes(v), {\n message: `Please choose a valid option for ${field.label}`,\n });\n break;\n case 'textarea':\n validator = z.string().max(5000, { message: `${field.label} is too long` });\n break;\n case 'text':\n default:\n validator = z.string().max(1000, { message: `${field.label} is too long` });\n break;\n }\n if (field.required) {\n validator =\n field.type === 'checkbox'\n ? z.literal(true, { message: `${field.label} is required` })\n : (validator as z.ZodString).min(1, { message: `${field.label} is required` });\n } else if (field.type !== 'checkbox') {\n validator = (validator as z.ZodString).optional().or(z.literal(''));\n } else {\n validator = z.boolean().optional();\n }\n answers[field.name] = validator;\n }\n\n const requiredConsentIds = (legalConsent?.communicationConsentCheckboxes ?? [])\n .filter(c => c.required)\n .map(c => c.communicationTypeId);\n\n // A required answer cannot be enforced by an `.optional()` parent object —\n // omitting the `formFields` key entirely would skip every per-question\n // rule. When the link declares at least one required supported question,\n // the object itself is required.\n const hasRequiredAnswers = formFields.some(f => isSupportedFormField(f) && f.required);\n const answersObject = z.object(answers);\n\n return (\n z\n .object({\n meetingId: z.string().min(1),\n startTimeMs: slot.startTimeMs,\n durationMs: slot.durationMs,\n firstName: z.string().min(1, { message: 'First name is required' }).max(255),\n lastName: z.string().min(1, { message: 'Last name is required' }).max(255),\n email: z.string().email({ message: 'Please enter a valid email address' }).max(255),\n timezone: slot.timezone,\n locale: z.string().refine(isValidBcp47Locale, { message: 'Invalid locale' }).optional(),\n // Plain `.optional()` (no `.default()`) so zod's input and output types\n // match — react-hook-form's zodResolver needs them identical, and the\n // server handles `undefined` explicitly anyway. REQUIRED when the link\n // declares required questions (see `hasRequiredAnswers` above).\n formFields: hasRequiredAnswers ? answersObject : answersObject.optional(),\n legalConsentResponses: z\n .array(z.object({ communicationTypeId: z.string(), consented: z.boolean() }))\n .optional(),\n })\n // Object-level rule: `.refine` on an `.optional()` field is skipped when\n // the field is absent — required consents must reject even on a payload\n // that omits the array entirely.\n .superRefine((data, ctx) => {\n const responses = data.legalConsentResponses ?? [];\n const ok = requiredConsentIds.every(id =>\n responses.some(r => r.communicationTypeId === id && r.consented === true),\n );\n if (!ok) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['legalConsentResponses'],\n message: 'Required consent checkboxes must be accepted',\n });\n }\n })\n );\n}\n\n/**\n * The STRICT schema — the wire contract. The server rebuilds it from the link's\n * own fetched metadata and validates every booking against it; a slot and a\n * duration are not optional on anything that reaches HubSpot.\n */\nexport function makeBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive(),\n durationMs: z.number().int().positive(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }),\n });\n}\n\n/**\n * The DEFERRED schema — same fields, with the slot/duration/timezone triple\n * relaxed. `flow=\"details-first\"` collects answers BEFORE a slot exists, so the\n * form validates against this and the parent re-attaches the authoritative\n * values at POST time.\n *\n * Two named exports over one private builder rather than an overload or an\n * options flag: `MeetingBookingPayload` is `z.infer<ReturnType<...>>`, and\n * either of those alternatives would widen `startTimeMs`/`durationMs` to\n * `number | undefined` for EVERY consumer — including the server's\n * `durationsMs.includes(data.durationMs)`.\n */\nexport function makeDeferredBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n // `.nullish()`, not `.optional()`: the widget passes these straight into\n // `defaultValues`, and details-first has `timezone === null` on the server\n // render and the first client render (zone resolution is post-hydration).\n // Accepting only `undefined` would reject a field with no rendered control\n // and no FieldWrapper — the submit button silently dead, type-check clean.\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive().nullish(),\n durationMs: z.number().int().positive().nullish(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }).nullish(),\n });\n}\n\n/** The wire payload. Pinned to the STRICT builder — see above. */\nexport type MeetingBookingPayload = z.infer<ReturnType<typeof makeBookingSchema>>;\n\n/**\n * The form's value type, used as the `useForm` generic in BOTH flows: a relaxed\n * resolver is not assignable to `Resolver<MeetingBookingPayload>`, and mixing\n * the two survives only on TS's bivariant method-parameter check.\n */\nexport type BookingFormValues = z.infer<ReturnType<typeof makeDeferredBookingSchema>>;\n"]}
1
+ {"version":3,"sources":["../../src/schemas/meeting-booking-schema.ts"],"names":[],"m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GAAA,GAAM,QAAA,EAAS;AAAA,IACvC,YAAY,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,QAAA,EAAS;AAAA,IACtC,QAAA,EAAU,EAAE,MAAA,EAAO,CAAE,OAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB;AAAA,GACjF,CAAA;AACH;AAcO,SAAS,yBAAA,CAA0B,YAAgC,YAAA,EAA0C;AAMlH,EAAA,OAAO,kBAAA,CAAmB,YAAY,YAAA,EAAc;AAAA,IAClD,WAAA,EAAa,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IACjD,UAAA,EAAY,EAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,GAAW,OAAA,EAAQ;AAAA,IAChD,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,MAAA,CAAO,mBAAA,EAAqB,EAAE,OAAA,EAAS,kBAAA,EAAoB,CAAA,CAAE,OAAA;AAAQ,GAC3F,CAAA;AACH","file":"meeting-booking-schema.js","sourcesContent":["import { z } from 'zod';\n\n/**\n * Meeting-booking wire contracts + validation factory.\n *\n * SERVER-SAFE tsup entry (no \"use client\" banner) with its OWN per-file\n * subpath (`./schemas/meeting-booking-schema`) — same pattern and reasons as\n * `schemas/contact-schema`: used by BOTH the lib's `<HubSpotMeetingScheduler>`\n * (client-side validation) AND the host's server-side booking route, which\n * REBUILDS the schema from the link's own fetched metadata and never trusts a\n * client-shaped instance. zod is an optional peer quarantined to per-subpath\n * verticals — do NOT re-export this module through any broad barrel.\n *\n * Every cross-boundary type for the scheduling feature lives HERE (the lib\n * owns the contract; hosts import this subpath directly, type-only where\n * possible).\n */\n\n// ---------------------------------------------------------------------------\n// Wire types\n// ---------------------------------------------------------------------------\n\n/**\n * Sanitized availability payload served by the host proxy\n * (`GET {apiBaseUrl}/api/meetings/availability?meeting=<id>&monthOffset=<n>`).\n *\n * NO timezone field on purpose: slot starts are absolute epoch-ms instants\n * (verified timezone-independent against the live API), upstream fetches are\n * UTC-pinned, and ALL zone rendering happens client-side. Slots must be\n * whitelist-copied from HubSpot's `linkAvailability` ONLY — never derived\n * from busy-time data.\n */\nexport interface MeetingAvailability {\n meetingId: string;\n monthOffset: number;\n hasMore: boolean;\n /** Offered durations in ms — HubSpot's native unit for the booking POST. */\n durationsMs: number[];\n /** Bookable slot start times (epoch ms), keyed by duration in ms. */\n slotsByDurationMs: Record<string, number[]>;\n formFields: MeetingFormField[];\n /** Verbatim whitelist-copy of HubSpot's `legalConsentOptions` when consent is enabled; null when disabled. */\n legalConsent: MeetingLegalConsent | null;\n /**\n * Who the visitor is meeting — whitelisted DISPLAY projection the host DAL\n * builds from its own people data (e.g. a profiles table matched\n * server-side). NEVER carries emails or busy-time data; optional so\n * existing hosts stay wire-compatible.\n */\n hosts?: MeetingHost[];\n}\n\n/** Display-only host identity for the scheduler's context panel. */\nexport interface MeetingHost {\n name: string;\n avatarUrl: string | null;\n /** Job title / role line under the name (null → omitted). */\n title: string | null;\n}\n\n/**\n * One scheduling link on the DIRECTORY wire (`GET /api/meetings`) — the\n * host-DAL whitelist projection consumed by `MeetingSchedulerDirectory` and\n * host pages. Never carries organizer emails/busy-time data.\n */\nexport interface SchedulingLink {\n id: string;\n /** The link's public HubSpot booking URL — escape-hatch target only. */\n link: string;\n /** HubSpot slug path — the row's in-app destination is `<basePath>/<slug>`. */\n slug: string;\n /** Audience group key (slugified audience label; `\"other\"` in scope=all). */\n purpose: string;\n title: string;\n description: string | null;\n kind: 'personal' | 'team';\n /** Display-only minutes projection (booking stays ms end-to-end). */\n durationsMinutes: number[];\n hosts: MeetingHost[];\n /** Earliest bookable slot (epoch ms) from the current-month payload. */\n nextAvailableMs: number | null;\n}\n\nexport interface SchedulingLinksPayload {\n purposes: Array<{ purpose: string; label: string; links: SchedulingLink[] }>;\n fetchedAt: string;\n}\n\nexport interface MeetingFormField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n options?: string[];\n}\n\n/**\n * HubSpot's consent copy, rendered VERBATIM by the widget (GDPR surface —\n * never edited, never summarized). Responses are keyed by\n * `communicationTypeId`.\n */\nexport interface MeetingLegalConsent {\n processingConsentText: string;\n processingConsentCheckboxLabel: string | null;\n communicationConsentText: string | null;\n communicationConsentCheckboxes: Array<{\n communicationTypeId: string;\n label: string;\n required: boolean;\n }>;\n privacyPolicyText: string | null;\n isLegitimateInterest: boolean;\n}\n\n/**\n * Whitelisted booking result returned by the host proxy — the THIRD HubSpot\n * payload that reaches a browser, so it gets the same whitelist-copy\n * treatment as the two GETs. Nothing organizer-derived.\n */\nexport interface BookingConfirmation {\n meetingId: string;\n title: string;\n startTimeMs: number;\n durationMs: number;\n}\n\n/**\n * Typed domain errors the booking route emits; the widget keys its recovery\n * UI off these. `SLOT_TAKEN` → refetch-and-recover; `TEMPORARILY_UNAVAILABLE`\n * → retry affordance; `MEETING_UNAVAILABLE` → daily ceiling exhausted\n * (escape hatch, not a retry timer); `LINK_GONE` → link deleted upstream;\n * `INVALID_EMAIL` → HubSpot rejected the attendee address (its\n * MeetingsBookingCreatedError.INVALID_EMAIL class — fake/unreachable\n * mailboxes), so the widget tells the visitor to fix the email instead of\n * blaming the slot or their other details.\n */\nexport const MEETING_BOOKING_ERROR_CODES = [\n 'SLOT_TAKEN',\n 'VALIDATION',\n 'INVALID_EMAIL',\n 'LINK_GONE',\n 'TEMPORARILY_UNAVAILABLE',\n 'MEETING_UNAVAILABLE',\n] as const;\n\n/**\n * Derived from the runtime array ABOVE — the array is the single source of\n * truth. The booking hook validates server codes against it at runtime, so a\n * code added only to a hand-written type would be silently coerced to\n * TEMPORARILY_UNAVAILABLE by every deployed widget (exactly how the\n * INVALID_EMAIL rollout mis-rendered on 2026-08-27: type extended, runtime\n * allowlist stale — an array annotation is not exhaustiveness-checked).\n */\nexport type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[number];\n\n// ---------------------------------------------------------------------------\n// Field-type vocabulary — ONE set drives the renderer AND the validator\n// ---------------------------------------------------------------------------\n\n/**\n * HubSpot custom-question types the native form supports. The widget's\n * renderer switches over THIS set and `makeBookingSchema` maps over THIS set;\n * fail-closed = a field whose `type` is not in the set (the widget then\n * renders the \"Open in HubSpot\" escape hatch for that link instead of a\n * half-working native form). Exact upstream type strings are pinned against\n * the rollout fixture link — extend here (renderer + validator move together).\n */\n// HubSpot `fieldType` values the widget can render faithfully. Anything else\n// (phonenumber, date, booleancheckbox, file, …) makes the link \"not natively\n// bookable\" and the card fails closed to the HubSpot escape hatch — so adding a\n// type here means adding a control in `booking-form.tsx` AND a validator below.\n// `number` is a Number property: the wire value stays a STRING like every other\n// answer (HubSpot's book endpoint takes `{ name, value: string }`), validated as\n// a decimal literal.\nexport const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox', 'number'] as const;\nexport type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];\n\nexport function isSupportedFormField(field: MeetingFormField): boolean {\n return (SUPPORTED_FORM_FIELD_TYPES as readonly string[]).includes(field.type);\n}\n\n// ---------------------------------------------------------------------------\n// Validators (single home — client widget and server rebuild both use these)\n// ---------------------------------------------------------------------------\n\nconst IANA_TZ_RE = /^(?:UTC|[A-Za-z_]+(?:\\/[A-Za-z0-9_+-]+)+)$/;\n\n/**\n * IANA timezone check. Shape prefilter, then the authoritative resolution\n * test: `Intl.DateTimeFormat` throws on unknown zones. NOT\n * `Intl.supportedValuesOf('timeZone')` — that list excludes `'UTC'` itself\n * (verified in Node), which is a legitimate booking zone. Reject, never coerce.\n */\nexport function isValidIanaTimezone(tz: string): boolean {\n if (!IANA_TZ_RE.test(tz)) return false;\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/** BCP-47 locale shape check via `Intl.getCanonicalLocales`. Reject, never coerce. */\nexport function isValidBcp47Locale(locale: string): boolean {\n try {\n return Intl.getCanonicalLocales(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Schema factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build the booking-form schema for ONE link's declared questions + consent.\n *\n * A factory (not a static schema) because per-link required questions cannot\n * be expressed statically. The widget builds it from the availability payload\n * it rendered; the server REBUILDS it from the link's own fetched metadata —\n * required-consent enforcement flows from this rebuild, not a parallel check.\n *\n * Deliberately NOT `.strict()`: the humanity-signal fields\n * (`HUMANITY_SIGNAL_KEYS` from `utils/humanity-signals`) ride alongside in\n * the same POST body (read raw by the host's bot gate BEFORE parsing) and are\n * stripped server-side before anything reaches HubSpot. zod's default\n * unknown-key stripping means the parsed output never contains them.\n *\n * `timezone`/`locale` are POST-only presentation fields (the invite renders\n * in the visitor's local time) — this schema is the ONLY place a\n * client-supplied zone is accepted; the availability path is UTC-pinned.\n */\nfunction buildBookingSchema<TStart extends z.ZodTypeAny, TDuration extends z.ZodTypeAny, TZone extends z.ZodTypeAny>(\n formFields: MeetingFormField[],\n legalConsent: MeetingLegalConsent | null,\n // Passed IN rather than switched on a boolean: a `deferSlot: boolean`\n // parameter cannot be narrowed at type level, so every ternary inside would\n // infer a union and widen `startTimeMs`/`durationMs` to `number | null |\n // undefined` for BOTH schemas — including the server's wire type.\n slot: { startTimeMs: TStart; durationMs: TDuration; timezone: TZone },\n) {\n const answers: Record<string, z.ZodTypeAny> = {};\n for (const field of formFields) {\n if (!isSupportedFormField(field)) continue; // unsupported types are fail-closed at render time\n let validator: z.ZodTypeAny;\n switch (field.type as SupportedFormFieldType) {\n case 'checkbox':\n validator = z.boolean();\n break;\n case 'select':\n case 'radio':\n validator = z.string().refine(v => !v || (field.options ?? []).includes(v), {\n message: `Please choose a valid option for ${field.label}`,\n });\n break;\n case 'textarea':\n validator = z.string().max(5000, { message: `${field.label} is too long` });\n break;\n case 'number':\n // Optional integer sign, digits, optional decimal part — what\n // `<input type=\"number\">` emits and what a Number property stores.\n validator = z\n .string()\n .max(32, { message: `${field.label} is too long` })\n .regex(/^-?\\d+(\\.\\d+)?$/, { message: `${field.label} must be a number` });\n break;\n case 'text':\n default:\n validator = z.string().max(1000, { message: `${field.label} is too long` });\n break;\n }\n if (field.required) {\n validator =\n field.type === 'checkbox'\n ? z.literal(true, { message: `${field.label} is required` })\n : (validator as z.ZodString).min(1, { message: `${field.label} is required` });\n } else if (field.type !== 'checkbox') {\n validator = (validator as z.ZodString).optional().or(z.literal(''));\n } else {\n validator = z.boolean().optional();\n }\n answers[field.name] = validator;\n }\n\n const requiredConsentIds = (legalConsent?.communicationConsentCheckboxes ?? [])\n .filter(c => c.required)\n .map(c => c.communicationTypeId);\n\n // A required answer cannot be enforced by an `.optional()` parent object —\n // omitting the `formFields` key entirely would skip every per-question\n // rule. When the link declares at least one required supported question,\n // the object itself is required.\n const hasRequiredAnswers = formFields.some(f => isSupportedFormField(f) && f.required);\n const answersObject = z.object(answers);\n\n return (\n z\n .object({\n meetingId: z.string().min(1),\n startTimeMs: slot.startTimeMs,\n durationMs: slot.durationMs,\n firstName: z.string().min(1, { message: 'First name is required' }).max(255),\n lastName: z.string().min(1, { message: 'Last name is required' }).max(255),\n email: z.string().email({ message: 'Please enter a valid email address' }).max(255),\n timezone: slot.timezone,\n locale: z.string().refine(isValidBcp47Locale, { message: 'Invalid locale' }).optional(),\n // Plain `.optional()` (no `.default()`) so zod's input and output types\n // match — react-hook-form's zodResolver needs them identical, and the\n // server handles `undefined` explicitly anyway. REQUIRED when the link\n // declares required questions (see `hasRequiredAnswers` above).\n formFields: hasRequiredAnswers ? answersObject : answersObject.optional(),\n legalConsentResponses: z\n .array(z.object({ communicationTypeId: z.string(), consented: z.boolean() }))\n .optional(),\n })\n // Object-level rule: `.refine` on an `.optional()` field is skipped when\n // the field is absent — required consents must reject even on a payload\n // that omits the array entirely.\n .superRefine((data, ctx) => {\n const responses = data.legalConsentResponses ?? [];\n const ok = requiredConsentIds.every(id =>\n responses.some(r => r.communicationTypeId === id && r.consented === true),\n );\n if (!ok) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['legalConsentResponses'],\n message: 'Required consent checkboxes must be accepted',\n });\n }\n })\n );\n}\n\n/**\n * The STRICT schema — the wire contract. The server rebuilds it from the link's\n * own fetched metadata and validates every booking against it; a slot and a\n * duration are not optional on anything that reaches HubSpot.\n */\nexport function makeBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive(),\n durationMs: z.number().int().positive(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }),\n });\n}\n\n/**\n * The DEFERRED schema — same fields, with the slot/duration/timezone triple\n * relaxed. `flow=\"details-first\"` collects answers BEFORE a slot exists, so the\n * form validates against this and the parent re-attaches the authoritative\n * values at POST time.\n *\n * Two named exports over one private builder rather than an overload or an\n * options flag: `MeetingBookingPayload` is `z.infer<ReturnType<...>>`, and\n * either of those alternatives would widen `startTimeMs`/`durationMs` to\n * `number | undefined` for EVERY consumer — including the server's\n * `durationsMs.includes(data.durationMs)`.\n */\nexport function makeDeferredBookingSchema(formFields: MeetingFormField[], legalConsent: MeetingLegalConsent | null) {\n // `.nullish()`, not `.optional()`: the widget passes these straight into\n // `defaultValues`, and details-first has `timezone === null` on the server\n // render and the first client render (zone resolution is post-hydration).\n // Accepting only `undefined` would reject a field with no rendered control\n // and no FieldWrapper — the submit button silently dead, type-check clean.\n return buildBookingSchema(formFields, legalConsent, {\n startTimeMs: z.number().int().positive().nullish(),\n durationMs: z.number().int().positive().nullish(),\n timezone: z.string().refine(isValidIanaTimezone, { message: 'Invalid timezone' }).nullish(),\n });\n}\n\n/** The wire payload. Pinned to the STRICT builder — see above. */\nexport type MeetingBookingPayload = z.infer<ReturnType<typeof makeBookingSchema>>;\n\n/**\n * The form's value type, used as the `useForm` generic in BOTH flows: a relaxed\n * resolver is not assignable to `Resolver<MeetingBookingPayload>`, and mixing\n * the two survives only on TS's bivariant method-parameter check.\n */\nexport type BookingFormValues = z.infer<ReturnType<typeof makeDeferredBookingSchema>>;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flamingo-stack/openframe-frontend-core",
3
- "version": "0.0.596-2034.5671.1",
3
+ "version": "0.0.596-2034.5675.1",
4
4
  "description": "Shared design system and components for all Flamingo platforms",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,69 @@
1
+ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
2
+ import { createRef } from 'react';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import { BookingForm } from '../components/meeting-scheduler/booking-form';
5
+ import type { MeetingAvailability } from '../schemas/meeting-booking-schema';
6
+
7
+ const availability: MeetingAvailability = {
8
+ meetingId: '1',
9
+ monthOffset: 0,
10
+ hasMore: false,
11
+ durationsMs: [1_800_000],
12
+ slotsByDurationMs: { '1800000': [1_700_000_000_000] },
13
+ formFields: [{ name: 'number_of_endpoints', label: 'Number of endpoints', type: 'number', required: true }],
14
+ legalConsent: null,
15
+ hosts: [],
16
+ };
17
+
18
+ type Submit = (payload: Record<string, unknown>) => Promise<void>;
19
+
20
+ function mount(onSubmit = vi.fn<Submit>(() => Promise.resolve())) {
21
+ render(
22
+ <BookingForm
23
+ availability={availability}
24
+ meetingId="1"
25
+ startTimeMs={1_700_000_000_000}
26
+ durationMs={1_800_000}
27
+ timezone="America/New_York"
28
+ isSubmitting={false}
29
+ onSubmit={onSubmit}
30
+ honeypotInputProps={{ ref: createRef<HTMLInputElement>(), name: 'form_extra_note' }}
31
+ getSignals={() => ({})}
32
+ />,
33
+ );
34
+ return onSubmit;
35
+ }
36
+
37
+ const type = (el: HTMLElement, value: string) => fireEvent.input(el, { target: { value } });
38
+
39
+ describe('BookingForm — a HubSpot Number question', () => {
40
+ it('renders as a numeric input under the property label', () => {
41
+ mount();
42
+ const input = screen.getByLabelText('Number of endpoints');
43
+ expect(input).toHaveAttribute('type', 'number');
44
+ expect(input).toHaveAttribute('inputmode', 'numeric');
45
+ });
46
+
47
+ it('refuses a non-numeric answer and never calls onSubmit', async () => {
48
+ const onSubmit = mount();
49
+ type(screen.getByLabelText('Email'), 'a@b.co');
50
+ type(screen.getByLabelText('First Name'), 'A');
51
+ type(screen.getByLabelText('Last Name'), 'B');
52
+ // jsdom lets a number input hold arbitrary text; the resolver is the gate.
53
+ type(screen.getByLabelText('Number of endpoints'), 'lots');
54
+ fireEvent.click(screen.getByRole('button', { name: 'Confirm Booking' }));
55
+ expect(await screen.findByText('Number of endpoints must be a number')).toBeInTheDocument();
56
+ expect(onSubmit).not.toHaveBeenCalled();
57
+ });
58
+
59
+ it('submits a numeric answer as a string under the declared name', async () => {
60
+ const onSubmit = mount();
61
+ type(screen.getByLabelText('Email'), 'a@b.co');
62
+ type(screen.getByLabelText('First Name'), 'A');
63
+ type(screen.getByLabelText('Last Name'), 'B');
64
+ type(screen.getByLabelText('Number of endpoints'), '150');
65
+ fireEvent.click(screen.getByRole('button', { name: 'Confirm Booking' }));
66
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
67
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ formFields: { number_of_endpoints: '150' } }));
68
+ });
69
+ });
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ isSupportedFormField,
4
+ makeBookingSchema,
5
+ makeDeferredBookingSchema,
6
+ type MeetingFormField,
7
+ } from '../schemas/meeting-booking-schema';
8
+
9
+ const base = {
10
+ meetingId: '1',
11
+ startTimeMs: 1_700_000_000_000,
12
+ durationMs: 1_800_000,
13
+ firstName: 'A',
14
+ lastName: 'B',
15
+ email: 'a@b.co',
16
+ timezone: 'America/New_York',
17
+ };
18
+
19
+ const endpoints = (required: boolean): MeetingFormField => ({
20
+ name: 'number_of_endpoints',
21
+ label: 'Number of endpoints',
22
+ type: 'number',
23
+ required,
24
+ });
25
+
26
+ describe('meeting booking schema — number questions', () => {
27
+ it('treats a Number property as natively bookable, and unknown types as not', () => {
28
+ expect(isSupportedFormField(endpoints(true))).toBe(true);
29
+ expect(isSupportedFormField({ name: 'phone', label: 'Phone', type: 'phonenumber', required: false })).toBe(false);
30
+ });
31
+
32
+ it('accepts a decimal literal and keeps it a string on the wire', () => {
33
+ const schema = makeBookingSchema([endpoints(true)], null);
34
+ // `parse` throws on failure, so the value assertion is unconditional.
35
+ expect(schema.parse({ ...base, formFields: { number_of_endpoints: '150' } }).formFields?.number_of_endpoints).toBe(
36
+ '150',
37
+ );
38
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: '12.5' } }).success).toBe(true);
39
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: '-3' } }).success).toBe(true);
40
+ });
41
+
42
+ it('rejects text, and an empty answer when required', () => {
43
+ const schema = makeBookingSchema([endpoints(true)], null);
44
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: 'lots' } }).success).toBe(false);
45
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: '' } }).success).toBe(false);
46
+ expect(schema.safeParse({ ...base, formFields: {} }).success).toBe(false);
47
+ });
48
+
49
+ it('allows an empty answer when optional', () => {
50
+ const schema = makeBookingSchema([endpoints(false)], null);
51
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: '' } }).success).toBe(true);
52
+ expect(schema.safeParse({ ...base }).success).toBe(true);
53
+ expect(schema.safeParse({ ...base, formFields: { number_of_endpoints: 'x' } }).success).toBe(false);
54
+ });
55
+
56
+ it('applies the same rule in the deferred (details-first) schema', () => {
57
+ const schema = makeDeferredBookingSchema([endpoints(true)], null);
58
+ const { startTimeMs: _s, durationMs: _d, timezone: _t, ...noSlot } = base;
59
+ expect(schema.safeParse({ ...noSlot, formFields: { number_of_endpoints: '40' } }).success).toBe(true);
60
+ expect(schema.safeParse({ ...noSlot, formFields: { number_of_endpoints: 'forty' } }).success).toBe(false);
61
+ });
62
+ });
@@ -313,6 +313,16 @@ export function BookingForm({
313
313
  {...register(`formFields.${field.name}` as never)}
314
314
  />
315
315
  )}
316
+ {field.type === 'number' && (
317
+ <Input
318
+ id={`ms-q-${field.name}`}
319
+ type="number"
320
+ inputMode="numeric"
321
+ step="any"
322
+ className="h-11 border-ods-border bg-ods-card px-3 text-ods-text-primary placeholder-ods-text-secondary md:h-12"
323
+ {...register(`formFields.${field.name}` as never)}
324
+ />
325
+ )}
316
326
  {(field.type === 'select' || field.type === 'radio') && (
317
327
  <Controller
318
328
  control={control}
@@ -165,7 +165,14 @@ export type MeetingBookingErrorCode = (typeof MEETING_BOOKING_ERROR_CODES)[numbe
165
165
  * half-working native form). Exact upstream type strings are pinned against
166
166
  * the rollout fixture link — extend here (renderer + validator move together).
167
167
  */
168
- export const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox'] as const;
168
+ // HubSpot `fieldType` values the widget can render faithfully. Anything else
169
+ // (phonenumber, date, booleancheckbox, file, …) makes the link "not natively
170
+ // bookable" and the card fails closed to the HubSpot escape hatch — so adding a
171
+ // type here means adding a control in `booking-form.tsx` AND a validator below.
172
+ // `number` is a Number property: the wire value stays a STRING like every other
173
+ // answer (HubSpot's book endpoint takes `{ name, value: string }`), validated as
174
+ // a decimal literal.
175
+ export const SUPPORTED_FORM_FIELD_TYPES = ['text', 'textarea', 'select', 'radio', 'checkbox', 'number'] as const;
169
176
  export type SupportedFormFieldType = (typeof SUPPORTED_FORM_FIELD_TYPES)[number];
170
177
 
171
178
  export function isSupportedFormField(field: MeetingFormField): boolean {
@@ -251,6 +258,14 @@ function buildBookingSchema<TStart extends z.ZodTypeAny, TDuration extends z.Zod
251
258
  case 'textarea':
252
259
  validator = z.string().max(5000, { message: `${field.label} is too long` });
253
260
  break;
261
+ case 'number':
262
+ // Optional integer sign, digits, optional decimal part — what
263
+ // `<input type="number">` emits and what a Number property stores.
264
+ validator = z
265
+ .string()
266
+ .max(32, { message: `${field.label} is too long` })
267
+ .regex(/^-?\d+(\.\d+)?$/, { message: `${field.label} must be a number` });
268
+ break;
254
269
  case 'text':
255
270
  default:
256
271
  validator = z.string().max(1000, { message: `${field.label} is too long` });
@@ -112,7 +112,10 @@ describe('makeBookingSchema × SUPPORTED_FORM_FIELD_TYPES', () => {
112
112
  };
113
113
  expect(isSupportedFormField(field)).toBe(true);
114
114
  const schema = makeBookingSchema([field], null);
115
- const answer = type === 'checkbox' ? true : type === 'select' || type === 'radio' ? 'a' : 'hello';
115
+ // One well-formed answer per type: a boolean for the box, an option for the
116
+ // pickers, a decimal literal for a Number property, free text otherwise.
117
+ const answer =
118
+ type === 'checkbox' ? true : type === 'select' || type === 'radio' ? 'a' : type === 'number' ? '42' : 'hello';
116
119
  const ok = schema.safeParse({ ...base, formFields: { [field.name]: answer } });
117
120
  expect(ok.success).toBe(true);
118
121
  const missing = schema.safeParse({ ...base, formFields: {} });