@10x-media/form-builder 0.1.0-beta.11 → 0.1.0-beta.13

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.
Files changed (151) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
  3. package/dist/aggregation/resolveResultsRequest.js +32 -3
  4. package/dist/aggregation/resolveResultsRequest.js.map +1 -1
  5. package/dist/calc/computeCalcFields.d.ts +5 -3
  6. package/dist/calc/computeCalcFields.js +4 -3
  7. package/dist/calc/computeCalcFields.js.map +1 -1
  8. package/dist/calc/evaluate.d.ts +26 -3
  9. package/dist/calc/evaluate.js +33 -11
  10. package/dist/calc/evaluate.js.map +1 -1
  11. package/dist/calc/formatCalc.d.ts +11 -0
  12. package/dist/calc/formatCalc.js +35 -0
  13. package/dist/calc/formatCalc.js.map +1 -0
  14. package/dist/calc/formatCalcValue.d.ts +17 -0
  15. package/dist/calc/formatCalcValue.js +17 -0
  16. package/dist/calc/formatCalcValue.js.map +1 -0
  17. package/dist/calc/normalizeCalc.d.ts +17 -3
  18. package/dist/calc/normalizeCalc.js +39 -17
  19. package/dist/calc/normalizeCalc.js.map +1 -1
  20. package/dist/calc/registry.d.ts +43 -0
  21. package/dist/calc/registry.js +27 -0
  22. package/dist/calc/registry.js.map +1 -0
  23. package/dist/calc/resolveCalcContext.d.ts +36 -0
  24. package/dist/calc/resolveCalcContext.js +87 -0
  25. package/dist/calc/resolveCalcContext.js.map +1 -0
  26. package/dist/calc/types.d.ts +18 -3
  27. package/dist/calc/types.js +2 -1
  28. package/dist/calc/types.js.map +1 -1
  29. package/dist/client/CalcExpressionBuilder.d.ts +20 -0
  30. package/dist/client/CalcExpressionBuilder.js +890 -0
  31. package/dist/client/CalcExpressionBuilder.js.map +1 -0
  32. package/dist/client/admin.css +282 -0
  33. package/dist/collections/formSubmissions.js +7 -9
  34. package/dist/collections/formSubmissions.js.map +1 -1
  35. package/dist/collections/forms.js +59 -34
  36. package/dist/collections/forms.js.map +1 -1
  37. package/dist/collections/formsEndpoints.js +4 -2
  38. package/dist/collections/formsEndpoints.js.map +1 -1
  39. package/dist/collections/settingsFields.d.ts +31 -0
  40. package/dist/collections/settingsFields.js +45 -0
  41. package/dist/collections/settingsFields.js.map +1 -0
  42. package/dist/exports/client.d.ts +2 -1
  43. package/dist/exports/client.js +2 -1
  44. package/dist/exports/react.d.ts +7 -3
  45. package/dist/exports/react.js +6 -2
  46. package/dist/exports/rsc.js +1 -1
  47. package/dist/exports/types.d.ts +1 -1
  48. package/dist/fields/buildFieldBlocks.js +2 -1
  49. package/dist/fields/buildFieldBlocks.js.map +1 -1
  50. package/dist/fields/builtin/calculation.d.ts +17 -0
  51. package/dist/fields/builtin/calculation.js +170 -115
  52. package/dist/fields/builtin/calculation.js.map +1 -1
  53. package/dist/fields/builtin/checkbox.js +15 -0
  54. package/dist/fields/builtin/checkbox.js.map +1 -1
  55. package/dist/fields/builtin/email.js +7 -0
  56. package/dist/fields/builtin/email.js.map +1 -1
  57. package/dist/fields/builtin/index.d.ts +6 -2
  58. package/dist/fields/builtin/index.js +9 -4
  59. package/dist/fields/builtin/index.js.map +1 -1
  60. package/dist/fields/builtin/select.js +20 -1
  61. package/dist/fields/builtin/select.js.map +1 -1
  62. package/dist/fields/builtin/text.js +7 -0
  63. package/dist/fields/builtin/text.js.map +1 -1
  64. package/dist/fields/instanceOptions.js +1 -1
  65. package/dist/fields/instanceOptions.js.map +1 -1
  66. package/dist/fields/sharedConfig.js +15 -11
  67. package/dist/fields/sharedConfig.js.map +1 -1
  68. package/dist/fields/types.d.ts +8 -2
  69. package/dist/form/toFormDocument.d.ts +7 -0
  70. package/dist/form/toFormDocument.js +2 -1
  71. package/dist/form/toFormDocument.js.map +1 -1
  72. package/dist/form/types.d.ts +7 -0
  73. package/dist/index.d.ts +12 -4
  74. package/dist/index.js +35 -8
  75. package/dist/index.js.map +1 -1
  76. package/dist/options.d.ts +35 -0
  77. package/dist/plugin/registerCollections.js +29 -19
  78. package/dist/plugin/registerCollections.js.map +1 -1
  79. package/dist/poll/closeJob.d.ts +4 -3
  80. package/dist/poll/closeJob.js +6 -4
  81. package/dist/poll/closeJob.js.map +1 -1
  82. package/dist/poll/pollTypeRegistry.js +1 -1
  83. package/dist/poll/resolvePollCloseRequest.js +2 -1
  84. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  85. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  86. package/dist/poll/resolvePollOutcome.js +17 -3
  87. package/dist/poll/resolvePollOutcome.js.map +1 -1
  88. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  89. package/dist/poll/votes/aggregateFromVotes.js +53 -0
  90. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  91. package/dist/poll/votes/bumpPollVote.js +88 -0
  92. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  93. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  94. package/dist/poll/votes/recountPollVotes.js +63 -0
  95. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  96. package/dist/poll/votes/voteTallyHook.js +58 -0
  97. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  98. package/dist/poll/votes/votesCollection.d.ts +19 -0
  99. package/dist/poll/votes/votesCollection.js +89 -0
  100. package/dist/poll/votes/votesCollection.js.map +1 -0
  101. package/dist/react/Form.d.ts +7 -0
  102. package/dist/react/Form.js +20 -3
  103. package/dist/react/Form.js.map +1 -1
  104. package/dist/react/FormContext.d.ts +8 -1
  105. package/dist/react/FormContext.js.map +1 -1
  106. package/dist/react/primitives/Checkbox.d.ts +4 -2
  107. package/dist/react/primitives/Checkbox.js +3 -2
  108. package/dist/react/primitives/Checkbox.js.map +1 -1
  109. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  110. package/dist/react/primitives/ChoiceGroup.js +33 -0
  111. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  112. package/dist/react/primitives/FieldShell.d.ts +11 -1
  113. package/dist/react/primitives/FieldShell.js +43 -33
  114. package/dist/react/primitives/FieldShell.js.map +1 -1
  115. package/dist/react/primitives/Input.d.ts +3 -1
  116. package/dist/react/primitives/Input.js +2 -1
  117. package/dist/react/primitives/Input.js.map +1 -1
  118. package/dist/react/renderers/calculation.js +6 -1
  119. package/dist/react/renderers/calculation.js.map +1 -1
  120. package/dist/react/renderers/checkbox.js +2 -1
  121. package/dist/react/renderers/checkbox.js.map +1 -1
  122. package/dist/react/renderers/email.js +3 -1
  123. package/dist/react/renderers/email.js.map +1 -1
  124. package/dist/react/renderers/select.js +20 -2
  125. package/dist/react/renderers/select.js.map +1 -1
  126. package/dist/react/renderers/text.js +3 -1
  127. package/dist/react/renderers/text.js.map +1 -1
  128. package/dist/react/useCalcValues.d.ts +10 -0
  129. package/dist/react/useCalcValues.js +13 -0
  130. package/dist/react/useCalcValues.js.map +1 -0
  131. package/dist/recall/resolver.js +1 -1
  132. package/dist/recall/resolver.js.map +1 -1
  133. package/dist/submissions/formIdOf.js +13 -0
  134. package/dist/submissions/formIdOf.js.map +1 -0
  135. package/dist/submissions/runSubmission.js +3 -3
  136. package/dist/submissions/runSubmission.js.map +1 -1
  137. package/dist/submissions/validateSubmission.js +26 -2
  138. package/dist/submissions/validateSubmission.js.map +1 -1
  139. package/dist/translations/de.js +58 -3
  140. package/dist/translations/de.js.map +1 -1
  141. package/dist/translations/en.js +58 -3
  142. package/dist/translations/en.js.map +1 -1
  143. package/dist/translations/keys.d.ts +56 -1
  144. package/dist/translations/keys.js +56 -1
  145. package/dist/translations/keys.js.map +1 -1
  146. package/dist/validation/builtin/index.js +2 -0
  147. package/dist/validation/builtin/index.js.map +1 -1
  148. package/dist/validation/builtin/integer.js +15 -0
  149. package/dist/validation/builtin/integer.js.map +1 -0
  150. package/package.json +10 -4
  151. package/styles/form-builder.css +84 -0
@@ -6,6 +6,7 @@ import { validateUrl } from "../validation/validateUrl.js";
6
6
  import { normalizeCalc } from "../calc/normalizeCalc.js";
7
7
  import { isLoggedIn } from "../plugin/access.js";
8
8
  import { buildActionBlocks } from "../actions/buildActionBlocks.js";
9
+ import { calcUsesSources, resolveCalcContext } from "../calc/resolveCalcContext.js";
9
10
  import { buildConditionTypeMap } from "../conditions/conditionType.js";
10
11
  import { buildOperandTypes, normalizeFormConditions, normalizeWhere } from "../conditions/normalizeConditions.js";
11
12
  import { resolveConsentStatements } from "../consent/resolveConsentStatements.js";
@@ -20,11 +21,14 @@ import { buildDefaultOutcomeFields } from "../poll/outcomeFields.js";
20
21
  import { buildValidateResultsField, pollEligibleTypes } from "../poll/resultsField.js";
21
22
  import { buildDefaultButtonFields } from "./buttonFields.js";
22
23
  import { buildFormsEndpoints } from "./formsEndpoints.js";
24
+ import { composeSettingsFields } from "./settingsFields.js";
23
25
  import { ValidationError } from "payload";
24
26
  //#region src/collections/forms.ts
25
27
  const FORMS_SLUG = "forms";
26
28
  /** `req.context` key under which `consentAfterRead` tracks the form ids it is currently resolving, to break re-entrant reads. */
27
29
  const CONSENT_AFTER_READ_GUARD = "formBuilderConsentAfterReadInFlight";
30
+ /** `req.context` key under which `calcAfterRead` tracks the form ids it is currently resolving, to break re-entrant reads. */
31
+ const CALC_AFTER_READ_GUARD = "formBuilderCalcAfterReadInFlight";
28
32
  /**
29
33
  * Require the title in the default locale (and on hosts without localization), but let it be empty in
30
34
  * other locales so a localized form falls back to the default-locale title rather than forcing a
@@ -46,21 +50,22 @@ const validateFormTitle = (value, { req }) => {
46
50
  * references, so the unknown-target checks mainly protect partial API updates that send `flow`
47
51
  * without `fields`.
48
52
  */
