@10x-media/form-builder 0.1.0-beta.9 → 4.0.0-alpha.2

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 (367) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +12 -4
  3. package/dist/actions/assertNoBlockCollision.js +18 -0
  4. package/dist/actions/assertNoBlockCollision.js.map +1 -0
  5. package/dist/actions/body/serializeBody.d.ts +16 -14
  6. package/dist/actions/body/serializeBody.js +5 -8
  7. package/dist/actions/body/serializeBody.js.map +1 -1
  8. package/dist/actions/builtin/confirmation.js +2 -1
  9. package/dist/actions/builtin/confirmation.js.map +1 -1
  10. package/dist/actions/builtin/emailAction.d.ts +15 -3
  11. package/dist/actions/builtin/emailAction.js +72 -20
  12. package/dist/actions/builtin/emailAction.js.map +1 -1
  13. package/dist/actions/builtin/emailTeam.js +11 -5
  14. package/dist/actions/builtin/emailTeam.js.map +1 -1
  15. package/dist/actions/defineAction.d.ts +37 -6
  16. package/dist/actions/defineAction.js +14 -1
  17. package/dist/actions/defineAction.js.map +1 -1
  18. package/dist/actions/dispatch.d.ts +12 -0
  19. package/dist/actions/dispatch.js +103 -30
  20. package/dist/actions/dispatch.js.map +1 -1
  21. package/dist/actions/dispatchContext.js +19 -0
  22. package/dist/actions/dispatchContext.js.map +1 -0
  23. package/dist/actions/emailRecipients.js +38 -8
  24. package/dist/actions/emailRecipients.js.map +1 -1
  25. package/dist/actions/emailRender.d.ts +27 -0
  26. package/dist/actions/fromAddresses.d.ts +19 -1
  27. package/dist/actions/fromAddresses.js +66 -9
  28. package/dist/actions/fromAddresses.js.map +1 -1
  29. package/dist/actions/recipientSources.d.ts +23 -0
  30. package/dist/actions/recipientSources.js +11 -0
  31. package/dist/actions/recipientSources.js.map +1 -0
  32. package/dist/actions/registry.js +3 -1
  33. package/dist/actions/registry.js.map +1 -1
  34. package/dist/actions/runActions.d.ts +2 -0
  35. package/dist/actions/runActions.js +13 -8
  36. package/dist/actions/runActions.js.map +1 -1
  37. package/dist/actions/sign.js.map +1 -1
  38. package/dist/actions/submissionContext.d.ts +34 -0
  39. package/dist/actions/task.js +43 -16
  40. package/dist/actions/task.js.map +1 -1
  41. package/dist/aggregation/aggregateResponses.js +3 -4
  42. package/dist/aggregation/aggregateResponses.js.map +1 -1
  43. package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
  44. package/dist/aggregation/resolveResultsRequest.js +69 -26
  45. package/dist/aggregation/resolveResultsRequest.js.map +1 -1
  46. package/dist/calc/computeCalcFields.d.ts +5 -3
  47. package/dist/calc/computeCalcFields.js +4 -3
  48. package/dist/calc/computeCalcFields.js.map +1 -1
  49. package/dist/calc/evaluate.d.ts +26 -3
  50. package/dist/calc/evaluate.js +33 -11
  51. package/dist/calc/evaluate.js.map +1 -1
  52. package/dist/calc/formatCalc.d.ts +11 -0
  53. package/dist/calc/formatCalc.js +35 -0
  54. package/dist/calc/formatCalc.js.map +1 -0
  55. package/dist/calc/formatCalcValue.d.ts +17 -0
  56. package/dist/calc/formatCalcValue.js +17 -0
  57. package/dist/calc/formatCalcValue.js.map +1 -0
  58. package/dist/calc/normalizeCalc.d.ts +17 -3
  59. package/dist/calc/normalizeCalc.js +39 -17
  60. package/dist/calc/normalizeCalc.js.map +1 -1
  61. package/dist/calc/registry.d.ts +43 -0
  62. package/dist/calc/registry.js +27 -0
  63. package/dist/calc/registry.js.map +1 -0
  64. package/dist/calc/resolveCalcContext.d.ts +36 -0
  65. package/dist/calc/resolveCalcContext.js +87 -0
  66. package/dist/calc/resolveCalcContext.js.map +1 -0
  67. package/dist/calc/types.d.ts +19 -4
  68. package/dist/calc/types.js +3 -2
  69. package/dist/calc/types.js.map +1 -1
  70. package/dist/client/ByteSizeField.js +11 -8
  71. package/dist/client/ByteSizeField.js.map +1 -1
  72. package/dist/client/CalcExpressionBuilder.d.ts +20 -0
  73. package/dist/client/CalcExpressionBuilder.js +888 -0
  74. package/dist/client/CalcExpressionBuilder.js.map +1 -0
  75. package/dist/client/ClosePollButton.js +3 -3
  76. package/dist/client/ClosePollButton.js.map +1 -1
  77. package/dist/client/CondensedArray.d.ts +2 -2
  78. package/dist/client/CondensedArray.js +5 -7
  79. package/dist/client/CondensedArray.js.map +1 -1
  80. package/dist/client/ConditionBuilder.js +5 -7
  81. package/dist/client/ConditionBuilder.js.map +1 -1
  82. package/dist/client/ConditionRow.js +3 -3
  83. package/dist/client/ConditionRow.js.map +1 -1
  84. package/dist/client/ConsentBlockLabel.js +2 -2
  85. package/dist/client/ConsentBlockLabel.js.map +1 -1
  86. package/dist/client/ConsentRetentionNotice.d.ts +11 -0
  87. package/dist/client/ConsentRetentionNotice.js +23 -0
  88. package/dist/client/ConsentRetentionNotice.js.map +1 -0
  89. package/dist/client/EndpointOptionsSelect.d.ts +17 -7
  90. package/dist/client/EndpointOptionsSelect.js +18 -14
  91. package/dist/client/EndpointOptionsSelect.js.map +1 -1
  92. package/dist/client/FieldBlockLabel.js +2 -2
  93. package/dist/client/FieldBlockLabel.js.map +1 -1
  94. package/dist/client/FieldNameSelect.d.ts +1 -0
  95. package/dist/client/FieldNameSelect.js +2 -4
  96. package/dist/client/FieldNameSelect.js.map +1 -1
  97. package/dist/client/FlowBuilder.js +31 -23
  98. package/dist/client/FlowBuilder.js.map +1 -1
  99. package/dist/client/FormConditionField.js +0 -1
  100. package/dist/client/FormConditionField.js.map +1 -1
  101. package/dist/client/RecipientsSelect.d.ts +9 -2
  102. package/dist/client/RecipientsSelect.js +31 -10
  103. package/dist/client/RecipientsSelect.js.map +1 -1
  104. package/dist/client/admin.css +345 -72
  105. package/dist/client/endpointOptions.d.ts +11 -0
  106. package/dist/client/endpointOptions.js +17 -8
  107. package/dist/client/endpointOptions.js.map +1 -1
  108. package/dist/collections/formSubmissions.js +145 -51
  109. package/dist/collections/formSubmissions.js.map +1 -1
  110. package/dist/collections/forms.js +170 -65
  111. package/dist/collections/forms.js.map +1 -1
  112. package/dist/collections/formsEndpoints.js +31 -26
  113. package/dist/collections/formsEndpoints.js.map +1 -1
  114. package/dist/collections/settingsFields.d.ts +32 -0
  115. package/dist/collections/settingsFields.js +55 -0
  116. package/dist/collections/settingsFields.js.map +1 -0
  117. package/dist/consent/captureConsent.d.ts +2 -1
  118. package/dist/consent/captureConsent.js +4 -1
  119. package/dist/consent/captureConsent.js.map +1 -1
  120. package/dist/consent/consentSourcesField.d.ts +7 -1
  121. package/dist/consent/consentSourcesField.js +15 -1
  122. package/dist/consent/consentSourcesField.js.map +1 -1
  123. package/dist/consent/effectiveStatement.js +16 -0
  124. package/dist/consent/effectiveStatement.js.map +1 -0
  125. package/dist/consent/resolveConsentSourcesRequest.js +2 -2
  126. package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
  127. package/dist/consent/resolveConsentStatements.js +3 -1
  128. package/dist/consent/resolveConsentStatements.js.map +1 -1
  129. package/dist/consent/resolvePublishedVersionRef.js +1 -0
  130. package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
  131. package/dist/consent/types.d.ts +8 -0
  132. package/dist/context/formContext.d.ts +30 -0
  133. package/dist/context/formContext.js +54 -0
  134. package/dist/context/formContext.js.map +1 -0
  135. package/dist/email/departmentsField.d.ts +6 -1
  136. package/dist/email/departmentsField.js +6 -1
  137. package/dist/email/departmentsField.js.map +1 -1
  138. package/dist/exports/client.d.ts +3 -1
  139. package/dist/exports/client.js +3 -1
  140. package/dist/exports/i18n.d.ts +14 -2
  141. package/dist/exports/i18n.js +14 -2
  142. package/dist/exports/react.d.ts +23 -5
  143. package/dist/exports/react.js +17 -1
  144. package/dist/exports/rsc.d.ts +4 -1
  145. package/dist/exports/rsc.js +7 -4
  146. package/dist/exports/shared.d.ts +21 -0
  147. package/dist/exports/shared.js +18 -0
  148. package/dist/exports/types.d.ts +4 -3
  149. package/dist/fields/buildFieldBlocks.js +2 -1
  150. package/dist/fields/buildFieldBlocks.js.map +1 -1
  151. package/dist/fields/builtin/calculation.d.ts +17 -0
  152. package/dist/fields/builtin/calculation.js +70 -127
  153. package/dist/fields/builtin/calculation.js.map +1 -1
  154. package/dist/fields/builtin/checkbox.js +15 -0
  155. package/dist/fields/builtin/checkbox.js.map +1 -1
  156. package/dist/fields/builtin/consent.js +21 -1
  157. package/dist/fields/builtin/consent.js.map +1 -1
  158. package/dist/fields/builtin/email.js +7 -0
  159. package/dist/fields/builtin/email.js.map +1 -1
  160. package/dist/fields/builtin/index.d.ts +6 -2
  161. package/dist/fields/builtin/index.js +9 -4
  162. package/dist/fields/builtin/index.js.map +1 -1
  163. package/dist/fields/builtin/select.js +20 -1
  164. package/dist/fields/builtin/select.js.map +1 -1
  165. package/dist/fields/builtin/text.js +7 -0
  166. package/dist/fields/builtin/text.js.map +1 -1
  167. package/dist/fields/instanceOptions.js +1 -1
  168. package/dist/fields/instanceOptions.js.map +1 -1
  169. package/dist/fields/sharedConfig.js +15 -11
  170. package/dist/fields/sharedConfig.js.map +1 -1
  171. package/dist/fields/types.d.ts +8 -2
  172. package/dist/form/findFormAtLocale.d.ts +30 -0
  173. package/dist/form/findFormAtLocale.js +88 -0
  174. package/dist/form/findFormAtLocale.js.map +1 -0
  175. package/dist/form/pollState.d.ts +2 -1
  176. package/dist/form/pollState.js.map +1 -1
  177. package/dist/form/toFormDocument.d.ts +18 -6
  178. package/dist/form/toFormDocument.js +3 -1
  179. package/dist/form/toFormDocument.js.map +1 -1
  180. package/dist/form/types.d.ts +9 -1
  181. package/dist/index.d.ts +29 -7
  182. package/dist/index.js +74 -18
  183. package/dist/index.js.map +1 -1
  184. package/dist/options.d.ts +119 -4
  185. package/dist/plugin/collectionSlugs.d.ts +28 -0
  186. package/dist/plugin/collectionSlugs.js +65 -0
  187. package/dist/plugin/collectionSlugs.js.map +1 -0
  188. package/dist/plugin/customState.js +1 -1
  189. package/dist/plugin/customState.js.map +1 -1
  190. package/dist/plugin/registerCollections.js +38 -21
  191. package/dist/plugin/registerCollections.js.map +1 -1
  192. package/dist/poll/closeJob.d.ts +4 -3
  193. package/dist/poll/closeJob.js +13 -10
  194. package/dist/poll/closeJob.js.map +1 -1
  195. package/dist/poll/outcomeBeforeChange.js +2 -2
  196. package/dist/poll/outcomeBeforeChange.js.map +1 -1
  197. package/dist/poll/pollTypeRegistry.js +1 -1
  198. package/dist/poll/resolvePollCloseRequest.js +5 -4
  199. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  200. package/dist/poll/resolvePollOptionsRequest.js +2 -2
  201. package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
  202. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  203. package/dist/poll/resolvePollOutcome.js +20 -6
  204. package/dist/poll/resolvePollOutcome.js.map +1 -1
  205. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  206. package/dist/poll/votes/aggregateFromVotes.js +55 -0
  207. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  208. package/dist/poll/votes/answerValues.js +16 -0
  209. package/dist/poll/votes/answerValues.js.map +1 -0
  210. package/dist/poll/votes/bumpPollVote.js +91 -0
  211. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  212. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  213. package/dist/poll/votes/recountPollVotes.js +63 -0
  214. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  215. package/dist/poll/votes/voteTallyHook.js +76 -0
  216. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  217. package/dist/poll/votes/votesCollection.d.ts +23 -0
  218. package/dist/poll/votes/votesCollection.js +96 -0
  219. package/dist/poll/votes/votesCollection.js.map +1 -0
  220. package/dist/react/Form.d.ts +49 -7
  221. package/dist/react/Form.js +48 -13
  222. package/dist/react/Form.js.map +1 -1
  223. package/dist/react/FormContext.d.ts +8 -1
  224. package/dist/react/FormContext.js.map +1 -1
  225. package/dist/react/FormResults.d.ts +4 -2
  226. package/dist/react/FormResults.js +21 -8
  227. package/dist/react/FormResults.js.map +1 -1
  228. package/dist/react/Poll.d.ts +25 -2
  229. package/dist/react/Poll.js +76 -25
  230. package/dist/react/Poll.js.map +1 -1
  231. package/dist/react/adapters.d.ts +35 -0
  232. package/dist/react/adapters.js +11 -0
  233. package/dist/react/adapters.js.map +1 -0
  234. package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
  235. package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
  236. package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
  237. package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
  238. package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
  239. package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
  240. package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
  241. package/dist/react/captcha/TurnstileCaptcha.js +2 -2
  242. package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
  243. package/dist/react/captcha/useCaptchaScript.js +23 -5
  244. package/dist/react/captcha/useCaptchaScript.js.map +1 -1
  245. package/dist/react/fetchResults.d.ts +6 -3
  246. package/dist/react/fetchResults.js +10 -5
  247. package/dist/react/fetchResults.js.map +1 -1
  248. package/dist/react/primitives/Checkbox.d.ts +4 -2
  249. package/dist/react/primitives/Checkbox.js +3 -2
  250. package/dist/react/primitives/Checkbox.js.map +1 -1
  251. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  252. package/dist/react/primitives/ChoiceGroup.js +33 -0
  253. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  254. package/dist/react/primitives/FieldShell.d.ts +11 -1
  255. package/dist/react/primitives/FieldShell.js +43 -33
  256. package/dist/react/primitives/FieldShell.js.map +1 -1
  257. package/dist/react/primitives/Input.d.ts +3 -1
  258. package/dist/react/primitives/Input.js +2 -1
  259. package/dist/react/primitives/Input.js.map +1 -1
  260. package/dist/react/renderers/calculation.js +6 -1
  261. package/dist/react/renderers/calculation.js.map +1 -1
  262. package/dist/react/renderers/checkbox.js +2 -1
  263. package/dist/react/renderers/checkbox.js.map +1 -1
  264. package/dist/react/renderers/consent.js +8 -3
  265. package/dist/react/renderers/consent.js.map +1 -1
  266. package/dist/react/renderers/email.js +3 -1
  267. package/dist/react/renderers/email.js.map +1 -1
  268. package/dist/react/renderers/repeater.js +5 -0
  269. package/dist/react/renderers/repeater.js.map +1 -1
  270. package/dist/react/renderers/select.js +20 -2
  271. package/dist/react/renderers/select.js.map +1 -1
  272. package/dist/react/renderers/text.js +3 -1
  273. package/dist/react/renderers/text.js.map +1 -1
  274. package/dist/react/state.d.ts +10 -0
  275. package/dist/react/state.js +45 -1
  276. package/dist/react/state.js.map +1 -1
  277. package/dist/react/submitForm.d.ts +20 -3
  278. package/dist/react/submitForm.js +8 -4
  279. package/dist/react/submitForm.js.map +1 -1
  280. package/dist/react/useCalcValues.d.ts +10 -0
  281. package/dist/react/useCalcValues.js +13 -0
  282. package/dist/react/useCalcValues.js.map +1 -0
  283. package/dist/react/useField.js +2 -1
  284. package/dist/react/useField.js.map +1 -1
  285. package/dist/recall/resolver.js +1 -1
  286. package/dist/recall/resolver.js.map +1 -1
  287. package/dist/spam/constants.js +7 -1
  288. package/dist/spam/constants.js.map +1 -1
  289. package/dist/spam/spamGuard.js +2 -1
  290. package/dist/spam/spamGuard.js.map +1 -1
  291. package/dist/submissions/SubmissionAnswersClient.js +14 -14
  292. package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
  293. package/dist/submissions/createSubmission.d.ts +7 -1
  294. package/dist/submissions/createSubmission.js +10 -5
  295. package/dist/submissions/createSubmission.js.map +1 -1
  296. package/dist/submissions/formIdOf.js +13 -0
  297. package/dist/submissions/formIdOf.js.map +1 -0
  298. package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
  299. package/dist/submissions/resolveVotedSubmission.js +51 -0
  300. package/dist/submissions/resolveVotedSubmission.js.map +1 -0
  301. package/dist/submissions/runSubmission.js +6 -5
  302. package/dist/submissions/runSubmission.js.map +1 -1
  303. package/dist/submissions/submissionLocale.js +39 -0
  304. package/dist/submissions/submissionLocale.js.map +1 -0
  305. package/dist/submissions/validateSubmission.js +125 -79
  306. package/dist/submissions/validateSubmission.js.map +1 -1
  307. package/dist/submissions/verifyContext.js +35 -0
  308. package/dist/submissions/verifyContext.js.map +1 -0
  309. package/dist/submissions/voteChange.js +21 -0
  310. package/dist/submissions/voteChange.js.map +1 -0
  311. package/dist/submissions/voteChangeEndpoint.js +110 -0
  312. package/dist/submissions/voteChangeEndpoint.js.map +1 -0
  313. package/dist/submissions/votedCookie.d.ts +10 -4
  314. package/dist/submissions/votedCookie.js +49 -11
  315. package/dist/submissions/votedCookie.js.map +1 -1
  316. package/dist/translations/ar.d.ts +7 -0
  317. package/dist/translations/ar.js +379 -0
  318. package/dist/translations/ar.js.map +1 -0
  319. package/dist/translations/clientRuntimeKeys.d.ts +17 -0
  320. package/dist/translations/clientRuntimeKeys.js +48 -0
  321. package/dist/translations/clientRuntimeKeys.js.map +1 -0
  322. package/dist/translations/de.d.ts +12 -0
  323. package/dist/translations/de.js +78 -3
  324. package/dist/translations/de.js.map +1 -1
  325. package/dist/translations/en.js +78 -3
  326. package/dist/translations/en.js.map +1 -1
  327. package/dist/translations/es.d.ts +7 -0
  328. package/dist/translations/es.js +379 -0
  329. package/dist/translations/es.js.map +1 -0
  330. package/dist/translations/fr.d.ts +7 -0
  331. package/dist/translations/fr.js +379 -0
  332. package/dist/translations/fr.js.map +1 -0
  333. package/dist/translations/id.d.ts +7 -0
  334. package/dist/translations/id.js +379 -0
  335. package/dist/translations/id.js.map +1 -0
  336. package/dist/translations/index.d.ts +23 -6
  337. package/dist/translations/index.js +31 -6
  338. package/dist/translations/index.js.map +1 -1
  339. package/dist/translations/keys.d.ts +76 -1
  340. package/dist/translations/keys.js +76 -1
  341. package/dist/translations/keys.js.map +1 -1
  342. package/dist/translations/ko.d.ts +7 -0
  343. package/dist/translations/ko.js +379 -0
  344. package/dist/translations/ko.js.map +1 -0
  345. package/dist/translations/makeTranslate.d.ts +7 -3
  346. package/dist/translations/makeTranslate.js +12 -3
  347. package/dist/translations/makeTranslate.js.map +1 -1
  348. package/dist/translations/pt.d.ts +7 -0
  349. package/dist/translations/pt.js +379 -0
  350. package/dist/translations/pt.js.map +1 -0
  351. package/dist/translations/ru.d.ts +7 -0
  352. package/dist/translations/ru.js +379 -0
  353. package/dist/translations/ru.js.map +1 -0
  354. package/dist/translations/uk.d.ts +7 -0
  355. package/dist/translations/uk.js +379 -0
  356. package/dist/translations/uk.js.map +1 -0
  357. package/dist/translations/zh.d.ts +7 -0
  358. package/dist/translations/zh.js +379 -0
  359. package/dist/translations/zh.js.map +1 -0
  360. package/dist/validation/builtin/index.js +2 -0
  361. package/dist/validation/builtin/index.js.map +1 -1
  362. package/dist/validation/builtin/integer.js +15 -0
  363. package/dist/validation/builtin/integer.js.map +1 -0
  364. package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
  365. package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
  366. package/package.json +29 -16
  367. package/styles/form-builder.css +84 -0