49
- const validateFlow = (raw) => {
53
+ const validateFlow = (raw, { req }) => {
50
54
  if (raw === null || raw === void 0) return true;
51
55
  const r = raw;
52
56
  if (!Array.isArray(r.steps)) return true;
53
57
  const steps = r.steps;
54
- if (steps.find((s) => typeof s?.id !== "string" || s.id.length === 0)) return "Flow: every step must have a non-empty ID";
55
- if (steps.some((s) => s.id === "__end__")) return `Flow: step ID "${END_OF_FORM}" is reserved`;
58
+ const t = asTranslate(req.t);
59
+ if (steps.find((s) => typeof s?.id !== "string" || s.id.length === 0)) return t(keys.flowStepIdEmpty);
60
+ if (steps.some((s) => s.id === "__end__")) return t(keys.flowStepIdReserved).replace("{id}", END_OF_FORM);
56
61
  const ids = steps.map((s) => s.id);
57
- if (new Set(ids).size !== ids.length) return "Flow: duplicate step IDs found";
62
+ if (new Set(ids).size !== ids.length) return t(keys.flowDuplicateStepIds);
58
63
  const idSet = new Set(ids);
59
64
  for (const step of steps) {
60
65
  const id = step.id;
61
- if (typeof step.next === "string" && step.next.length > 0 && !idSet.has(step.next)) return `Flow: step "${id}" references unknown next step "${step.next}"`;
66
+ if (typeof step.next === "string" && step.next.length > 0 && !idSet.has(step.next)) return t(keys.flowUnknownNext).replace("{id}", id).replace("{next}", step.next);
62
67
  if (Array.isArray(step.transitions)) {
63
- for (const t of step.transitions) if (typeof t?.to === "string" && t.to.length > 0 && !idSet.has(t.to)) return `Flow: step "${id}" has a transition to unknown step "${t.to}"`;
68
+ for (const trans of step.transitions) if (typeof trans?.to === "string" && trans.to.length > 0 && !idSet.has(trans.to)) return t(keys.flowUnknownTransition).replace("{id}", id).replace("{to}", trans.to);
64
69
  }
65
70
  }
66
71
  return true;
@@ -84,7 +89,7 @@ const stampFileCollections = (rows, slug) => {
84
89
  if (Array.isArray(subFields)) stampFileCollections(subFields, slug);
85
90
  }
86
91
  };
87
- const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSources, consentResolveOnRead, actionRegistry = /* @__PURE__ */ new Map(), localizeContent = true, richText, uploadsCollectionSlug, resultsAccess, pollSourceRegistry, pollTypeRegistry, outcomeFields, buttons, response, fromAddresses, departments, redirectRelationships }) => {
92
+ const buildFormsCollection = ({ overrides, registry, ruleRegistry, calcAllowed, calcSources, consentSources, consentResolveOnRead, actionRegistry = /* @__PURE__ */ new Map(), localizeContent = true, richText, uploadsCollectionSlug, resultsAccess, pollVotesEnabled = false, pollSourceRegistry, pollTypeRegistry, outcomeFields, buttons, settings, response, fromAddresses, departments, redirectRelationships }) => {
88
93
  const conditionTypes = buildConditionTypeMap(registry);
89
94
  const pollTypes = pollTypeRegistry ?? resolvePollTypes();
90
95
  const pollResultsTypes = pollEligibleTypes(registry);
@@ -98,10 +103,21 @@ const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSource
98
103
  const CLOSE_POLL_BUTTON_REF = "@10x-media/form-builder/client#ClosePollButton";
99
104
  const hasOptionSources = (pollSourceRegistry?.size ?? 0) > 0;
100
105
  const orderedPollTypes = [...[...pollTypes.values()].filter((strategy) => strategy.type === "mostVoted"), ...[...pollTypes.values()].filter((strategy) => strategy.type !== "mostVoted")];
101
- const beforeValidate = ({ data, req }) => {
106
+ const beforeValidate = ({ data, originalDoc, req }) => {
107
+ if (!pollVotesEnabled) {
108
+ const pollOn = (data?.pollEnabled ?? originalDoc?.pollEnabled) === true;
109
+ const persistOff = (data?.persistSubmissions ?? originalDoc?.persistSubmissions) === false;
110
+ if (pollOn && persistOff) throw new ValidationError({
111
+ collection: FORMS_SLUG,
112
+ errors: [{
113
+ path: "persistSubmissions",
114
+ message: asTranslate(req.t)(keys.pollNeedsPersistedSubmissions)
115
+ }]
116
+ }, req.t);
117
+ }
102
118
  if (data && Array.isArray(data.fields)) {
103
119
  const normalized = normalizeFormConditions(data.fields, conditionTypes);
104
- for (const field of normalized) if ("expression" in field) field.expression = normalizeCalc(field.expression);
120
+ for (const field of normalized) if ("expression" in field) field.expression = normalizeCalc(field.expression, calcAllowed);
105
121
  if (uploadsCollectionSlug) stampFileCollections(normalized, uploadsCollectionSlug);
106
122
  data.fields = normalized;
107
123
  const fieldKeys = normalized.map((field) => {
@@ -114,7 +130,7 @@ const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSource
114
130
  collection: FORMS_SLUG,
115
131
  errors: [{
116
132
  path: "flow",
117
- message: "A flow needs at least two steps. Add another step or remove the flow."
133
+ message: asTranslate(req.t)(keys.flowNeedsTwoSteps)
118
134
  }]
119
135
  }, req.t);
120
136
  data.flow = normalizedFlow;
@@ -366,29 +382,7 @@ const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSource
366
382
  ...localizedIf(localizeContent),
367
383
  validate: validateFormTitle
368
384
  },
369
- {
370
- type: "row",
371
- fields: [{
372
- name: "multistep",
373
- type: "checkbox",
374
- defaultValue: false,
375
- label: labelForKey(keys.formMultistep),
376
- admin: { width: "50%" }
377
- }, {
378
- name: "pollEnabled",
379
- type: "checkbox",
380
- defaultValue: false,
381
- label: labelForKey(keys.formPollEnabled),
382
- admin: { width: "50%" }
383
- }]
384
- },
385
- {
386
- name: "persistSubmissions",
387
- type: "checkbox",
388
- defaultValue: true,
389
- label: labelForKey(keys.formPersistSubmissions),
390
- admin: { width: "50%" }
391
- },
385
+ ...composeSettingsFields(settings),
392
386
  {
393
387
  type: "tabs",
394
388
  tabs: [
@@ -441,9 +435,36 @@ const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSource
441
435
  }
442
436
  return doc;
443
437
  } : void 0;
438
+ const calcAfterRead = calcSources && Object.keys(calcSources).length > 0 ? async ({ doc, req }) => {
439
+ const fields = Array.isArray(doc.fields) ? doc.fields : [];
440
+ if (!calcUsesSources(fields)) return doc;
441
+ const id = doc.id;
442
+ const key = id == null ? void 0 : String(id);
443
+ if (key !== void 0 && req.context) {
444
+ const inFlight = req.context[CALC_AFTER_READ_GUARD] ?? /* @__PURE__ */ new Set();
445
+ if (inFlight.has(key)) return doc;
446
+ inFlight.add(key);
447
+ req.context[CALC_AFTER_READ_GUARD] = inFlight;
448
+ }
449
+ try {
450
+ doc.calcResolved = await resolveCalcContext({
451
+ fields,
452
+ sources: calcSources,
453
+ form: doc,
454
+ payload: req.payload,
455
+ req
456
+ });
457
+ } catch (error) {
458
+ req.payload.logger?.warn(`form-builder calc afterRead: ${String(error)}`);
459
+ } finally {
460
+ if (key !== void 0 && req.context) req.context[CALC_AFTER_READ_GUARD]?.delete(key);
461
+ }
462
+ return doc;
463
+ } : void 0;
444
464
  const defaultEndpoints = buildFormsEndpoints({
445
465
  resultsAccess,
446
466
  pollResultsTypes,
467
+ pollVotesEnabled,
447
468
  consentSources,
448
469
  fromAddresses,
449
470
  departments
@@ -477,7 +498,11 @@ const buildFormsCollection = ({ overrides, registry, ruleRegistry, consentSource
477
498
  beforeValidate: [beforeValidate, ...overrides?.hooks?.beforeValidate ?? []],
478
499
  beforeChange: [pollOutcomeBeforeChange, ...overrides?.hooks?.beforeChange ?? []],
479
500
  afterChange: [pollCloseAfterChange, ...overrides?.hooks?.afterChange ?? []],
480
- afterRead: [...consentAfterRead ? [consentAfterRead] : [], ...overrides?.hooks?.afterRead ?? []]
501
+ afterRead: [
502
+ ...consentAfterRead ? [consentAfterRead] : [],
503
+ ...calcAfterRead ? [calcAfterRead] : [],
504
+ ...overrides?.hooks?.afterRead ?? []
505
+ ]
481
506
  },
482
507
  endpoints: [...defaultEndpoints, ...Array.isArray(overrides?.endpoints) ? overrides.endpoints : []],
483
508
  fields: overrides?.fields ? overrides.fields({ defaultFields }) : defaultFields
@@ -1 +1 @@
1
- {"version":3,"file":"forms.js","names":[],"sources":["../../src/collections/forms.ts"],"sourcesContent":["import {\n\ttype CollectionAfterChangeHook,\n\ttype CollectionAfterReadHook,\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype CollectionSlug,\n\ttype Field,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n} from 'payload'\nimport type { RichTextBodyOption } from '../actions/body/serializeBody'\nimport { buildActionBlocks } from '../actions/buildActionBlocks'\nimport type { FromAddressesResolver } from '../actions/fromAddresses'\nimport type { ActionRegistry } from '../actions/registry'\nimport type { FormResultsAccess } from '../aggregation/resolveResultsRequest'\nimport { normalizeCalc } from '../calc/normalizeCalc'\nimport { buildConditionTypeMap } from '../conditions/conditionType'\nimport {\n\tbuildOperandTypes,\n\ttype FieldRow,\n\tnormalizeFormConditions,\n\tnormalizeWhere,\n} from '../conditions/normalizeConditions'\nimport { resolveConsentStatements } from '../consent/resolveConsentStatements'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport { buildFieldBlocks } from '../fields/buildFieldBlocks'\nimport { fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { localizedIf } from '../fields/localizedIf'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { normalizeFlow } from '../flow/normalizeFlow'\nimport { END_OF_FORM } from '../flow/types'\nimport { isLoggedIn } from '../plugin/access'\nimport type { CollectionOverrides } from '../plugin/collectionOverrides'\nimport { buildPollOptionSourceFields } from '../poll/buildPollOptionSourceFields'\nimport { enqueuePollClose } from '../poll/closeJob'\nimport { pollOutcomeBeforeChange } from '../poll/outcomeBeforeChange'\nimport { buildDefaultOutcomeFields, type OutcomeFieldsOverride } from '../poll/outcomeFields'\nimport { type PollTypeRegistry, resolvePollTypes } from '../poll/pollTypeRegistry'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport { buildValidateResultsField, pollEligibleTypes } from '../poll/resultsField'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelForKey, resolveDefinitionLabel } from '../translations/server'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport { validateUrl } from '../validation/validateUrl'\nimport { type ButtonsOption, buildDefaultButtonFields } from './buttonFields'\nimport { buildFormsEndpoints } from './formsEndpoints'\nimport type { ResponseOption } from './redirectFields'\n\nexport const FORMS_SLUG = 'forms'\n\n/** `req.context` key under which `consentAfterRead` tracks the form ids it is currently resolving, to break re-entrant reads. */\nconst CONSENT_AFTER_READ_GUARD = 'formBuilderConsentAfterReadInFlight'\n\n/**\n * Require the title in the default locale (and on hosts without localization), but let it be empty in\n * other locales so a localized form falls back to the default-locale title rather than forcing a\n * translation for every locale. Payload's field-level `required` cannot express this: it enforces per\n * write-locale, which would make a title mandatory in every locale and break the documented fallback.\n */\nconst validateFormTitle: TextFieldSingleValidation = (value, { req }) => {\n\tconst localization = req.payload.config.localization\n\tconst defaultLocale = localization ? localization.defaultLocale : undefined\n\tconst enforced =\n\t\tdefaultLocale === undefined || req.locale === undefined || req.locale === defaultLocale\n\tif (enforced && (typeof value !== 'string' || value.trim().length === 0)) {\n\t\treturn req.t('validation:required')\n\t}\n\treturn true\n}\n\n/**\n * Field-level validation for the raw flow JSON: step ids must be non-empty, unique, and not the\n * reserved `END_OF_FORM` sentinel, and every explicit step-id reference (a string `next`, a\n * transition `to`) must resolve to a known step. `next: null` (explicit end of form) and an\n * absent `next` (fall through to the next step in array order) are always valid. On full-document\n * saves the beforeValidate pass has already run `normalizeFlow` and laundered dangling\n * references, so the unknown-target checks mainly protect partial API updates that send `flow`\n * without `fields`.\n */\nconst validateFlow = (raw: unknown): string | true => {\n\tif (raw === null || raw === undefined) return true\n\tconst r = raw as Record<string, unknown>\n\tif (!Array.isArray(r.steps)) return true\n\tconst steps = r.steps as Array<Record<string, unknown>>\n\tconst emptyIdStep = steps.find((s) => typeof s?.id !== 'string' || s.id.length === 0)\n\tif (emptyIdStep) return 'Flow: every step must have a non-empty ID'\n\tif (steps.some((s) => s.id === END_OF_FORM)) {\n\t\treturn `Flow: step ID \"${END_OF_FORM}\" is reserved`\n\t}\n\tconst ids = steps.map((s) => s.id as string)\n\tif (new Set(ids).size !== ids.length) {\n\t\treturn 'Flow: duplicate step IDs found'\n\t}\n\tconst idSet = new Set(ids)\n\tfor (const step of steps) {\n\t\tconst id = step.id as string\n\t\tif (typeof step.next === 'string' && step.next.length > 0 && !idSet.has(step.next)) {\n\t\t\treturn `Flow: step \"${id}\" references unknown next step \"${step.next}\"`\n\t\t}\n\t\tif (Array.isArray(step.transitions)) {\n\t\t\tfor (const t of step.transitions as Array<Record<string, unknown>>) {\n\t\t\t\tif (typeof t?.to === 'string' && t.to.length > 0 && !idSet.has(t.to)) {\n\t\t\t\t\treturn `Flow: step \"${id}\" has a transition to unknown step \"${t.to}\"`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n/** How many steps the caller actually submitted, before normalization strips/collapses the flow. */\nconst providedFlowStepCount = (raw: unknown): number => {\n\tif (raw === null || typeof raw !== 'object') return 0\n\tconst steps = (raw as { steps?: unknown }).steps\n\treturn Array.isArray(steps) ? steps.length : 0\n}\n\n/**\n * Stamp the configured uploads collection slug onto every `file` block (including repeater\n * sub-fields) on each save. The block carries a hidden `uploadsCollection` field so the slug\n * reaches the client renderer through the form document; the server always overwrites it from\n * plugin config, so the stored value is never author- or client-controlled.\n */\nconst stampFileCollections = (rows: FieldRow[], slug: string): void => {\n\tfor (const row of rows) {\n\t\tif (row.blockType === 'file') {\n\t\t\t;(row as { uploadsCollection?: string }).uploadsCollection = slug\n\t\t}\n\t\tconst subFields = (row as { subFields?: unknown }).subFields\n\t\tif (Array.isArray(subFields)) {\n\t\t\tstampFileCollections(subFields as FieldRow[], slug)\n\t\t}\n\t}\n}\n\ntype BuildFormsCollectionArgs = {\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\t/**\n\t * The plugin `consent.sources` option. Present: the `/:id/consent-sources` endpoint backing the\n\t * consent field's source select is registered. Absent: neither it nor the consent field type exists.\n\t */\n\tconsentSources?: ConsentSourcesResolver\n\t/** Plugin `consent.resolveOnRead` (default true); `false` skips the per-read consent afterRead hook. */\n\tconsentResolveOnRead?: boolean\n\tactionRegistry?: ActionRegistry\n\tlocalizeContent?: boolean\n\t/** The plugin `richText` option; `responseEditor ?? editor` sets the response message field's editor. */\n\trichText?: RichTextBodyOption\n\t/** The host-owned uploads collection slug from plugin config; absent when uploads are disabled. */\n\tuploadsCollectionSlug?: string\n\t/** Host seam gating anonymous results reads (plugin option `results.access`). */\n\tresultsAccess?: FormResultsAccess\n\t/** Registered poll option sources (plugin option `poll.sources`); empty registry means no source fields. */\n\tpollSourceRegistry?: PollOptionSourceRegistry\n\t/** Registered poll outcome strategies (`poll.types`); drives the poll `type` select options. Defaults to the built-ins. */\n\tpollTypeRegistry?: PollTypeRegistry\n\t/** The plugin `poll.outcomeFields` seam; composes the outcome group from the two default fields. */\n\toutcomeFields?: OutcomeFieldsOverride\n\t/** The plugin `buttons` option; `fields` composes the `{ submit, prev, next }` labels from the localized defaults. */\n\tbuttons?: ButtonsOption\n\t/** The plugin `response` option; `redirect.fields` composes the `response.redirect` group from its default fields. */\n\tresponse?: ResponseOption\n\t/**\n\t * The plugin `email.fromAddresses` option. Present: both email actions gain a `from` select and\n\t * the `/:id/from-addresses` endpoint is registered. Absent: neither exists.\n\t */\n\tfromAddresses?: FromAddressesResolver\n\t/**\n\t * The plugin `email.departments` option. Present: the `emailTeam` `to` becomes a department select\n\t * and the `/:id/departments` endpoint backing it is registered. Absent: `to` stays a plain field.\n\t */\n\tdepartments?: DepartmentEmailsResolver\n\t/**\n\t * The plugin `redirectRelationships` option. Non-empty: `response.redirect` gains a polymorphic\n\t * `reference` relationship field so an author can redirect to an internal document instead of\n\t * (or alongside) a URL. Absent or empty: no `reference` field exists, matching today's URL-only\n\t * redirect.\n\t */\n\tredirectRelationships?: CollectionSlug[]\n\toverrides?: CollectionOverrides\n}\n\nexport const buildFormsCollection = ({\n\toverrides,\n\tregistry,\n\truleRegistry,\n\tconsentSources,\n\tconsentResolveOnRead,\n\tactionRegistry = new Map(),\n\tlocalizeContent = true,\n\trichText,\n\tuploadsCollectionSlug,\n\tresultsAccess,\n\tpollSourceRegistry,\n\tpollTypeRegistry,\n\toutcomeFields,\n\tbuttons,\n\tresponse,\n\tfromAddresses,\n\tdepartments,\n\tredirectRelationships,\n}: BuildFormsCollectionArgs): CollectionConfig => {\n\tconst conditionTypes = buildConditionTypeMap(registry)\n\tconst pollTypes = pollTypeRegistry ?? resolvePollTypes()\n\tconst pollResultsTypes = pollEligibleTypes(registry)\n\tconst bareTypes = new Set(\n\t\t[...registry.values()].filter((d) => d.bare === true).map((d) => d.type)\n\t)\n\t// Handed to the FlowBuilder so it can list bare (nameless) blocks in the step picker: slug ->\n\t// label (an i18n key or literal, resolved client-side).\n\tconst bareTypeLabels = Object.fromEntries(\n\t\t[...registry.values()].filter((d) => d.bare === true).map((d) => [d.type, d.label])\n\t)\n\t// The success `response` message field's editor: `richText.responseEditor` overrides the plugin-wide\n\t// `richText.editor` for this field alone (mirroring `bodyEditor` for action bodies).\n\tconst responseEditor = richText?.responseEditor ?? richText?.editor\n\tconst FLOW_BUILDER_REF = '@10x-media/form-builder/client#FlowBuilder'\n\tconst FIELD_NAME_SELECT_REF = '@10x-media/form-builder/client#FieldNameSelect'\n\tconst FLOW_STEPS_CELL_REF = '@10x-media/form-builder/client#FlowStepsCell'\n\tconst FIELD_COUNT_CELL_REF = '@10x-media/form-builder/client#FieldCountCell'\n\tconst CLOSE_POLL_BUTTON_REF = '@10x-media/form-builder/client#ClosePollButton'\n\t// The `source` outcome strategy delegates to the poll's option source, so it is useless without one:\n\t// offer it in the author-facing select only when option sources are registered. The strategy stays in\n\t// the registry regardless, so `resolvePollOutcome` and host code can still address it.\n\tconst hasOptionSources = (pollSourceRegistry?.size ?? 0) > 0\n\t// `mostVoted` leads the author-facing select because it is the default: an enabled poll works\n\t// immediately, with no winner to hand-pick. Only the select order changes; the registry keeps its\n\t// own order (host strategies stay after the built-ins).\n\tconst orderedPollTypes = [\n\t\t...[...pollTypes.values()].filter((strategy) => strategy.type === 'mostVoted'),\n\t\t...[...pollTypes.values()].filter((strategy) => strategy.type !== 'mostVoted'),\n\t]\n\n\tconst beforeValidate: CollectionBeforeValidateHook = ({ data, req }) => {\n\t\tif (data && Array.isArray(data.fields)) {\n\t\t\tconst normalized: FieldRow[] = normalizeFormConditions(\n\t\t\t\tdata.fields as FieldRow[],\n\t\t\t\tconditionTypes\n\t\t\t)\n\t\t\tfor (const field of normalized) {\n\t\t\t\tif ('expression' in field) {\n\t\t\t\t\tfield.expression = normalizeCalc(field.expression)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (uploadsCollectionSlug) {\n\t\t\t\tstampFileCollections(normalized, uploadsCollectionSlug)\n\t\t\t}\n\t\t\tdata.fields = normalized\n\t\t\t// Flow step assignments store field keys: machine names for named fields, block row ids\n\t\t\t// for bare (nameless) blocks. Mirrors `fieldKey` over the raw rows.\n\t\t\tconst fieldKeys = normalized\n\t\t\t\t.map((field: FieldRow) => {\n\t\t\t\t\tif (typeof field.name === 'string' && field.name.length > 0) {\n\t\t\t\t\t\treturn field.name\n\t\t\t\t\t}\n\t\t\t\t\treturn bareTypes.has(field.blockType) && field.id != null ? String(field.id) : undefined\n\t\t\t\t})\n\t\t\t\t.filter((key): key is string => key !== undefined)\n\t\t\t// Launder flow transition `when` clauses with the same operand-type rules as field conditions,\n\t\t\t// so a transition referencing a deleted field is dropped, not left as a route that always\n\t\t\t// matches at navigation time and force-routes the visitor.\n\t\t\tconst operandTypes = buildOperandTypes(normalized, conditionTypes)\n\t\t\tconst normalizedFlow = normalizeFlow(data.flow, fieldKeys, (w) =>\n\t\t\t\tnormalizeWhere(w, operandTypes)\n\t\t\t)\n\t\t\t// A flow the author built but that collapses to fewer than two valid steps would\n\t\t\t// otherwise vanish silently. Surface it instead of discarding their work.\n\t\t\tif (providedFlowStepCount(data.flow) > 0 && normalizedFlow === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection: FORMS_SLUG,\n\t\t\t\t\t\terrors: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpath: 'flow',\n\t\t\t\t\t\t\t\tmessage: 'A flow needs at least two steps. Add another step or remove the flow.',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\treq.t\n\t\t\t\t)\n\t\t\t}\n\t\t\tdata.flow = normalizedFlow\n\t\t\t// A poll needs a field whose answers are the votes. With the poll enabled and no vote field\n\t\t\t// chosen (and the outcome not coming from an option source), bind one: auto-fill the sole\n\t\t\t// eligible field for a one-choice form, otherwise surface a clear error rather than storing a\n\t\t\t// poll that can never aggregate. The optionSource/`source` exemption preserves domain-driven\n\t\t\t// polls that have no on-form vote field. `buildValidateResultsField` still checks a set value;\n\t\t\t// this is the enforcer for enabled polls.\n\t\t\tif (data.pollEnabled === true) {\n\t\t\t\tconst poll =\n\t\t\t\t\tdata.poll != null && typeof data.poll === 'object'\n\t\t\t\t\t\t? (data.poll as Record<string, unknown>)\n\t\t\t\t\t\t: {}\n\t\t\t\tconst resultsField = typeof poll.resultsField === 'string' ? poll.resultsField.trim() : ''\n\t\t\t\tconst optionSource = typeof poll.optionSource === 'string' ? poll.optionSource.trim() : ''\n\t\t\t\tconst sourceDriven = optionSource.length > 0 || poll.type === 'source'\n\t\t\t\tif (resultsField.length === 0 && !sourceDriven) {\n\t\t\t\t\tconst eligible = fieldNamesOfType(data.fields, pollResultsTypes)\n\t\t\t\t\tif (eligible.length === 1) {\n\t\t\t\t\t\tdata.poll = { ...poll, resultsField: eligible[0] }\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst messageKey =\n\t\t\t\t\t\t\teligible.length > 1 ? keys.pollVoteFieldChoose : keys.pollVoteFieldMissing\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcollection: FORMS_SLUG,\n\t\t\t\t\t\t\t\terrors: [{ path: 'poll.resultsField', message: asTranslate(req.t)(messageKey) }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\treq.t\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data\n\t}\n\n\t// After every save, (re)schedule the poll's auto-close job when it applies (enabled + closesAt +\n\t// unresolved + non-manual strategy + a job runner present). Best-effort and non-throwing, so it\n\t// never affects the save; without a runner the resolve-on-read fallback in the results endpoint\n\t// heals the outcome instead.\n\tconst pollCloseAfterChange: CollectionAfterChangeHook = async ({ doc, req }) => {\n\t\tawait enqueuePollClose({ payload: req.payload, form: doc, req })\n\t\treturn doc\n\t}\n\n\tconst fieldsField: Field = {\n\t\tname: 'fields',\n\t\ttype: 'blocks',\n\t\tblocks: buildFieldBlocks({ registry, ruleRegistry, localize: localizeContent }),\n\t\tadmin: { components: { Cell: FIELD_COUNT_CELL_REF } },\n\t}\n\n\tconst flowField: Field = {\n\t\tname: 'flow',\n\t\ttype: 'json',\n\t\tvalidate: validateFlow,\n\t\tadmin: {\n\t\t\tcomponents: {\n\t\t\t\tCell: FLOW_STEPS_CELL_REF,\n\t\t\t\tField: { path: FLOW_BUILDER_REF, clientProps: { conditionTypes, bareTypeLabels } },\n\t\t\t},\n\t\t},\n\t\t// Narrows the generated TypeScript type from opaque JSON to FormFlow so callers\n\t\t// don't need a cast. Keep this in sync with src/flow/types.ts.\n\t\ttypescriptSchema: [\n\t\t\t() => ({\n\t\t\t\ttype: 'object' as const,\n\t\t\t\trequired: ['steps'],\n\t\t\t\tadditionalProperties: false,\n\t\t\t\tproperties: {\n\t\t\t\t\tsteps: {\n\t\t\t\t\t\ttype: 'array' as const,\n\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\ttype: 'object' as const,\n\t\t\t\t\t\t\trequired: ['id'],\n\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tid: { type: 'string' as const },\n\t\t\t\t\t\t\t\ttitle: { type: 'string' as const },\n\t\t\t\t\t\t\t\tfields: { type: 'array' as const, items: { type: 'string' as const } },\n\t\t\t\t\t\t\t\tnext: { type: ['string', 'null'] as ('string' | 'null')[] },\n\t\t\t\t\t\t\t\ttransitions: {\n\t\t\t\t\t\t\t\t\ttype: 'array' as const,\n\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\ttype: 'object' as const,\n\t\t\t\t\t\t\t\t\t\trequired: ['to'],\n\t\t\t\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\t\tto: { type: 'string' as const },\n\t\t\t\t\t\t\t\t\t\t\twhen: { type: 'object' as const, additionalProperties: true },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t],\n\t}\n\n\tconst actionsField: Field = {\n\t\tname: 'actions',\n\t\ttype: 'blocks',\n\t\tblocks: buildActionBlocks(actionRegistry),\n\t\tlabel: labelForKey(keys.configActions),\n\t\t// Action config can contain secrets (e.g. signedWebhook.secret). The collection\n\t\t// itself is publicly readable so forms can be rendered by anonymous clients, but\n\t\t// action config must never be exposed to anonymous callers.\n\t\taccess: { read: isLoggedIn },\n\t}\n\n\t// Optional polymorphic reference to an internal document, for `response.redirect` to point at\n\t// instead of (or alongside) a URL. Absent unless `redirectRelationships` is a non-empty array:\n\t// always polymorphic even for one slug (the consent `page` field's precedent), so a host adding\n\t// a second collection later never changes the stored shape. The plugin never resolves this to a\n\t// URL itself; `toFormDocument` passes the raw `{ relationTo, value }` through for the host to\n\t// resolve, since only the host knows its own routing.\n\tconst redirectReferenceField: Field[] =\n\t\tredirectRelationships && redirectRelationships.length > 0\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'reference',\n\t\t\t\t\t\ttype: 'relationship',\n\t\t\t\t\t\trelationTo: redirectRelationships,\n\t\t\t\t\t\tlabel: labelForKey(keys.responseRedirectReference),\n\t\t\t\t\t\tadmin: { description: labelForKey(keys.responseRedirectReferenceDescription) },\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []\n\n\t// The redirect group's fields: the `url` text field plus the optional polymorphic `reference`.\n\t// The `response.redirect.fields` seam composes them (mirroring `buttons.fields`), so a host can\n\t// prepend a custom link field, swap `url` for their own picker, or filter; the default (no\n\t// override) is the same `[url, ...reference]` as before. Built-in redirect handling still reads\n\t// `redirect.url`/`redirect.reference`, so a host replacing `url` owns resolving their field to a\n\t// destination in their frontend.\n\tconst urlField: Field = {\n\t\tname: 'url',\n\t\ttype: 'text',\n\t\tlabel: labelForKey(keys.responseUrl),\n\t\tvalidate: validateUrl,\n\t}\n\tconst defaultRedirectFields: Field[] = [urlField, ...redirectReferenceField]\n\tconst redirectFields = response?.redirect?.fields\n\t\t? response.redirect.fields({ defaultFields: defaultRedirectFields })\n\t\t: defaultRedirectFields\n\n\t// What the visitor sees after a successful submit. Publicly readable (unlike actions): the\n\t// client renderer needs message/redirect. `type`/`url` are behavior, never localized;\n\t// `message` is visitor-facing content and follows `localizeContent`.\n\t// `type` is defaulted and not clearable rather than `required`: a required member would make\n\t// the whole group required in generated types, breaking typed `payload.create` calls that\n\t// omit `response`. Consumers treat a missing type as 'message'.\n\tconst responseField: Field = {\n\t\tname: 'response',\n\t\ttype: 'group',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'type',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'message',\n\t\t\t\tlabel: labelForKey(keys.responseType),\n\t\t\t\tadmin: { isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: labelForKey(keys.responseTypeMessage), value: 'message' },\n\t\t\t\t\t{ label: labelForKey(keys.responseTypeRedirect), value: 'redirect' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'message',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelForKey(keys.responseMessage),\n\t\t\t\t// Unset type (docs predating this field) means 'message', matching the client fallback.\n\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.type !== 'redirect' },\n\t\t\t\t...(responseEditor ? { editor: responseEditor } : {}),\n\t\t\t\t...localizedIf(localizeContent),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'redirect',\n\t\t\t\ttype: 'group',\n\t\t\t\tlabel: labelForKey(keys.responseRedirect),\n\t\t\t\tadmin: {\n\t\t\t\t\tcondition: (_data, siblingData) => siblingData?.type === 'redirect',\n\t\t\t\t\thideGutter: true,\n\t\t\t\t},\n\t\t\t\tfields: redirectFields,\n\t\t\t},\n\t\t],\n\t}\n\n\tconst defaultOutcomeFields = buildDefaultOutcomeFields()\n\tconst defaultButtonFields = buildDefaultButtonFields(localizeContent)\n\t// Half-width copy of a default field for the prev/next row; merges width into whatever admin the\n\t// field already carries (a host's `buttons.fields` override may add its own) rather than replacing\n\t// it. The cast is safe: `width` is a valid admin option on every field variant, but spreading a\n\t// `Field`-typed value's `admin` back into a union-typed object literal loses the discriminant TS\n\t// needs to check it structurally.\n\tconst halfWidth = (field: Field): Field =>\n\t\t({ ...field, admin: { ...field.admin, width: '50%' } }) as Field\n\t// The three button-label fields sit at the document root now (no `buttons` group): `submit` at\n\t// the bottom of the Fields tab, `prev`/`next` in a row on the Flow tab. The `buttons.fields` seam\n\t// composes each slot from the already-localized defaults, so a host can wrap a default in a row\n\t// with its own field (e.g. an icon select) or replace it; `toFormDocument` reassembles the three\n\t// labels into `FormDocument.buttons` for the client.\n\tconst composedButtons = buttons?.fields\n\t\t? buttons.fields({ defaultFields: defaultButtonFields })\n\t\t: defaultButtonFields\n\tconst submitField = composedButtons.submit\n\tconst prevNextRow: Field = {\n\t\ttype: 'row',\n\t\t// The prev/next labels only matter once the flow has a step; the Flow tab itself is gated on\n\t\t// `multistep`. `data` (1st arg) is the whole document, so `flow.steps` reads the stored flow.\n\t\tadmin: {\n\t\t\tcondition: (data) => {\n\t\t\t\tconst steps = (data as { flow?: { steps?: unknown } })?.flow?.steps\n\t\t\t\treturn Array.isArray(steps) && steps.length >= 1\n\t\t\t},\n\t\t},\n\t\tfields: [halfWidth(composedButtons.prev), halfWidth(composedButtons.next)],\n\t}\n\n\t// Poll lifecycle config; identifiers and behavior, never localized. Lives inside the conditional\n\t// Poll tab (gated on the top-level `pollEnabled` flag), so the per-field enabled conditions are\n\t// gone; `label: false` suppresses the group header the tab label already provides.\n\t// `resultsVisibility` is defaulted and not clearable rather than `required` for the same\n\t// generated-types reason as `response.type`.\n\tconst pollGroupField: Field = {\n\t\tname: 'poll',\n\t\ttype: 'group',\n\t\tlabel: false,\n\t\tfields: [\n\t\t\t// Authored by picking from the form's poll-eligible fields; the stored value stays a plain\n\t\t\t// text field name. Select options and server validate share `pollResultsTypes`, so they\n\t\t\t// cannot drift.\n\t\t\t{\n\t\t\t\tname: 'resultsField',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelForKey(keys.pollResultsField),\n\t\t\t\tvalidate: buildValidateResultsField(pollResultsTypes),\n\t\t\t\tadmin: {\n\t\t\t\t\tcomponents: {\n\t\t\t\t\t\tField: {\n\t\t\t\t\t\t\tpath: FIELD_NAME_SELECT_REF,\n\t\t\t\t\t\t\tclientProps: {\n\t\t\t\t\t\t\t\ttypes: pollResultsTypes,\n\t\t\t\t\t\t\t\tdescriptionKey: keys.pollResultsFieldDescription,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t// How the winning value(s) get decided. `mostVoted` (default) and `source` auto-resolve on close\n\t\t\t// (via the scheduled job or the results-read fallback); `manual` leaves it to an admin. Options\n\t\t\t// come from the registered `poll.types` strategies, so a host strategy appears here too, with\n\t\t\t// `mostVoted` first so an enabled poll works with no winner to hand-pick.\n\t\t\t{\n\t\t\t\tname: 'type',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'mostVoted',\n\t\t\t\tlabel: labelForKey(keys.pollType),\n\t\t\t\tadmin: { isClearable: false, description: labelForKey(keys.pollTypeDescription) },\n\t\t\t\toptions: orderedPollTypes\n\t\t\t\t\t.filter((strategy) => strategy.type !== 'source' || hasOptionSources)\n\t\t\t\t\t.map((strategy) => ({\n\t\t\t\t\t\tlabel: resolveDefinitionLabel(strategy.label),\n\t\t\t\t\t\tvalue: strategy.type,\n\t\t\t\t\t})),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'resultsVisibility',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'afterVote',\n\t\t\t\tlabel: labelForKey(keys.pollResultsVisibility),\n\t\t\t\tadmin: { isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: labelForKey(keys.pollVisibilityAfterVote), value: 'afterVote' },\n\t\t\t\t\t{ label: labelForKey(keys.pollVisibilityAfterClose), value: 'afterClose' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'closesAt',\n\t\t\t\ttype: 'date',\n\t\t\t\tlabel: labelForKey(keys.pollClosesAt),\n\t\t\t\tadmin: { date: { pickerAppearance: 'dayAndTime' } },\n\t\t\t},\n\t\t\t// Close / reopen the poll from the admin. The button toggles on the live `closesAt` and saves the\n\t\t\t// whole document (persisting an unsaved winner alongside `closesAt`) rather than calling the close\n\t\t\t// endpoint, so there is no DB-vs-form-state mismatch. Always mounted inside the (pollEnabled-gated)\n\t\t\t// Poll tab now; the button owns both states, so it carries no `admin.condition` of its own.\n\t\t\t{\n\t\t\t\tname: 'closePoll',\n\t\t\t\ttype: 'ui',\n\t\t\t\tadmin: {\n\t\t\t\t\tcomponents: { Field: CLOSE_POLL_BUTTON_REF },\n\t\t\t\t},\n\t\t\t},\n\t\t\t...buildPollOptionSourceFields(pollSourceRegistry ?? new Map()),\n\t\t\t// `winningValues` is recorded either by an admin picking from the poll's effective options\n\t\t\t// (served by `/:id/poll-options`) or by `resolvePollOutcome` (host domain logic); more than\n\t\t\t// one value records a tie. The `pollOutcomeBeforeChange` hook validates both paths and owns\n\t\t\t// the `resolvedAt` stamp. `resolvedAt` itself stays fully locked: field-level create/update\n\t\t\t// access blocks every non-override caller write (Payload silently drops the denied value\n\t\t\t// rather than erroring) while the hook's stamp, applied after access filtering, still\n\t\t\t// persists. The `poll.outcomeFields` seam receives both defaults and its return becomes the\n\t\t\t// group's fields verbatim, so a host can swap `winningValues` for its own component; the hook\n\t\t\t// still validates every stored value against the effective options, so no swap bypasses it.\n\t\t\t// `hideGutter` stays: outcome is still a group nested inside the poll group.\n\t\t\t{\n\t\t\t\tname: 'outcome',\n\t\t\t\ttype: 'group',\n\t\t\t\tlabel: labelForKey(keys.pollOutcome),\n\t\t\t\tadmin: { hideGutter: true },\n\t\t\t\tfields: outcomeFields\n\t\t\t\t\t? outcomeFields({ defaultFields: defaultOutcomeFields })\n\t\t\t\t\t: [defaultOutcomeFields.winningValues, defaultOutcomeFields.resolvedAt],\n\t\t\t},\n\t\t],\n\t}\n\n\tconst defaultFields: Field[] = [\n\t\t// The document title is the only visitor-facing text the collection renders itself: it is\n\t\t// always required (drives `useAsTitle` in the admin list/relationship views) and is passed\n\t\t// through `toFormDocument` as `FormDocument.title`. Whether and how a host renders it above\n\t\t// the fields is entirely the host's call; the plugin does not gate or duplicate it.\n\t\t{\n\t\t\tname: 'title',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.fieldTitle),\n\t\t\t// Visitor-facing content, so it follows `localizeContent` like the response message and\n\t\t\t// consent statement: hosts with localization get a per-locale title (and a locale-aware\n\t\t\t// `useAsTitle`), hosts without it are unaffected since Payload strips the flag. `validate`\n\t\t\t// (not `required`) keeps it mandatory only in the default locale so other locales fall back.\n\t\t\t...localizedIf(localizeContent),\n\t\t\tvalidate: validateFormTitle,\n\t\t},\n\t\t// The two form-type flags: behavior, never localized. `multistep` gates the Flow tab and the\n\t\t// client's step navigation; `pollEnabled` gates the Poll tab and marks the form a poll.\n\t\t{\n\t\t\ttype: 'row',\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tname: 'multistep',\n\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\tdefaultValue: false,\n\t\t\t\t\tlabel: labelForKey(keys.formMultistep),\n\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: 'pollEnabled',\n\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\tdefaultValue: false,\n\t\t\t\t\tlabel: labelForKey(keys.formPollEnabled),\n\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\t// Storage flag, server-only: when unchecked, the plugin deletes the submission after its actions\n\t\t// run (pruning a pure signup form's row). Default checked, so unchecking it is the opt-out.\n\t\t{\n\t\t\tname: 'persistSubmissions',\n\t\t\ttype: 'checkbox',\n\t\t\tdefaultValue: true,\n\t\t\tlabel: labelForKey(keys.formPersistSubmissions),\n\t\t\tadmin: { width: '50%' },\n\t\t},\n\t\t// Unnamed tabs are presentational: their fields stay at the document root. An unnamed tab's\n\t\t// `admin.condition` receives the whole document as its 2nd arg, so the Flow and Poll tabs gate\n\t\t// on the root-level flags. The poll group nests its config under `form.poll` as before.\n\t\t{\n\t\t\ttype: 'tabs',\n\t\t\ttabs: [\n\t\t\t\t{ label: labelForKey(keys.tabFields), fields: [fieldsField, submitField] },\n\t\t\t\t{\n\t\t\t\t\tlabel: labelForKey(keys.tabFlow),\n\t\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.multistep === true },\n\t\t\t\t\tfields: [flowField, prevNextRow],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: labelForKey(keys.pollGroup),\n\t\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.pollEnabled === true },\n\t\t\t\t\tfields: [pollGroupField],\n\t\t\t\t},\n\t\t\t\t{ label: labelForKey(keys.tabActions), fields: [actionsField] },\n\t\t\t\t{ label: labelForKey(keys.tabResponse), fields: [responseField] },\n\t\t\t],\n\t\t},\n\t]\n\n\t// When `consent.sources` is set, resolve the visitor-facing consent statements onto every read of\n\t// a form doc (REST, local API, relationship population), so a client/modal fetch renders consent,\n\t// not only the RSC path that calls `resolveConsentStatements` itself. Fails open: a resolver outage\n\t// must never break form/admin/relationship reads, and the renderer already tolerates a missing\n\t// statement. `resolveConsentStatements` returns `{}` without calling the resolver when the form has\n\t// no consent fields, and entries are cached per request+form, so the cost stays bounded.\n\tconst consentAfterRead: CollectionAfterReadHook | undefined =\n\t\tconsentSources && consentResolveOnRead !== false\n\t\t\t? async ({ doc, req }) => {\n\t\t\t\t\tconst id = (doc as { id?: unknown }).id\n\t\t\t\t\tconst key = id == null ? undefined : String(id)\n\t\t\t\t\t// Re-entrance guard: a host resolver that reads this same form back (threading req) would\n\t\t\t\t\t// otherwise re-enter this hook and recurse. Payload runs collection afterRead concurrently\n\t\t\t\t\t// across list docs on one shared req.context, so this must be a per-id Set (a boolean would\n\t\t\t\t\t// make sibling docs skip), mutated in place and never reassigned after fan-out. Mirrors\n\t\t\t\t\t// @payloadcms/plugin-search's syncDocAsSearchIndex guard.\n\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\tconst inFlight =\n\t\t\t\t\t\t\t(req.context[CONSENT_AFTER_READ_GUARD] as Set<string> | undefined) ??\n\t\t\t\t\t\t\tnew Set<string>()\n\t\t\t\t\t\tif (inFlight.has(key)) {\n\t\t\t\t\t\t\treturn doc\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinFlight.add(key)\n\t\t\t\t\t\treq.context[CONSENT_AFTER_READ_GUARD] = inFlight\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst statements = await resolveConsentStatements({\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tform: doc,\n\t\t\t\t\t\t\tsources: consentSources,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tif (Object.keys(statements).length > 0) {\n\t\t\t\t\t\t\t;(doc as Record<string, unknown>).consentStatements = statements\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treq.payload.logger?.warn(`form-builder consent afterRead: ${String(error)}`)\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\t\t;(req.context[CONSENT_AFTER_READ_GUARD] as Set<string> | undefined)?.delete(key)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn doc\n\t\t\t\t}\n\t\t\t: undefined\n\n\tconst defaultEndpoints = buildFormsEndpoints({\n\t\tresultsAccess,\n\t\tpollResultsTypes,\n\t\tconsentSources,\n\t\tfromAddresses,\n\t\tdepartments,\n\t})\n\n\treturn {\n\t\t...(overrides ?? {}),\n\t\tslug: FORMS_SLUG,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.collectionFormSingular),\n\t\t\tplural: labelForKey(keys.collectionFormPlural),\n\t\t\t...(overrides?.labels ?? {}),\n\t\t},\n\t\tadmin: {\n\t\t\tgroup: 'Forms',\n\t\t\tuseAsTitle: 'title',\n\t\t\tdefaultColumns: ['title', 'fields', 'flow', 'pollEnabled', 'updatedAt'],\n\t\t\t...(overrides?.admin ?? {}),\n\t\t},\n\t\taccess: { read: () => true, ...(overrides?.access ?? {}) },\n\t\thooks: {\n\t\t\t...(overrides?.hooks ?? {}),\n\t\t\t// beforeValidate normalizes conditions and flow; consumer hooks run after\n\t\t\tbeforeValidate: [beforeValidate, ...(overrides?.hooks?.beforeValidate ?? [])],\n\t\t\tbeforeChange: [pollOutcomeBeforeChange, ...(overrides?.hooks?.beforeChange ?? [])],\n\t\t\tafterChange: [pollCloseAfterChange, ...(overrides?.hooks?.afterChange ?? [])],\n\t\t\tafterRead: [\n\t\t\t\t...(consentAfterRead ? [consentAfterRead] : []),\n\t\t\t\t...(overrides?.hooks?.afterRead ?? []),\n\t\t\t],\n\t\t},\n\t\tendpoints: [\n\t\t\t...defaultEndpoints,\n\t\t\t...(Array.isArray(overrides?.endpoints) ? overrides.endpoints : []),\n\t\t],\n\t\tfields: overrides?.fields ? overrides.fields({ defaultFields }) : defaultFields,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAa,aAAa;;AAG1B,MAAM,2BAA2B;;;;;;;AAQjC,MAAM,qBAAgD,OAAO,EAAE,UAAU;CACxE,MAAM,eAAe,IAAI,QAAQ,OAAO;CACxC,MAAM,gBAAgB,eAAe,aAAa,gBAAgB,KAAA;CAGlE,KADC,kBAAkB,KAAA,KAAa,IAAI,WAAW,KAAA,KAAa,IAAI,W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GACN,GAAI,WAAW,SAAS,CAAC;GAEzB,gBAAgB,CAAC,gBAAgB,GAAI,WAAW,OAAO,kBAAkB,CAAC,CAAE;GAC5E,cAAc,CAAC,yBAAyB,GAAI,WAAW,OAAO,gBAAgB,CAAC,CAAE;GACjF,aAAa,CAAC,sBAAsB,GAAI,WAAW,OAAO,eAAe,CAAC,CAAE;GAC5E,WAAW,CACV,GAAI,mBAAmB,CAAC,gBAAgB,IAAI,CAAC,GAC7C,GAAI,WAAW,OAAO,aAAa,CAAC,CACrC;EACD;EACA,WAAW,CACV,GAAG,kBACH,GAAI,MAAM,QAAQ,WAAW,SAAS,IAAI,UAAU,YAAY,CAAC,CAClE;EACA,QAAQ,WAAW,SAAS,UAAU,OAAO,EAAE,cAAc,CAAC,IAAI;CACnE;AACD"}
1
+ {"version":3,"file":"forms.js","names":[],"sources":["../../src/collections/forms.ts"],"sourcesContent":["import {\n\ttype CollectionAfterChangeHook,\n\ttype CollectionAfterReadHook,\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype CollectionSlug,\n\ttype Field,\n\ttype PayloadRequest,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n} from 'payload'\nimport type { RichTextBodyOption } from '../actions/body/serializeBody'\nimport { buildActionBlocks } from '../actions/buildActionBlocks'\nimport type { FromAddressesResolver } from '../actions/fromAddresses'\nimport type { ActionRegistry } from '../actions/registry'\nimport type { FormResultsAccess } from '../aggregation/resolveResultsRequest'\nimport { type CalcAllowed, normalizeCalc } from '../calc/normalizeCalc'\nimport type { CalcSource } from '../calc/registry'\nimport { calcUsesSources, resolveCalcContext } from '../calc/resolveCalcContext'\nimport { buildConditionTypeMap } from '../conditions/conditionType'\nimport {\n\tbuildOperandTypes,\n\ttype FieldRow,\n\tnormalizeFormConditions,\n\tnormalizeWhere,\n} from '../conditions/normalizeConditions'\nimport { resolveConsentStatements } from '../consent/resolveConsentStatements'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport { buildFieldBlocks } from '../fields/buildFieldBlocks'\nimport { fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { localizedIf } from '../fields/localizedIf'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { normalizeFlow } from '../flow/normalizeFlow'\nimport { END_OF_FORM } from '../flow/types'\nimport { isLoggedIn } from '../plugin/access'\nimport type { CollectionOverrides } from '../plugin/collectionOverrides'\nimport { buildPollOptionSourceFields } from '../poll/buildPollOptionSourceFields'\nimport { enqueuePollClose } from '../poll/closeJob'\nimport { pollOutcomeBeforeChange } from '../poll/outcomeBeforeChange'\nimport { buildDefaultOutcomeFields, type OutcomeFieldsOverride } from '../poll/outcomeFields'\nimport { type PollTypeRegistry, resolvePollTypes } from '../poll/pollTypeRegistry'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport { buildValidateResultsField, pollEligibleTypes } from '../poll/resultsField'\nimport type { FormFieldInstance } from '../submissions/types'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelForKey, resolveDefinitionLabel } from '../translations/server'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport { validateUrl } from '../validation/validateUrl'\nimport { type ButtonsOption, buildDefaultButtonFields } from './buttonFields'\nimport { buildFormsEndpoints } from './formsEndpoints'\nimport type { ResponseOption } from './redirectFields'\nimport { composeSettingsFields, type SettingsOption } from './settingsFields'\n\nexport const FORMS_SLUG = 'forms'\n\n/** `req.context` key under which `consentAfterRead` tracks the form ids it is currently resolving, to break re-entrant reads. */\nconst CONSENT_AFTER_READ_GUARD = 'formBuilderConsentAfterReadInFlight'\n\n/** `req.context` key under which `calcAfterRead` tracks the form ids it is currently resolving, to break re-entrant reads. */\nconst CALC_AFTER_READ_GUARD = 'formBuilderCalcAfterReadInFlight'\n\n/**\n * Require the title in the default locale (and on hosts without localization), but let it be empty in\n * other locales so a localized form falls back to the default-locale title rather than forcing a\n * translation for every locale. Payload's field-level `required` cannot express this: it enforces per\n * write-locale, which would make a title mandatory in every locale and break the documented fallback.\n */\nconst validateFormTitle: TextFieldSingleValidation = (value, { req }) => {\n\tconst localization = req.payload.config.localization\n\tconst defaultLocale = localization ? localization.defaultLocale : undefined\n\tconst enforced =\n\t\tdefaultLocale === undefined || req.locale === undefined || req.locale === defaultLocale\n\tif (enforced && (typeof value !== 'string' || value.trim().length === 0)) {\n\t\treturn req.t('validation:required')\n\t}\n\treturn true\n}\n\n/**\n * Field-level validation for the raw flow JSON: step ids must be non-empty, unique, and not the\n * reserved `END_OF_FORM` sentinel, and every explicit step-id reference (a string `next`, a\n * transition `to`) must resolve to a known step. `next: null` (explicit end of form) and an\n * absent `next` (fall through to the next step in array order) are always valid. On full-document\n * saves the beforeValidate pass has already run `normalizeFlow` and laundered dangling\n * references, so the unknown-target checks mainly protect partial API updates that send `flow`\n * without `fields`.\n */\nconst validateFlow = (\n\traw: unknown,\n\t{ req }: { data?: unknown; req: PayloadRequest }\n): string | true => {\n\tif (raw === null || raw === undefined) return true\n\tconst r = raw as Record<string, unknown>\n\tif (!Array.isArray(r.steps)) return true\n\tconst steps = r.steps as Array<Record<string, unknown>>\n\tconst t = asTranslate(req.t)\n\tconst emptyIdStep = steps.find((s) => typeof s?.id !== 'string' || s.id.length === 0)\n\tif (emptyIdStep) return t(keys.flowStepIdEmpty)\n\tif (steps.some((s) => s.id === END_OF_FORM)) {\n\t\treturn t(keys.flowStepIdReserved).replace('{id}', END_OF_FORM)\n\t}\n\tconst ids = steps.map((s) => s.id as string)\n\tif (new Set(ids).size !== ids.length) {\n\t\treturn t(keys.flowDuplicateStepIds)\n\t}\n\tconst idSet = new Set(ids)\n\tfor (const step of steps) {\n\t\tconst id = step.id as string\n\t\tif (typeof step.next === 'string' && step.next.length > 0 && !idSet.has(step.next)) {\n\t\t\treturn t(keys.flowUnknownNext).replace('{id}', id).replace('{next}', step.next)\n\t\t}\n\t\tif (Array.isArray(step.transitions)) {\n\t\t\tfor (const trans of step.transitions as Array<Record<string, unknown>>) {\n\t\t\t\tif (typeof trans?.to === 'string' && trans.to.length > 0 && !idSet.has(trans.to)) {\n\t\t\t\t\treturn t(keys.flowUnknownTransition).replace('{id}', id).replace('{to}', trans.to)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n/** How many steps the caller actually submitted, before normalization strips/collapses the flow. */\nconst providedFlowStepCount = (raw: unknown): number => {\n\tif (raw === null || typeof raw !== 'object') return 0\n\tconst steps = (raw as { steps?: unknown }).steps\n\treturn Array.isArray(steps) ? steps.length : 0\n}\n\n/**\n * Stamp the configured uploads collection slug onto every `file` block (including repeater\n * sub-fields) on each save. The block carries a hidden `uploadsCollection` field so the slug\n * reaches the client renderer through the form document; the server always overwrites it from\n * plugin config, so the stored value is never author- or client-controlled.\n */\nconst stampFileCollections = (rows: FieldRow[], slug: string): void => {\n\tfor (const row of rows) {\n\t\tif (row.blockType === 'file') {\n\t\t\t;(row as { uploadsCollection?: string }).uploadsCollection = slug\n\t\t}\n\t\tconst subFields = (row as { subFields?: unknown }).subFields\n\t\tif (Array.isArray(subFields)) {\n\t\t\tstampFileCollections(subFields as FieldRow[], slug)\n\t\t}\n\t}\n}\n\ntype BuildFormsCollectionArgs = {\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\t/** Registered calc extension names; expressions referencing anything else are dropped on save. */\n\tcalcAllowed?: CalcAllowed\n\t/** Registered calc sources; when a form's expressions use any, an afterRead hook stamps `doc.calcResolved`. */\n\tcalcSources?: Record<string, CalcSource>\n\t/**\n\t * The plugin `consent.sources` option. Present: the `/:id/consent-sources` endpoint backing the\n\t * consent field's source select is registered. Absent: neither it nor the consent field type exists.\n\t */\n\tconsentSources?: ConsentSourcesResolver\n\t/** Plugin `consent.resolveOnRead` (default true); `false` skips the per-read consent afterRead hook. */\n\tconsentResolveOnRead?: boolean\n\tactionRegistry?: ActionRegistry\n\tlocalizeContent?: boolean\n\t/** The plugin `richText` option; `responseEditor ?? editor` sets the response message field's editor. */\n\trichText?: RichTextBodyOption\n\t/** The host-owned uploads collection slug from plugin config; absent when uploads are disabled. */\n\tuploadsCollectionSlug?: string\n\t/** Host seam gating anonymous results reads (plugin option `results.access`). */\n\tresultsAccess?: FormResultsAccess\n\t/**\n\t * Whether the hidden tally store is registered (`poll.votes !== false`). Threads into the poll\n\t * endpoints (tally-backed reads) and, when false, forbids poll forms from disabling\n\t * `persistSubmissions`: with neither store nor submissions there would be nothing to count.\n\t */\n\tpollVotesEnabled?: boolean\n\t/** Registered poll option sources (plugin option `poll.sources`); empty registry means no source fields. */\n\tpollSourceRegistry?: PollOptionSourceRegistry\n\t/** Registered poll outcome strategies (`poll.types`); drives the poll `type` select options. Defaults to the built-ins. */\n\tpollTypeRegistry?: PollTypeRegistry\n\t/** The plugin `poll.outcomeFields` seam; composes the outcome group from the two default fields. */\n\toutcomeFields?: OutcomeFieldsOverride\n\t/** The plugin `buttons` option; `fields` composes the `{ submit, prev, next }` labels from the localized defaults. */\n\tbuttons?: ButtonsOption\n\t/** The plugin `settings` option; `fields` composes the sidebar flag checkboxes from the defaults. */\n\tsettings?: SettingsOption\n\t/** The plugin `response` option; `redirect.fields` composes the `response.redirect` group from its default fields. */\n\tresponse?: ResponseOption\n\t/**\n\t * The plugin `email.fromAddresses` option. Present: both email actions gain a `from` select and\n\t * the `/:id/from-addresses` endpoint is registered. Absent: neither exists.\n\t */\n\tfromAddresses?: FromAddressesResolver\n\t/**\n\t * The plugin `email.departments` option. Present: the `emailTeam` `to` becomes a department select\n\t * and the `/:id/departments` endpoint backing it is registered. Absent: `to` stays a plain field.\n\t */\n\tdepartments?: DepartmentEmailsResolver\n\t/**\n\t * The plugin `redirectRelationships` option. Non-empty: `response.redirect` gains a polymorphic\n\t * `reference` relationship field so an author can redirect to an internal document instead of\n\t * (or alongside) a URL. Absent or empty: no `reference` field exists, matching today's URL-only\n\t * redirect.\n\t */\n\tredirectRelationships?: CollectionSlug[]\n\toverrides?: CollectionOverrides\n}\n\nexport const buildFormsCollection = ({\n\toverrides,\n\tregistry,\n\truleRegistry,\n\tcalcAllowed,\n\tcalcSources,\n\tconsentSources,\n\tconsentResolveOnRead,\n\tactionRegistry = new Map(),\n\tlocalizeContent = true,\n\trichText,\n\tuploadsCollectionSlug,\n\tresultsAccess,\n\tpollVotesEnabled = false,\n\tpollSourceRegistry,\n\tpollTypeRegistry,\n\toutcomeFields,\n\tbuttons,\n\tsettings,\n\tresponse,\n\tfromAddresses,\n\tdepartments,\n\tredirectRelationships,\n}: BuildFormsCollectionArgs): CollectionConfig => {\n\tconst conditionTypes = buildConditionTypeMap(registry)\n\tconst pollTypes = pollTypeRegistry ?? resolvePollTypes()\n\tconst pollResultsTypes = pollEligibleTypes(registry)\n\tconst bareTypes = new Set(\n\t\t[...registry.values()].filter((d) => d.bare === true).map((d) => d.type)\n\t)\n\t// Handed to the FlowBuilder so it can list bare (nameless) blocks in the step picker: slug ->\n\t// label (an i18n key or literal, resolved client-side).\n\tconst bareTypeLabels = Object.fromEntries(\n\t\t[...registry.values()].filter((d) => d.bare === true).map((d) => [d.type, d.label])\n\t)\n\t// The success `response` message field's editor: `richText.responseEditor` overrides the plugin-wide\n\t// `richText.editor` for this field alone (mirroring `bodyEditor` for action bodies).\n\tconst responseEditor = richText?.responseEditor ?? richText?.editor\n\tconst FLOW_BUILDER_REF = '@10x-media/form-builder/client#FlowBuilder'\n\tconst FIELD_NAME_SELECT_REF = '@10x-media/form-builder/client#FieldNameSelect'\n\tconst FLOW_STEPS_CELL_REF = '@10x-media/form-builder/client#FlowStepsCell'\n\tconst FIELD_COUNT_CELL_REF = '@10x-media/form-builder/client#FieldCountCell'\n\tconst CLOSE_POLL_BUTTON_REF = '@10x-media/form-builder/client#ClosePollButton'\n\t// The `source` outcome strategy delegates to the poll's option source, so it is useless without one:\n\t// offer it in the author-facing select only when option sources are registered. The strategy stays in\n\t// the registry regardless, so `resolvePollOutcome` and host code can still address it.\n\tconst hasOptionSources = (pollSourceRegistry?.size ?? 0) > 0\n\t// `mostVoted` leads the author-facing select because it is the default: an enabled poll works\n\t// immediately, with no winner to hand-pick. Only the select order changes; the registry keeps its\n\t// own order (host strategies stay after the built-ins).\n\tconst orderedPollTypes = [\n\t\t...[...pollTypes.values()].filter((strategy) => strategy.type === 'mostVoted'),\n\t\t...[...pollTypes.values()].filter((strategy) => strategy.type !== 'mostVoted'),\n\t]\n\n\tconst beforeValidate: CollectionBeforeValidateHook = ({ data, originalDoc, req }) => {\n\t\t// Without the tally store, pruned submissions would erase every vote: a poll form may only\n\t\t// turn `persistSubmissions` off while the store is registered to carry the counts. Evaluated\n\t\t// on the incoming partial merged over the stored doc (outcomeBeforeChange precedent), so a\n\t\t// PATCH flipping either flag alone cannot slip past the guard.\n\t\tif (!pollVotesEnabled) {\n\t\t\tconst pollOn = (data?.pollEnabled ?? originalDoc?.pollEnabled) === true\n\t\t\tconst persistOff = (data?.persistSubmissions ?? originalDoc?.persistSubmissions) === false\n\t\t\tif (pollOn && persistOff) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection: FORMS_SLUG,\n\t\t\t\t\t\terrors: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpath: 'persistSubmissions',\n\t\t\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.pollNeedsPersistedSubmissions),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\treq.t\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (data && Array.isArray(data.fields)) {\n\t\t\tconst normalized: FieldRow[] = normalizeFormConditions(\n\t\t\t\tdata.fields as FieldRow[],\n\t\t\t\tconditionTypes\n\t\t\t)\n\t\t\tfor (const field of normalized) {\n\t\t\t\tif ('expression' in field) {\n\t\t\t\t\tfield.expression = normalizeCalc(field.expression, calcAllowed)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (uploadsCollectionSlug) {\n\t\t\t\tstampFileCollections(normalized, uploadsCollectionSlug)\n\t\t\t}\n\t\t\tdata.fields = normalized\n\t\t\t// Flow step assignments store field keys: machine names for named fields, block row ids\n\t\t\t// for bare (nameless) blocks. Mirrors `fieldKey` over the raw rows.\n\t\t\tconst fieldKeys = normalized\n\t\t\t\t.map((field: FieldRow) => {\n\t\t\t\t\tif (typeof field.name === 'string' && field.name.length > 0) {\n\t\t\t\t\t\treturn field.name\n\t\t\t\t\t}\n\t\t\t\t\treturn bareTypes.has(field.blockType) && field.id != null ? String(field.id) : undefined\n\t\t\t\t})\n\t\t\t\t.filter((key): key is string => key !== undefined)\n\t\t\t// Launder flow transition `when` clauses with the same operand-type rules as field conditions,\n\t\t\t// so a transition referencing a deleted field is dropped, not left as a route that always\n\t\t\t// matches at navigation time and force-routes the visitor.\n\t\t\tconst operandTypes = buildOperandTypes(normalized, conditionTypes)\n\t\t\tconst normalizedFlow = normalizeFlow(data.flow, fieldKeys, (w) =>\n\t\t\t\tnormalizeWhere(w, operandTypes)\n\t\t\t)\n\t\t\t// A flow the author built but that collapses to fewer than two valid steps would\n\t\t\t// otherwise vanish silently. Surface it instead of discarding their work.\n\t\t\tif (providedFlowStepCount(data.flow) > 0 && normalizedFlow === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t{\n\t\t\t\t\t\tcollection: FORMS_SLUG,\n\t\t\t\t\t\terrors: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpath: 'flow',\n\t\t\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.flowNeedsTwoSteps),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\treq.t\n\t\t\t\t)\n\t\t\t}\n\t\t\tdata.flow = normalizedFlow\n\t\t\t// A poll needs a field whose answers are the votes. With the poll enabled and no vote field\n\t\t\t// chosen (and the outcome not coming from an option source), bind one: auto-fill the sole\n\t\t\t// eligible field for a one-choice form, otherwise surface a clear error rather than storing a\n\t\t\t// poll that can never aggregate. The optionSource/`source` exemption preserves domain-driven\n\t\t\t// polls that have no on-form vote field. `buildValidateResultsField` still checks a set value;\n\t\t\t// this is the enforcer for enabled polls.\n\t\t\tif (data.pollEnabled === true) {\n\t\t\t\tconst poll =\n\t\t\t\t\tdata.poll != null && typeof data.poll === 'object'\n\t\t\t\t\t\t? (data.poll as Record<string, unknown>)\n\t\t\t\t\t\t: {}\n\t\t\t\tconst resultsField = typeof poll.resultsField === 'string' ? poll.resultsField.trim() : ''\n\t\t\t\tconst optionSource = typeof poll.optionSource === 'string' ? poll.optionSource.trim() : ''\n\t\t\t\tconst sourceDriven = optionSource.length > 0 || poll.type === 'source'\n\t\t\t\tif (resultsField.length === 0 && !sourceDriven) {\n\t\t\t\t\tconst eligible = fieldNamesOfType(data.fields, pollResultsTypes)\n\t\t\t\t\tif (eligible.length === 1) {\n\t\t\t\t\t\tdata.poll = { ...poll, resultsField: eligible[0] }\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst messageKey =\n\t\t\t\t\t\t\teligible.length > 1 ? keys.pollVoteFieldChoose : keys.pollVoteFieldMissing\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcollection: FORMS_SLUG,\n\t\t\t\t\t\t\t\terrors: [{ path: 'poll.resultsField', message: asTranslate(req.t)(messageKey) }],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\treq.t\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data\n\t}\n\n\t// After every save, (re)schedule the poll's auto-close job when it applies (enabled + closesAt +\n\t// unresolved + non-manual strategy + a job runner present). Best-effort and non-throwing, so it\n\t// never affects the save; without a runner the resolve-on-read fallback in the results endpoint\n\t// heals the outcome instead.\n\tconst pollCloseAfterChange: CollectionAfterChangeHook = async ({ doc, req }) => {\n\t\tawait enqueuePollClose({ payload: req.payload, form: doc, req })\n\t\treturn doc\n\t}\n\n\tconst fieldsField: Field = {\n\t\tname: 'fields',\n\t\ttype: 'blocks',\n\t\tblocks: buildFieldBlocks({ registry, ruleRegistry, localize: localizeContent }),\n\t\tadmin: { components: { Cell: FIELD_COUNT_CELL_REF } },\n\t}\n\n\tconst flowField: Field = {\n\t\tname: 'flow',\n\t\ttype: 'json',\n\t\tvalidate: validateFlow,\n\t\tadmin: {\n\t\t\tcomponents: {\n\t\t\t\tCell: FLOW_STEPS_CELL_REF,\n\t\t\t\tField: { path: FLOW_BUILDER_REF, clientProps: { conditionTypes, bareTypeLabels } },\n\t\t\t},\n\t\t},\n\t\t// Narrows the generated TypeScript type from opaque JSON to FormFlow so callers\n\t\t// don't need a cast. Keep this in sync with src/flow/types.ts.\n\t\ttypescriptSchema: [\n\t\t\t() => ({\n\t\t\t\ttype: 'object' as const,\n\t\t\t\trequired: ['steps'],\n\t\t\t\tadditionalProperties: false,\n\t\t\t\tproperties: {\n\t\t\t\t\tsteps: {\n\t\t\t\t\t\ttype: 'array' as const,\n\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\ttype: 'object' as const,\n\t\t\t\t\t\t\trequired: ['id'],\n\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\tid: { type: 'string' as const },\n\t\t\t\t\t\t\t\ttitle: { type: 'string' as const },\n\t\t\t\t\t\t\t\tfields: { type: 'array' as const, items: { type: 'string' as const } },\n\t\t\t\t\t\t\t\tnext: { type: ['string', 'null'] as ('string' | 'null')[] },\n\t\t\t\t\t\t\t\ttransitions: {\n\t\t\t\t\t\t\t\t\ttype: 'array' as const,\n\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\ttype: 'object' as const,\n\t\t\t\t\t\t\t\t\t\trequired: ['to'],\n\t\t\t\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\t\tto: { type: 'string' as const },\n\t\t\t\t\t\t\t\t\t\t\twhen: { type: 'object' as const, additionalProperties: true },\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t],\n\t}\n\n\tconst actionsField: Field = {\n\t\tname: 'actions',\n\t\ttype: 'blocks',\n\t\tblocks: buildActionBlocks(actionRegistry),\n\t\tlabel: labelForKey(keys.configActions),\n\t\t// Action config can contain secrets (e.g. signedWebhook.secret). The collection\n\t\t// itself is publicly readable so forms can be rendered by anonymous clients, but\n\t\t// action config must never be exposed to anonymous callers.\n\t\taccess: { read: isLoggedIn },\n\t}\n\n\t// Optional polymorphic reference to an internal document, for `response.redirect` to point at\n\t// instead of (or alongside) a URL. Absent unless `redirectRelationships` is a non-empty array:\n\t// always polymorphic even for one slug (the consent `page` field's precedent), so a host adding\n\t// a second collection later never changes the stored shape. The plugin never resolves this to a\n\t// URL itself; `toFormDocument` passes the raw `{ relationTo, value }` through for the host to\n\t// resolve, since only the host knows its own routing.\n\tconst redirectReferenceField: Field[] =\n\t\tredirectRelationships && redirectRelationships.length > 0\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'reference',\n\t\t\t\t\t\ttype: 'relationship',\n\t\t\t\t\t\trelationTo: redirectRelationships,\n\t\t\t\t\t\tlabel: labelForKey(keys.responseRedirectReference),\n\t\t\t\t\t\tadmin: { description: labelForKey(keys.responseRedirectReferenceDescription) },\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []\n\n\t// The redirect group's fields: the `url` text field plus the optional polymorphic `reference`.\n\t// The `response.redirect.fields` seam composes them (mirroring `buttons.fields`), so a host can\n\t// prepend a custom link field, swap `url` for their own picker, or filter; the default (no\n\t// override) is the same `[url, ...reference]` as before. Built-in redirect handling still reads\n\t// `redirect.url`/`redirect.reference`, so a host replacing `url` owns resolving their field to a\n\t// destination in their frontend.\n\tconst urlField: Field = {\n\t\tname: 'url',\n\t\ttype: 'text',\n\t\tlabel: labelForKey(keys.responseUrl),\n\t\tvalidate: validateUrl,\n\t}\n\tconst defaultRedirectFields: Field[] = [urlField, ...redirectReferenceField]\n\tconst redirectFields = response?.redirect?.fields\n\t\t? response.redirect.fields({ defaultFields: defaultRedirectFields })\n\t\t: defaultRedirectFields\n\n\t// What the visitor sees after a successful submit. Publicly readable (unlike actions): the\n\t// client renderer needs message/redirect. `type`/`url` are behavior, never localized;\n\t// `message` is visitor-facing content and follows `localizeContent`.\n\t// `type` is defaulted and not clearable rather than `required`: a required member would make\n\t// the whole group required in generated types, breaking typed `payload.create` calls that\n\t// omit `response`. Consumers treat a missing type as 'message'.\n\tconst responseField: Field = {\n\t\tname: 'response',\n\t\ttype: 'group',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'type',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'message',\n\t\t\t\tlabel: labelForKey(keys.responseType),\n\t\t\t\tadmin: { isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: labelForKey(keys.responseTypeMessage), value: 'message' },\n\t\t\t\t\t{ label: labelForKey(keys.responseTypeRedirect), value: 'redirect' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'message',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelForKey(keys.responseMessage),\n\t\t\t\t// Unset type (docs predating this field) means 'message', matching the client fallback.\n\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.type !== 'redirect' },\n\t\t\t\t...(responseEditor ? { editor: responseEditor } : {}),\n\t\t\t\t...localizedIf(localizeContent),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'redirect',\n\t\t\t\ttype: 'group',\n\t\t\t\tlabel: labelForKey(keys.responseRedirect),\n\t\t\t\tadmin: {\n\t\t\t\t\tcondition: (_data, siblingData) => siblingData?.type === 'redirect',\n\t\t\t\t\thideGutter: true,\n\t\t\t\t},\n\t\t\t\tfields: redirectFields,\n\t\t\t},\n\t\t],\n\t}\n\n\tconst defaultOutcomeFields = buildDefaultOutcomeFields()\n\tconst defaultButtonFields = buildDefaultButtonFields(localizeContent)\n\t// Half-width copy of a default field for the prev/next row; merges width into whatever admin the\n\t// field already carries (a host's `buttons.fields` override may add its own) rather than replacing\n\t// it. The cast is safe: `width` is a valid admin option on every field variant, but spreading a\n\t// `Field`-typed value's `admin` back into a union-typed object literal loses the discriminant TS\n\t// needs to check it structurally.\n\tconst halfWidth = (field: Field): Field =>\n\t\t({ ...field, admin: { ...field.admin, width: '50%' } }) as Field\n\t// The three button-label fields sit at the document root now (no `buttons` group): `submit` at\n\t// the bottom of the Fields tab, `prev`/`next` in a row on the Flow tab. The `buttons.fields` seam\n\t// composes each slot from the already-localized defaults, so a host can wrap a default in a row\n\t// with its own field (e.g. an icon select) or replace it; `toFormDocument` reassembles the three\n\t// labels into `FormDocument.buttons` for the client.\n\tconst composedButtons = buttons?.fields\n\t\t? buttons.fields({ defaultFields: defaultButtonFields })\n\t\t: defaultButtonFields\n\tconst submitField = composedButtons.submit\n\tconst prevNextRow: Field = {\n\t\ttype: 'row',\n\t\t// The prev/next labels only matter once the flow has a step; the Flow tab itself is gated on\n\t\t// `multistep`. `data` (1st arg) is the whole document, so `flow.steps` reads the stored flow.\n\t\tadmin: {\n\t\t\tcondition: (data) => {\n\t\t\t\tconst steps = (data as { flow?: { steps?: unknown } })?.flow?.steps\n\t\t\t\treturn Array.isArray(steps) && steps.length >= 1\n\t\t\t},\n\t\t},\n\t\tfields: [halfWidth(composedButtons.prev), halfWidth(composedButtons.next)],\n\t}\n\n\t// Poll lifecycle config; identifiers and behavior, never localized. Lives inside the conditional\n\t// Poll tab (gated on the top-level `pollEnabled` flag), so the per-field enabled conditions are\n\t// gone; `label: false` suppresses the group header the tab label already provides.\n\t// `resultsVisibility` is defaulted and not clearable rather than `required` for the same\n\t// generated-types reason as `response.type`.\n\tconst pollGroupField: Field = {\n\t\tname: 'poll',\n\t\ttype: 'group',\n\t\tlabel: false,\n\t\tfields: [\n\t\t\t// Authored by picking from the form's poll-eligible fields; the stored value stays a plain\n\t\t\t// text field name. Select options and server validate share `pollResultsTypes`, so they\n\t\t\t// cannot drift.\n\t\t\t{\n\t\t\t\tname: 'resultsField',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelForKey(keys.pollResultsField),\n\t\t\t\tvalidate: buildValidateResultsField(pollResultsTypes),\n\t\t\t\tadmin: {\n\t\t\t\t\tcomponents: {\n\t\t\t\t\t\tField: {\n\t\t\t\t\t\t\tpath: FIELD_NAME_SELECT_REF,\n\t\t\t\t\t\t\tclientProps: {\n\t\t\t\t\t\t\t\ttypes: pollResultsTypes,\n\t\t\t\t\t\t\t\tdescriptionKey: keys.pollResultsFieldDescription,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t// How the winning value(s) get decided. `mostVoted` (default) and `source` auto-resolve on close\n\t\t\t// (via the scheduled job or the results-read fallback); `manual` leaves it to an admin. Options\n\t\t\t// come from the registered `poll.types` strategies, so a host strategy appears here too, with\n\t\t\t// `mostVoted` first so an enabled poll works with no winner to hand-pick.\n\t\t\t{\n\t\t\t\tname: 'type',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'mostVoted',\n\t\t\t\tlabel: labelForKey(keys.pollType),\n\t\t\t\tadmin: { isClearable: false, description: labelForKey(keys.pollTypeDescription) },\n\t\t\t\toptions: orderedPollTypes\n\t\t\t\t\t.filter((strategy) => strategy.type !== 'source' || hasOptionSources)\n\t\t\t\t\t.map((strategy) => ({\n\t\t\t\t\t\tlabel: resolveDefinitionLabel(strategy.label),\n\t\t\t\t\t\tvalue: strategy.type,\n\t\t\t\t\t})),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'resultsVisibility',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'afterVote',\n\t\t\t\tlabel: labelForKey(keys.pollResultsVisibility),\n\t\t\t\tadmin: { isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: labelForKey(keys.pollVisibilityAfterVote), value: 'afterVote' },\n\t\t\t\t\t{ label: labelForKey(keys.pollVisibilityAfterClose), value: 'afterClose' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'closesAt',\n\t\t\t\ttype: 'date',\n\t\t\t\tlabel: labelForKey(keys.pollClosesAt),\n\t\t\t\tadmin: { date: { pickerAppearance: 'dayAndTime' } },\n\t\t\t},\n\t\t\t// Close / reopen the poll from the admin. The button toggles on the live `closesAt` and saves the\n\t\t\t// whole document (persisting an unsaved winner alongside `closesAt`) rather than calling the close\n\t\t\t// endpoint, so there is no DB-vs-form-state mismatch. Always mounted inside the (pollEnabled-gated)\n\t\t\t// Poll tab now; the button owns both states, so it carries no `admin.condition` of its own.\n\t\t\t{\n\t\t\t\tname: 'closePoll',\n\t\t\t\ttype: 'ui',\n\t\t\t\tadmin: {\n\t\t\t\t\tcomponents: { Field: CLOSE_POLL_BUTTON_REF },\n\t\t\t\t},\n\t\t\t},\n\t\t\t...buildPollOptionSourceFields(pollSourceRegistry ?? new Map()),\n\t\t\t// `winningValues` is recorded either by an admin picking from the poll's effective options\n\t\t\t// (served by `/:id/poll-options`) or by `resolvePollOutcome` (host domain logic); more than\n\t\t\t// one value records a tie. The `pollOutcomeBeforeChange` hook validates both paths and owns\n\t\t\t// the `resolvedAt` stamp. `resolvedAt` itself stays fully locked: field-level create/update\n\t\t\t// access blocks every non-override caller write (Payload silently drops the denied value\n\t\t\t// rather than erroring) while the hook's stamp, applied after access filtering, still\n\t\t\t// persists. The `poll.outcomeFields` seam receives both defaults and its return becomes the\n\t\t\t// group's fields verbatim, so a host can swap `winningValues` for its own component; the hook\n\t\t\t// still validates every stored value against the effective options, so no swap bypasses it.\n\t\t\t// `hideGutter` stays: outcome is still a group nested inside the poll group.\n\t\t\t{\n\t\t\t\tname: 'outcome',\n\t\t\t\ttype: 'group',\n\t\t\t\tlabel: labelForKey(keys.pollOutcome),\n\t\t\t\tadmin: { hideGutter: true },\n\t\t\t\tfields: outcomeFields\n\t\t\t\t\t? outcomeFields({ defaultFields: defaultOutcomeFields })\n\t\t\t\t\t: [defaultOutcomeFields.winningValues, defaultOutcomeFields.resolvedAt],\n\t\t\t},\n\t\t],\n\t}\n\n\tconst defaultFields: Field[] = [\n\t\t// The document title is the only visitor-facing text the collection renders itself: it is\n\t\t// always required (drives `useAsTitle` in the admin list/relationship views) and is passed\n\t\t// through `toFormDocument` as `FormDocument.title`. Whether and how a host renders it above\n\t\t// the fields is entirely the host's call; the plugin does not gate or duplicate it.\n\t\t{\n\t\t\tname: 'title',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.fieldTitle),\n\t\t\t// Visitor-facing content, so it follows `localizeContent` like the response message and\n\t\t\t// consent statement: hosts with localization get a per-locale title (and a locale-aware\n\t\t\t// `useAsTitle`), hosts without it are unaffected since Payload strips the flag. `validate`\n\t\t\t// (not `required`) keeps it mandatory only in the default locale so other locales fall back.\n\t\t\t...localizedIf(localizeContent),\n\t\t\tvalidate: validateFormTitle,\n\t\t},\n\t\t// The three form-level flags: behavior, never localized, sidebar checkboxes by default.\n\t\t// `multistep` gates the Flow tab and the client's step navigation; `pollEnabled` gates the\n\t\t// Poll tab and marks the form a poll; `persistSubmissions` (default checked) tells the plugin\n\t\t// whether to keep a submission's row after its actions run, or prune it. The `settings.fields`\n\t\t// seam composes them from the defaults, mirroring `buttons.fields`.\n\t\t...composeSettingsFields(settings),\n\t\t// Unnamed tabs are presentational: their fields stay at the document root. An unnamed tab's\n\t\t// `admin.condition` receives the whole document as its 2nd arg, so the Flow and Poll tabs gate\n\t\t// on the root-level flags. The poll group nests its config under `form.poll` as before.\n\t\t{\n\t\t\ttype: 'tabs',\n\t\t\ttabs: [\n\t\t\t\t{ label: labelForKey(keys.tabFields), fields: [fieldsField, submitField] },\n\t\t\t\t{\n\t\t\t\t\tlabel: labelForKey(keys.tabFlow),\n\t\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.multistep === true },\n\t\t\t\t\tfields: [flowField, prevNextRow],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tlabel: labelForKey(keys.pollGroup),\n\t\t\t\t\tadmin: { condition: (_data, siblingData) => siblingData?.pollEnabled === true },\n\t\t\t\t\tfields: [pollGroupField],\n\t\t\t\t},\n\t\t\t\t{ label: labelForKey(keys.tabActions), fields: [actionsField] },\n\t\t\t\t{ label: labelForKey(keys.tabResponse), fields: [responseField] },\n\t\t\t],\n\t\t},\n\t]\n\n\t// When `consent.sources` is set, resolve the visitor-facing consent statements onto every read of\n\t// a form doc (REST, local API, relationship population), so a client/modal fetch renders consent,\n\t// not only the RSC path that calls `resolveConsentStatements` itself. Fails open: a resolver outage\n\t// must never break form/admin/relationship reads, and the renderer already tolerates a missing\n\t// statement. `resolveConsentStatements` returns `{}` without calling the resolver when the form has\n\t// no consent fields, and entries are cached per request+form, so the cost stays bounded.\n\tconst consentAfterRead: CollectionAfterReadHook | undefined =\n\t\tconsentSources && consentResolveOnRead !== false\n\t\t\t? async ({ doc, req }) => {\n\t\t\t\t\tconst id = (doc as { id?: unknown }).id\n\t\t\t\t\tconst key = id == null ? undefined : String(id)\n\t\t\t\t\t// Re-entrance guard: a host resolver that reads this same form back (threading req) would\n\t\t\t\t\t// otherwise re-enter this hook and recurse. Payload runs collection afterRead concurrently\n\t\t\t\t\t// across list docs on one shared req.context, so this must be a per-id Set (a boolean would\n\t\t\t\t\t// make sibling docs skip), mutated in place and never reassigned after fan-out. Mirrors\n\t\t\t\t\t// @payloadcms/plugin-search's syncDocAsSearchIndex guard.\n\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\tconst inFlight =\n\t\t\t\t\t\t\t(req.context[CONSENT_AFTER_READ_GUARD] as Set<string> | undefined) ??\n\t\t\t\t\t\t\tnew Set<string>()\n\t\t\t\t\t\tif (inFlight.has(key)) {\n\t\t\t\t\t\t\treturn doc\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinFlight.add(key)\n\t\t\t\t\t\treq.context[CONSENT_AFTER_READ_GUARD] = inFlight\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst statements = await resolveConsentStatements({\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tform: doc,\n\t\t\t\t\t\t\tsources: consentSources,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tif (Object.keys(statements).length > 0) {\n\t\t\t\t\t\t\t;(doc as Record<string, unknown>).consentStatements = statements\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treq.payload.logger?.warn(`form-builder consent afterRead: ${String(error)}`)\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\t\t;(req.context[CONSENT_AFTER_READ_GUARD] as Set<string> | undefined)?.delete(key)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn doc\n\t\t\t\t}\n\t\t\t: undefined\n\n\t// When calc sources are registered, resolve the values a form's expressions reference onto every\n\t// read of its doc, stamped as `doc.calcResolved` (`toFormDocument` passes it through), so the\n\t// client's live preview computes with real values. Fails open: a resolver outage must never break\n\t// form/admin/relationship reads; the preview degrades to 0 and submit re-resolves loudly.\n\tconst calcAfterRead: CollectionAfterReadHook | undefined =\n\t\tcalcSources && Object.keys(calcSources).length > 0\n\t\t\t? async ({ doc, req }) => {\n\t\t\t\t\tconst fields = Array.isArray((doc as { fields?: unknown }).fields)\n\t\t\t\t\t\t? ((doc as { fields: unknown[] }).fields as FormFieldInstance[])\n\t\t\t\t\t\t: []\n\t\t\t\t\tif (!calcUsesSources(fields)) {\n\t\t\t\t\t\treturn doc\n\t\t\t\t\t}\n\t\t\t\t\tconst id = (doc as { id?: unknown }).id\n\t\t\t\t\tconst key = id == null ? undefined : String(id)\n\t\t\t\t\t// Re-entrance guard: a host resolver that reads this same form back (threading req) would\n\t\t\t\t\t// otherwise re-enter this hook and recurse. Per-id Set, mutated in place, exactly like\n\t\t\t\t\t// `consentAfterRead` above (afterRead fans out concurrently over one shared req.context).\n\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\tconst inFlight =\n\t\t\t\t\t\t\t(req.context[CALC_AFTER_READ_GUARD] as Set<string> | undefined) ?? new Set<string>()\n\t\t\t\t\t\tif (inFlight.has(key)) {\n\t\t\t\t\t\t\treturn doc\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinFlight.add(key)\n\t\t\t\t\t\treq.context[CALC_AFTER_READ_GUARD] = inFlight\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst resolved = await resolveCalcContext({\n\t\t\t\t\t\t\tfields,\n\t\t\t\t\t\t\tsources: calcSources,\n\t\t\t\t\t\t\tform: doc as { id: number | string } & Record<string, unknown>,\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t;(doc as Record<string, unknown>).calcResolved = resolved\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treq.payload.logger?.warn(`form-builder calc afterRead: ${String(error)}`)\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (key !== undefined && req.context) {\n\t\t\t\t\t\t\t;(req.context[CALC_AFTER_READ_GUARD] as Set<string> | undefined)?.delete(key)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn doc\n\t\t\t\t}\n\t\t\t: undefined\n\n\tconst defaultEndpoints = buildFormsEndpoints({\n\t\tresultsAccess,\n\t\tpollResultsTypes,\n\t\tpollVotesEnabled,\n\t\tconsentSources,\n\t\tfromAddresses,\n\t\tdepartments,\n\t})\n\n\treturn {\n\t\t...(overrides ?? {}),\n\t\tslug: FORMS_SLUG,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.collectionFormSingular),\n\t\t\tplural: labelForKey(keys.collectionFormPlural),\n\t\t\t...(overrides?.labels ?? {}),\n\t\t},\n\t\tadmin: {\n\t\t\tgroup: 'Forms',\n\t\t\tuseAsTitle: 'title',\n\t\t\tdefaultColumns: ['title', 'fields', 'flow', 'pollEnabled', 'updatedAt'],\n\t\t\t...(overrides?.admin ?? {}),\n\t\t},\n\t\taccess: { read: () => true, ...(overrides?.access ?? {}) },\n\t\thooks: {\n\t\t\t...(overrides?.hooks ?? {}),\n\t\t\t// beforeValidate normalizes conditions and flow; consumer hooks run after\n\t\t\tbeforeValidate: [beforeValidate, ...(overrides?.hooks?.beforeValidate ?? [])],\n\t\t\tbeforeChange: [pollOutcomeBeforeChange, ...(overrides?.hooks?.beforeChange ?? [])],\n\t\t\tafterChange: [pollCloseAfterChange, ...(overrides?.hooks?.afterChange ?? [])],\n\t\t\tafterRead: [\n\t\t\t\t...(consentAfterRead ? [consentAfterRead] : []),\n\t\t\t\t...(calcAfterRead ? [calcAfterRead] : []),\n\t\t\t\t...(overrides?.hooks?.afterRead ?? []),\n\t\t\t],\n\t\t},\n\t\tendpoints: [\n\t\t\t...defaultEndpoints,\n\t\t\t...(Array.isArray(overrides?.endpoints) ? overrides.endpoints : []),\n\t\t],\n\t\tfields: overrides?.fields ? overrides.fields({ defaultFields }) : defaultFields,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,MAAa,aAAa;;AAG1B,MAAM,2BAA2B;;AAGjC,MAAM,wBAAwB;;;;;;;AAQ9B,MAAM,qBAAgD,OAAO,EAAE,UAAU;CACxE,MAAM,eAAe,IAAI,QAAQ,OAAO;CACxC,MAAM,gBAAgB,eAAe,aAAa,gBAAgB,KAAA;CAGlE,KADC,kBAAkB,KAAA,KAAa,IAAI,WAAW,KAAA,KAAa,IAAI,WAAW,mBAC1D,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,WAAW,IACrE,OAAO,IAAI,EAAE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B,IAAI,CAAC;IAC7C,GAAI,gBAAgB,CAAC,aAAa,IAAI,CAAC;IACvC,GAAI,WAAW,OAAO,aAAa,CAAC;GACrC;EACD;EACA,WAAW,CACV,GAAG,kBACH,GAAI,MAAM,QAAQ,WAAW,SAAS,IAAI,UAAU,YAAY,CAAC,CAClE;EACA,QAAQ,WAAW,SAAS,UAAU,OAAO,EAAE,cAAc,CAAC,IAAI;CACnE;AACD"}
@@ -12,7 +12,7 @@ import { resolvePollOptionsRequest } from "../poll/resolvePollOptionsRequest.js"
12
12
  * (anonymous callers get a 403 from the helper, not here). Extracted from `buildFormsCollection`
13
13
  * so the collection builder stays focused on field and hook composition.
14
14
  */
15
- const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources, fromAddresses, departments }) => [
15
+ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, pollVotesEnabled, consentSources, fromAddresses, departments }) => [
16
16
  {
17
17
  path: "/:id/results",
18
18
  method: "get",
@@ -25,7 +25,8 @@ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources,
25
25
  isAuthed: Boolean(req.user),
26
26
  req,
27
27
  access: resultsAccess,
28
- eligibleTypes: pollResultsTypes
28
+ eligibleTypes: pollResultsTypes,
29
+ pollVotesEnabled
29
30
  });
30
31
  return Response.json(body, { status });
31
32
  }
@@ -51,6 +52,7 @@ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources,
51
52
  payload: req.payload,
52
53
  formId: req.routeParams?.id,
53
54
  isAuthed: Boolean(req.user),
55
+ pollVotesEnabled,
54
56
  req
55
57
  });
56
58
  return Response.json(body, { status });
@@ -1 +1 @@
1
- {"version":3,"file":"formsEndpoints.js","names":[],"sources":["../../src/collections/formsEndpoints.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\nimport { type FromAddressesResolver, resolveFromAddressesRequest } from '../actions/fromAddresses'\nimport {\n\ttype FormResultsAccess,\n\tresolveFormResultsRequest,\n} from '../aggregation/resolveResultsRequest'\nimport { resolveConsentSourcesRequest } from '../consent/resolveConsentSourcesRequest'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport { type DepartmentEmailsResolver, resolveDepartmentsRequest } from '../email/departments'\nimport { resolvePollCloseRequest } from '../poll/resolvePollCloseRequest'\nimport { resolvePollOptionsRequest } from '../poll/resolvePollOptionsRequest'\n\ntype FormsEndpointDeps = {\n\t/** Host seam gating anonymous results reads (plugin option `results.access`). */\n\tresultsAccess?: FormResultsAccess\n\t/** The poll-eligible field-type names; the `/:id/results` endpoint restricts reads to these. */\n\tpollResultsTypes: string[]\n\t/** The plugin `consent.sources` option; present registers the `/:id/consent-sources` endpoint. */\n\tconsentSources?: ConsentSourcesResolver\n\t/** The plugin `email.fromAddresses` option; present registers the `/:id/from-addresses` endpoint. */\n\tfromAddresses?: FromAddressesResolver\n\t/** The plugin `email.departments` option; present registers the `/:id/departments` endpoint. */\n\tdepartments?: DepartmentEmailsResolver\n}\n\n/**\n * The forms collection's built-in endpoints: poll results/options/close, plus the optional\n * consent-sources, from-addresses, and departments option endpoints that only exist when the\n * matching plugin option is set. Each delegates to its request helper, which owns the auth check\n * (anonymous callers get a 403 from the helper, not here). Extracted from `buildFormsCollection`\n * so the collection builder stays focused on field and hook composition.\n */\nexport const buildFormsEndpoints = ({\n\tresultsAccess,\n\tpollResultsTypes,\n\tconsentSources,\n\tfromAddresses,\n\tdepartments,\n}: FormsEndpointDeps): Exclude<CollectionConfig['endpoints'], false | undefined> => [\n\t{\n\t\tpath: '/:id/results',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst field = typeof req.query?.field === 'string' ? req.query.field : undefined\n\t\t\tconst { status, body } = await resolveFormResultsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tfield,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t\taccess: resultsAccess,\n\t\t\t\teligibleTypes: pollResultsTypes,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t{\n\t\tpath: '/:id/poll-options',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollOptionsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t// Trusted admin action (authenticated only): close a poll now and resolve its outcome. A POST\n\t// because it mutates; auth is `Boolean(req.user)` so an anonymous caller gets 403 from the helper.\n\t{\n\t\tpath: '/:id/close',\n\t\tmethod: 'post',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollCloseRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t...(consentSources\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/consent-sources',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveConsentSourcesRequest({\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: consentSources,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n\t// The route id is unused: the from-addresses set is request-scoped (e.g. per tenant), not\n\t// per-form. Registered as a doc-scoped route only so the admin field can reuse\n\t// EndpointOptionsSelect unmodified (see buildFromField).\n\t...(fromAddresses\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/from-addresses',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveFromAddressesRequest({\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: fromAddresses,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n\t// Same request-scoped, id-unused shape as from-addresses: registered doc-scoped only so the\n\t// recipient selects can fetch it (see RecipientsSelect / buildRecipientField).\n\t...(departments\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/departments',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveDepartmentsRequest({\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: departments,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n]\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,uBAAuB,EACnC,eACA,kBACA,gBACA,eACA,kBACmF;CACnF;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,QAAQ,OAAO,IAAI,OAAO,UAAU,WAAW,IAAI,MAAM,QAAQ,KAAA;GACvE,MAAM,EAAE,QAAQ,SAAS,MAAM,0BAA0B;IACxD,SAAS,IAAI;IACb,QAAQ,IAAI,aAAa;IACzB;IACA,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA,QAAQ;IACR,eAAe;GAChB,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CA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OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD,CACD,IACC,CAAC;AACL"}
1
+ {"version":3,"file":"formsEndpoints.js","names":[],"sources":["../../src/collections/formsEndpoints.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\nimport { type FromAddressesResolver, resolveFromAddressesRequest } from '../actions/fromAddresses'\nimport {\n\ttype FormResultsAccess,\n\tresolveFormResultsRequest,\n} from '../aggregation/resolveResultsRequest'\nimport { resolveConsentSourcesRequest } from '../consent/resolveConsentSourcesRequest'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport { type DepartmentEmailsResolver, resolveDepartmentsRequest } from '../email/departments'\nimport { resolvePollCloseRequest } from '../poll/resolvePollCloseRequest'\nimport { resolvePollOptionsRequest } from '../poll/resolvePollOptionsRequest'\n\ntype FormsEndpointDeps = {\n\t/** Host seam gating anonymous results reads (plugin option `results.access`). */\n\tresultsAccess?: FormResultsAccess\n\t/** The poll-eligible field-type names; the `/:id/results` endpoint restricts reads to these. */\n\tpollResultsTypes: string[]\n\t/** Whether the hidden tally store backs poll reads and the close endpoint's outcome aggregation. */\n\tpollVotesEnabled: boolean\n\t/** The plugin `consent.sources` option; present registers the `/:id/consent-sources` endpoint. */\n\tconsentSources?: ConsentSourcesResolver\n\t/** The plugin `email.fromAddresses` option; present registers the `/:id/from-addresses` endpoint. */\n\tfromAddresses?: FromAddressesResolver\n\t/** The plugin `email.departments` option; present registers the `/:id/departments` endpoint. */\n\tdepartments?: DepartmentEmailsResolver\n}\n\n/**\n * The forms collection's built-in endpoints: poll results/options/close, plus the optional\n * consent-sources, from-addresses, and departments option endpoints that only exist when the\n * matching plugin option is set. Each delegates to its request helper, which owns the auth check\n * (anonymous callers get a 403 from the helper, not here). Extracted from `buildFormsCollection`\n * so the collection builder stays focused on field and hook composition.\n */\nexport const buildFormsEndpoints = ({\n\tresultsAccess,\n\tpollResultsTypes,\n\tpollVotesEnabled,\n\tconsentSources,\n\tfromAddresses,\n\tdepartments,\n}: FormsEndpointDeps): Exclude<CollectionConfig['endpoints'], false | undefined> => [\n\t{\n\t\tpath: '/:id/results',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst field = typeof req.query?.field === 'string' ? req.query.field : undefined\n\t\t\tconst { status, body } = await resolveFormResultsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tfield,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t\taccess: resultsAccess,\n\t\t\t\teligibleTypes: pollResultsTypes,\n\t\t\t\tpollVotesEnabled,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t{\n\t\tpath: '/:id/poll-options',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollOptionsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t// Trusted admin action (authenticated only): close a poll now and resolve its outcome. A POST\n\t// because it mutates; auth is `Boolean(req.user)` so an anonymous caller gets 403 from the helper.\n\t{\n\t\tpath: '/:id/close',\n\t\tmethod: 'post',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollCloseRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\tpollVotesEnabled,\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t...(consentSources\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/consent-sources',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveConsentSourcesRequest({\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: consentSources,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n\t// The route id is unused: the from-addresses set is request-scoped (e.g. per tenant), not\n\t// per-form. Registered as a doc-scoped route only so the admin field can reuse\n\t// EndpointOptionsSelect unmodified (see buildFromField).\n\t...(fromAddresses\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/from-addresses',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveFromAddressesRequest({\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: fromAddresses,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n\t// Same request-scoped, id-unused shape as from-addresses: registered doc-scoped only so the\n\t// recipient selects can fetch it (see RecipientsSelect / buildRecipientField).\n\t...(departments\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/departments',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveDepartmentsRequest({\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: departments,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n]\n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;CAIJ,GAAI,gBACD,CACA;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,EAAE,QAAQ,SAAS,MAAM,4BAA4B;IAC1D,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA,UAAU;GACX,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD,CACD,IACC,CAAC;CAGJ,GAAI,cACD,CACA;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,EAAE,QAAQ,SAAS,MAAM,0BAA0B;IACxD,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA,UAAU;GACX,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD,CACD,IACC,CAAC;AACL"}
@@ -0,0 +1,31 @@
1
+ import { Field } from "payload";
2
+
3
+ //#region src/collections/settingsFields.d.ts
4
+ /** The default form-level flag fields, keyed by flag. What the `settings.fields` seam receives. */
5
+ type DefaultSettingsFields = {
6
+ multistep: Field;
7
+ pollEnabled: Field;
8
+ persistSubmissions: Field;
9
+ };
10
+ /**
11
+ * Composes the three form-level flag fields. Receives the defaults and returns the final field
12
+ * array placed verbatim at the forms collection root, so a host can relocate a flag (strip
13
+ * `admin.position`), wrap them in a row, append its own, or drop one.
14
+ */
15
+ type SettingsFieldsOverride = (args: {
16
+ defaultFields: DefaultSettingsFields;
17
+ }) => Field[];
18
+ /** The plugin `settings` option: the three form-level flags and their composition seam. */
19
+ type SettingsOption = {
20
+ fields?: SettingsFieldsOverride;
21
+ };
22
+ /**
23
+ * The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the
24
+ * Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a
25
+ * poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row
26
+ * after its actions run, or prune it (a pure signup form's opt-out).
27
+ */
28
+ declare const buildDefaultSettingsFields: () => DefaultSettingsFields;
29
+ //#endregion
30
+ export { DefaultSettingsFields, SettingsFieldsOverride, SettingsOption, buildDefaultSettingsFields };
31
+ //# sourceMappingURL=settingsFields.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { labelForKey } from "../translations/server.js";
3
+ //#region src/collections/settingsFields.ts
4
+ /**
5
+ * The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the
6
+ * Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a
7
+ * poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row
8
+ * after its actions run, or prune it (a pure signup form's opt-out).
9
+ */
10
+ const buildDefaultSettingsFields = () => ({
11
+ multistep: {
12
+ name: "multistep",
13
+ type: "checkbox",
14
+ defaultValue: false,
15
+ label: labelForKey(keys.formMultistep),
16
+ admin: { position: "sidebar" }
17
+ },
18
+ pollEnabled: {
19
+ name: "pollEnabled",
20
+ type: "checkbox",
21
+ defaultValue: false,
22
+ label: labelForKey(keys.formPollEnabled),
23
+ admin: { position: "sidebar" }
24
+ },
25
+ persistSubmissions: {
26
+ name: "persistSubmissions",
27
+ type: "checkbox",
28
+ defaultValue: true,
29
+ label: labelForKey(keys.formPersistSubmissions),
30
+ admin: { position: "sidebar" }
31
+ }
32
+ });
33
+ const composeSettingsFields = (settings) => {
34
+ const defaultFields = buildDefaultSettingsFields();
35
+ if (settings?.fields) return settings.fields({ defaultFields });
36
+ return [
37
+ defaultFields.multistep,
38
+ defaultFields.pollEnabled,
39
+ defaultFields.persistSubmissions
40
+ ];
41
+ };
42
+ //#endregion
43
+ export { buildDefaultSettingsFields, composeSettingsFields };
44
+
45
+ //# sourceMappingURL=settingsFields.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"settingsFields.js","names":[],"sources":["../../src/collections/settingsFields.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\n/** The default form-level flag fields, keyed by flag. What the `settings.fields` seam receives. */\nexport type DefaultSettingsFields = {\n\tmultistep: Field\n\tpollEnabled: Field\n\tpersistSubmissions: Field\n}\n\n/**\n * Composes the three form-level flag fields. Receives the defaults and returns the final field\n * array placed verbatim at the forms collection root, so a host can relocate a flag (strip\n * `admin.position`), wrap them in a row, append its own, or drop one.\n */\nexport type SettingsFieldsOverride = (args: { defaultFields: DefaultSettingsFields }) => Field[]\n\n/** The plugin `settings` option: the three form-level flags and their composition seam. */\nexport type SettingsOption = {\n\tfields?: SettingsFieldsOverride\n}\n\n/**\n * The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the\n * Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a\n * poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row\n * after its actions run, or prune it (a pure signup form's opt-out).\n */\nexport const buildDefaultSettingsFields = (): DefaultSettingsFields => ({\n\tmultistep: {\n\t\tname: 'multistep',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: false,\n\t\tlabel: labelForKey(keys.formMultistep),\n\t\tadmin: { position: 'sidebar' },\n\t},\n\tpollEnabled: {\n\t\tname: 'pollEnabled',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: false,\n\t\tlabel: labelForKey(keys.formPollEnabled),\n\t\tadmin: { position: 'sidebar' },\n\t},\n\tpersistSubmissions: {\n\t\tname: 'persistSubmissions',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: true,\n\t\tlabel: labelForKey(keys.formPersistSubmissions),\n\t\tadmin: { position: 'sidebar' },\n\t},\n})\n\nexport const composeSettingsFields = (settings: SettingsOption | undefined): Field[] => {\n\tconst defaultFields = buildDefaultSettingsFields()\n\tif (settings?.fields) {\n\t\treturn settings.fields({ defaultFields })\n\t}\n\treturn [defaultFields.multistep, defaultFields.pollEnabled, defaultFields.persistSubmissions]\n}\n"],"mappings":";;;;;;;;;AA6BA,MAAa,oCAA2D;CACvE,WAAW;EACV,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,aAAa;EACrC,OAAO,EAAE,UAAU,UAAU;CAC9B;CACA,aAAa;EACZ,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,eAAe;EACvC,OAAO,EAAE,UAAU,UAAU;CAC9B;CACA,oBAAoB;EACnB,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,sBAAsB;EAC9C,OAAO,EAAE,UAAU,UAAU;CAC9B;AACD;AAEA,MAAa,yBAAyB,aAAkD;CACvF,MAAM,gBAAgB,2BAA2B;CACjD,IAAI,UAAU,QACb,OAAO,SAAS,OAAO,EAAE,cAAc,CAAC;CAEzC,OAAO;EAAC,cAAc;EAAW,cAAc;EAAa,cAAc;CAAkB;AAC7F"}
@@ -1,4 +1,5 @@
1
1
  import { ByteSizeField } from "../client/ByteSizeField.js";
2
+ import { CalcExpressionBuilder } from "../client/CalcExpressionBuilder.js";
2
3
  import { ClosePollButton } from "../client/ClosePollButton.js";
3
4
  import { CondensedArray } from "../client/CondensedArray.js";
4
5
  import { ConsentBlockLabel } from "../client/ConsentBlockLabel.js";
@@ -12,4 +13,4 @@ import { RecipientsSelect } from "../client/RecipientsSelect.js";
12
13
  import { RuleDescription } from "../client/RuleDescription.js";
13
14
  import { FieldCountCell } from "../collections/cells/FieldCountCell.js";
14
15
  import { FlowStepsCell } from "../collections/cells/FlowStepsCell.js";
15
- export { ByteSizeField, ClosePollButton, CondensedArray, ConsentBlockLabel, ConsentSourceRowLabel, EndpointOptionsSelect, FieldBlockLabel, FieldCountCell, FieldNameSelect, FlowBuilder, FlowStepsCell, FormConditionField, RecipientsSelect, RuleDescription };
16
+ export { ByteSizeField, CalcExpressionBuilder, ClosePollButton, CondensedArray, ConsentBlockLabel, ConsentSourceRowLabel, EndpointOptionsSelect, FieldBlockLabel, FieldCountCell, FieldNameSelect, FlowBuilder, FlowStepsCell, FormConditionField, RecipientsSelect, RuleDescription };
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { ByteSizeField } from "../client/ByteSizeField.js";
3
+ import { CalcExpressionBuilder } from "../client/CalcExpressionBuilder.js";
3
4
  import { ClosePollButton } from "../client/ClosePollButton.js";
4
5
  import { CondensedArray } from "../client/CondensedArray.js";
5
6
  import { ConsentBlockLabel } from "../client/ConsentBlockLabel.js";
@@ -13,4 +14,4 @@ import { RecipientsSelect } from "../client/RecipientsSelect.js";
13
14
  import { RuleDescription } from "../client/RuleDescription.js";
14
15
  import { FieldCountCell } from "../collections/cells/FieldCountCell.js";
15
16
  import { FlowStepsCell } from "../collections/cells/FlowStepsCell.js";
16
- export { ByteSizeField, ClosePollButton, CondensedArray, ConsentBlockLabel, ConsentSourceRowLabel, EndpointOptionsSelect, FieldBlockLabel, FieldCountCell, FieldNameSelect, FlowBuilder, FlowStepsCell, FormConditionField, RecipientsSelect, RuleDescription };
17
+ export { ByteSizeField, CalcExpressionBuilder, ClosePollButton, CondensedArray, ConsentBlockLabel, ConsentSourceRowLabel, EndpointOptionsSelect, FieldBlockLabel, FieldCountCell, FieldNameSelect, FlowBuilder, FlowStepsCell, FormConditionField, RecipientsSelect, RuleDescription };