@@ -1 +1 @@
1
- {"version":3,"file":"sharedConfig.js","names":[],"sources":["../../src/fields/sharedConfig.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport type { ConditionFieldType } from '../conditions/fieldTypes'\nimport { keys } from '../translations/keys'\nimport { labelFor } from '../translations/server'\nimport { localizedIf } from './localizedIf'\nimport type { OmittableSharedField } from './types'\n\nconst CONDITION_FIELD_REF = '@10x-media/form-builder/client#FormConditionField'\n\nconst conditionField = (\n\tname: 'visibleWhen' | 'validateWhen',\n\tlabelKey: string,\n\tconditionTypes: Record<string, ConditionFieldType>\n): Field => ({\n\tname,\n\ttype: 'json',\n\tlabel: labelFor(labelKey),\n\tadmin: {\n\t\tcomponents: {\n\t\t\tField: { path: CONDITION_FIELD_REF, clientProps: { conditionTypes } },\n\t\t},\n\t},\n})\n\n/**\n * Let a lone row survivor span its row: Payload styles a row child with no `admin.width` as\n * `flex: 1 1 auto` (see `mergeFieldStyles`), so dropping the key is the \"fill the row\" signal.\n * Without this, omitting one half of a 50/50 row would strand the other half at 50%.\n */\nconst spanRow = <T extends Field>(field: T): T => {\n\tif (field.admin?.width === undefined) {\n\t\treturn field\n\t}\n\tconst { width: _width, ...admin } = field.admin\n\treturn { ...field, admin }\n}\n\n/**\n * Drop the shared fields a type never uses, descending into the presentational rows so a nested\n * field is reachable. An emptied row is dropped whole; a row pruned down to one field lets that\n * field span it. A row that lost nothing is left exactly as authored, single-child rows included.\n */\nconst applyOmissions = (fields: Field[], omit: ReadonlySet<string>): Field[] =>\n\tfields.flatMap((field): Field[] => {\n\t\tif (field.type === 'row') {\n\t\t\tconst kept = applyOmissions(field.fields, omit)\n\t\t\tif (kept.length === 0) {\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst strandsSurvivor = kept.length === 1 && kept.length < field.fields.length\n\t\t\treturn [{ ...field, fields: strandsSurvivor ? kept.map(spanRow) : kept }]\n\t\t}\n\t\treturn 'name' in field && omit.has(field.name) ? [] : [field]\n\t})\n\n/** The full shared config, before a type's `omitShared` prunes it. See `sharedFieldConfig`. */\nconst baseSharedFieldConfig = (localize: boolean): Field[] => [\n\t{\n\t\ttype: 'row',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\trequired: true,\n\t\t\t\tlabel: labelFor(keys.configName),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'label',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.configLabel),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t],\n\t},\n\t{\n\t\ttype: 'row',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'width',\n\t\t\t\ttype: 'select',\n\t\t\t\trequired: true,\n\t\t\t\tdefaultValue: 'full',\n\t\t\t\tlabel: labelFor(keys.configWidth),\n\t\t\t\tadmin: { width: '50%', isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: 'Full', value: 'full' },\n\t\t\t\t\t{ label: 'Half', value: 'half' },\n\t\t\t\t\t{ label: 'Third', value: 'third' },\n\t\t\t\t\t{ label: 'Two thirds', value: 'twoThirds' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'placeholder',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.configPlaceholder),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t],\n\t},\n\t{\n\t\tname: 'description',\n\t\ttype: 'textarea',\n\t\tlabel: labelFor(keys.configDescription),\n\t\t...localizedIf(localize),\n\t},\n\t{ name: 'required', type: 'checkbox', label: labelFor(keys.configRequired) },\n]\n\n/**\n * Config every field instance carries regardless of type. `name` is the machine key written into\n * submissions; `width` is stored for the layout grid. Field types add their own `config` after\n * these inside the Field tab (see `fieldBlockTabs`) and drop the ones they never read via\n * `omitShared`, so an author is never offered a setting the renderer ignores. Content-bearing\n * fields (`label`, `placeholder`, `description`) are localized unless `localize` is false;\n * identifiers and behavior flags never are. The rows are presentational only (unnamed, data paths\n * stay flat); `required` sits last, under `description`, per the admin layout.\n */\nexport const sharedFieldConfig = (\n\tlocalize = true,\n\tomitShared: readonly OmittableSharedField[] = []\n): Field[] => {\n\tconst omit = new Set<string>(omitShared)\n\t// `name` is the storage key every read and write path gates on (`isNamedField`). The type\n\t// already excludes it; dropping it here too keeps an untyped caller from breaking storage.\n\tomit.delete('name')\n\treturn applyOmissions(baseSharedFieldConfig(localize), omit)\n}\n\n/**\n * The single field of every field block: unnamed tabs (presentational only, data paths stay flat).\n * Field tab holds the shared basics plus the type's own config; Validation holds the rule blocks and\n * `validateWhen`; Advanced holds `visibleWhen` and `hidden`. `visibleWhen`/`validateWhen` store a\n * canonical Payload `Where`, edited by the native condition builder.\n */\ntype FieldBlockTabsArgs = {\n\tconditionTypes: Record<string, ConditionFieldType>\n\ttypeConfig: Field[]\n\tvalidations: Field\n\tlocalize?: boolean\n\t/** See `FormFieldDefinition.omitShared`: shared basics this type never uses, left unauthored. */\n\tomitShared?: readonly OmittableSharedField[]\n}\n\nexport const fieldBlockTabs = ({\n\tconditionTypes,\n\ttypeConfig,\n\tvalidations,\n\tlocalize = true,\n\tomitShared,\n}: FieldBlockTabsArgs): Field => ({\n\ttype: 'tabs',\n\ttabs: [\n\t\t{\n\t\t\tlabel: labelFor(keys.tabField),\n\t\t\tfields: [...sharedFieldConfig(localize, omitShared), ...typeConfig],\n\t\t},\n\t\t{\n\t\t\tlabel: labelFor(keys.tabValidation),\n\t\t\tfields: [\n\t\t\t\tvalidations,\n\t\t\t\tconditionField('validateWhen', keys.configValidateWhen, conditionTypes),\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tlabel: labelFor(keys.tabAdvanced),\n\t\t\tfields: [\n\t\t\t\tconditionField('visibleWhen', keys.configVisibleWhen, conditionTypes),\n\t\t\t\t{ name: 'hidden', type: 'checkbox', label: labelFor(keys.configHidden) },\n\t\t\t],\n\t\t},\n\t],\n})\n"],"mappings":"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"}
1
+ {"version":3,"file":"sharedConfig.js","names":[],"sources":["../../src/fields/sharedConfig.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport type { ConditionFieldType } from '../conditions/fieldTypes'\nimport { keys } from '../translations/keys'\nimport { labelFor } from '../translations/server'\nimport { localizedIf } from './localizedIf'\nimport type { OmittableSharedField } from './types'\n\nconst CONDITION_FIELD_REF = '@10x-media/form-builder/client#FormConditionField'\n\nconst conditionField = (\n\tname: 'visibleWhen' | 'validateWhen',\n\tlabelKey: string,\n\tconditionTypes: Record<string, ConditionFieldType>\n): Field => ({\n\tname,\n\ttype: 'json',\n\tlabel: labelFor(labelKey),\n\tadmin: {\n\t\tcomponents: {\n\t\t\tField: { path: CONDITION_FIELD_REF, clientProps: { conditionTypes } },\n\t\t},\n\t},\n})\n\n/**\n * Let a lone row survivor span its row: Payload styles a row child with no `admin.width` as\n * `flex: 1 1 auto` (see `mergeFieldStyles`), so dropping the key is the \"fill the row\" signal.\n * Without this, omitting one half of a 50/50 row would strand the other half at 50%.\n */\nconst spanRow = <T extends Field>(field: T): T => {\n\tif (field.admin?.width === undefined) {\n\t\treturn field\n\t}\n\tconst { width: _width, ...admin } = field.admin\n\treturn { ...field, admin }\n}\n\n/**\n * Drop the shared fields a type never uses, descending into the presentational rows so a nested\n * field is reachable. An emptied row is dropped whole; a row pruned down to one field lets that\n * field span it. A row that lost nothing is left exactly as authored, single-child rows included.\n */\nconst applyOmissions = (fields: Field[], omit: ReadonlySet<string>): Field[] =>\n\tfields.flatMap((field): Field[] => {\n\t\tif (field.type === 'row') {\n\t\t\tconst kept = applyOmissions(field.fields, omit)\n\t\t\tif (kept.length === 0) {\n\t\t\t\treturn []\n\t\t\t}\n\t\t\tconst strandsSurvivor = kept.length === 1 && kept.length < field.fields.length\n\t\t\treturn [{ ...field, fields: strandsSurvivor ? kept.map(spanRow) : kept }]\n\t\t}\n\t\treturn 'name' in field && omit.has(field.name) ? [] : [field]\n\t})\n\n/** The full shared config, before a type's `omitShared` prunes it. See `sharedFieldConfig`. */\nconst baseSharedFieldConfig = (localize: boolean): Field[] => [\n\t{\n\t\ttype: 'row',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\trequired: true,\n\t\t\t\tlabel: labelFor(keys.configName),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'label',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.configLabel),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t],\n\t},\n\t{\n\t\ttype: 'row',\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'width',\n\t\t\t\ttype: 'select',\n\t\t\t\tdefaultValue: 'full',\n\t\t\t\tlabel: labelFor(keys.configWidth),\n\t\t\t\tadmin: { width: '50%', isClearable: false },\n\t\t\t\toptions: [\n\t\t\t\t\t{ label: labelFor(keys.widthFull), value: 'full' },\n\t\t\t\t\t{ label: labelFor(keys.widthHalf), value: 'half' },\n\t\t\t\t\t{ label: labelFor(keys.widthThird), value: 'third' },\n\t\t\t\t\t{ label: labelFor(keys.widthTwoThirds), value: 'twoThirds' },\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'placeholder',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.configPlaceholder),\n\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t],\n\t},\n\t{\n\t\tname: 'description',\n\t\ttype: 'textarea',\n\t\tlabel: labelFor(keys.configDescription),\n\t\t...localizedIf(localize),\n\t},\n\t{ name: 'required', type: 'checkbox', label: labelFor(keys.configRequired) },\n]\n\n/**\n * Config every field instance carries regardless of type. `name` is the machine key written into\n * submissions; `width` is stored for the layout grid. Field types add their own `config` after\n * these inside the Field tab (see `fieldBlockTabs`) and drop the ones they never read via\n * `omitShared`, so an author is never offered a setting the renderer ignores. Content-bearing\n * fields (`label`, `placeholder`, `description`) are localized unless `localize` is false;\n * identifiers and behavior flags never are. The rows are presentational only (unnamed, data paths\n * stay flat); `required` sits last, under `description`, per the admin layout.\n */\nexport const sharedFieldConfig = (\n\tlocalize = true,\n\tomitShared: readonly OmittableSharedField[] = []\n): Field[] => {\n\tconst omit = new Set<string>(omitShared)\n\t// `name` is the storage key every read and write path gates on (`isNamedField`). The type\n\t// already excludes it; dropping it here too keeps an untyped caller from breaking storage.\n\tomit.delete('name')\n\treturn applyOmissions(baseSharedFieldConfig(localize), omit)\n}\n\n/**\n * The single field of every field block: unnamed tabs (presentational only, data paths stay flat).\n * Field tab holds the shared basics plus the type's own config; Validation holds the rule blocks and\n * `validateWhen`; Advanced holds `visibleWhen` and `hidden`. `visibleWhen`/`validateWhen` store a\n * canonical Payload `Where`, edited by the native condition builder.\n */\ntype FieldBlockTabsArgs = {\n\tconditionTypes: Record<string, ConditionFieldType>\n\ttypeConfig: Field[]\n\tvalidations: Field\n\tlocalize?: boolean\n\t/** See `FormFieldDefinition.omitShared`: shared basics this type never uses, left unauthored. */\n\tomitShared?: readonly OmittableSharedField[]\n\t/** See `FormFieldDefinition.advancedConfig`: extra fields appended to the Advanced tab. */\n\tadvancedConfig?: Field[]\n}\n\nexport const fieldBlockTabs = ({\n\tconditionTypes,\n\ttypeConfig,\n\tvalidations,\n\tlocalize = true,\n\tomitShared,\n\tadvancedConfig,\n}: FieldBlockTabsArgs): Field => ({\n\ttype: 'tabs',\n\ttabs: [\n\t\t{\n\t\t\tlabel: labelFor(keys.tabField),\n\t\t\tfields: [...sharedFieldConfig(localize, omitShared), ...typeConfig],\n\t\t},\n\t\t{\n\t\t\tlabel: labelFor(keys.tabValidation),\n\t\t\tfields: [\n\t\t\t\tvalidations,\n\t\t\t\tconditionField('validateWhen', keys.configValidateWhen, conditionTypes),\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tlabel: labelFor(keys.tabAdvanced),\n\t\t\tfields: [\n\t\t\t\tconditionField('visibleWhen', keys.configVisibleWhen, conditionTypes),\n\t\t\t\t{\n\t\t\t\t\tname: 'hidden',\n\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\tlabel: labelFor(keys.configHidden),\n\t\t\t\t\tadmin: { description: labelFor(keys.configHiddenDescription) },\n\t\t\t\t},\n\t\t\t\t...(advancedConfig ?? []),\n\t\t\t],\n\t\t},\n\t],\n})\n"],"mappings":";;;;AAOA,MAAM,sBAAsB;AAE5B,MAAM,kBACL,MACA,UACA,oBACY;CACZ;CACA,MAAM;CACN,OAAO,SAAS,QAAQ;CACxB,OAAO,EACN,YAAY,EACX,OAAO;EAAE,MAAM;EAAqB,aAAa,EAAE,eAAe;CAAE,EACrE,EACD;AACD;;;;;;AAOA,MAAM,WAA4B,UAAgB;CACjD,IAAI,MAAM,OAAO,UAAU,KAAA,GAC1B,OAAO;CAER,MAAM,EAAE,OAAO,QAAQ,GAAG,UAAU,MAAM;CAC1C,OAAO;EAAE,GAAG;EAAO;CAAM;AAC1B;;;;;;AAOA,MAAM,kBAAkB,QAAiB,SACxC,OAAO,SAAS,UAAmB;CAClC,IAAI,MAAM,SAAS,OAAO;EACzB,MAAM,OAAO,eAAe,MAAM,QAAQ,IAAI;EAC9C,IAAI,KAAK,WAAW,GACnB,OAAO,CAAC;EAET,MAAM,kBAAkB,KAAK,WAAW,KAAK,KAAK,SAAS,MAAM,OAAO;EACxE,OAAO,CAAC;GAAE,GAAG;GAAO,QAAQ,kBAAkB,KAAK,IAAI,OAAO,IAAI;EAAK,CAAC;CACzE;CACA,OAAO,UAAU,SAAS,KAAK,IAAI,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK;AAC7D,CAAC;;AAGF,MAAM,yBAAyB,aAA+B;CAC7D;EACC,MAAM;EACN,QAAQ,CACP;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,OAAO,SAAS,KAAK,UAAU;GAC/B,OAAO,EAAE,OAAO,MAAM;EACvB,GACA;GACC,MAAM;GACN,MAAM;GACN,OAAO,SAAS,KAAK,WAAW;GAChC,OAAO,EAAE,OAAO,MAAM;GACtB,GAAG,YAAY,QAAQ;EACxB,CACD;CACD;CACA;EACC,MAAM;EACN,QAAQ,CACP;GACC,MAAM;GACN,MAAM;GACN,cAAc;GACd,OAAO,SAAS,KAAK,WAAW;GAChC,OAAO;IAAE,OAAO;IAAO,aAAa;GAAM;GAC1C,SAAS;IACR;KAAE,OAAO,SAAS,KAAK,SAAS;KAAG,OAAO;IAAO;IACjD;KAAE,OAAO,SAAS,KAAK,SAAS;KAAG,OAAO;IAAO;IACjD;KAAE,OAAO,SAAS,KAAK,UAAU;KAAG,OAAO;IAAQ;IACnD;KAAE,OAAO,SAAS,KAAK,cAAc;KAAG,OAAO;IAAY;GAC5D;EACD,GACA;GACC,MAAM;GACN,MAAM;GACN,OAAO,SAAS,KAAK,iBAAiB;GACtC,OAAO,EAAE,OAAO,MAAM;GACtB,GAAG,YAAY,QAAQ;EACxB,CACD;CACD;CACA;EACC,MAAM;EACN,MAAM;EACN,OAAO,SAAS,KAAK,iBAAiB;EACtC,GAAG,YAAY,QAAQ;CACxB;CACA;EAAE,MAAM;EAAY,MAAM;EAAY,OAAO,SAAS,KAAK,cAAc;CAAE;AAC5E;;;;;;;;;;AAWA,MAAa,qBACZ,WAAW,MACX,aAA8C,CAAC,MAClC;CACb,MAAM,OAAO,IAAI,IAAY,UAAU;CAGvC,KAAK,OAAO,MAAM;CAClB,OAAO,eAAe,sBAAsB,QAAQ,GAAG,IAAI;AAC5D;AAmBA,MAAa,kBAAkB,EAC9B,gBACA,YACA,aACA,WAAW,MACX,YACA,sBACiC;CACjC,MAAM;CACN,MAAM;EACL;GACC,OAAO,SAAS,KAAK,QAAQ;GAC7B,QAAQ,CAAC,GAAG,kBAAkB,UAAU,UAAU,GAAG,GAAG,UAAU;EACnE;EACA;GACC,OAAO,SAAS,KAAK,aAAa;GAClC,QAAQ,CACP,aACA,eAAe,gBAAgB,KAAK,oBAAoB,cAAc,CACvE;EACD;EACA;GACC,OAAO,SAAS,KAAK,WAAW;GAChC,QAAQ;IACP,eAAe,eAAe,KAAK,mBAAmB,cAAc;IACpE;KACC,MAAM;KACN,MAAM;KACN,OAAO,SAAS,KAAK,YAAY;KACjC,OAAO,EAAE,aAAa,SAAS,KAAK,uBAAuB,EAAE;IAC9D;IACA,GAAI,kBAAkB,CAAC;GACxB;EACD;CACD;AACD"}
@@ -1,7 +1,7 @@
1
+ import { ConditionFieldType } from "../conditions/fieldTypes.js";
1
2
  import { PollOption } from "../poll/definePollOptionSource.js";
2
3
  import { FormFieldInstance } from "../submissions/types.js";
3
4
  import { FileRef } from "../uploads/types.js";
4
- import { ConditionFieldType } from "../conditions/fieldTypes.js";
5
5
  import { Field, Payload, PayloadRequest } from "payload";
6
6
  import { StandardSchemaV1 } from "@standard-schema/spec";
7
7
 
@@ -70,6 +70,11 @@ type FormFieldDefinition<K extends FormFieldValueKind = FormFieldValueKind, TCon
70
70
  label: string;
71
71
  value: K;
72
72
  config?: Field[];
73
+ /**
74
+ * Extra per-type fields for the Advanced tab, after `visibleWhen`/`hidden`. Lets a type add
75
+ * behavior settings (e.g. `autocomplete`) without crowding the Field tab.
76
+ */
77
+ advancedConfig?: Field[];
73
78
  validate?: FormFieldValidate<K, TConfig>;
74
79
  format?: FormFieldFormat<K, TConfig>;
75
80
  Field?: string;
@@ -133,7 +138,8 @@ type AnyFormFieldDefinition = {
133
138
  type: string;
134
139
  label: string;
135
140
  value: FormFieldValueKind;
136
- config?: Field[];
141
+ config?: Field[]; /** See `FormFieldDefinition.advancedConfig`: extra per-type fields for the Advanced tab. */
142
+ advancedConfig?: Field[];
137
143
  validate?: AnyFormFieldValidate;
138
144
  format?: AnyFormFieldFormat;
139
145
  Field?: string; /** See `FormFieldDefinition.blockLabel`: import-map ref for a custom block row Label. */
@@ -0,0 +1,30 @@
1
+ import { SubmissionForm } from "../actions/submissionContext.js";
2
+ import { Payload, PayloadRequest } from "payload";
3
+
4
+ //#region src/form/findFormAtLocale.d.ts
5
+ /**
6
+ * What a `fallbackLocale` resolver returns: a locale code, an ordered list of codes, `false` for no
7
+ * fallback, or `undefined` to keep the default.
8
+ */
9
+ type FormFallbackLocaleResult = string | string[] | false | undefined;
10
+ type FormFallbackLocaleArgs = {
11
+ /**
12
+ * The form as first read at `locale` with the config's own fallback, at depth 0: a non-localized
13
+ * owner relationship (a multi-tenant host's `form.tenant`) is already on it, so no read of your own
14
+ * is needed. Decide from non-localized fields: a localized one may be empty at `locale`.
15
+ */
16
+ form: SubmissionForm; /** The locale the form is being read at (the submission's, clamped). */
17
+ locale: string;
18
+ payload: Payload;
19
+ req?: PayloadRequest;
20
+ };
21
+ /**
22
+ * Host seam choosing the fallback locale per form (plugin option `fallbackLocale`), for hosts where
23
+ * the right fallback depends on the form's owner rather than on the config, e.g. a tenant whose own
24
+ * default locale is not the config-wide one. Runs before the plugin acts on a form server-side
25
+ * (validating a submission, running its actions, serving poll results).
26
+ */
27
+ type FormFallbackLocale = (args: FormFallbackLocaleArgs) => Promise<FormFallbackLocaleResult> | FormFallbackLocaleResult;
28
+ //#endregion
29
+ export { FormFallbackLocale, FormFallbackLocaleArgs, FormFallbackLocaleResult };
30
+ //# sourceMappingURL=findFormAtLocale.d.ts.map
@@ -0,0 +1,88 @@
1
+ import { customStateOf, stashCustomState } from "../plugin/customState.js";
2
+ import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
3
+ import { sanitizeFallbackLocale } from "payload";
4
+ //#region src/form/findFormAtLocale.ts
5
+ const stashFallbackLocale = (custom, fallbackLocale) => stashCustomState(custom, { fallbackLocale });
6
+ /**
7
+ * A host `fallbackLocale` resolver threw. Kept distinct so callers that read a failed form load as a
8
+ * deleted form (and skip quietly) let this one through instead: a transient failure in host I/O must
9
+ * fail the action run (and retry it on the queued path), never drop it.
10
+ */
11
+ var FallbackLocaleError = class extends Error {
12
+ constructor(cause) {
13
+ super(`@10x-media/form-builder: fallbackLocale resolver failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
14
+ this.name = "FallbackLocaleError";
15
+ }
16
+ };
17
+ /**
18
+ * `.catch` handler for callers that treat a form that cannot be read as missing: `null` for a read
19
+ * failure, rethrowing a `FallbackLocaleError`.
20
+ */
21
+ const missingFormOnReadError = (error) => {
22
+ if (error instanceof FallbackLocaleError) throw error;
23
+ return null;
24
+ };
25
+ /**
26
+ * Loads a form (depth 0) at `locale` for server work done on a visitor's behalf: validating a
27
+ * submission, running its actions, serving poll results. The read falls back exactly like any other
28
+ * Payload read, so with `localization.fallback: false` content the author never filled in at
29
+ * `locale` stays empty, matching what the host's own page renders.
30
+ *
31
+ * With the plugin's `fallbackLocale` resolver set, it gets the form as read and may choose another
32
+ * fallback (the way a host forces one); the form is read again only when that differs from the one
33
+ * already applied.
34
+ *
35
+ * Payload's local API writes `locale` and `fallbackLocale` onto the `req` it is handed. Both are
36
+ * restored afterwards, so a host (or job runner) request passed in comes back unchanged. The restore
37
+ * assumes one operation per `req` at a time: concurrent reads sharing a `req` (a `Promise.all` of
38
+ * creates at different locales) can interleave it, so give each its own request.
39
+ */
40
+ const findFormAtLocale = async ({ payload, id, locale, req, overrideAccess }) => {
41
+ const { localization } = payload.config;
42
+ const read = (fallbackLocale) => payload.findByID({
43
+ collection: pluginSlugsOf(payload).forms,
44
+ id,
45
+ depth: 0,
46
+ locale,
47
+ ...fallbackLocale === void 0 ? {} : { fallbackLocale },
48
+ ...overrideAccess === void 0 ? {} : { overrideAccess },
49
+ req
50
+ });
51
+ const previous = req ? {
52
+ locale: req.locale,
53
+ fallbackLocale: req.fallbackLocale
54
+ } : void 0;
55
+ try {
56
+ if (!localization) return await read(void 0);
57
+ const form = await read(void 0);
58
+ const resolver = customStateOf(payload).fallbackLocale;
59
+ if (!resolver) return form;
60
+ let chosen;
61
+ try {
62
+ chosen = await resolver({
63
+ form,
64
+ locale,
65
+ payload,
66
+ req
67
+ });
68
+ } catch (error) {
69
+ throw new FallbackLocaleError(error);
70
+ }
71
+ const applied = sanitizeFallbackLocale({
72
+ fallbackLocale: void 0,
73
+ locale,
74
+ localization
75
+ });
76
+ if (chosen === void 0 || chosen === locale || chosen === applied) return form;
77
+ return await read(chosen);
78
+ } finally {
79
+ if (req && previous) {
80
+ req.locale = previous.locale;
81
+ req.fallbackLocale = previous.fallbackLocale;
82
+ }
83
+ }
84
+ };
85
+ //#endregion
86
+ export { findFormAtLocale, missingFormOnReadError, stashFallbackLocale };
87
+
88
+ //# sourceMappingURL=findFormAtLocale.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"findFormAtLocale.js","names":[],"sources":["../../src/form/findFormAtLocale.ts"],"sourcesContent":["import {\n\ttype Payload,\n\ttype PayloadRequest,\n\tsanitizeFallbackLocale,\n\ttype TypedFallbackLocale,\n\ttype TypedLocale,\n} from 'payload'\nimport type { SubmissionForm } from '../actions/submissionContext'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport { customStateOf, stashCustomState } from '../plugin/customState'\n\n/**\n * What a `fallbackLocale` resolver returns: a locale code, an ordered list of codes, `false` for no\n * fallback, or `undefined` to keep the default.\n */\nexport type FormFallbackLocaleResult = string | string[] | false | undefined\n\nexport type FormFallbackLocaleArgs = {\n\t/**\n\t * The form as first read at `locale` with the config's own fallback, at depth 0: a non-localized\n\t * owner relationship (a multi-tenant host's `form.tenant`) is already on it, so no read of your own\n\t * is needed. Decide from non-localized fields: a localized one may be empty at `locale`.\n\t */\n\tform: SubmissionForm\n\t/** The locale the form is being read at (the submission's, clamped). */\n\tlocale: string\n\tpayload: Payload\n\treq?: PayloadRequest\n}\n\n/**\n * Host seam choosing the fallback locale per form (plugin option `fallbackLocale`), for hosts where\n * the right fallback depends on the form's owner rather than on the config, e.g. a tenant whose own\n * default locale is not the config-wide one. Runs before the plugin acts on a form server-side\n * (validating a submission, running its actions, serving poll results).\n */\nexport type FormFallbackLocale = (\n\targs: FormFallbackLocaleArgs\n) => Promise<FormFallbackLocaleResult> | FormFallbackLocaleResult\n\ntype FallbackState = { fallbackLocale?: FormFallbackLocale }\n\nexport const stashFallbackLocale = (\n\tcustom: Record<string, unknown> | undefined,\n\tfallbackLocale: FormFallbackLocale\n): Record<string, unknown> => stashCustomState<FallbackState>(custom, { fallbackLocale })\n\nexport type FindFormAtLocaleArgs = {\n\tpayload: Payload\n\tid: number | string\n\t/** A clamped locale (see `resolveSubmissionLocale`), never raw visitor input. */\n\tlocale: string\n\treq?: PayloadRequest\n\toverrideAccess?: boolean\n}\n\n/**\n * A host `fallbackLocale` resolver threw. Kept distinct so callers that read a failed form load as a\n * deleted form (and skip quietly) let this one through instead: a transient failure in host I/O must\n * fail the action run (and retry it on the queued path), never drop it.\n */\nexport class FallbackLocaleError extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(\n\t\t\t`@10x-media/form-builder: fallbackLocale resolver failed: ${\n\t\t\t\tcause instanceof Error ? cause.message : String(cause)\n\t\t\t}`,\n\t\t\t{ cause }\n\t\t)\n\t\tthis.name = 'FallbackLocaleError'\n\t}\n}\n\n/**\n * `.catch` handler for callers that treat a form that cannot be read as missing: `null` for a read\n * failure, rethrowing a `FallbackLocaleError`.\n */\nexport const missingFormOnReadError = (error: unknown): null => {\n\tif (error instanceof FallbackLocaleError) {\n\t\tthrow error\n\t}\n\treturn null\n}\n\n/**\n * Loads a form (depth 0) at `locale` for server work done on a visitor's behalf: validating a\n * submission, running its actions, serving poll results. The read falls back exactly like any other\n * Payload read, so with `localization.fallback: false` content the author never filled in at\n * `locale` stays empty, matching what the host's own page renders.\n *\n * With the plugin's `fallbackLocale` resolver set, it gets the form as read and may choose another\n * fallback (the way a host forces one); the form is read again only when that differs from the one\n * already applied.\n *\n * Payload's local API writes `locale` and `fallbackLocale` onto the `req` it is handed. Both are\n * restored afterwards, so a host (or job runner) request passed in comes back unchanged. The restore\n * assumes one operation per `req` at a time: concurrent reads sharing a `req` (a `Promise.all` of\n * creates at different locales) can interleave it, so give each its own request.\n */\nexport const findFormAtLocale = async ({\n\tpayload,\n\tid,\n\tlocale,\n\treq,\n\toverrideAccess,\n}: FindFormAtLocaleArgs) => {\n\tconst { localization } = payload.config\n\tconst read = (fallbackLocale: string | string[] | false | undefined) =>\n\t\tpayload.findByID({\n\t\t\tcollection: pluginSlugsOf(payload).forms,\n\t\t\tid,\n\t\t\tdepth: 0,\n\t\t\t// Cast: a clamped locale is one of the host's own codes, but its concrete `TypedLocale` union\n\t\t\t// is unknowable from the plugin.\n\t\t\tlocale: locale as TypedLocale,\n\t\t\t...(fallbackLocale === undefined ? {} : { fallbackLocale: fallbackLocale as TypedLocale }),\n\t\t\t...(overrideAccess === undefined ? {} : { overrideAccess }),\n\t\t\treq,\n\t\t})\n\tconst previous = req ? { locale: req.locale, fallbackLocale: req.fallbackLocale } : undefined\n\ttry {\n\t\tif (!localization) {\n\t\t\treturn await read(undefined)\n\t\t}\n\t\tconst form = await read(undefined)\n\t\tconst resolver = customStateOf<FallbackState>(payload).fallbackLocale\n\t\tif (!resolver) {\n\t\t\treturn form\n\t\t}\n\t\tlet chosen: FormFallbackLocaleResult\n\t\ttry {\n\t\t\tchosen = await resolver({\n\t\t\t\t// Double cast: a host's generated Form interface has no index signature.\n\t\t\t\tform: form as unknown as SubmissionForm,\n\t\t\t\tlocale,\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new FallbackLocaleError(error)\n\t\t}\n\t\t// Falling back to the read's own locale, or to the fallback Payload already applied (resolved by\n\t\t// Payload's own sanitizer, so the two cannot drift), changes nothing.\n\t\tconst applied = sanitizeFallbackLocale({\n\t\t\tfallbackLocale: undefined as unknown as TypedFallbackLocale,\n\t\t\tlocale,\n\t\t\tlocalization,\n\t\t})\n\t\tif (chosen === undefined || chosen === locale || chosen === applied) {\n\t\t\treturn form\n\t\t}\n\t\treturn await read(chosen)\n\t} finally {\n\t\tif (req && previous) {\n\t\t\treq.locale = previous.locale\n\t\t\treq.fallbackLocale = previous.fallbackLocale\n\t\t}\n\t}\n}\n"],"mappings":";;;;AA0CA,MAAa,uBACZ,QACA,mBAC6B,iBAAgC,QAAQ,EAAE,eAAe,CAAC;;;;;;AAgBxF,IAAa,sBAAb,cAAyC,MAAM;CAC9C,YAAY,OAAgB;EAC3B,MACC,4DACC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAEtD,EAAE,MAAM,CACT;EACA,KAAK,OAAO;CACb;AACD;;;;;AAMA,MAAa,0BAA0B,UAAyB;CAC/D,IAAI,iBAAiB,qBACpB,MAAM;CAEP,OAAO;AACR;;;;;;;;;;;;;;;;AAiBA,MAAa,mBAAmB,OAAO,EACtC,SACA,IACA,QACA,KACA,qBAC2B;CAC3B,MAAM,EAAE,iBAAiB,QAAQ;CACjC,MAAM,QAAQ,mBACb,QAAQ,SAAS;EAChB,YAAY,cAAc,OAAO,EAAE;EACnC;EACA,OAAO;EAGC;EACR,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAkB,eAA8B;EACxF,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;EACzD;CACD,CAAC;CACF,MAAM,WAAW,MAAM;EAAE,QAAQ,IAAI;EAAQ,gBAAgB,IAAI;CAAe,IAAI,KAAA;CACpF,IAAI;EACH,IAAI,CAAC,cACJ,OAAO,MAAM,KAAK,KAAA,CAAS;EAE5B,MAAM,OAAO,MAAM,KAAK,KAAA,CAAS;EACjC,MAAM,WAAW,cAA6B,OAAO,EAAE;EACvD,IAAI,CAAC,UACJ,OAAO;EAER,IAAI;EACJ,IAAI;GACH,SAAS,MAAM,SAAS;IAEjB;IACN;IACA;IACA;GACD,CAAC;EACF,SAAS,OAAO;GACf,MAAM,IAAI,oBAAoB,KAAK;EACpC;EAGA,MAAM,UAAU,uBAAuB;GACtC,gBAAgB,KAAA;GAChB;GACA;EACD,CAAC;EACD,IAAI,WAAW,KAAA,KAAa,WAAW,UAAU,WAAW,SAC3D,OAAO;EAER,OAAO,MAAM,KAAK,MAAM;CACzB,UAAU;EACT,IAAI,OAAO,UAAU;GACpB,IAAI,SAAS,SAAS;GACtB,IAAI,iBAAiB,SAAS;EAC/B;CACD;AACD"}
@@ -3,7 +3,8 @@
3
3
  type PollConfigLike = {
4
4
  resultsField?: string | null;
5
5
  resultsVisibility?: string | null;
6
- closesAt?: string | null; /** The outcome-resolution strategy slug (`poll.types` registry). Absent is treated as `manual`. */
6
+ closesAt?: string | null;
7
+ allowChange?: boolean | null; /** The outcome-resolution strategy slug (`poll.types` registry). Absent is treated as `manual`. */
7
8
  type?: string | null;
8
9
  optionSource?: string | null;
9
10
  sourceConfig?: Record<string, unknown> | null;
@@ -1 +1 @@
1
- {"version":3,"file":"pollState.js","names":[],"sources":["../../src/form/pollState.ts"],"sourcesContent":["/** Poll settings as loaded from a forms document (server) or a `FormDocument` (client). */\nexport type PollConfigLike = {\n\tresultsField?: string | null\n\tresultsVisibility?: string | null\n\tclosesAt?: string | null\n\t/** The outcome-resolution strategy slug (`poll.types` registry). Absent is treated as `manual`. */\n\ttype?: string | null\n\toptionSource?: string | null\n\tsourceConfig?: Record<string, unknown> | null\n\toutcome?: { winningValues?: (string | null)[] | null; resolvedAt?: string | null } | null\n}\n\n/** Narrow a forms document's untyped `poll` member. */\nexport const pollConfigOf = (poll: unknown): PollConfigLike | undefined =>\n\tpoll != null && typeof poll === 'object' ? (poll as PollConfigLike) : undefined\n\n/**\n * Whether the poll's `closesAt` has passed. An unset or unparseable `closesAt` never closes;\n * framework-agnostic so the server guard, the results gate, and the client `<Poll>` agree.\n */\nexport const isPollClosed = (\n\tpoll: PollConfigLike | null | undefined,\n\tnow: number = Date.now()\n): boolean => {\n\tconst closesAt = poll?.closesAt\n\tif (typeof closesAt !== 'string' || closesAt.length === 0) {\n\t\treturn false\n\t}\n\tconst ts = Date.parse(closesAt)\n\treturn Number.isFinite(ts) && ts <= now\n}\n"],"mappings":";;AAaA,MAAa,gBAAgB,SAC5B,QAAQ,QAAQ,OAAO,SAAS,WAAY,OAA0B,KAAA;;;;;AAMvE,MAAa,gBACZ,MACA,MAAc,KAAK,IAAI,MACV;CACb,MAAM,WAAW,MAAM;CACvB,IAAI,OAAO,aAAa,YAAY,SAAS,WAAW,GACvD,OAAO;CAER,MAAM,KAAK,KAAK,MAAM,QAAQ;CAC9B,OAAO,OAAO,SAAS,EAAE,KAAK,MAAM;AACrC"}
1
+ {"version":3,"file":"pollState.js","names":[],"sources":["../../src/form/pollState.ts"],"sourcesContent":["/** Poll settings as loaded from a forms document (server) or a `FormDocument` (client). */\nexport type PollConfigLike = {\n\tresultsField?: string | null\n\tresultsVisibility?: string | null\n\tclosesAt?: string | null\n\tallowChange?: boolean | null\n\t/** The outcome-resolution strategy slug (`poll.types` registry). Absent is treated as `manual`. */\n\ttype?: string | null\n\toptionSource?: string | null\n\tsourceConfig?: Record<string, unknown> | null\n\toutcome?: { winningValues?: (string | null)[] | null; resolvedAt?: string | null } | null\n}\n\n/** Narrow a forms document's untyped `poll` member. */\nexport const pollConfigOf = (poll: unknown): PollConfigLike | undefined =>\n\tpoll != null && typeof poll === 'object' ? (poll as PollConfigLike) : undefined\n\n/**\n * Whether the poll's `closesAt` has passed. An unset or unparseable `closesAt` never closes;\n * framework-agnostic so the server guard, the results gate, and the client `<Poll>` agree.\n */\nexport const isPollClosed = (\n\tpoll: PollConfigLike | null | undefined,\n\tnow: number = Date.now()\n): boolean => {\n\tconst closesAt = poll?.closesAt\n\tif (typeof closesAt !== 'string' || closesAt.length === 0) {\n\t\treturn false\n\t}\n\tconst ts = Date.parse(closesAt)\n\treturn Number.isFinite(ts) && ts <= now\n}\n"],"mappings":";;AAcA,MAAa,gBAAgB,SAC5B,QAAQ,QAAQ,OAAO,SAAS,WAAY,OAA0B,KAAA;;;;;AAMvE,MAAa,gBACZ,MACA,MAAc,KAAK,IAAI,MACV;CACb,MAAM,WAAW,MAAM;CACvB,IAAI,OAAO,aAAa,YAAY,SAAS,WAAW,GACvD,OAAO;CAER,MAAM,KAAK,KAAK,MAAM,QAAQ;CAC9B,OAAO,OAAO,SAAS,EAAE,KAAK,MAAM;AACrC"}
@@ -1,4 +1,5 @@
1
1
  import { PollOption } from "../poll/definePollOptionSource.js";
2
+ import { CalcResolved } from "../calc/evaluate.js";
2
3
  import { ConsentStatements } from "../consent/resolveConsentStatements.js";
3
4
  import { FormDocument } from "./types.js";
4
5
 
@@ -57,13 +58,17 @@ type ToFormDocumentOptions = {
57
58
  * Pure and framework-agnostic (no 'use client'): safe to call from a Server Component or any
58
59
  * other server-side code before handing the result to the client `<Form>`.
59
60
  */
60
- declare function toFormDocument(form: {
61
+ declare function toFormDocument<TField extends {
62
+ blockType: string;
63
+ name?: string | null;
64
+ }>(form: {
61
65
  id: number | string;
62
- fields?: {
63
- blockType: string;
64
- name?: string;
65
- [key: string]: unknown;
66
- }[] | null;
66
+ /**
67
+ * Generic over the row and with no index signature: a block generated with an
68
+ * `interfaceName` is an interface, which TypeScript never treats as indexable, so an index
69
+ * signature would reject every host's generated form type.
70
+ */
71
+ fields?: readonly TField[] | null;
67
72
  flow?: unknown;
68
73
  response?: {
69
74
  type?: string | null;
@@ -86,6 +91,7 @@ declare function toFormDocument(form: {
86
91
  resultsField?: string | null;
87
92
  resultsVisibility?: string | null;
88
93
  closesAt?: string | null;
94
+ allowChange?: boolean | null;
89
95
  outcome?: {
90
96
  winningValues?: (string | null)[] | null;
91
97
  } | null;
@@ -96,6 +102,12 @@ declare function toFormDocument(form: {
96
102
  * An explicit `options.consentStatements` takes precedence when both are present.
97
103
  */
98
104
  consentStatements?: ConsentStatements;
105
+ /**
106
+ * Calc source values resolved onto the doc by the plugin's forms `afterRead` hook (when calc
107
+ * sources are registered and used); passed through so the client's live preview computes with
108
+ * real values. `functions` can never ride a document, hence the Pick.
109
+ */
110
+ calcResolved?: Pick<CalcResolved, 'sources' | 'weights'>;
99
111
  }, options?: ToFormDocumentOptions): FormDocument;
100
112
  //#endregion
101
113
  export { ToFormDocumentOptions, toFormDocument };
@@ -52,6 +52,7 @@ function toFormDocument(form, options) {
52
52
  const poll = form.poll ? {
53
53
  resultsVisibility: form.poll.resultsVisibility ?? void 0,
54
54
  closesAt: form.poll.closesAt ?? void 0,
55
+ ...form.poll.allowChange === true ? { allowChange: true } : {},
55
56
  ...winningValues.length > 0 ? { outcome: { winningValues } } : {}
56
57
  } : void 0;
57
58
  let fields = form.fields ?? [];
@@ -78,7 +79,8 @@ function toFormDocument(form, options) {
78
79
  title: form.title ?? void 0,
79
80
  multistep: form.multistep === true,
80
81
  pollEnabled: form.pollEnabled === true,
81
- poll
82
+ poll,
83
+ calcResolved: form.calcResolved
82
84
  };
83
85
  }
84
86
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"toFormDocument.js","names":[],"sources":["../../src/form/toFormDocument.ts"],"sourcesContent":["import { applyConsentStatements } from '../consent/applyConsentStatements'\nimport type { ConsentStatements } from '../consent/resolveConsentStatements'\nimport type { FormFlow } from '../flow/types'\nimport { applyPollOptions } from '../poll/applyPollOptions'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport type { FormFieldInstance } from '../submissions/types'\nimport type { FormButtonSettings, FormDocument, FormResponseSettings } from './types'\n\nexport type ToFormDocumentOptions = {\n\t/**\n\t * Source-resolved poll options (from `resolvePollOptions`), injected as the options of the\n\t * field instance named by the form's `poll.resultsField` so the client renders the host's\n\t * current choices instead of hand-authored ones.\n\t */\n\tpollOptions?: PollOption[]\n\t/**\n\t * Source-resolved consent statements (from `resolveConsentStatements`), injected into the\n\t * consent field instances they name. A form stores only a source id, so without these its\n\t * consent fields render with no statement at all.\n\t */\n\tconsentStatements?: ConsentStatements\n\t/**\n\t * Resolve an internal redirect `reference` to a same-site URL. Called only when\n\t * `response.type === 'redirect'`, a `reference` is present, and no `redirect.url` is set. Keep it\n\t * sync: operate on the already-loaded (populated) reference, since resolving a Doc to a URL is host\n\t * routing knowledge the plugin cannot supply. The result is written to `redirect.url`, so `<Form>`\n\t * navigates with no client change.\n\t */\n\tresolveRedirect?: (reference: {\n\t\trelationTo: string\n\t\tvalue: number | string | object\n\t}) => string | null | undefined\n}\n\n/**\n * Reassemble the client button labels from the document's top-level `submitLabel`/`prevLabel`/\n * `nextLabel` fields, keeping only non-empty strings (mirroring the client's own `storedLabel`\n * fallback). Returns `undefined` when the author set no label, so the client uses its defaults.\n */\nconst buttonSettingsOf = (form: {\n\tsubmitLabel?: string | null\n\tprevLabel?: string | null\n\tnextLabel?: string | null\n}): FormButtonSettings | undefined => {\n\tconst label = (value: unknown): string | undefined =>\n\t\ttypeof value === 'string' && value.length > 0 ? value : undefined\n\tconst settings: FormButtonSettings = {}\n\tconst submitLabel = label(form.submitLabel)\n\tconst prevLabel = label(form.prevLabel)\n\tconst nextLabel = label(form.nextLabel)\n\tif (submitLabel !== undefined) settings.submitLabel = submitLabel\n\tif (prevLabel !== undefined) settings.prevLabel = prevLabel\n\tif (nextLabel !== undefined) settings.nextLabel = nextLabel\n\treturn Object.keys(settings).length > 0 ? settings : undefined\n}\n\n/**\n * Narrows a Payload-generated form document (from `getPayload().findByID()` or `fetch`) to\n * `FormDocument` without an unsafe `as` cast. Handles the small structural mismatches between\n * the auto-generated collection types and what `<Form>` expects:\n * - `fields` may be a typed blocks-union array or null; normalized to `FormFieldInstance[]`\n * (nameless bare rows, e.g. message blocks, pass through with their row `id` intact)\n * - `flow` is stored as opaque JSON; typed as `FormFlow | undefined`\n * - `response` may be null; coerced to `undefined`, otherwise passed through wholesale, which\n * includes `response.redirect.reference` (present only when the plugin's `redirectRelationships`\n * option is set): `value` may be a bare id (`depth: 0`) or a populated document, and the host\n * resolves it to a URL either by writing `redirect.url` or by passing `options.resolveRedirect`\n * - the button labels (`submitLabel`/`prevLabel`/`nextLabel`) live at the document root now (there\n * is no `buttons` group); the non-empty ones are reassembled into `FormDocument.buttons`\n * - `title` may be null; coerced to `undefined`\n * - `multistep`/`pollEnabled` are the two top-level form-type flags, coerced to strict booleans\n * - `poll` may be null; coerced to `undefined` (`resultsField`, `optionSource`, and\n * `sourceConfig` are dropped: server-side only; `outcome` passes through `winningValues` only)\n *\n * Unknown keys survive on `response` but not on `poll`, which is deliberate rather than incidental.\n * `response` is a visitor-facing group a host is meant to extend (`overrides.forms.fields`) and read\n * back off `FormDocument` in custom chrome, so it is cast wholesale. `poll` is plugin-owned config\n * that is split between\n * client-safe lifecycle state and server-only members, so it is rebuilt from an allowlist: a\n * passthrough would ship whatever a host put in `sourceConfig` (domain config, ids, credentials)\n * to every anonymous visitor. Adding a client-visible poll member means naming it here.\n *\n * Pure and framework-agnostic (no 'use client'): safe to call from a Server Component or any\n * other server-side code before handing the result to the client `<Form>`.\n */\nexport function toFormDocument(\n\tform: {\n\t\tid: number | string\n\t\tfields?: { blockType: string; name?: string; [key: string]: unknown }[] | null\n\t\tflow?: unknown\n\t\tresponse?: {\n\t\t\ttype?: string | null\n\t\t\tmessage?: unknown\n\t\t\tredirect?: {\n\t\t\t\turl?: string | null\n\t\t\t\treference?: { relationTo?: string | null; value?: number | string | object | null } | null\n\t\t\t} | null\n\t\t} | null\n\t\tsubmitLabel?: string | null\n\t\tprevLabel?: string | null\n\t\tnextLabel?: string | null\n\t\ttitle?: string | null\n\t\tmultistep?: boolean | null\n\t\tpollEnabled?: boolean | null\n\t\tpoll?: {\n\t\t\tresultsField?: string | null\n\t\t\tresultsVisibility?: string | null\n\t\t\tclosesAt?: string | null\n\t\t\toutcome?: { winningValues?: (string | null)[] | null } | null\n\t\t} | null\n\t\t/**\n\t\t * Consent statements resolved onto the doc by the plugin's forms `afterRead` hook (when\n\t\t * `consent.sources` is set), so consent renders on any fetch path (modal/client, not just RSC).\n\t\t * An explicit `options.consentStatements` takes precedence when both are present.\n\t\t */\n\t\tconsentStatements?: ConsentStatements\n\t},\n\toptions?: ToFormDocumentOptions\n): FormDocument {\n\tconst rawWinningValues = form.poll?.outcome?.winningValues\n\tconst winningValues = Array.isArray(rawWinningValues)\n\t\t? rawWinningValues.filter(\n\t\t\t\t(value): value is string => typeof value === 'string' && value.length > 0\n\t\t\t)\n\t\t: []\n\tconst poll = form.poll\n\t\t? {\n\t\t\t\tresultsVisibility: (form.poll.resultsVisibility ?? undefined) as\n\t\t\t\t\t| 'afterVote'\n\t\t\t\t\t| 'afterClose'\n\t\t\t\t\t| undefined,\n\t\t\t\tclosesAt: form.poll.closesAt ?? undefined,\n\t\t\t\t...(winningValues.length > 0 ? { outcome: { winningValues } } : {}),\n\t\t\t}\n\t\t: undefined\n\tlet fields = (form.fields ?? []) as FormFieldInstance[]\n\tif (options?.pollOptions) {\n\t\tfields = applyPollOptions(fields, form.poll?.resultsField, options.pollOptions)\n\t}\n\tconst consentStatements = options?.consentStatements ?? form.consentStatements\n\tif (consentStatements) {\n\t\tfields = applyConsentStatements(fields, consentStatements)\n\t}\n\tlet response = (form.response as FormResponseSettings | null | undefined) ?? undefined\n\t// A host that passes `resolveRedirect` gets internal references turned into `redirect.url` (all\n\t// `<Form>` navigates by), but only when the author set no explicit url. Non-mutating: clone the group.\n\tif (\n\t\toptions?.resolveRedirect &&\n\t\tresponse?.type === 'redirect' &&\n\t\tresponse.redirect?.reference &&\n\t\t!response.redirect.url\n\t) {\n\t\tconst url = options.resolveRedirect(response.redirect.reference)\n\t\tif (url) {\n\t\t\tresponse = { ...response, redirect: { ...response.redirect, url } }\n\t\t}\n\t}\n\treturn {\n\t\tid: form.id,\n\t\tfields,\n\t\tflow: form.flow as FormFlow | undefined,\n\t\tresponse,\n\t\tbuttons: buttonSettingsOf(form),\n\t\ttitle: form.title ?? undefined,\n\t\tmultistep: form.multistep === true,\n\t\tpollEnabled: form.pollEnabled === true,\n\t\tpoll,\n\t}\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,oBAAoB,SAIY;CACrC,MAAM,SAAS,UACd,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;CACzD,MAAM,WAA+B,CAAC;CACtC,MAAM,cAAc,MAAM,KAAK,WAAW;CAC1C,MAAM,YAAY,MAAM,KAAK,SAAS;CACtC,MAAM,YAAY,MAAM,KAAK,SAAS;CACtC,IAAI,gBAAgB,KAAA,GAAW,SAAS,cAAc;CACtD,IAAI,cAAc,KAAA,GAAW,SAAS,YAAY;CAClD,IAAI,cAAc,KAAA,GAAW,SAAS,YAAY;CAClD,OAAO,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,WAAW,KAAA;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACf,MA+BA,SACe;CACf,MAAM,mBAAmB,KAAK,MAAM,SAAS;CAC7C,MAAM,gBAAgB,MAAM,QAAQ,gBAAgB,IACjD,iBAAiB,QAChB,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CACzE,IACC,CAAC;CACJ,MAAM,OAAO,KAAK,OACf;EACA,mBAAoB,KAAK,KAAK,qBAAqB,KAAA;EAInD,UAAU,KAAK,KAAK,YAAY,KAAA;EAChC,GAAI,cAAc,SAAS,IAAI,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,CAAC;CAClE,IACC,KAAA;CACH,IAAI,SAAU,KAAK,UAAU,CAAC;CAC9B,IAAI,SAAS,aACZ,SAAS,iBAAiB,QAAQ,KAAK,MAAM,cAAc,QAAQ,WAAW;CAE/E,MAAM,oBAAoB,SAAS,qBAAqB,KAAK;CAC7D,IAAI,mBACH,SAAS,uBAAuB,QAAQ,iBAAiB;CAE1D,IAAI,WAAY,KAAK,YAAwD,KAAA;CAG7E,IACC,SAAS,mBACT,UAAU,SAAS,cACnB,SAAS,UAAU,aACnB,CAAC,SAAS,SAAS,KAClB;EACD,MAAM,MAAM,QAAQ,gBAAgB,SAAS,SAAS,SAAS;EAC/D,IAAI,KACH,WAAW;GAAE,GAAG;GAAU,UAAU;IAAE,GAAG,SAAS;IAAU;GAAI;EAAE;CAEpE;CACA,OAAO;EACN,IAAI,KAAK;EACT;EACA,MAAM,KAAK;EACX;EACA,SAAS,iBAAiB,IAAI;EAC9B,OAAO,KAAK,SAAS,KAAA;EACrB,WAAW,KAAK,cAAc;EAC9B,aAAa,KAAK,gBAAgB;EAClC;CACD;AACD"}
1
+ {"version":3,"file":"toFormDocument.js","names":[],"sources":["../../src/form/toFormDocument.ts"],"sourcesContent":["import type { CalcResolved } from '../calc/evaluate'\nimport { applyConsentStatements } from '../consent/applyConsentStatements'\nimport type { ConsentStatements } from '../consent/resolveConsentStatements'\nimport type { FormFlow } from '../flow/types'\nimport { applyPollOptions } from '../poll/applyPollOptions'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport type { FormFieldInstance } from '../submissions/types'\nimport type { FormButtonSettings, FormDocument, FormResponseSettings } from './types'\n\nexport type ToFormDocumentOptions = {\n\t/**\n\t * Source-resolved poll options (from `resolvePollOptions`), injected as the options of the\n\t * field instance named by the form's `poll.resultsField` so the client renders the host's\n\t * current choices instead of hand-authored ones.\n\t */\n\tpollOptions?: PollOption[]\n\t/**\n\t * Source-resolved consent statements (from `resolveConsentStatements`), injected into the\n\t * consent field instances they name. A form stores only a source id, so without these its\n\t * consent fields render with no statement at all.\n\t */\n\tconsentStatements?: ConsentStatements\n\t/**\n\t * Resolve an internal redirect `reference` to a same-site URL. Called only when\n\t * `response.type === 'redirect'`, a `reference` is present, and no `redirect.url` is set. Keep it\n\t * sync: operate on the already-loaded (populated) reference, since resolving a Doc to a URL is host\n\t * routing knowledge the plugin cannot supply. The result is written to `redirect.url`, so `<Form>`\n\t * navigates with no client change.\n\t */\n\tresolveRedirect?: (reference: {\n\t\trelationTo: string\n\t\tvalue: number | string | object\n\t}) => string | null | undefined\n}\n\n/**\n * Reassemble the client button labels from the document's top-level `submitLabel`/`prevLabel`/\n * `nextLabel` fields, keeping only non-empty strings (mirroring the client's own `storedLabel`\n * fallback). Returns `undefined` when the author set no label, so the client uses its defaults.\n */\nconst buttonSettingsOf = (form: {\n\tsubmitLabel?: string | null\n\tprevLabel?: string | null\n\tnextLabel?: string | null\n}): FormButtonSettings | undefined => {\n\tconst label = (value: unknown): string | undefined =>\n\t\ttypeof value === 'string' && value.length > 0 ? value : undefined\n\tconst settings: FormButtonSettings = {}\n\tconst submitLabel = label(form.submitLabel)\n\tconst prevLabel = label(form.prevLabel)\n\tconst nextLabel = label(form.nextLabel)\n\tif (submitLabel !== undefined) settings.submitLabel = submitLabel\n\tif (prevLabel !== undefined) settings.prevLabel = prevLabel\n\tif (nextLabel !== undefined) settings.nextLabel = nextLabel\n\treturn Object.keys(settings).length > 0 ? settings : undefined\n}\n\n/**\n * Narrows a Payload-generated form document (from `getPayload().findByID()` or `fetch`) to\n * `FormDocument` without an unsafe `as` cast. Handles the small structural mismatches between\n * the auto-generated collection types and what `<Form>` expects:\n * - `fields` may be a typed blocks-union array or null; normalized to `FormFieldInstance[]`\n * (nameless bare rows, e.g. message blocks, pass through with their row `id` intact)\n * - `flow` is stored as opaque JSON; typed as `FormFlow | undefined`\n * - `response` may be null; coerced to `undefined`, otherwise passed through wholesale, which\n * includes `response.redirect.reference` (present only when the plugin's `redirectRelationships`\n * option is set): `value` may be a bare id (`depth: 0`) or a populated document, and the host\n * resolves it to a URL either by writing `redirect.url` or by passing `options.resolveRedirect`\n * - the button labels (`submitLabel`/`prevLabel`/`nextLabel`) live at the document root now (there\n * is no `buttons` group); the non-empty ones are reassembled into `FormDocument.buttons`\n * - `title` may be null; coerced to `undefined`\n * - `multistep`/`pollEnabled` are the two top-level form-type flags, coerced to strict booleans\n * - `poll` may be null; coerced to `undefined` (`resultsField`, `optionSource`, and\n * `sourceConfig` are dropped: server-side only; `outcome` passes through `winningValues` only)\n *\n * Unknown keys survive on `response` but not on `poll`, which is deliberate rather than incidental.\n * `response` is a visitor-facing group a host is meant to extend (`overrides.forms.fields`) and read\n * back off `FormDocument` in custom chrome, so it is cast wholesale. `poll` is plugin-owned config\n * that is split between\n * client-safe lifecycle state and server-only members, so it is rebuilt from an allowlist: a\n * passthrough would ship whatever a host put in `sourceConfig` (domain config, ids, credentials)\n * to every anonymous visitor. Adding a client-visible poll member means naming it here.\n *\n * Pure and framework-agnostic (no 'use client'): safe to call from a Server Component or any\n * other server-side code before handing the result to the client `<Form>`.\n */\nexport function toFormDocument<TField extends { blockType: string; name?: string | null }>(\n\tform: {\n\t\tid: number | string\n\t\t/**\n\t\t * Generic over the row and with no index signature: a block generated with an\n\t\t * `interfaceName` is an interface, which TypeScript never treats as indexable, so an index\n\t\t * signature would reject every host's generated form type.\n\t\t */\n\t\tfields?: readonly TField[] | null\n\t\tflow?: unknown\n\t\tresponse?: {\n\t\t\ttype?: string | null\n\t\t\tmessage?: unknown\n\t\t\tredirect?: {\n\t\t\t\turl?: string | null\n\t\t\t\treference?: { relationTo?: string | null; value?: number | string | object | null } | null\n\t\t\t} | null\n\t\t} | null\n\t\tsubmitLabel?: string | null\n\t\tprevLabel?: string | null\n\t\tnextLabel?: string | null\n\t\ttitle?: string | null\n\t\tmultistep?: boolean | null\n\t\tpollEnabled?: boolean | null\n\t\tpoll?: {\n\t\t\tresultsField?: string | null\n\t\t\tresultsVisibility?: string | null\n\t\t\tclosesAt?: string | null\n\t\t\tallowChange?: boolean | null\n\t\t\toutcome?: { winningValues?: (string | null)[] | null } | null\n\t\t} | null\n\t\t/**\n\t\t * Consent statements resolved onto the doc by the plugin's forms `afterRead` hook (when\n\t\t * `consent.sources` is set), so consent renders on any fetch path (modal/client, not just RSC).\n\t\t * An explicit `options.consentStatements` takes precedence when both are present.\n\t\t */\n\t\tconsentStatements?: ConsentStatements\n\t\t/**\n\t\t * Calc source values resolved onto the doc by the plugin's forms `afterRead` hook (when calc\n\t\t * sources are registered and used); passed through so the client's live preview computes with\n\t\t * real values. `functions` can never ride a document, hence the Pick.\n\t\t */\n\t\tcalcResolved?: Pick<CalcResolved, 'sources' | 'weights'>\n\t},\n\toptions?: ToFormDocumentOptions\n): FormDocument {\n\tconst rawWinningValues = form.poll?.outcome?.winningValues\n\tconst winningValues = Array.isArray(rawWinningValues)\n\t\t? rawWinningValues.filter(\n\t\t\t\t(value): value is string => typeof value === 'string' && value.length > 0\n\t\t\t)\n\t\t: []\n\tconst poll = form.poll\n\t\t? {\n\t\t\t\tresultsVisibility: (form.poll.resultsVisibility ?? undefined) as\n\t\t\t\t\t| 'afterVote'\n\t\t\t\t\t| 'afterClose'\n\t\t\t\t\t| undefined,\n\t\t\t\tclosesAt: form.poll.closesAt ?? undefined,\n\t\t\t\t...(form.poll.allowChange === true ? { allowChange: true } : {}),\n\t\t\t\t...(winningValues.length > 0 ? { outcome: { winningValues } } : {}),\n\t\t\t}\n\t\t: undefined\n\tlet fields = (form.fields ?? []) as unknown as FormFieldInstance[]\n\tif (options?.pollOptions) {\n\t\tfields = applyPollOptions(fields, form.poll?.resultsField, options.pollOptions)\n\t}\n\tconst consentStatements = options?.consentStatements ?? form.consentStatements\n\tif (consentStatements) {\n\t\tfields = applyConsentStatements(fields, consentStatements)\n\t}\n\tlet response = (form.response as FormResponseSettings | null | undefined) ?? undefined\n\t// A host that passes `resolveRedirect` gets internal references turned into `redirect.url` (all\n\t// `<Form>` navigates by), but only when the author set no explicit url. Non-mutating: clone the group.\n\tif (\n\t\toptions?.resolveRedirect &&\n\t\tresponse?.type === 'redirect' &&\n\t\tresponse.redirect?.reference &&\n\t\t!response.redirect.url\n\t) {\n\t\tconst url = options.resolveRedirect(response.redirect.reference)\n\t\tif (url) {\n\t\t\tresponse = { ...response, redirect: { ...response.redirect, url } }\n\t\t}\n\t}\n\treturn {\n\t\tid: form.id,\n\t\tfields,\n\t\tflow: form.flow as FormFlow | undefined,\n\t\tresponse,\n\t\tbuttons: buttonSettingsOf(form),\n\t\ttitle: form.title ?? undefined,\n\t\tmultistep: form.multistep === true,\n\t\tpollEnabled: form.pollEnabled === true,\n\t\tpoll,\n\t\tcalcResolved: form.calcResolved,\n\t}\n}\n"],"mappings":";;;;;;;;AAwCA,MAAM,oBAAoB,SAIY;CACrC,MAAM,SAAS,UACd,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;CACzD,MAAM,WAA+B,CAAC;CACtC,MAAM,cAAc,MAAM,KAAK,WAAW;CAC1C,MAAM,YAAY,MAAM,KAAK,SAAS;CACtC,MAAM,YAAY,MAAM,KAAK,SAAS;CACtC,IAAI,gBAAgB,KAAA,GAAW,SAAS,cAAc;CACtD,IAAI,cAAc,KAAA,GAAW,SAAS,YAAY;CAClD,IAAI,cAAc,KAAA,GAAW,SAAS,YAAY;CAClD,OAAO,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,WAAW,KAAA;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACf,MA2CA,SACe;CACf,MAAM,mBAAmB,KAAK,MAAM,SAAS;CAC7C,MAAM,gBAAgB,MAAM,QAAQ,gBAAgB,IACjD,iBAAiB,QAChB,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CACzE,IACC,CAAC;CACJ,MAAM,OAAO,KAAK,OACf;EACA,mBAAoB,KAAK,KAAK,qBAAqB,KAAA;EAInD,UAAU,KAAK,KAAK,YAAY,KAAA;EAChC,GAAI,KAAK,KAAK,gBAAgB,OAAO,EAAE,aAAa,KAAK,IAAI,CAAC;EAC9D,GAAI,cAAc,SAAS,IAAI,EAAE,SAAS,EAAE,cAAc,EAAE,IAAI,CAAC;CAClE,IACC,KAAA;CACH,IAAI,SAAU,KAAK,UAAU,CAAC;CAC9B,IAAI,SAAS,aACZ,SAAS,iBAAiB,QAAQ,KAAK,MAAM,cAAc,QAAQ,WAAW;CAE/E,MAAM,oBAAoB,SAAS,qBAAqB,KAAK;CAC7D,IAAI,mBACH,SAAS,uBAAuB,QAAQ,iBAAiB;CAE1D,IAAI,WAAY,KAAK,YAAwD,KAAA;CAG7E,IACC,SAAS,mBACT,UAAU,SAAS,cACnB,SAAS,UAAU,aACnB,CAAC,SAAS,SAAS,KAClB;EACD,MAAM,MAAM,QAAQ,gBAAgB,SAAS,SAAS,SAAS;EAC/D,IAAI,KACH,WAAW;GAAE,GAAG;GAAU,UAAU;IAAE,GAAG,SAAS;IAAU;GAAI;EAAE;CAEpE;CACA,OAAO;EACN,IAAI,KAAK;EACT;EACA,MAAM,KAAK;EACX;EACA,SAAS,iBAAiB,IAAI;EAC9B,OAAO,KAAK,SAAS,KAAA;EACrB,WAAW,KAAK,cAAc;EAC9B,aAAa,KAAK,gBAAgB;EAClC;EACA,cAAc,KAAK;CACpB;AACD"}
@@ -1,4 +1,5 @@
1
1
  import { FormFieldInstance } from "../submissions/types.js";
2
+ import { CalcResolved } from "../calc/evaluate.js";
2
3
  import { FormFlow } from "../flow/types.js";
3
4
 
4
5
  //#region src/form/types.d.ts
@@ -39,7 +40,8 @@ type FormButtonSettings = {
39
40
  */
40
41
  type FormPollSettings = {
41
42
  /** When anonymous callers may read aggregate results. Default 'afterVote'. */resultsVisibility?: 'afterVote' | 'afterClose' | null; /** ISO date after which submissions are rejected and the poll renders as closed. */
42
- closesAt?: string | null; /** Present once the host recorded a final outcome via `resolvePollOutcome`; `<Poll>` renders the final state. A tie carries more than one value. */
43
+ closesAt?: string | null; /** Whether a voter may change their vote while the poll is open (`poll.allowChange`). Present only when enabled. */
44
+ allowChange?: boolean; /** Present once the host recorded a final outcome via `resolvePollOutcome`; `<Poll>` renders the final state. A tie carries more than one value. */
43
45
  outcome?: {
44
46
  winningValues?: string[];
45
47
  };
@@ -59,6 +61,12 @@ type FormDocument = {
59
61
  multistep: boolean; /** Whether this form is a poll. Gates poll rendering and results; the poll config lives under `poll`. */
60
62
  pollEnabled: boolean;
61
63
  poll?: FormPollSettings;
64
+ /**
65
+ * Server-resolved calc source values, stamped by the plugin's forms afterRead hook when calc
66
+ * sources are registered and the form's expressions use them. Only `sources`/`weights` can ride
67
+ * the document, hence the Pick (`functions` cannot serialize; the client supplies those itself).
68
+ */
69
+ calcResolved?: Pick<CalcResolved, 'sources' | 'weights'>;
62
70
  };
63
71
  //#endregion
64
72
  export { FormButtonSettings, FormDocument, FormPollSettings, FormResponseSettings };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,18 @@
1
+ import { CalcExpression } from "./calc/types.js";
1
2
  import { AnyPollOptionSource, PollOption, PollOptionResolveArgs, PollOptionSource, definePollOptionSource } from "./poll/definePollOptionSource.js";
2
3
  import { FileFieldConfig, FileRef, FileRefError } from "./uploads/types.js";
3
4
  import { AnyFormFieldDefinition, FormFieldDefinition, FormFieldFormat, FormFieldValidate, FormFieldValueKind, OmittableSharedField, ResolveFieldOptionsArgs } from "./fields/types.js";
5
+ import { CalcAllowed, normalizeCalc } from "./calc/normalizeCalc.js";
4
6
  import { BodyConverter, BodyConverterArgs, BodyRender, defaultBodyConverters, sanitizeUrl } from "./actions/body/converters.js";
7
+ import { FormContextReference, signFormContext, verifyFormContext } from "./context/formContext.js";
8
+ import { SubmissionContextArgs, SubmissionForm } from "./actions/submissionContext.js";
5
9
  import { BodyContext, RichTextBodyOption, SerializeBodyArgs, serializeBody } from "./actions/body/serializeBody.js";
6
10
  import { textOfBody } from "./actions/body/textOfBody.js";
7
11
  import { AggregationBucket, AggregationRow, FieldAggregation, FieldMeta, SubmissionStatusFilter } from "./aggregation/types.js";
8
- import { CalcExpression } from "./calc/types.js";
12
+ import { CalcResolved, calcWeightKey, evaluateCalc } from "./calc/evaluate.js";
9
13
  import { calcExpressionOf, computeCalcFields } from "./calc/computeCalcFields.js";
10
- import { evaluateCalc } from "./calc/evaluate.js";
14
+ import { formatCalc } from "./calc/formatCalc.js";
15
+ import { CalcDisplayConfig, formatCalcValue } from "./calc/formatCalcValue.js";
11
16
  import { evaluateCondition } from "./conditions/evaluate.js";
12
17
  import { ConsentSourceEntry, ConsentSourcePage, ConsentSourcesResolver } from "./consent/types.js";
13
18
  import { ConsentStatement, ConsentStatements, ResolveConsentStatementsArgs, resolveConsentStatements } from "./consent/resolveConsentStatements.js";
@@ -16,9 +21,11 @@ import { FormButtonSettings, FormDocument, FormPollSettings, FormResponseSetting
16
21
  import { ToFormDocumentOptions, toFormDocument } from "./form/toFormDocument.js";
17
22
  import { FieldTypeOption, FieldTypeRegistry, FieldTypesConfig } from "./fields/registry.js";
18
23
  import { PrefillOptions, valuesFromSearchParams } from "./prefill/valuesFromSearchParams.js";
24
+ import { DEFAULT_COLLECTION_SLUGS, DEFAULT_VOTED_COOKIE_PREFIX, FormBuilderCollectionSlugs, collectionSlugsOf } from "./plugin/collectionSlugs.js";
19
25
  import { AnyValidationRuleDefinition, ValidationRuleDefinition, ValidationRuleResult } from "./validation/types.js";
20
26
  import { PresentationDensity, PresentationDescriptor, PresentationSurface } from "./presentations/types.js";
21
27
  import { RecallResolver, buildRecallResolver, optionLabelsFor } from "./recall/resolver.js";
28
+ import { VotedSubmission, resolveVotedSubmission } from "./submissions/resolveVotedSubmission.js";
22
29
  import { interpolate } from "./recall/interpolate.js";
23
30
  import { CAPTCHA_TOKEN_KEY, DEFAULT_HONEYPOT_FIELD } from "./spam/constants.js";
24
31
  import { formatBytes } from "./uploads/formatBytes.js";
@@ -28,8 +35,9 @@ import { ResolveEffectivePollOptionsArgs, resolveEffectivePollOptions } from "./
28
35
  import { ResolvePollOptionsArgs, resolvePollOptions } from "./poll/resolvePollOptions.js";
29
36
  import { ResolvePollOutcomeArgs, resolvePollOutcome } from "./poll/resolvePollOutcome.js";
30
37
  import { hasVotedCookie, votedCookieName } from "./submissions/votedCookie.js";
31
- import { ActionDefinition, ActionRunArgs, AnyActionDefinition, defineAction } from "./actions/defineAction.js";
32
- import { FromAddressOption, FromAddressesResolver } from "./actions/fromAddresses.js";
38
+ import { ActionDefinition, ActionError, ActionRunArgs, ActionValidateArgs, AnyActionDefinition, defineAction } from "./actions/defineAction.js";
39
+ import { RecipientResolveArgs, RecipientSource, RecipientSourceRegistry } from "./actions/recipientSources.js";
40
+ import { FromAddressOption, FromAddressSource, FromAddressSourceRegistry, FromAddressesResolver } from "./actions/fromAddresses.js";
33
41
  import { ActionOption, ActionRegistry, ActionsConfig, resolveActions } from "./actions/registry.js";
34
42
  import { ActionResult } from "./actions/runActions.js";
35
43
  import { AggregateFieldResponsesArgs, AggregateFormResponsesArgs, aggregateFieldResponses, aggregateFormResponses, fieldHasOptions } from "./aggregation/aggregateResponses.js";
@@ -42,7 +50,11 @@ import { ResolveConsentEntriesArgs, resolveConsentEntries } from "./consent/reso
42
50
  import { ConsentSourceOption, ResolveConsentSourcesRequestArgs, ResolveConsentSourcesRequestResult, resolveConsentSourcesRequest } from "./consent/resolveConsentSourcesRequest.js";
43
51
  import { ResolvePublishedVersionRefArgs, resolvePublishedVersionRef } from "./consent/resolvePublishedVersionRef.js";
44
52
  import { DepartmentEmailsResolver, DepartmentOption, ResolveDepartmentOptionsArgs, ResolveDepartmentsRequestArgs, ResolveDepartmentsRequestResult, resolveDepartmentOptions } from "./email/departments.js";
53
+ import { EmailActionType, EmailRender, EmailRenderArgs } from "./actions/emailRender.js";
54
+ import { CalcFunction, CalcSource, CalcSourceResolveArgs, CalcWeightResolveArgs, defineCalcFunction, defineCalcSource } from "./calc/registry.js";
45
55
  import { RedirectFieldsOverride, RedirectOption, ResponseOption } from "./collections/redirectFields.js";
56
+ import { DefaultSettingsFields, SettingsFieldsOverride, SettingsOption, buildDefaultSettingsFields } from "./collections/settingsFields.js";
57
+ import { FormFallbackLocale, FormFallbackLocaleArgs, FormFallbackLocaleResult } from "./form/findFormAtLocale.js";
46
58
  import { CaptchaProvider, CaptchaVerifyArgs, IdentifyFn, RateLimitCheckArgs, RateLimitConfig, RateLimitResult, RateLimiter, SpamConfig, SpamMetadataConfig, SpamOption } from "./spam/types.js";
47
59
  import { UploadsOption } from "./plugin/uploadsCollection.js";
48
60
  import { DefaultOutcomeFields, OutcomeFieldsOverride, buildDefaultOutcomeFields, buildResolvedAtField, buildWinningValuesField } from "./poll/outcomeFields.js";
@@ -53,9 +65,10 @@ import { FormBuilderPluginOptions } from "./options.js";
53
65
  import { escapeHtml } from "./actions/body/escapeHtml.js";
54
66
  import { renderAllValues, renderAllValuesTable } from "./actions/body/wildcards.js";
55
67
  import { buildDefaultActionDefinitions, defaultActionDefinitions } from "./actions/builtin/index.js";
68
+ import { INLINE_DISPATCH_DEADLINE_MS } from "./actions/dispatch.js";
56
69
  import { SIGNATURE_HEADER, signPayload } from "./actions/sign.js";
57
70
  import { aggregateRowForField, aggregateRowsForFields } from "./aggregation/aggregateRows.js";
58
- import { normalizeCalc } from "./calc/normalizeCalc.js";
71
+ import { ResolveCalcContextArgs, calcUsesSources, resolveCalcContext } from "./calc/resolveCalcContext.js";
59
72
  import { applyConsentStatements } from "./consent/applyConsentStatements.js";
60
73
  import { DepartmentsFieldOptions, departmentsField } from "./email/departmentsField.js";
61
74
  import { buildDefaultFieldDefinitions, defaultFieldDefinitions, defaultFieldDefinitionsByType } from "./fields/builtin/index.js";
@@ -66,6 +79,9 @@ import { defineFormField } from "./fields/defineFormField.js";
66
79
  import { localizedIf } from "./fields/localizedIf.js";
67
80
  import { POLL_CLOSE_TASK_SLUG, PollCloseTaskInput, buildPollCloseTask, enqueuePollClose, registerPollCloseTask, runPollClose, shouldAutoResolvePoll } from "./poll/closeJob.js";
68
81
  import { mostVotedStrategy, topBucketValues } from "./poll/mostVoted.js";
82
+ import { aggregateFromVotes } from "./poll/votes/aggregateFromVotes.js";
83
+ import { recountPollVotes } from "./poll/votes/recountPollVotes.js";
84
+ import { POLL_VOTES_SLUG, RESPONDENTS_VALUE, VOTE_SHARDS } from "./poll/votes/votesCollection.js";
69
85
  import { DEFAULT_PRESENTATION_NAME, defaultPresentationDescriptors } from "./presentations/defaults.js";
70
86
  import { defineCaptchaProvider } from "./spam/captcha.js";
71
87
  import { defaultIdentify } from "./spam/identify.js";
@@ -80,9 +96,15 @@ import { captureFileRef } from "./uploads/captureFileRef.js";
80
96
  import { defaultValidationRules, defaultValidationRulesByType } from "./validation/builtin/index.js";
81
97
  import { defineValidationRule } from "./validation/defineValidationRule.js";
82
98
  import { FieldTargetParamOptions, fieldTargetParam } from "./validation/fieldTargetParam.js";
99
+ import { Plugin } from "payload";
83
100
 
84
101
  //#region src/index.d.ts
85
- declare const formBuilder: (options: FormBuilderPluginOptions) => import("payload").Plugin;
102
+ /**
103
+ * Form builder plugin for Payload: forms, submissions and their actions.
104
+ * Runs at `options.order` (default `50`), so a plugin that wraps every
105
+ * collection already in the config sets a higher order of its own.
106
+ */
107
+ declare const formBuilder: (options?: FormBuilderPluginOptions) => Plugin;
86
108
  //#endregion
87
- export { type ActionDefinition, type ActionOption, type ActionRegistry, type ActionResult, type ActionRunArgs, type ActionsConfig, type AggregateFieldResponsesArgs, type AggregateFormResponsesArgs, type AggregationBucket, type AggregationRow, type AnyActionDefinition, type AnyFormFieldDefinition, type AnyPollOptionSource, type AnyValidationRuleDefinition, type BodyContext, type BodyConverter, type BodyConverterArgs, type BodyRender, type ButtonFieldsOverride, type ButtonsOption, CAPTCHA_TOKEN_KEY, type CalcExpression, type CaptchaProvider, type CaptchaVerifyArgs, type ConsentProof, type ConsentSnapshotMode, type ConsentSourceEntry, type ConsentSourceOption, type ConsentSourcePage, type ConsentSourcesFieldOptions, type ConsentSourcesResolver, type ConsentStatement, type ConsentStatements, type CreateSubmissionArgs, type CreatedSubmission, DEFAULT_HONEYPOT_FIELD, DEFAULT_PRESENTATION_NAME, type DefaultButtonFields, type DefaultOutcomeFields, type DepartmentEmailsResolver, type DepartmentOption, type DepartmentsFieldOptions, type FieldAggregation, type FieldCondition, type FieldMeta, type FieldTargetParamOptions, type FieldTypeOption, type FieldTypeRegistry, type FieldTypesConfig, type FileFieldConfig, type FileRef, type FileRefError, type FormBuilderPluginOptions, type FormButtonSettings, type FormDocument, type FormFieldDefinition, type FormFieldFormat, type FormFieldValidate, type FormFieldValueKind, type FormPollSettings, type FormResponseSettings, type FormResultsAccess, type FormResultsAccessArgs, type FromAddressOption, type FromAddressesResolver, type HcaptchaProviderOptions, type IdentifyFn, type OmittableSharedField, type OutcomeFieldsOverride, POLL_CLOSE_TASK_SLUG, type FormBuilderPluginOptions as PluginOptions, type PollCloseTaskInput, type PollOption, type PollOptionResolveArgs, type PollOptionSource, type PollOptionSourceOption, type PollOptionSourceRegistry, type PollOptionSourcesConfig, type PollOutcomeStrategy, type PollOutcomeStrategyArgs, type PollTypeRegistry, type PollTypesConfig, type PrefillOptions, type PresentationDensity, type PresentationDescriptor, type PresentationSurface, type RateLimitCheckArgs, type RateLimitConfig, type RateLimitResult, type RateLimiter, type RecallResolver, type RecaptchaProviderOptions, type RedirectFieldsOverride, type RedirectOption, type ResolveConsentEntriesArgs, type ResolveConsentSourcesRequestArgs, type ResolveConsentSourcesRequestResult, type ResolveConsentStatementsArgs, type ResolveDepartmentOptionsArgs, type ResolveDepartmentsRequestArgs, type ResolveDepartmentsRequestResult, type ResolveEffectivePollOptionsArgs, type ResolveFieldOptionsArgs, type ResolvePollOptionsArgs, type ResolvePollOutcomeArgs, type ResolvePublishedVersionRefArgs, type ResolveResultsRequestArgs, type ResolveResultsRequestResult, type ResponseOption, type RichTextBodyOption, SIGNATURE_HEADER, type SerializeBodyArgs, type SpamConfig, type SpamMetadataConfig, type SpamOption, type SubmissionStatusFilter, type ToFormDocumentOptions, type TurnstileProviderOptions, type UploadsOption, type ValidationRuleDefinition, type ValidationRuleOption, type ValidationRuleRegistry, type ValidationRuleResult, type ValidationRulesConfig, aggregateFieldResponses, aggregateFormResponses, aggregateRowForField, aggregateRowsForFields, applyConsentStatements, buildDefaultActionDefinitions, buildDefaultButtonFields, buildDefaultFieldDefinitions, buildDefaultOutcomeFields, buildNextLabelField, buildPollCloseTask, buildPrevLabelField, buildRecallResolver, buildResolvedAtField, buildSubmitLabelField, buildWinningValuesField, calcExpressionOf, captureConsent, captureFileRef, computeCalcFields, consentSourcesField, countryField, createKvRateLimiter, createSubmission, defaultActionDefinitions, defaultBodyConverters, defaultFieldDefinitions, defaultFieldDefinitionsByType, defaultIdentify, defaultPresentationDescriptors, defaultValidationRules, defaultValidationRulesByType, defineAction, defineCaptchaProvider, defineFormField, definePollOptionSource, definePollType, defineValidationRule, departmentsField, enqueuePollClose, escapeHtml, evaluateCalc, evaluateCondition, fieldHasOptions, fieldKey, fieldTargetParam, fileMimeTypeOptions, formBuilder, formatBytes, hasVotedCookie, hcaptchaProvider, interpolate, isPollClosed, localizedIf, manualStrategy, mostVotedStrategy, normalizeCalc, optionLabelsFor, pollTypesOf, recaptchaProvider, registerPollCloseTask, renderAllValues, renderAllValuesTable, resolveActions, resolveConsentEntries, resolveConsentSourcesRequest, resolveConsentStatements, resolveDepartmentOptions, resolveEffectivePollOptions, resolveFileRef, resolveFormResultsRequest, resolvePollOptionSources, resolvePollOptions, resolvePollOutcome, resolvePollTypes, resolvePublishedVersionRef, resolveSpamConfig, runPollClose, sanitizeUrl, serializeBody, shouldAutoResolvePoll, signPayload, sourceStrategy, stashPollTypes, stateField, textOfBody, toFormDocument, topBucketValues, turnstileProvider, valuesFromSearchParams, votedCookieName };
109
+ export { type ActionDefinition, ActionError, type ActionOption, type ActionRegistry, type ActionResult, type ActionRunArgs, type ActionValidateArgs, type ActionsConfig, type AggregateFieldResponsesArgs, type AggregateFormResponsesArgs, type AggregationBucket, type AggregationRow, type AnyActionDefinition, type AnyFormFieldDefinition, type AnyPollOptionSource, type AnyValidationRuleDefinition, type BodyContext, type BodyConverter, type BodyConverterArgs, type BodyRender, type ButtonFieldsOverride, type ButtonsOption, CAPTCHA_TOKEN_KEY, type CalcAllowed, type CalcDisplayConfig, type CalcExpression, type CalcFunction, type CalcResolved, type CalcSource, type CalcSourceResolveArgs, type CalcWeightResolveArgs, type CaptchaProvider, type CaptchaVerifyArgs, type ConsentProof, type ConsentSnapshotMode, type ConsentSourceEntry, type ConsentSourceOption, type ConsentSourcePage, type ConsentSourcesFieldOptions, type ConsentSourcesResolver, type ConsentStatement, type ConsentStatements, type CreateSubmissionArgs, type CreatedSubmission, DEFAULT_COLLECTION_SLUGS, DEFAULT_HONEYPOT_FIELD, DEFAULT_PRESENTATION_NAME, DEFAULT_VOTED_COOKIE_PREFIX, type DefaultButtonFields, type DefaultOutcomeFields, type DefaultSettingsFields, type DepartmentEmailsResolver, type DepartmentOption, type DepartmentsFieldOptions, type EmailActionType, type EmailRender, type EmailRenderArgs, type FieldAggregation, type FieldCondition, type FieldMeta, type FieldTargetParamOptions, type FieldTypeOption, type FieldTypeRegistry, type FieldTypesConfig, type FileFieldConfig, type FileRef, type FileRefError, type FormBuilderCollectionSlugs, type FormBuilderPluginOptions, type FormButtonSettings, type FormContextReference, type FormDocument, type FormFallbackLocale, type FormFallbackLocaleArgs, type FormFallbackLocaleResult, type FormFieldDefinition, type FormFieldFormat, type FormFieldValidate, type FormFieldValueKind, type FormPollSettings, type FormResponseSettings, type FormResultsAccess, type FormResultsAccessArgs, type FromAddressOption, type FromAddressSource, type FromAddressSourceRegistry, type FromAddressesResolver, type HcaptchaProviderOptions, INLINE_DISPATCH_DEADLINE_MS, type IdentifyFn, type OmittableSharedField, type OutcomeFieldsOverride, POLL_CLOSE_TASK_SLUG, POLL_VOTES_SLUG, type FormBuilderPluginOptions as PluginOptions, type PollCloseTaskInput, type PollOption, type PollOptionResolveArgs, type PollOptionSource, type PollOptionSourceOption, type PollOptionSourceRegistry, type PollOptionSourcesConfig, type PollOutcomeStrategy, type PollOutcomeStrategyArgs, type PollTypeRegistry, type PollTypesConfig, type PrefillOptions, type PresentationDensity, type PresentationDescriptor, type PresentationSurface, RESPONDENTS_VALUE, type RateLimitCheckArgs, type RateLimitConfig, type RateLimitResult, type RateLimiter, type RecallResolver, type RecaptchaProviderOptions, type RecipientResolveArgs, type RecipientSource, type RecipientSourceRegistry, type RedirectFieldsOverride, type RedirectOption, type ResolveCalcContextArgs, type ResolveConsentEntriesArgs, type ResolveConsentSourcesRequestArgs, type ResolveConsentSourcesRequestResult, type ResolveConsentStatementsArgs, type ResolveDepartmentOptionsArgs, type ResolveDepartmentsRequestArgs, type ResolveDepartmentsRequestResult, type ResolveEffectivePollOptionsArgs, type ResolveFieldOptionsArgs, type ResolvePollOptionsArgs, type ResolvePollOutcomeArgs, type ResolvePublishedVersionRefArgs, type ResolveResultsRequestArgs, type ResolveResultsRequestResult, type ResponseOption, type RichTextBodyOption, SIGNATURE_HEADER, type SerializeBodyArgs, type SettingsFieldsOverride, type SettingsOption, type SpamConfig, type SpamMetadataConfig, type SpamOption, type SubmissionContextArgs, type SubmissionForm, type SubmissionStatusFilter, type ToFormDocumentOptions, type TurnstileProviderOptions, type UploadsOption, VOTE_SHARDS, type ValidationRuleDefinition, type ValidationRuleOption, type ValidationRuleRegistry, type ValidationRuleResult, type ValidationRulesConfig, type VotedSubmission, aggregateFieldResponses, aggregateFormResponses, aggregateFromVotes, aggregateRowForField, aggregateRowsForFields, applyConsentStatements, buildDefaultActionDefinitions, buildDefaultButtonFields, buildDefaultFieldDefinitions, buildDefaultOutcomeFields, buildDefaultSettingsFields, buildNextLabelField, buildPollCloseTask, buildPrevLabelField, buildRecallResolver, buildResolvedAtField, buildSubmitLabelField, buildWinningValuesField, calcExpressionOf, calcUsesSources, calcWeightKey, captureConsent, captureFileRef, collectionSlugsOf, computeCalcFields, consentSourcesField, countryField, createKvRateLimiter, createSubmission, defaultActionDefinitions, defaultBodyConverters, defaultFieldDefinitions, defaultFieldDefinitionsByType, defaultIdentify, defaultPresentationDescriptors, defaultValidationRules, defaultValidationRulesByType, defineAction, defineCalcFunction, defineCalcSource, defineCaptchaProvider, defineFormField, definePollOptionSource, definePollType, defineValidationRule, departmentsField, enqueuePollClose, escapeHtml, evaluateCalc, evaluateCondition, fieldHasOptions, fieldKey, fieldTargetParam, fileMimeTypeOptions, formBuilder, formatBytes, formatCalc, formatCalcValue, hasVotedCookie, hcaptchaProvider, interpolate, isPollClosed, localizedIf, manualStrategy, mostVotedStrategy, normalizeCalc, optionLabelsFor, pollTypesOf, recaptchaProvider, recountPollVotes, registerPollCloseTask, renderAllValues, renderAllValuesTable, resolveActions, resolveCalcContext, resolveConsentEntries, resolveConsentSourcesRequest, resolveConsentStatements, resolveDepartmentOptions, resolveEffectivePollOptions, resolveFileRef, resolveFormResultsRequest, resolvePollOptionSources, resolvePollOptions, resolvePollOutcome, resolvePollTypes, resolvePublishedVersionRef, resolveSpamConfig, resolveVotedSubmission, runPollClose, sanitizeUrl, serializeBody, shouldAutoResolvePoll, signFormContext, signPayload, sourceStrategy, stashPollTypes, stateField, textOfBody, toFormDocument, topBucketValues, turnstileProvider, valuesFromSearchParams, verifyFormContext, votedCookieName };
88
110
  //# sourceMappingURL=index.d.ts.map