@10x-media/form-builder 0.1.0-beta.8 → 4.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +11 -3
  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/types.d.ts +4 -3
  147. package/dist/fields/buildFieldBlocks.js +2 -1
  148. package/dist/fields/buildFieldBlocks.js.map +1 -1
  149. package/dist/fields/builtin/calculation.d.ts +17 -0
  150. package/dist/fields/builtin/calculation.js +70 -127
  151. package/dist/fields/builtin/calculation.js.map +1 -1
  152. package/dist/fields/builtin/checkbox.js +15 -0
  153. package/dist/fields/builtin/checkbox.js.map +1 -1
  154. package/dist/fields/builtin/consent.js +21 -1
  155. package/dist/fields/builtin/consent.js.map +1 -1
  156. package/dist/fields/builtin/email.js +7 -0
  157. package/dist/fields/builtin/email.js.map +1 -1
  158. package/dist/fields/builtin/index.d.ts +6 -2
  159. package/dist/fields/builtin/index.js +9 -4
  160. package/dist/fields/builtin/index.js.map +1 -1
  161. package/dist/fields/builtin/select.js +20 -1
  162. package/dist/fields/builtin/select.js.map +1 -1
  163. package/dist/fields/builtin/text.js +7 -0
  164. package/dist/fields/builtin/text.js.map +1 -1
  165. package/dist/fields/instanceOptions.js +1 -1
  166. package/dist/fields/instanceOptions.js.map +1 -1
  167. package/dist/fields/sharedConfig.js +15 -11
  168. package/dist/fields/sharedConfig.js.map +1 -1
  169. package/dist/fields/types.d.ts +8 -2
  170. package/dist/form/findFormAtLocale.d.ts +30 -0
  171. package/dist/form/findFormAtLocale.js +88 -0
  172. package/dist/form/findFormAtLocale.js.map +1 -0
  173. package/dist/form/pollState.d.ts +2 -1
  174. package/dist/form/pollState.js.map +1 -1
  175. package/dist/form/toFormDocument.d.ts +8 -0
  176. package/dist/form/toFormDocument.js +3 -1
  177. package/dist/form/toFormDocument.js.map +1 -1
  178. package/dist/form/types.d.ts +9 -1
  179. package/dist/index.d.ts +22 -6
  180. package/dist/index.js +63 -17
  181. package/dist/index.js.map +1 -1
  182. package/dist/options.d.ts +113 -4
  183. package/dist/plugin/collectionSlugs.d.ts +28 -0
  184. package/dist/plugin/collectionSlugs.js +65 -0
  185. package/dist/plugin/collectionSlugs.js.map +1 -0
  186. package/dist/plugin/customState.js +1 -1
  187. package/dist/plugin/customState.js.map +1 -1
  188. package/dist/plugin/registerCollections.js +38 -21
  189. package/dist/plugin/registerCollections.js.map +1 -1
  190. package/dist/poll/closeJob.d.ts +4 -3
  191. package/dist/poll/closeJob.js +13 -10
  192. package/dist/poll/closeJob.js.map +1 -1
  193. package/dist/poll/outcomeBeforeChange.js +2 -2
  194. package/dist/poll/outcomeBeforeChange.js.map +1 -1
  195. package/dist/poll/pollTypeRegistry.js +1 -1
  196. package/dist/poll/resolvePollCloseRequest.js +5 -4
  197. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  198. package/dist/poll/resolvePollOptionsRequest.js +2 -2
  199. package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
  200. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  201. package/dist/poll/resolvePollOutcome.js +20 -6
  202. package/dist/poll/resolvePollOutcome.js.map +1 -1
  203. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  204. package/dist/poll/votes/aggregateFromVotes.js +55 -0
  205. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  206. package/dist/poll/votes/answerValues.js +16 -0
  207. package/dist/poll/votes/answerValues.js.map +1 -0
  208. package/dist/poll/votes/bumpPollVote.js +91 -0
  209. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  210. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  211. package/dist/poll/votes/recountPollVotes.js +63 -0
  212. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  213. package/dist/poll/votes/voteTallyHook.js +76 -0
  214. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  215. package/dist/poll/votes/votesCollection.d.ts +23 -0
  216. package/dist/poll/votes/votesCollection.js +96 -0
  217. package/dist/poll/votes/votesCollection.js.map +1 -0
  218. package/dist/react/Form.d.ts +49 -7
  219. package/dist/react/Form.js +183 -37
  220. package/dist/react/Form.js.map +1 -1
  221. package/dist/react/FormContext.d.ts +10 -2
  222. package/dist/react/FormContext.js.map +1 -1
  223. package/dist/react/FormResults.d.ts +4 -2
  224. package/dist/react/FormResults.js +21 -8
  225. package/dist/react/FormResults.js.map +1 -1
  226. package/dist/react/Poll.d.ts +25 -2
  227. package/dist/react/Poll.js +76 -25
  228. package/dist/react/Poll.js.map +1 -1
  229. package/dist/react/adapters.d.ts +35 -0
  230. package/dist/react/adapters.js +11 -0
  231. package/dist/react/adapters.js.map +1 -0
  232. package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
  233. package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
  234. package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
  235. package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
  236. package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
  237. package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
  238. package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
  239. package/dist/react/captcha/TurnstileCaptcha.js +2 -2
  240. package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
  241. package/dist/react/captcha/useCaptchaScript.js +23 -5
  242. package/dist/react/captcha/useCaptchaScript.js.map +1 -1
  243. package/dist/react/fetchResults.d.ts +6 -3
  244. package/dist/react/fetchResults.js +10 -5
  245. package/dist/react/fetchResults.js.map +1 -1
  246. package/dist/react/primitives/Checkbox.d.ts +4 -2
  247. package/dist/react/primitives/Checkbox.js +3 -2
  248. package/dist/react/primitives/Checkbox.js.map +1 -1
  249. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  250. package/dist/react/primitives/ChoiceGroup.js +33 -0
  251. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  252. package/dist/react/primitives/FieldShell.d.ts +11 -1
  253. package/dist/react/primitives/FieldShell.js +43 -33
  254. package/dist/react/primitives/FieldShell.js.map +1 -1
  255. package/dist/react/primitives/Input.d.ts +3 -1
  256. package/dist/react/primitives/Input.js +2 -1
  257. package/dist/react/primitives/Input.js.map +1 -1
  258. package/dist/react/renderers/calculation.js +6 -1
  259. package/dist/react/renderers/calculation.js.map +1 -1
  260. package/dist/react/renderers/checkbox.js +2 -1
  261. package/dist/react/renderers/checkbox.js.map +1 -1
  262. package/dist/react/renderers/consent.js +8 -3
  263. package/dist/react/renderers/consent.js.map +1 -1
  264. package/dist/react/renderers/email.js +3 -1
  265. package/dist/react/renderers/email.js.map +1 -1
  266. package/dist/react/renderers/repeater.js +5 -0
  267. package/dist/react/renderers/repeater.js.map +1 -1
  268. package/dist/react/renderers/select.js +20 -2
  269. package/dist/react/renderers/select.js.map +1 -1
  270. package/dist/react/renderers/text.js +3 -1
  271. package/dist/react/renderers/text.js.map +1 -1
  272. package/dist/react/state.d.ts +20 -1
  273. package/dist/react/state.js +57 -4
  274. package/dist/react/state.js.map +1 -1
  275. package/dist/react/submitForm.d.ts +20 -3
  276. package/dist/react/submitForm.js +8 -4
  277. package/dist/react/submitForm.js.map +1 -1
  278. package/dist/react/useCalcValues.d.ts +10 -0
  279. package/dist/react/useCalcValues.js +13 -0
  280. package/dist/react/useCalcValues.js.map +1 -0
  281. package/dist/react/useField.js +7 -5
  282. package/dist/react/useField.js.map +1 -1
  283. package/dist/recall/resolver.js +1 -1
  284. package/dist/recall/resolver.js.map +1 -1
  285. package/dist/spam/constants.js +7 -1
  286. package/dist/spam/constants.js.map +1 -1
  287. package/dist/spam/spamGuard.js +2 -1
  288. package/dist/spam/spamGuard.js.map +1 -1
  289. package/dist/submissions/SubmissionAnswersClient.js +14 -14
  290. package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
  291. package/dist/submissions/createSubmission.d.ts +7 -1
  292. package/dist/submissions/createSubmission.js +10 -5
  293. package/dist/submissions/createSubmission.js.map +1 -1
  294. package/dist/submissions/formIdOf.js +13 -0
  295. package/dist/submissions/formIdOf.js.map +1 -0
  296. package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
  297. package/dist/submissions/resolveVotedSubmission.js +51 -0
  298. package/dist/submissions/resolveVotedSubmission.js.map +1 -0
  299. package/dist/submissions/runSubmission.js +6 -5
  300. package/dist/submissions/runSubmission.js.map +1 -1
  301. package/dist/submissions/submissionLocale.js +39 -0
  302. package/dist/submissions/submissionLocale.js.map +1 -0
  303. package/dist/submissions/validateSubmission.js +125 -79
  304. package/dist/submissions/validateSubmission.js.map +1 -1
  305. package/dist/submissions/verifyContext.js +35 -0
  306. package/dist/submissions/verifyContext.js.map +1 -0
  307. package/dist/submissions/voteChange.js +21 -0
  308. package/dist/submissions/voteChange.js.map +1 -0
  309. package/dist/submissions/voteChangeEndpoint.js +110 -0
  310. package/dist/submissions/voteChangeEndpoint.js.map +1 -0
  311. package/dist/submissions/votedCookie.d.ts +10 -4
  312. package/dist/submissions/votedCookie.js +49 -11
  313. package/dist/submissions/votedCookie.js.map +1 -1
  314. package/dist/translations/ar.d.ts +7 -0
  315. package/dist/translations/ar.js +379 -0
  316. package/dist/translations/ar.js.map +1 -0
  317. package/dist/translations/clientRuntimeKeys.d.ts +17 -0
  318. package/dist/translations/clientRuntimeKeys.js +48 -0
  319. package/dist/translations/clientRuntimeKeys.js.map +1 -0
  320. package/dist/translations/de.d.ts +12 -0
  321. package/dist/translations/de.js +80 -3
  322. package/dist/translations/de.js.map +1 -1
  323. package/dist/translations/en.js +80 -3
  324. package/dist/translations/en.js.map +1 -1
  325. package/dist/translations/es.d.ts +7 -0
  326. package/dist/translations/es.js +379 -0
  327. package/dist/translations/es.js.map +1 -0
  328. package/dist/translations/fr.d.ts +7 -0
  329. package/dist/translations/fr.js +379 -0
  330. package/dist/translations/fr.js.map +1 -0
  331. package/dist/translations/id.d.ts +7 -0
  332. package/dist/translations/id.js +379 -0
  333. package/dist/translations/id.js.map +1 -0
  334. package/dist/translations/index.d.ts +23 -6
  335. package/dist/translations/index.js +31 -6
  336. package/dist/translations/index.js.map +1 -1
  337. package/dist/translations/keys.d.ts +78 -1
  338. package/dist/translations/keys.js +78 -1
  339. package/dist/translations/keys.js.map +1 -1
  340. package/dist/translations/ko.d.ts +7 -0
  341. package/dist/translations/ko.js +379 -0
  342. package/dist/translations/ko.js.map +1 -0
  343. package/dist/translations/makeTranslate.d.ts +7 -3
  344. package/dist/translations/makeTranslate.js +12 -3
  345. package/dist/translations/makeTranslate.js.map +1 -1
  346. package/dist/translations/pt.d.ts +7 -0
  347. package/dist/translations/pt.js +379 -0
  348. package/dist/translations/pt.js.map +1 -0
  349. package/dist/translations/ru.d.ts +7 -0
  350. package/dist/translations/ru.js +379 -0
  351. package/dist/translations/ru.js.map +1 -0
  352. package/dist/translations/uk.d.ts +7 -0
  353. package/dist/translations/uk.js +379 -0
  354. package/dist/translations/uk.js.map +1 -0
  355. package/dist/translations/zh.d.ts +7 -0
  356. package/dist/translations/zh.js +379 -0
  357. package/dist/translations/zh.js.map +1 -0
  358. package/dist/validation/builtin/index.js +2 -0
  359. package/dist/validation/builtin/index.js.map +1 -1
  360. package/dist/validation/builtin/integer.js +15 -0
  361. package/dist/validation/builtin/integer.js.map +1 -0
  362. package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
  363. package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
  364. package/package.json +23 -15
  365. package/styles/form-builder.css +84 -0
@@ -1 +1 @@
1
- {"version":3,"file":"emailAction.js","names":[],"sources":["../../../src/actions/builtin/emailAction.ts"],"sourcesContent":["import type { Field, RichTextField } from 'payload'\nimport type { DepartmentEmailsResolver } from '../../email/departments'\nimport { localizedIf } from '../../fields/localizedIf'\nimport { interpolate } from '../../recall/interpolate'\nimport { keys } from '../../translations/keys'\nimport { labelFor } from '../../translations/server'\nimport { resolverFor } from '../body/serializeBody'\nimport { type ActionDefinition, defineAction } from '../defineAction'\nimport { buildRecipientField, type RecipientsConfig, resolveRecipients } from '../emailRecipients'\nimport { buildFromField, type FromAddressesResolver } from '../fromAddresses'\n\n/** The plugin-derived options every built-in email action is built from (was five positional args). */\nexport type EmailActionOptions = {\n\tlocalize: boolean\n\teditor?: RichTextField['editor']\n\tfromAddresses?: FromAddressesResolver\n\tdepartments?: DepartmentEmailsResolver\n\trecipients?: RecipientsConfig\n}\n\n/** The config fields shared by every built-in email action (each action adds its own `to` target). */\nexport type EmailActionConfig = {\n\tfrom?: string\n\tcc?: string[]\n\tbcc?: string[]\n\treplyTo?: string[]\n\tsubject?: string\n\tbody?: unknown\n}\n\n/** Builds a recipient-list field (`to`/`cc`/`bcc`/`replyTo`) with the shared width, endpoint, and options. */\ntype RecipientFieldBuilder = (name: string, labelKey: string) => Field\n\ntype Resolver = ReturnType<typeof resolverFor>\n\n/** What distinguishes one email action from another: identity, its primary target, and how it resolves/guards that target. */\ntype EmailActionSpec<TConfig extends EmailActionConfig> = {\n\ttype: string\n\tlabel: string\n\t/** The first cell of the opening row (paired with `replyTo`): a recipient list, or an email-field select. */\n\ttarget: (recip: RecipientFieldBuilder) => Field\n\t/** Resolve the primary `to` from the stored config, or `undefined` when there is no recipient. */\n\tresolveTo: (config: TConfig, resolve: Resolver) => string | undefined\n\t/** With no resolved `to`, `emailTeam` treats it as a misconfiguration (`throw`), `confirmation` as a silent skip. */\n\tonMissingTo: 'throw' | 'skip'\n}\n\n/**\n * The shared skeleton of the built-in email actions (`emailTeam`, `confirmation`): an identical\n * config (a first row pairing the action's target with `replyTo`, an optional `from` select, a\n * cc/bcc row, a subject, and a rich text body, content and recipient fields carrying `localized`\n * when `localize`) and an identical send (interpolate the subject, render the body, resolve\n * cc/bcc/replyTo, and hand a single comma-joined string per list to `payload.sendEmail`). Only the\n * primary `to` target and its missing-value behavior differ, threaded through `spec`.\n */\nexport const buildEmailAction = <TConfig extends EmailActionConfig>(\n\toptions: EmailActionOptions,\n\tspec: EmailActionSpec<TConfig>\n): ActionDefinition<TConfig> => {\n\tconst { localize, editor, fromAddresses, departments, recipients } = options\n\tconst endpoint = departments ? 'departments' : undefined\n\tconst recip: RecipientFieldBuilder = (name, labelKey) =>\n\t\tbuildRecipientField(name, labelKey, localize, {\n\t\t\tendpoint,\n\t\t\trecipients,\n\t\t\twidth: '50%',\n\t\t\tdepartments,\n\t\t})\n\treturn defineAction<TConfig>({\n\t\ttype: spec.type,\n\t\tlabel: spec.label,\n\t\tconfig: [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [spec.target(recip), recip('replyTo', keys.actionConfigReplyTo)],\n\t\t\t},\n\t\t\t...(fromAddresses ? [buildFromField(fromAddresses)] : []),\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [recip('cc', keys.actionConfigCc), recip('bcc', keys.actionConfigBcc)],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'subject',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.actionConfigSubject),\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'body',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelFor(keys.actionConfigBody),\n\t\t\t\tadmin: { description: labelFor(keys.actionConfigBodyDescription) },\n\t\t\t\t...localizedIf(localize),\n\t\t\t\t...(editor ? { editor } : {}),\n\t\t\t},\n\t\t],\n\t\trun: async ({ config, values, payload, renderBody }) => {\n\t\t\tconst resolve = resolverFor(values)\n\t\t\tconst to = spec.resolveTo(config, resolve)\n\t\t\tif (!to) {\n\t\t\t\tif (spec.onMissingTo === 'throw') {\n\t\t\t\t\tthrow new Error(`${spec.type}: missing \"to\" address`)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (typeof payload.sendEmail !== 'function') {\n\t\t\t\tthrow new Error(`${spec.type}: no email adapter configured`)\n\t\t\t}\n\n\t\t\tconst subject = interpolate(config.subject ?? '', resolve)\n\t\t\tconst html = await renderBody(config.body)\n\t\t\tconst cc = resolveRecipients(config.cc, resolve)\n\t\t\tconst bcc = resolveRecipients(config.bcc, resolve)\n\t\t\tconst replyTo = resolveRecipients(config.replyTo, resolve)\n\n\t\t\t// `from` was validated at save time against `fromAddresses(req)`; not re-checked here\n\t\t\t// (the job's `req` may differ from the authoring admin's, and the config is admin-authored,\n\t\t\t// not visitor-controlled), so the stored value is forwarded verbatim.\n\t\t\tawait payload.sendEmail({\n\t\t\t\tto,\n\t\t\t\tsubject,\n\t\t\t\thtml,\n\t\t\t\t...(config.from ? { from: config.from } : {}),\n\t\t\t\t...(cc ? { cc } : {}),\n\t\t\t\t...(bcc ? { bcc } : {}),\n\t\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AM,UAAU,YAAY,OAAO,WAAW,IAAI,OAAO;GACzD,MAAM,OAAO,MAAM,WAAW,OAAO,IAAI;GACzC,MAAM,KAAK,kBAAkB,OAAO,IAAI,OAAO;GAC/C,MAAM,MAAM,kBAAkB,OAAO,KAAK,OAAO;GACjD,MAAM,UAAU,kBAAkB,OAAO,SAAS,OAAO;GAKzD,MAAM,QAAQ,UAAU;IACvB;IACA;IACA;IACA,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;IAC3C,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;IACnB,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;IACrB,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;GAC9B,CAAC;EACF;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"emailAction.js","names":[],"sources":["../../../src/actions/builtin/emailAction.ts"],"sourcesContent":["import type { Field, RichTextField } from 'payload'\nimport type { DepartmentEmailsResolver } from '../../email/departments'\nimport { localizedIf } from '../../fields/localizedIf'\nimport { interpolate } from '../../recall/interpolate'\nimport { keys } from '../../translations/keys'\nimport { labelFor } from '../../translations/server'\nimport { resolverFor } from '../body/serializeBody'\nimport { type ActionDefinition, defineAction } from '../defineAction'\nimport {\n\tbuildRecipientField,\n\ttype RecipientsConfig,\n\tresolveRecipientEntries,\n} from '../emailRecipients'\nimport type { EmailActionType, EmailRender } from '../emailRender'\nimport {\n\tbuildFromField,\n\ttype FromAddressesResolver,\n\ttype FromAddressSourceRegistry,\n\tresolveSendFrom,\n} from '../fromAddresses'\nimport {\n\ttype RecipientResolveArgs,\n\ttype RecipientSource,\n\ttype RecipientSourceRegistry,\n\tsourcesByValue,\n} from '../recipientSources'\n\n/** The plugin-derived options every built-in email action is built from (was five positional args). */\nexport type EmailActionOptions = {\n\tlocalize: boolean\n\t/**\n\t * Localize the recipient lists (`to`, `cc`, `bcc`, `replyTo`) too, so each locale routes to its\n\t * own addresses (plugin option `email.localizeRecipients`). Off by default: routing is usually\n\t * the same in every locale, and a list left empty in a locale that does not fall back fails\n\t * `emailTeam` there. Only applies while `localize` is on.\n\t */\n\tlocalizeRecipients?: boolean\n\teditor?: RichTextField['editor']\n\tfromAddresses?: FromAddressesResolver\n\t/** Send-time-resolved senders offered in the from select (plugin option `email.fromSources`). */\n\tfromSources?: FromAddressSourceRegistry\n\tdepartments?: DepartmentEmailsResolver\n\trecipients?: RecipientsConfig\n\t/** Server-resolved recipient sources offered in every recipient list (plugin option `email.recipientSources`). */\n\trecipientSources?: RecipientSourceRegistry\n\t/** Produces the final html from the serialized body (plugin option `email.render`). */\n\trender?: EmailRender\n}\n\n/** The config fields shared by every built-in email action (each action adds its own `to` target). */\nexport type EmailActionConfig = {\n\tfrom?: string\n\tcc?: string[]\n\tbcc?: string[]\n\treplyTo?: string[]\n\tsubject?: string\n\tbody?: unknown\n}\n\n/** Builds a recipient-list field (`to`/`cc`/`bcc`/`replyTo`) with the shared width, endpoint, and options. */\ntype RecipientFieldBuilder = (name: string, labelKey: string) => Field\n\ntype Resolver = ReturnType<typeof resolverFor>\n\n/**\n * Whether serialized body html carries anything beyond markup and whitespace: an empty editor\n * serializes to bare tags, while a lone image or rule is content even without text.\n */\nconst hasVisibleContent = (html: string): boolean =>\n\t/<(img|hr|table|iframe|video|svg)\\b/i.test(html) ||\n\thtml.replace(/<[^>]*>|&nbsp;/g, '').trim() !== ''\n\n/** What `resolveTo` needs to compute the primary target, including server-resolved sources. */\ntype ResolveToArgs<TConfig extends EmailActionConfig> = {\n\tconfig: TConfig\n\tresolve: Resolver\n\tsources: Map<string, RecipientSource>\n\tsourceArgs: RecipientResolveArgs\n}\n\n/** What distinguishes one email action from another: identity, its primary target, and how it resolves/guards that target. */\ntype EmailActionSpec<TConfig extends EmailActionConfig> = {\n\ttype: EmailActionType\n\tlabel: string\n\t/** The first cell of the opening row (paired with `replyTo`): a recipient list, or an email-field select. */\n\ttarget: (recip: RecipientFieldBuilder) => Field\n\t/** Resolve the primary `to` to a comma-joined address string, or `''` when nothing resolves. */\n\tresolveTo: (args: ResolveToArgs<TConfig>) => Promise<string> | string\n\t/**\n\t * Whether the author configured any target at all. A configured target that resolves empty (e.g. a\n\t * source returned `[]`) is a normal skip; only a target the author never set is a misconfiguration.\n\t */\n\thasTarget: (config: TConfig) => boolean\n\t/** With no target authored, `emailTeam` treats it as a misconfiguration (`throw`), `confirmation` as a silent skip. */\n\tonMissingTo: 'throw' | 'skip'\n}\n\n/**\n * The shared skeleton of the built-in email actions (`emailTeam`, `confirmation`): an identical\n * config (a first row pairing the action's target with `replyTo`, an optional `from` select, a\n * cc/bcc row, a subject, and a rich text body, content fields carrying `localized` when `localize`\n * and recipient fields only when `localizeRecipients` too) and an identical send (interpolate the\n * subject, render the body, fail on an email with neither, resolve cc/bcc/replyTo, pass the html\n * through `options.render` when set, and hand a single comma-joined string per list to\n * `payload.sendEmail`). Only the primary `to` target and its missing-value behavior differ,\n * threaded through `spec`.\n */\nexport const buildEmailAction = <TConfig extends EmailActionConfig>(\n\toptions: EmailActionOptions,\n\tspec: EmailActionSpec<TConfig>\n): ActionDefinition<TConfig> => {\n\tconst {\n\t\tlocalize,\n\t\tlocalizeRecipients,\n\t\teditor,\n\t\tfromAddresses,\n\t\tfromSources,\n\t\tdepartments,\n\t\trecipients,\n\t\trecipientSources,\n\t\trender,\n\t} = options\n\tconst fromSourcesByValue = sourcesByValue(fromSources)\n\tconst endpoint = departments ? 'departments' : undefined\n\tconst recip: RecipientFieldBuilder = (name, labelKey) =>\n\t\tbuildRecipientField(name, labelKey, localize && localizeRecipients === true, {\n\t\t\tendpoint,\n\t\t\trecipients,\n\t\t\twidth: '50%',\n\t\t\tdepartments,\n\t\t\tsources: recipientSources,\n\t\t})\n\treturn defineAction<TConfig>({\n\t\ttype: spec.type,\n\t\tlabel: spec.label,\n\t\tconfig: [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [spec.target(recip), recip('replyTo', keys.actionConfigReplyTo)],\n\t\t\t},\n\t\t\t...(fromAddresses || fromSources ? [buildFromField(fromAddresses, fromSources)] : []),\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [recip('cc', keys.actionConfigCc), recip('bcc', keys.actionConfigBcc)],\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'subject',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelFor(keys.actionConfigSubject),\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'body',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelFor(keys.actionConfigBody),\n\t\t\t\tadmin: { description: labelFor(keys.actionConfigBodyDescription) },\n\t\t\t\t...localizedIf(localize),\n\t\t\t\t...(editor ? { editor } : {}),\n\t\t\t},\n\t\t],\n\t\trun: async (args) => {\n\t\t\tconst { config, values } = args\n\t\t\tconst resolve = resolverFor(values)\n\t\t\tconst sources = sourcesByValue(recipientSources)\n\t\t\tconst sourceArgs: RecipientResolveArgs = {\n\t\t\t\tcontext: args.context,\n\t\t\t\tvalues,\n\t\t\t\tdescriptors: args.descriptors,\n\t\t\t\tform: args.form,\n\t\t\t\tsubmissionId: args.submissionId,\n\t\t\t\tpayload: args.payload,\n\t\t\t\treq: args.req,\n\t\t\t\tlocale: args.locale,\n\t\t\t}\n\t\t\tconst to = await spec.resolveTo({ config, resolve, sources, sourceArgs })\n\t\t\tif (!to) {\n\t\t\t\t// Nothing to send to. A target the author never configured is a misconfiguration (emailTeam\n\t\t\t\t// throws); a configured target that resolved empty (e.g. a source returned []) is a normal skip.\n\t\t\t\tif (!spec.hasTarget(config) && spec.onMissingTo === 'throw') {\n\t\t\t\t\tthrow new Error(`${spec.type}: missing \"to\" address`)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (typeof args.payload.sendEmail !== 'function') {\n\t\t\t\tthrow new Error(`${spec.type}: no email adapter configured`)\n\t\t\t}\n\n\t\t\tconst subject = interpolate(config.subject ?? '', resolve)\n\t\t\tconst serialized = await args.renderBody(config.body)\n\t\t\t// Checked before `render`, which may wrap an empty body in a frame that has content of its own.\n\t\t\tif (!subject.trim() && !hasVisibleContent(serialized)) {\n\t\t\t\tthrow new Error(`${spec.type}: empty subject and body`)\n\t\t\t}\n\t\t\tconst html = render\n\t\t\t\t? await render({\n\t\t\t\t\t\t...sourceArgs,\n\t\t\t\t\t\thtml: serialized,\n\t\t\t\t\t\tbody: config.body,\n\t\t\t\t\t\tsubject,\n\t\t\t\t\t\tactionType: spec.type,\n\t\t\t\t\t})\n\t\t\t\t: serialized\n\t\t\tconst cc = (await resolveRecipientEntries(config.cc, { resolve, sources, sourceArgs })).join(\n\t\t\t\t', '\n\t\t\t)\n\t\t\tconst bcc = (\n\t\t\t\tawait resolveRecipientEntries(config.bcc, { resolve, sources, sourceArgs })\n\t\t\t).join(', ')\n\t\t\tconst replyTo = (\n\t\t\t\tawait resolveRecipientEntries(config.replyTo, { resolve, sources, sourceArgs })\n\t\t\t).join(', ')\n\n\t\t\t// A literal `from` was validated at save time against `fromAddresses(req)`; not re-checked\n\t\t\t// here (the job's `req` may differ from the authoring admin's, and the config is\n\t\t\t// admin-authored, not visitor-controlled), so it is forwarded verbatim. A stored source\n\t\t\t// value instead resolves freshly on every send, so the sender follows the host (e.g. a\n\t\t\t// tenant that changed its address) rather than freezing at authoring time.\n\t\t\tconst from = await resolveSendFrom({\n\t\t\t\tconfigured: config.from,\n\t\t\t\tsources: fromSourcesByValue,\n\t\t\t\tsourceArgs,\n\t\t\t})\n\t\t\tawait args.payload.sendEmail({\n\t\t\t\tto,\n\t\t\t\tsubject,\n\t\t\t\thtml,\n\t\t\t\t...(from ? { from } : {}),\n\t\t\t\t...(cc ? { cc } : {}),\n\t\t\t\t...(bcc ? { bcc } : {}),\n\t\t\t\t...(replyTo ? { replyTo } : {}),\n\t\t\t})\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;AAoEA,MAAM,qBAAqB,SAC1B,sCAAs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C;AACF"}
@@ -1,18 +1,24 @@
1
1
  import { keys } from "../../translations/keys.js";
2
- import { resolveRecipients } from "../emailRecipients.js";
2
+ import { resolveRecipientEntries } from "../emailRecipients.js";
3
3
  import { buildEmailAction } from "./emailAction.js";
4
4
  //#region src/actions/builtin/emailTeam.ts
5
5
  /**
6
6
  * The `emailTeam` action: its target is a `to` recipient list (`RecipientsSelect`, `string[]`) of
7
- * literal emails, picked department addresses, or `{{field}}` tokens resolved from the submission at
8
- * send. An empty `to` is a misconfiguration and throws. Everything else (from/cc/bcc/replyTo, subject,
9
- * body, localization) is the shared email-action skeleton.
7
+ * literal emails, picked department addresses, `{{field}}` tokens, or registered recipient sources,
8
+ * resolved at send. A `to` the author never configured is a misconfiguration and throws; a configured
9
+ * `to` that resolves empty (e.g. every source returned nothing) skips the send. Everything else
10
+ * (from/cc/bcc/replyTo, subject, body, localization) is the shared email-action skeleton.
10
11
  */
11
12
  const buildEmailTeam = (options) => buildEmailAction(options, {
12
13
  type: "emailTeam",
13
14
  label: keys.actionEmailTeam,
14
15
  target: (recip) => recip("to", keys.actionConfigTo),
15
- resolveTo: (config, resolve) => resolveRecipients(config.to, resolve),
16
+ resolveTo: async ({ config, resolve, sources, sourceArgs }) => (await resolveRecipientEntries(config.to, {
17
+ resolve,
18
+ sources,
19
+ sourceArgs
20
+ })).join(", "),
21
+ hasTarget: (config) => Array.isArray(config.to) ? config.to.length > 0 : Boolean(config.to),
16
22
  onMissingTo: "throw"
17
23
  });
18
24
  buildEmailTeam({ localize: true });
@@ -1 +1 @@
1
- {"version":3,"file":"emailTeam.js","names":[],"sources":["../../../src/actions/builtin/emailTeam.ts"],"sourcesContent":["import { keys } from '../../translations/keys'\nimport { resolveRecipients } from '../emailRecipients'\nimport { buildEmailAction, type EmailActionConfig, type EmailActionOptions } from './emailAction'\n\ntype EmailTeamConfig = EmailActionConfig & { to?: string[] }\n\n/**\n * The `emailTeam` action: its target is a `to` recipient list (`RecipientsSelect`, `string[]`) of\n * literal emails, picked department addresses, or `{{field}}` tokens resolved from the submission at\n * send. An empty `to` is a misconfiguration and throws. Everything else (from/cc/bcc/replyTo, subject,\n * body, localization) is the shared email-action skeleton.\n */\nexport const buildEmailTeam = (options: EmailActionOptions) =>\n\tbuildEmailAction<EmailTeamConfig>(options, {\n\t\ttype: 'emailTeam',\n\t\tlabel: keys.actionEmailTeam,\n\t\ttarget: (recip) => recip('to', keys.actionConfigTo),\n\t\tresolveTo: (config, resolve) => resolveRecipients(config.to, resolve),\n\t\tonMissingTo: 'throw',\n\t})\n\nexport const emailTeam = buildEmailTeam({ localize: true })\n"],"mappings":";;;;;;;;;;AAYA,MAAa,kBAAkB,YAC9B,iBAAkC,SAAS;CAC1C,MAAM;CACN,OAAO,KAAK;CACZ,SAAS,UAAU,MAAM,MAAM,KAAK,cAAc;CAClD,YAAY,QAAQ,YAAY,kBAAkB,OAAO,IAAI,OAAO;CACpE,aAAa;AACd,CAAC;AAEuB,eAAe,EAAE,UAAU,KAAK,CAAC"}
1
+ {"version":3,"file":"emailTeam.js","names":[],"sources":["../../../src/actions/builtin/emailTeam.ts"],"sourcesContent":["import { keys } from '../../translations/keys'\nimport { resolveRecipientEntries } from '../emailRecipients'\nimport { buildEmailAction, type EmailActionConfig, type EmailActionOptions } from './emailAction'\n\ntype EmailTeamConfig = EmailActionConfig & { to?: string[] }\n\n/**\n * The `emailTeam` action: its target is a `to` recipient list (`RecipientsSelect`, `string[]`) of\n * literal emails, picked department addresses, `{{field}}` tokens, or registered recipient sources,\n * resolved at send. A `to` the author never configured is a misconfiguration and throws; a configured\n * `to` that resolves empty (e.g. every source returned nothing) skips the send. Everything else\n * (from/cc/bcc/replyTo, subject, body, localization) is the shared email-action skeleton.\n */\nexport const buildEmailTeam = (options: EmailActionOptions) =>\n\tbuildEmailAction<EmailTeamConfig>(options, {\n\t\ttype: 'emailTeam',\n\t\tlabel: keys.actionEmailTeam,\n\t\ttarget: (recip) => recip('to', keys.actionConfigTo),\n\t\tresolveTo: async ({ config, resolve, sources, sourceArgs }) =>\n\t\t\t(await resolveRecipientEntries(config.to, { resolve, sources, sourceArgs })).join(', '),\n\t\thasTarget: (config) => (Array.isArray(config.to) ? config.to.length > 0 : Boolean(config.to)),\n\t\tonMissingTo: 'throw',\n\t})\n\nexport const emailTeam = buildEmailTeam({ localize: true })\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,kBAAkB,YAC9B,iBAAkC,SAAS;CAC1C,MAAM;CACN,OAAO,KAAK;CACZ,SAAS,UAAU,MAAM,MAAM,KAAK,cAAc;CAClD,WAAW,OAAO,EAAE,QAAQ,SAAS,SAAS,kBAC5C,MAAM,wBAAwB,OAAO,IAAI;EAAE;EAAS;EAAS;CAAW,CAAC,GAAG,KAAK,IAAI;CACvF,YAAY,WAAY,MAAM,QAAQ,OAAO,EAAE,IAAI,OAAO,GAAG,SAAS,IAAI,QAAQ,OAAO,EAAE;CAC3F,aAAa;AACd,CAAC;AAEuB,eAAe,EAAE,UAAU,KAAK,CAAC"}
@@ -1,17 +1,17 @@
1
1
  import { SubmissionDescriptor, SubmissionValue } from "../submissions/types.js";
2
2
  import { Translate } from "../fields/types.js";
3
+ import { FormContextReference } from "../context/formContext.js";
4
+ import { SubmissionForm } from "./submissionContext.js";
3
5
  import { Field, Payload, PayloadRequest } from "payload";
4
6
 
5
7
  //#region src/actions/defineAction.d.ts
6
8
  /** Context passed to an action's `run` when a submission completes. */
7
9
  type ActionRunArgs<TConfig extends Record<string, unknown> = Record<string, unknown>> = {
8
- form: {
9
- id: number | string;
10
- title?: string;
11
- };
10
+ /** The whole form document at depth 0, in the submission's locale; see `SubmissionForm`. */form: SubmissionForm;
12
11
  submissionId: number | string;
13
12
  values: SubmissionValue[];
14
- descriptors: SubmissionDescriptor[];
13
+ descriptors: SubmissionDescriptor[]; /** The verified form-context reference the submission was made through, or null when it had none. */
14
+ context: FormContextReference | null;
15
15
  config: TConfig;
16
16
  payload: Payload;
17
17
  req?: PayloadRequest;
@@ -19,6 +19,20 @@ type ActionRunArgs<TConfig extends Record<string, unknown> = Record<string, unkn
19
19
  t: Translate; /** Serialize a rich text (or legacy string) body config into channel-ready HTML. */
20
20
  renderBody: (body: unknown) => Promise<string>;
21
21
  };
22
+ /** Context passed to an action's `validateConfig` when a form carrying it is saved. */
23
+ type ActionValidateArgs = {
24
+ /** The whole form data under validation, merged over the stored doc on partial updates. */data: Record<string, unknown>;
25
+ req: PayloadRequest;
26
+ };
27
+ /**
28
+ * Throw from an action's `run` to attach structured context (a status code, a provider response)
29
+ * to the failed `ActionResult` without concatenating it into the message. The plugin logs `detail`
30
+ * alongside the failure; any thrown error carrying a `detail` property is treated the same.
31
+ */
32
+ declare class ActionError extends Error {
33
+ detail?: unknown;
34
+ constructor(message: string, detail?: unknown);
35
+ }
22
36
  /**
23
37
  * A post-submit action type, authored once: `config` is the admin `Field[]` for authoring;
24
38
  * `run` executes when a submission completes. Built-ins use this same primitive.
@@ -27,11 +41,28 @@ type ActionDefinition<TConfig extends Record<string, unknown> = Record<string, u
27
41
  type: string; /** i18n-key or literal (resolved like a field label), or a per-locale record. */
28
42
  label: string | Record<string, string>;
29
43
  config?: Field[];
44
+ /**
45
+ * This action's failure is the submission's failure: it runs inline before the response (never
46
+ * queued, bounded by the dispatch deadline), a throw or timeout turns the submit into an error
47
+ * the visitor sees, the remaining actions are skipped, and the submission is kept even on a
48
+ * `persistSubmissions: false` form so what the visitor sent is never lost. For an action that
49
+ * IS the point of the submission (a signup provider that is the system of record); leave unset
50
+ * for notifications and other fire-and-forget work.
51
+ */
52
+ essential?: boolean;
53
+ /**
54
+ * Cross-field check over one stored instance of this action, run alongside field validation on
55
+ * every form save. Return `true` to accept or an error message to refuse; the message is
56
+ * attached to the action block (`actions.<index>`) rather than to any one config field, which
57
+ * per-field `validate` cannot express (an optional array's `validate` never runs on the empty
58
+ * array, the case a "template token has no mapping" check cares about most).
59
+ */
60
+ validateConfig?: (config: TConfig, ctx: ActionValidateArgs) => string | true | Promise<string | true>;
30
61
  run: (args: ActionRunArgs<TConfig>) => Promise<void> | void;
31
62
  };
32
63
  /** Erased shape stored in the registry; config re-narrows per matched type at execution. */
33
64
  type AnyActionDefinition = ActionDefinition<Record<string, unknown>>;
34
65
  declare const defineAction: <TConfig extends Record<string, unknown> = Record<string, unknown>>(definition: ActionDefinition<TConfig>) => ActionDefinition<TConfig>;
35
66
  //#endregion
36
- export { ActionDefinition, ActionRunArgs, AnyActionDefinition, defineAction };
67
+ export { ActionDefinition, ActionError, ActionRunArgs, ActionValidateArgs, AnyActionDefinition, defineAction };
37
68
  //# sourceMappingURL=defineAction.d.ts.map
@@ -1,6 +1,19 @@
1
1
  //#region src/actions/defineAction.ts
2
+ /**
3
+ * Throw from an action's `run` to attach structured context (a status code, a provider response)
4
+ * to the failed `ActionResult` without concatenating it into the message. The plugin logs `detail`
5
+ * alongside the failure; any thrown error carrying a `detail` property is treated the same.
6
+ */
7
+ var ActionError = class extends Error {
8
+ detail;
9
+ constructor(message, detail) {
10
+ super(message);
11
+ this.name = "ActionError";
12
+ this.detail = detail;
13
+ }
14
+ };
2
15
  const defineAction = (definition) => definition;
3
16
  //#endregion
4
- export { defineAction };
17
+ export { ActionError, defineAction };
5
18
 
6
19
  //# sourceMappingURL=defineAction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"defineAction.js","names":[],"sources":["../../src/actions/defineAction.ts"],"sourcesContent":["import type { Field, Payload, PayloadRequest } from 'payload'\nimport type { Translate } from '../fields/types'\nimport type { SubmissionDescriptor, SubmissionValue } from '../submissions/types'\n\n/** Context passed to an action's `run` when a submission completes. */\nexport type ActionRunArgs<TConfig extends Record<string, unknown> = Record<string, unknown>> = {\n\tform: { id: number | string; title?: string }\n\tsubmissionId: number | string\n\tvalues: SubmissionValue[]\n\tdescriptors: SubmissionDescriptor[]\n\tconfig: TConfig\n\tpayload: Payload\n\treq?: PayloadRequest\n\tlocale: string\n\tt: Translate\n\t/** Serialize a rich text (or legacy string) body config into channel-ready HTML. */\n\trenderBody: (body: unknown) => Promise<string>\n}\n\n/**\n * A post-submit action type, authored once: `config` is the admin `Field[]` for authoring;\n * `run` executes when a submission completes. Built-ins use this same primitive.\n */\nexport type ActionDefinition<TConfig extends Record<string, unknown> = Record<string, unknown>> = {\n\ttype: string\n\t/** i18n-key or literal (resolved like a field label), or a per-locale record. */\n\tlabel: string | Record<string, string>\n\tconfig?: Field[]\n\trun: (args: ActionRunArgs<TConfig>) => Promise<void> | void\n}\n\n/** Erased shape stored in the registry; config re-narrows per matched type at execution. */\nexport type AnyActionDefinition = ActionDefinition<Record<string, unknown>>\n\nexport const defineAction = <TConfig extends Record<string, unknown> = Record<string, unknown>>(\n\tdefinition: ActionDefinition<TConfig>\n): ActionDefinition<TConfig> => definition\n"],"mappings":";AAkCA,MAAa,gBACZ,eAC+B"}
1
+ {"version":3,"file":"defineAction.js","names":[],"sources":["../../src/actions/defineAction.ts"],"sourcesContent":["import type { Field, Payload, PayloadRequest } from 'payload'\nimport type { FormContextReference } from '../context/formContext'\nimport type { Translate } from '../fields/types'\nimport type { SubmissionDescriptor, SubmissionValue } from '../submissions/types'\nimport type { SubmissionForm } from './submissionContext'\n\n/** Context passed to an action's `run` when a submission completes. */\nexport type ActionRunArgs<TConfig extends Record<string, unknown> = Record<string, unknown>> = {\n\t/** The whole form document at depth 0, in the submission's locale; see `SubmissionForm`. */\n\tform: SubmissionForm\n\tsubmissionId: number | string\n\tvalues: SubmissionValue[]\n\tdescriptors: SubmissionDescriptor[]\n\t/** The verified form-context reference the submission was made through, or null when it had none. */\n\tcontext: FormContextReference | null\n\tconfig: TConfig\n\tpayload: Payload\n\treq?: PayloadRequest\n\tlocale: string\n\tt: Translate\n\t/** Serialize a rich text (or legacy string) body config into channel-ready HTML. */\n\trenderBody: (body: unknown) => Promise<string>\n}\n\n/** Context passed to an action's `validateConfig` when a form carrying it is saved. */\nexport type ActionValidateArgs = {\n\t/** The whole form data under validation, merged over the stored doc on partial updates. */\n\tdata: Record<string, unknown>\n\treq: PayloadRequest\n}\n\n/**\n * Throw from an action's `run` to attach structured context (a status code, a provider response)\n * to the failed `ActionResult` without concatenating it into the message. The plugin logs `detail`\n * alongside the failure; any thrown error carrying a `detail` property is treated the same.\n */\nexport class ActionError extends Error {\n\tdetail?: unknown\n\n\tconstructor(message: string, detail?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'ActionError'\n\t\tthis.detail = detail\n\t}\n}\n\n/**\n * A post-submit action type, authored once: `config` is the admin `Field[]` for authoring;\n * `run` executes when a submission completes. Built-ins use this same primitive.\n */\nexport type ActionDefinition<TConfig extends Record<string, unknown> = Record<string, unknown>> = {\n\ttype: string\n\t/** i18n-key or literal (resolved like a field label), or a per-locale record. */\n\tlabel: string | Record<string, string>\n\tconfig?: Field[]\n\t/**\n\t * This action's failure is the submission's failure: it runs inline before the response (never\n\t * queued, bounded by the dispatch deadline), a throw or timeout turns the submit into an error\n\t * the visitor sees, the remaining actions are skipped, and the submission is kept even on a\n\t * `persistSubmissions: false` form so what the visitor sent is never lost. For an action that\n\t * IS the point of the submission (a signup provider that is the system of record); leave unset\n\t * for notifications and other fire-and-forget work.\n\t */\n\tessential?: boolean\n\t/**\n\t * Cross-field check over one stored instance of this action, run alongside field validation on\n\t * every form save. Return `true` to accept or an error message to refuse; the message is\n\t * attached to the action block (`actions.<index>`) rather than to any one config field, which\n\t * per-field `validate` cannot express (an optional array's `validate` never runs on the empty\n\t * array, the case a \"template token has no mapping\" check cares about most).\n\t */\n\tvalidateConfig?: (\n\t\tconfig: TConfig,\n\t\tctx: ActionValidateArgs\n\t) => string | true | Promise<string | true>\n\trun: (args: ActionRunArgs<TConfig>) => Promise<void> | void\n}\n\n/** Erased shape stored in the registry; config re-narrows per matched type at execution. */\nexport type AnyActionDefinition = ActionDefinition<Record<string, unknown>>\n\nexport const defineAction = <TConfig extends Record<string, unknown> = Record<string, unknown>>(\n\tdefinition: ActionDefinition<TConfig>\n): ActionDefinition<TConfig> => definition\n"],"mappings":";;;;;;AAoCA,IAAa,cAAb,cAAiC,MAAM;CACtC;CAEA,YAAY,SAAiB,QAAkB;EAC9C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;CACf;AACD;AAqCA,MAAa,gBACZ,eAC+B"}
@@ -0,0 +1,12 @@
1
+ import { Payload, PayloadRequest } from "payload";
2
+
3
+ //#region src/actions/dispatch.d.ts
4
+ /**
5
+ * Default cap on inline action work so a missing worker never hangs the submission response.
6
+ * Overridable per host via the `dispatch.deadlineMs` plugin option; an essential action making
7
+ * outbound calls should size its own timeouts under whichever value is in effect.
8
+ */
9
+ declare const INLINE_DISPATCH_DEADLINE_MS = 5000;
10
+ //#endregion
11
+ export { INLINE_DISPATCH_DEADLINE_MS };
12
+ //# sourceMappingURL=dispatch.d.ts.map
@@ -1,49 +1,122 @@
1
+ import { isEssentialAction } from "./registry.js";
1
2
  import { ACTIONS_TASK_SLUG, runActionsForSubmission } from "./task.js";
3
+ import { ESSENTIAL_ACTION_FAILED_CONTEXT_KEY, ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY } from "./dispatchContext.js";
4
+ //#region src/actions/dispatch.ts
5
+ /**
6
+ * Default cap on inline action work so a missing worker never hangs the submission response.
7
+ * Overridable per host via the `dispatch.deadlineMs` plugin option; an essential action making
8
+ * outbound calls should size its own timeouts under whichever value is in effect.
9
+ */
10
+ const INLINE_DISPATCH_DEADLINE_MS = 5e3;
2
11
  const canQueue = (payload) => typeof payload.jobs?.queue === "function";
3
12
  const deadline = (ms) => new Promise((resolve) => {
4
13
  setTimeout(resolve, ms).unref?.();
5
14
  });
15
+ /** Guard a caller-supplied callback so its throw can never break the dispatch flow. */
16
+ const guarded = async (payload, label, callback) => {
17
+ try {
18
+ await callback?.();
19
+ } catch (error) {
20
+ payload.logger?.error(`@10x-media/form-builder: ${label} callback threw: ${error instanceof Error ? error.message : String(error)}`);
21
+ }
22
+ };
6
23
  /**
7
24
  * Dispatch a submission's post-submit actions without throwing and without blocking the response on slow
8
25
  * action work. With no actions, returns immediately. When a job runner is present, enqueues the native
9
26
  * `form-builder-actions` task and returns (action work happens out of band). Otherwise runs the actions
10
27
  * inline but bounded by a deadline so a missing worker still delivers without hanging the request; any
11
- * error is swallowed (logged via `payload.logger`). Never rejects.
28
+ * error is swallowed (logged via `payload.logger`). Never rejects; the return reports whether an
29
+ * essential pass failed, so the caller can withhold success signals (the created event, the 201).
12
30
  */
13
31
  const dispatchActions = async (args) => {
14
32
  const { payload, registry, req, formId, submissionId } = args;
15
- if ((args.actions ?? []).length === 0) return;
16
- if (args.hasRunner && canQueue(payload)) {
17
- try {
18
- await payload.jobs.queue({
19
- task: ACTIONS_TASK_SLUG,
20
- input: {
21
- formId: String(formId),
22
- submissionId: String(submissionId)
23
- },
24
- req
25
- });
26
- } catch (error) {
27
- payload.logger?.error(`@10x-media/form-builder: failed to enqueue actions for submission ${String(submissionId)}: ${error instanceof Error ? error.message : String(error)}`);
33
+ const actions = args.actions ?? [];
34
+ const hasEssential = actions.some((instance) => isEssentialAction(registry, instance));
35
+ const rest = hasEssential ? actions.filter((instance) => !isEssentialAction(registry, instance)) : actions;
36
+ const runClosingPass = async (withReq) => {
37
+ const subset = hasEssential ? { subset: "rest" } : {};
38
+ if (args.hasRunner && canQueue(payload)) {
39
+ try {
40
+ await payload.jobs.queue({
41
+ task: ACTIONS_TASK_SLUG,
42
+ input: {
43
+ formId: String(formId),
44
+ submissionId: String(submissionId),
45
+ ...subset
46
+ },
47
+ overrideAccess: true,
48
+ ...withReq ? { req: withReq } : {}
49
+ });
50
+ } catch (error) {
51
+ payload.logger?.error(`@10x-media/form-builder: failed to enqueue actions for submission ${String(submissionId)}: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
53
+ return;
54
+ }
55
+ const ms = args.deadlineMs ?? 5e3;
56
+ const work = runActionsForSubmission({
57
+ input: {
58
+ formId,
59
+ submissionId,
60
+ ...subset
61
+ },
62
+ registry,
63
+ payload,
64
+ req: withReq,
65
+ richText: args.richText
66
+ }).catch((error) => {
67
+ payload.logger?.error(`@10x-media/form-builder: inline action dispatch for submission ${String(submissionId)} threw: ${error instanceof Error ? error.message : String(error)}`);
68
+ });
69
+ await (withReq ? Promise.race([work, deadline(ms)]) : work);
70
+ };
71
+ if (hasEssential) {
72
+ const ms = args.deadlineMs ?? 5e3;
73
+ const work = runActionsForSubmission({
74
+ input: {
75
+ formId,
76
+ submissionId,
77
+ subset: "essential"
78
+ },
79
+ registry,
80
+ payload,
81
+ req,
82
+ richText: args.richText
83
+ }).then((results) => ({
84
+ timedOut: false,
85
+ failed: results.some((result) => !result.ok)
86
+ }), (error) => {
87
+ payload.logger?.error(`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} threw: ${error instanceof Error ? error.message : String(error)}`);
88
+ return {
89
+ timedOut: false,
90
+ failed: true
91
+ };
92
+ });
93
+ const outcome = await Promise.race([work, deadline(ms).then(() => ({
94
+ timedOut: true,
95
+ failed: true
96
+ }))]);
97
+ if (outcome.failed) {
98
+ const contextKey = outcome.timedOut ? ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY : ESSENTIAL_ACTION_FAILED_CONTEXT_KEY;
99
+ if (req) req.context = {
100
+ ...req.context ?? {},
101
+ [contextKey]: true
102
+ };
103
+ await guarded(payload, "onEssentialFailed", () => args.onEssentialFailed?.({ timedOut: outcome.timedOut }));
104
+ if (outcome.timedOut) {
105
+ payload.logger?.error(`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} outlived its ${ms}ms deadline; reporting the submission uncertain (the work may still complete)`);
106
+ work.then(async (late) => {
107
+ payload.logger?.[late.failed ? "error" : "info"]?.(`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} settled after its deadline: ${late.failed ? "failed" : "succeeded"}`);
108
+ if (!late.failed && (rest.length > 0 || args.persistSubmissions === false)) await runClosingPass(void 0);
109
+ await guarded(payload, "onEssentialSettled", () => args.onEssentialSettled?.({ ok: !late.failed }));
110
+ });
111
+ }
112
+ return { essentialFailed: true };
28
113
  }
29
- return;
30
114
  }
31
- const ms = args.deadlineMs ?? 5e3;
32
- const work = runActionsForSubmission({
33
- input: {
34
- formId,
35
- submissionId
36
- },
37
- registry,
38
- payload,
39
- req,
40
- richText: args.richText
41
- }).catch((error) => {
42
- payload.logger?.error(`@10x-media/form-builder: inline action dispatch for submission ${String(submissionId)} threw: ${error instanceof Error ? error.message : String(error)}`);
43
- });
44
- await Promise.race([work, deadline(ms)]);
115
+ if (rest.length === 0 && args.persistSubmissions !== false) return { essentialFailed: false };
116
+ await runClosingPass(req);
117
+ return { essentialFailed: false };
45
118
  };
46
119
  //#endregion
47
- export { dispatchActions };
120
+ export { INLINE_DISPATCH_DEADLINE_MS, dispatchActions };
48
121
 
49
122
  //# sourceMappingURL=dispatch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.js","names":[],"sources":["../../src/actions/dispatch.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { RichTextBodyOption } from './body/serializeBody'\nimport type { ActionRegistry } from './registry'\nimport type { ActionInstance } from './runActions'\nimport { ACTIONS_TASK_SLUG, runActionsForSubmission } from './task'\n\n/** Default cap on inline action work so a missing worker never hangs the submission response. */\nexport const INLINE_DISPATCH_DEADLINE_MS = 5_000\n\nexport type DispatchActionsArgs = {\n\tactions: ActionInstance[] | null | undefined\n\tformId: number | string\n\tsubmissionId: number | string\n\tregistry: ActionRegistry\n\tpayload: Payload\n\treq?: PayloadRequest\n\t/** Whether a job runner is likely present (queued path); otherwise the bounded-inline fallback runs. */\n\thasRunner: boolean\n\tdeadlineMs?: number\n\trichText?: RichTextBodyOption\n}\n\nconst canQueue = (payload: Payload): boolean => typeof payload.jobs?.queue === 'function'\n\nconst deadline = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => {\n\t\tconst timer = setTimeout(resolve, ms)\n\t\ttimer.unref?.()\n\t})\n\n/**\n * Dispatch a submission's post-submit actions without throwing and without blocking the response on slow\n * action work. With no actions, returns immediately. When a job runner is present, enqueues the native\n * `form-builder-actions` task and returns (action work happens out of band). Otherwise runs the actions\n * inline but bounded by a deadline so a missing worker still delivers without hanging the request; any\n * error is swallowed (logged via `payload.logger`). Never rejects.\n */\nexport const dispatchActions = async (args: DispatchActionsArgs): Promise<void> => {\n\tconst { payload, registry, req, formId, submissionId } = args\n\tconst actions = args.actions ?? []\n\tif (actions.length === 0) {\n\t\treturn\n\t}\n\n\tif (args.hasRunner && canQueue(payload)) {\n\t\ttry {\n\t\t\tawait payload.jobs.queue({\n\t\t\t\ttask: ACTIONS_TASK_SLUG,\n\t\t\t\tinput: { formId: String(formId), submissionId: String(submissionId) },\n\t\t\t\treq,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tpayload.logger?.error(\n\t\t\t\t`@10x-media/form-builder: failed to enqueue actions for submission ${String(submissionId)}: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\n\tconst ms = args.deadlineMs ?? INLINE_DISPATCH_DEADLINE_MS\n\t// Guard the action arm itself (not just the race) so a rejection AFTER the deadline wins is never an unhandled rejection.\n\tconst work = runActionsForSubmission({\n\t\tinput: { formId, submissionId },\n\t\tregistry,\n\t\tpayload,\n\t\treq,\n\t\trichText: args.richText,\n\t}).catch((error) => {\n\t\tpayload.logger?.error(\n\t\t\t`@10x-media/form-builder: inline action dispatch for submission ${String(submissionId)} threw: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`\n\t\t)\n\t})\n\tawait Promise.race([work, deadline(ms)])\n}\n"],"mappings":";AAsBA,MAAM,YAAY,YAA8B,OAAO,QAAQ,MAAM,UAAU;AAE/E,MAAM,YAAY,OACjB,IAAI,SAAS,YAAY;CAExB,WADyB,SAAS,EAC9B,EAAE,QAAQ;AACf,CAAC;;;;;;;;AASF,MAAa,kBAAkB,OAAO,SAA6C;CAClF,MAAM,EAAE,SAAS,UAAU,KAAK,QAAQ,iBAAiB;CAEzD,KADgB,KAAK,WAAW,CAAC,GACrB,WAAW,GACtB;CAGD,IAAI,KAAK,aAAa,SAAS,OAAO,GAAG;EACxC,IAAI;GACH,MAAM,QAAQ,KAAK,MAAM;IACxB,MAAM;IACN,OAAO;KAAE,QAAQ,OAAO,MAAM;KAAG,cAAc,OAAO,YAAY;IAAE;IACpE;GACD,CAAC;EACF,SAAS,OAAO;GACf,QAAQ,QAAQ,MACf,qEAAqE,OAAO,YAAY,EAAE,IACzF,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEvD;EACD;EACA;CACD;CAEA,MAAM,KAAK,KAAK,cAAA;CAEhB,MAAM,OAAO,wBAAwB;EACpC,OAAO;GAAE;GAAQ;EAAa;EAC9B;EACA;EACA;EACA,UAAU,KAAK;CAChB,CAAC,EAAE,OAAO,UAAU;EACnB,QAAQ,QAAQ,MACf,kEAAkE,OAAO,YAAY,EAAE,UACtF,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEvD;CACD,CAAC;CACD,MAAM,QAAQ,KAAK,CAAC,MAAM,SAAS,EAAE,CAAC,CAAC;AACxC"}
1
+ {"version":3,"file":"dispatch.js","names":[],"sources":["../../src/actions/dispatch.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { RichTextBodyOption } from './body/serializeBody'\nimport {\n\tESSENTIAL_ACTION_FAILED_CONTEXT_KEY,\n\tESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY,\n} from './dispatchContext'\nimport { type ActionRegistry, isEssentialAction } from './registry'\nimport type { ActionInstance } from './runActions'\nimport { ACTIONS_TASK_SLUG, runActionsForSubmission } from './task'\n\nexport { ESSENTIAL_ACTION_FAILED_CONTEXT_KEY, ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY }\n\n/**\n * Default cap on inline action work so a missing worker never hangs the submission response.\n * Overridable per host via the `dispatch.deadlineMs` plugin option; an essential action making\n * outbound calls should size its own timeouts under whichever value is in effect.\n */\nexport const INLINE_DISPATCH_DEADLINE_MS = 5_000\n\nexport type DispatchActionsArgs = {\n\tactions: ActionInstance[] | null | undefined\n\tformId: number | string\n\tsubmissionId: number | string\n\tregistry: ActionRegistry\n\tpayload: Payload\n\treq?: PayloadRequest\n\t/** Whether a job runner is likely present (queued path); otherwise the bounded-inline fallback runs. */\n\thasRunner: boolean\n\t/** The owning form's `persistSubmissions`; when explicitly `false`, run the completion even with no actions so the row is pruned. */\n\tpersistSubmissions?: boolean\n\tdeadlineMs?: number\n\trichText?: RichTextBodyOption\n\t/**\n\t * Awaited before an essential failure is returned, while the create transaction is still open:\n\t * the caller stamps the submission (`actionFailed`, or `actionUncertain` on a deadline breach).\n\t */\n\tonEssentialFailed?: (outcome: { timedOut: boolean }) => void | Promise<void>\n\t/**\n\t * Called when a deadline-breached essential pass later settles, with the real outcome. Runs\n\t * after the response went out (no open transaction). On success it is awaited AFTER the late\n\t * closing pass (rest actions + prune), so the uncertain stamp outlives any partially completed\n\t * reconciliation and the caller's success signals follow the finished work; a stamp-clearing\n\t * caller must tolerate the row having been pruned. On failure it runs immediately.\n\t */\n\tonEssentialSettled?: (outcome: { ok: boolean }) => void | Promise<void>\n}\n\nconst canQueue = (payload: Payload): boolean => typeof payload.jobs?.queue === 'function'\n\nconst deadline = (ms: number): Promise<void> =>\n\tnew Promise((resolve) => {\n\t\tconst timer = setTimeout(resolve, ms)\n\t\ttimer.unref?.()\n\t})\n\n/** Guard a caller-supplied callback so its throw can never break the dispatch flow. */\nconst guarded = async (\n\tpayload: Payload,\n\tlabel: string,\n\tcallback: (() => void | Promise<void>) | undefined\n): Promise<void> => {\n\ttry {\n\t\tawait callback?.()\n\t} catch (error) {\n\t\tpayload.logger?.error(\n\t\t\t`@10x-media/form-builder: ${label} callback threw: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`\n\t\t)\n\t}\n}\n\n/**\n * Dispatch a submission's post-submit actions without throwing and without blocking the response on slow\n * action work. With no actions, returns immediately. When a job runner is present, enqueues the native\n * `form-builder-actions` task and returns (action work happens out of band). Otherwise runs the actions\n * inline but bounded by a deadline so a missing worker still delivers without hanging the request; any\n * error is swallowed (logged via `payload.logger`). Never rejects; the return reports whether an\n * essential pass failed, so the caller can withhold success signals (the created event, the 201).\n */\nexport const dispatchActions = async (\n\targs: DispatchActionsArgs\n): Promise<{ essentialFailed: boolean }> => {\n\tconst { payload, registry, req, formId, submissionId } = args\n\tconst actions = args.actions ?? []\n\tconst hasEssential = actions.some((instance) => isEssentialAction(registry, instance))\n\tconst rest = hasEssential\n\t\t? actions.filter((instance) => !isEssentialAction(registry, instance))\n\t\t: actions\n\n\t// The pass an essential failure skips: rest actions plus, for a `persistSubmissions: false`\n\t// form, the prune completion. Shared by the normal flow below and by late reconciliation, where\n\t// a breached-then-successful essential pass finishes what the timeout interrupted. `withReq`\n\t// only on the request path: by the time a late settlement runs, the request transaction is gone.\n\tconst runClosingPass = async (withReq: PayloadRequest | undefined): Promise<void> => {\n\t\tconst subset = hasEssential ? ({ subset: 'rest' } as const) : {}\n\t\tif (args.hasRunner && canQueue(payload)) {\n\t\t\ttry {\n\t\t\t\tawait payload.jobs.queue({\n\t\t\t\t\ttask: ACTIONS_TASK_SLUG,\n\t\t\t\t\tinput: { formId: String(formId), submissionId: String(submissionId), ...subset },\n\t\t\t\t\t// Queued for an anonymous submitter: the plugin's own task, not the visitor's.\n\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\t...(withReq ? { req: withReq } : {}),\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tpayload.logger?.error(\n\t\t\t\t\t`@10x-media/form-builder: failed to enqueue actions for submission ${String(submissionId)}: ${\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t}`\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tconst ms = args.deadlineMs ?? INLINE_DISPATCH_DEADLINE_MS\n\t\t// Guard the action arm itself (not just the race) so a rejection AFTER the deadline wins is never an unhandled rejection.\n\t\tconst work = runActionsForSubmission({\n\t\t\tinput: { formId, submissionId, ...subset },\n\t\t\tregistry,\n\t\t\tpayload,\n\t\t\treq: withReq,\n\t\t\trichText: args.richText,\n\t\t}).catch((error) => {\n\t\t\tpayload.logger?.error(\n\t\t\t\t`@10x-media/form-builder: inline action dispatch for submission ${String(submissionId)} threw: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`\n\t\t\t)\n\t\t})\n\t\t// Only the request path races the deadline; a late pass has no response waiting on it.\n\t\tawait (withReq ? Promise.race([work, deadline(ms)]) : work)\n\t}\n\n\t// Essential actions run first, inline and awaited, never queued: their failure is the\n\t// submission's failure, which the submit endpoint turns into an error response via the context\n\t// flag. On failure the remaining actions are skipped and so is the pruning completion, so a\n\t// `persistSubmissions: false` form keeps the row: the provider never received it, and the\n\t// stored copy is the only record of what the visitor sent.\n\tif (hasEssential) {\n\t\tconst ms = args.deadlineMs ?? INLINE_DISPATCH_DEADLINE_MS\n\t\tconst work = runActionsForSubmission({\n\t\t\tinput: { formId, submissionId, subset: 'essential' },\n\t\t\tregistry,\n\t\t\tpayload,\n\t\t\treq,\n\t\t\trichText: args.richText,\n\t\t}).then(\n\t\t\t(results) => ({ timedOut: false, failed: results.some((result) => !result.ok) }),\n\t\t\t(error) => {\n\t\t\t\tpayload.logger?.error(\n\t\t\t\t\t`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} threw: ${\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t\t}`\n\t\t\t\t)\n\t\t\t\treturn { timedOut: false, failed: true }\n\t\t\t}\n\t\t)\n\t\tconst outcome = await Promise.race([\n\t\t\twork,\n\t\t\tdeadline(ms).then(() => ({ timedOut: true, failed: true })),\n\t\t])\n\t\tif (outcome.failed) {\n\t\t\tconst contextKey = outcome.timedOut\n\t\t\t\t? ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY\n\t\t\t\t: ESSENTIAL_ACTION_FAILED_CONTEXT_KEY\n\t\t\tif (req) {\n\t\t\t\treq.context = { ...(req.context ?? {}), [contextKey]: true }\n\t\t\t}\n\t\t\tawait guarded(payload, 'onEssentialFailed', () =>\n\t\t\t\targs.onEssentialFailed?.({ timedOut: outcome.timedOut })\n\t\t\t)\n\t\t\tif (outcome.timedOut) {\n\t\t\t\tpayload.logger?.error(\n\t\t\t\t\t`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} outlived its ${ms}ms deadline; reporting the submission uncertain (the work may still complete)`\n\t\t\t\t)\n\t\t\t\t// The breached work is still running: when it settles, record the real outcome instead\n\t\t\t\t// of dropping it. On late success the closing pass the timeout skipped runs FIRST,\n\t\t\t\t// then the caller reconciles (clears the stamp, emits its success signals), matching\n\t\t\t\t// the on-time order and keeping the uncertain stamp truthful if the process dies\n\t\t\t\t// mid-reconciliation: a half-finished recovery stays flagged, never cleared.\n\t\t\t\tvoid work.then(async (late) => {\n\t\t\t\t\tpayload.logger?.[late.failed ? 'error' : 'info']?.(\n\t\t\t\t\t\t`@10x-media/form-builder: essential action pass for submission ${String(submissionId)} settled after its deadline: ${\n\t\t\t\t\t\t\tlate.failed ? 'failed' : 'succeeded'\n\t\t\t\t\t\t}`\n\t\t\t\t\t)\n\t\t\t\t\tif (!late.failed && (rest.length > 0 || args.persistSubmissions === false)) {\n\t\t\t\t\t\tawait runClosingPass(undefined)\n\t\t\t\t\t}\n\t\t\t\t\tawait guarded(payload, 'onEssentialSettled', () =>\n\t\t\t\t\t\targs.onEssentialSettled?.({ ok: !late.failed })\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { essentialFailed: true }\n\t\t}\n\t}\n\n\t// Nothing to run and nothing to prune: skip. An action-less form that opted out of persistence still\n\t// runs the completion below, so `runActionsForSubmission` can delete the row out of band.\n\tif (rest.length === 0 && args.persistSubmissions !== false) {\n\t\treturn { essentialFailed: false }\n\t}\n\n\t// With an essential pass already run, the closing pass covers only the rest (subset threading\n\t// keeps the queued task from re-running the essential actions).\n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AAU,UACxC,iEAAiE,OAAO,YAAY,EAAE,+BACrF,KAAK,SAAS,WAAW,aAE3B;KACA,IAAI,CAAC,KAAK,WAAW,KAAK,SAAS,KAAK,KAAK,uBAAuB,QACnE,MAAM,eAAe,KAAA,CAAS;KAE/B,MAAM,QAAQ,SAAS,4BACtB,KAAK,qBAAqB,EAAE,IAAI,CAAC,KAAK,OAAO,CAAC,CAC/C;IACD,CAAC;GACF;GACA,OAAO,EAAE,iBAAiB,KAAK;EAChC;CACD;CAIA,IAAI,KAAK,WAAW,KAAK,KAAK,uBAAuB,OACpD,OAAO,EAAE,iBAAiB,MAAM;CAKjC,MAAM,eAAe,GAAG;CACxB,OAAO,EAAE,iBAAiB,MAAM;AACjC"}
@@ -0,0 +1,19 @@
1
+ //#region src/actions/dispatchContext.ts
2
+ /**
3
+ * `req.context` key the dispatcher sets to `true` when an essential action failed (or outlived its
4
+ * deadline) for the submission this request created. The submit endpoint reads it to turn the 201
5
+ * into an error response; the submission itself stays stored, prune included, so a failed handoff
6
+ * to a provider never deletes the only copy of what the visitor sent. A leaf module (no imports)
7
+ * because both the dispatcher and the submit endpoint need it across an import cycle.
8
+ */
9
+ const ESSENTIAL_ACTION_FAILED_CONTEXT_KEY = "formBuilderEssentialActionFailed";
10
+ /**
11
+ * Set instead of the failed key when the essential pass outlived its deadline: the work may still
12
+ * complete, so the visitor is told the outcome is unknown (504), not that it failed (502). The two
13
+ * are different facts and prompt different visitor behavior (wait vs retry).
14
+ */
15
+ const ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY = "formBuilderEssentialActionUncertain";
16
+ //#endregion
17
+ export { ESSENTIAL_ACTION_FAILED_CONTEXT_KEY, ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY };
18
+
19
+ //# sourceMappingURL=dispatchContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatchContext.js","names":[],"sources":["../../src/actions/dispatchContext.ts"],"sourcesContent":["/**\n * `req.context` key the dispatcher sets to `true` when an essential action failed (or outlived its\n * deadline) for the submission this request created. The submit endpoint reads it to turn the 201\n * into an error response; the submission itself stays stored, prune included, so a failed handoff\n * to a provider never deletes the only copy of what the visitor sent. A leaf module (no imports)\n * because both the dispatcher and the submit endpoint need it across an import cycle.\n */\nexport const ESSENTIAL_ACTION_FAILED_CONTEXT_KEY = 'formBuilderEssentialActionFailed'\n\n/**\n * Set instead of the failed key when the essential pass outlived its deadline: the work may still\n * complete, so the visitor is told the outcome is unknown (504), not that it failed (502). The two\n * are different facts and prompt different visitor behavior (wait vs retry).\n */\nexport const ESSENTIAL_ACTION_UNCERTAIN_CONTEXT_KEY = 'formBuilderEssentialActionUncertain'\n"],"mappings":";;;;;;;;AAOA,MAAa,sCAAsC;;;;;;AAOnD,MAAa,yCAAyC"}
@@ -21,11 +21,30 @@ const toList = (value) => Array.isArray(value) ? value.filter((entry) => typeof
21
21
  */
22
22
  const firstAddress = (value) => value.split(/[,;\n\r]+/).map((part) => part.trim()).find(isPlausibleEmail) ?? "";
23
23
  /**
24
- * Resolve a stored recipient value (a `string[]`, or a legacy single string) to the comma-separated
25
- * list `payload.sendEmail` accepts: each entry is interpolated (a `{{field}}` token resolves from the
26
- * submission, a plain email passes through), sanitized to a single address, empties dropped, joined.
24
+ * Async recipient resolution for the email actions, extending `resolveRecipients` with server-resolved
25
+ * sources. A registered source value calls its `resolve` (each returned address reduced to one by
26
+ * `firstAddress`, so a source cannot inject headers or extra recipients either); a `{{token}}`/plain
27
+ * email resolves exactly as before. Returns a clean address list (`[]` when nothing resolves) so the
28
+ * caller can skip an empty send. A thrown resolver propagates, failing the action loudly rather than
29
+ * sending to a shortened list.
27
30
  */
28
- const resolveRecipients = (value, resolve) => toList(value).map((entry) => firstAddress(interpolate(entry, resolve))).filter((entry) => entry.length > 0).join(", ");
31
+ const resolveRecipientEntries = async (value, opts) => {
32
+ const out = [];
33
+ for (const entry of toList(value)) {
34
+ const source = opts.sources?.get(entry);
35
+ if (source) {
36
+ const resolved = opts.sourceArgs ? await source.resolve(opts.sourceArgs) : [];
37
+ for (const address of resolved) {
38
+ const clean = firstAddress(address);
39
+ if (clean) out.push(clean);
40
+ }
41
+ continue;
42
+ }
43
+ const clean = firstAddress(interpolate(entry, opts.resolve));
44
+ if (clean) out.push(clean);
45
+ }
46
+ return out;
47
+ };
29
48
  /**
30
49
  * Field `validate` for a recipient list: unset is fine; otherwise every entry must be a valid email
31
50
  * or a `{{field}}` token naming an existing field of an allowed token type. When `allowCustom` is
@@ -49,6 +68,7 @@ const validateRecipients = (opts) => async (value, { data, req }) => {
49
68
  }
50
69
  else allowedValues = /* @__PURE__ */ new Set();
51
70
  for (const entry of list) {
71
+ if (opts.sourceValues?.has(entry)) continue;
52
72
  const token = parseFieldToken(entry);
53
73
  if (token) {
54
74
  if (fieldTokens === false) return asTranslate(req.t)(keys.validationRecipientNotAllowed);
@@ -84,6 +104,8 @@ const resolveDepartmentAllowed = (req, departments) => {
84
104
  const buildRecipientField = (name, labelKey, localize, opts = {}) => {
85
105
  const { departments } = opts;
86
106
  const resolveAllowed = departments ? (req) => resolveDepartmentAllowed(req, departments) : void 0;
107
+ const sourceList = Object.values(opts.sources ?? {});
108
+ const sourceValues = sourceList.length > 0 ? new Set(sourceList.map((s) => s.value)) : void 0;
87
109
  return {
88
110
  name,
89
111
  type: "text",
@@ -93,7 +115,8 @@ const buildRecipientField = (name, labelKey, localize, opts = {}) => {
93
115
  tokenFieldTypes: opts.recipients?.tokenFieldTypes ?? ["email"],
94
116
  allowCustom: opts.recipients?.allowCustom,
95
117
  fieldTokens: opts.recipients?.fieldTokens,
96
- resolveAllowed
118
+ resolveAllowed,
119
+ sourceValues
97
120
  }),
98
121
  ...localizedIf(localize),
99
122
  admin: {
@@ -101,16 +124,23 @@ const buildRecipientField = (name, labelKey, localize, opts = {}) => {
101
124
  components: { Field: {
102
125
  path: RECIPIENTS_FIELD_REF,
103
126
  clientProps: {
104
- ...opts.endpoint ? { endpoint: opts.endpoint } : {},
127
+ ...opts.endpoint ? {
128
+ endpoint: opts.endpoint,
129
+ scope: "request"
130
+ } : {},
105
131
  ...opts.recipients?.allowCustom === false ? { allowCustom: false } : {},
106
132
  ...opts.recipients?.fieldTokens === false ? { fieldTokens: false } : {},
107
- ...opts.recipients?.tokenFieldTypes ? { tokenFieldTypes: opts.recipients.tokenFieldTypes } : {}
133
+ ...opts.recipients?.tokenFieldTypes ? { tokenFieldTypes: opts.recipients.tokenFieldTypes } : {},
134
+ ...sourceList.length > 0 ? { sources: sourceList.map((s) => ({
135
+ value: s.value,
136
+ label: s.label
137
+ })) } : {}
108
138
  }
109
139
  } }
110
140
  }
111
141
  };
112
142
  };
113
143
  //#endregion
114
- export { buildRecipientField, firstAddress, isPlausibleEmail, resolveRecipients };
144
+ export { buildRecipientField, firstAddress, isPlausibleEmail, resolveRecipientEntries };
115
145
 
116
146
  //# sourceMappingURL=emailRecipients.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"emailRecipients.js","names":[],"sources":["../../src/actions/emailRecipients.ts"],"sourcesContent":["import type { PayloadRequest, TextField } from 'payload'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { localizedIf } from '../fields/localizedIf'\nimport { interpolate } from '../recall/interpolate'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelFor } from '../translations/server'\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst TOKEN_RE = /^\\{\\{\\s*([\\w.-]+)\\s*\\}\\}$/\n\n/** A plausible email address (a permissive shape check, not full RFC validation). */\nexport const isPlausibleEmail = (value: string): boolean => EMAIL_RE.test(value.trim())\n\n/** The field name inside a `{{name}}` recipient token, or undefined when the string is not a token. */\nexport const parseFieldToken = (value: string): string | undefined => {\n\tconst match = TOKEN_RE.exec(value.trim())\n\treturn match ? match[1] : undefined\n}\n\nexport const isFieldToken = (value: string): boolean => parseFieldToken(value) !== undefined\n\nconst toList = (value: unknown): string[] =>\n\tArray.isArray(value)\n\t\t? value.filter((entry): entry is string => typeof entry === 'string')\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\n/**\n * The first plausible email in a resolved value, or empty. A recipient entry names a single address,\n * so this drops anything past a separator or CR/LF that a `{{field}}` token might interpolate from\n * visitor input, closing SMTP header injection and extra-recipient injection.\n */\nexport const firstAddress = (value: string): string =>\n\tvalue\n\t\t.split(/[,;\\n\\r]+/)\n\t\t.map((part) => part.trim())\n\t\t.find(isPlausibleEmail) ?? ''\n\n/**\n * Resolve a stored recipient value (a `string[]`, or a legacy single string) to the comma-separated\n * list `payload.sendEmail` accepts: each entry is interpolated (a `{{field}}` token resolves from the\n * submission, a plain email passes through), sanitized to a single address, empties dropped, joined.\n */\nexport const resolveRecipients = (value: unknown, resolve: (name: string) => string): string =>\n\ttoList(value)\n\t\t.map((entry) => firstAddress(interpolate(entry, resolve)))\n\t\t.filter((entry) => entry.length > 0)\n\t\t.join(', ')\n\n/**\n * Field `validate` for a recipient list: unset is fine; otherwise every entry must be a valid email\n * or a `{{field}}` token naming an existing field of an allowed token type. When `allowCustom` is\n * false, a non-token entry must additionally be a member of the resolved options (`resolveAllowed`,\n * e.g. the department addresses), matching the client constraint on the server. Fails closed if the\n * options resolver throws (mirroring the `from` field). Reads the form's `fields` off `data`. Like\n * `from`, Payload runs this on every save, so the resolver is consulted each save under\n * `allowCustom: false`; `buildRecipientField` memoizes it per request so all recipient fields share one call.\n */\nexport const validateRecipients =\n\t(opts: {\n\t\ttokenFieldTypes?: string[]\n\t\tallowCustom?: boolean\n\t\tfieldTokens?: boolean\n\t\tresolveAllowed?: (req: PayloadRequest) => Set<string> | Promise<Set<string>>\n\t}) =>\n\tasync (\n\t\tvalue: unknown,\n\t\t{ data, req }: { data?: unknown; req: PayloadRequest }\n\t): Promise<string | true> => {\n\t\tconst list = toList(value)\n\t\tif (list.length === 0) {\n\t\t\treturn true\n\t\t}\n\t\tconst fields =\n\t\t\tdata && typeof data === 'object' ? (data as Record<string, unknown>).fields : undefined\n\t\tconst { tokenFieldTypes, allowCustom, fieldTokens, resolveAllowed } = opts\n\t\tconst allowedFields = new Set(\n\t\t\ttokenFieldTypes && tokenFieldTypes.length > 0\n\t\t\t\t? fieldNamesOfType(fields, tokenFieldTypes)\n\t\t\t\t: fieldNames(fields)\n\t\t)\n\t\t// Only resolve the membership set when it is actually enforced (allowCustom explicitly false),\n\t\t// so the default (free-typed) path pays no resolver cost. Compare case-insensitively, matching\n\t\t// the client's dedupe, since email delivery ignores case.\n\t\tlet allowedValues: Set<string> | undefined\n\t\tif (allowCustom === false) {\n\t\t\tif (resolveAllowed) {\n\t\t\t\ttry {\n\t\t\t\t\tallowedValues = await resolveAllowed(req)\n\t\t\t\t} catch {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientOptionsUnavailable)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallowedValues = new Set()\n\t\t\t}\n\t\t}\n\t\tfor (const entry of list) {\n\t\t\tconst token = parseFieldToken(entry)\n\t\t\tif (token) {\n\t\t\t\t// `fieldTokens: false` disables recipient tokens; enforce it on the server, not just the client.\n\t\t\t\tif (fieldTokens === false) {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientNotAllowed)\n\t\t\t\t}\n\t\t\t\tif (!allowedFields.has(token)) {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientUnknownField)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!isPlausibleEmail(entry)) {\n\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientInvalid)\n\t\t\t}\n\t\t\tif (allowCustom === false && !allowedValues?.has(entry.trim().toLowerCase())) {\n\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientNotAllowed)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n/** Host-configurable behavior for the recipient fields (plugin option `email.recipients`). */\nexport type RecipientsConfig = {\n\t/** Allow free-typed emails (default true). */\n\tallowCustom?: boolean\n\t/** Offer the form's own fields as recipient tokens (default true). */\n\tfieldTokens?: boolean\n\t/** Field types eligible as tokens (default `['email']`). */\n\ttokenFieldTypes?: string[]\n}\n\nconst RECIPIENTS_FIELD_REF = '@10x-media/form-builder/client#RecipientsSelect'\n\nconst DEPARTMENT_ALLOWED_CACHE = 'formBuilderDepartmentAllowedSet'\n\n/**\n * The department option values as a lowercased Set, memoized on `req.context` so every recipient\n * field validated in one save shares a single `departments` call. Payload validates the fields\n * concurrently, so the in-flight promise is cached synchronously (not the resolved value) to avoid a\n * resolve-per-field race. Lowercased because email delivery ignores case, matching the client dedupe.\n */\nconst resolveDepartmentAllowed = (\n\treq: PayloadRequest,\n\tdepartments: DepartmentEmailsResolver\n): Promise<Set<string>> => {\n\tconst cached = req.context?.[DEPARTMENT_ALLOWED_CACHE]\n\tif (cached instanceof Promise) {\n\t\treturn cached as Promise<Set<string>>\n\t}\n\tconst promise = Promise.resolve()\n\t\t.then(() => departments({ req }))\n\t\t.then((options) => new Set(options.map((option) => option.value.trim().toLowerCase())))\n\tif (req.context) {\n\t\treq.context[DEPARTMENT_ALLOWED_CACHE] = promise\n\t}\n\treturn promise\n}\n\n/**\n * A `text hasMany` field rendered by `RecipientsSelect`, used for every email address list. `endpoint`\n * (when set) supplies preset options (e.g. the host's departments); `recipients` narrows the field's\n * behavior; `width` sets `admin.width` so a pair can share a row; `departments` (when set) backs\n * server-side `allowCustom: false` enforcement with the resolved option values.\n */\n// biome-ignore lint/complexity/useMaxParams: the field identity (name, label, localize) plus its grouped options is the minimal surface\nexport const buildRecipientField = (\n\tname: string,\n\tlabelKey: string,\n\tlocalize: boolean,\n\topts: {\n\t\tendpoint?: string\n\t\trecipients?: RecipientsConfig\n\t\twidth?: string\n\t\tdepartments?: DepartmentEmailsResolver\n\t} = {}\n): TextField => {\n\tconst { departments } = opts\n\tconst resolveAllowed = departments\n\t\t? (req: PayloadRequest) => resolveDepartmentAllowed(req, departments)\n\t\t: undefined\n\treturn {\n\t\tname,\n\t\ttype: 'text',\n\t\thasMany: true,\n\t\tlabel: labelFor(labelKey),\n\t\tvalidate: validateRecipients({\n\t\t\ttokenFieldTypes: opts.recipients?.tokenFieldTypes ?? ['email'],\n\t\t\tallowCustom: opts.recipients?.allowCustom,\n\t\t\tfieldTokens: opts.recipients?.fieldTokens,\n\t\t\tresolveAllowed,\n\t\t}),\n\t\t...localizedIf(localize),\n\t\tadmin: {\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: RECIPIENTS_FIELD_REF,\n\t\t\t\t\tclientProps: {\n\t\t\t\t\t\t...(opts.endpoint ? { endpoint: opts.endpoint } : {}),\n\t\t\t\t\t\t...(opts.recipients?.allowCustom === false ? { allowCustom: false } : {}),\n\t\t\t\t\t\t...(opts.recipients?.fieldTokens === false ? { fieldTokens: false } : {}),\n\t\t\t\t\t\t...(opts.recipients?.tokenFieldTypes\n\t\t\t\t\t\t\t? { tokenFieldTypes: opts.recipients.tokenFieldTypes }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAQA,MAAM,WAAW;AACjB,MAAM,WAAW;;AAGjB,MAAa,oBAAoB,UAA2B,SAAS,KAAK,MAAM,KAAK,CAAC;;AAGtF,MAAa,mBAAmB,UAAsC;CACrE,MAAM,QAAQ,SAAS,KAAK,MAAM,KAAK,CAAC;CACxC,OAAO,QAAQ,MAAM,KAAK,KAAA;AAC3B;AAIA,MAAM,UAAU,UACf,MAAM,QAAQ,KAAK,IAChB,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,IAClE,OAAO,UAAU,YAAY,MAAM,SAAS,IAC3C,CAAC,KAAK,IACN,CAAC;;;;;;AAON,MAAa,gBAAgB,UAC5B,MACE,MAAM,WAAW,EACjB,KAAK,SAAS,KAAK,KAAK,CAAC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B,MAAM,2BAA2B;;;;;;;AAQjC,MAAM,4BACL,KACA,gBAC0B;CAC1B,MAAM,SAAS,IAAI,UAAU;CAC7B,IAAI,kBAAkB,SACrB,OAAO;CAER,MAAM,UAAU,QAAQ,QAAQ,EAC9B,WAAW,YAAY,EAAE,IAAI,CAAC,CAAC,EAC/B,MAAM,YAAY,IAAI,IAAI,QAAQ,KAAK,WAAW,OAAO,MAAM,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC;CACvF,IAAI,IAAI,SACP,IAAI,QAAQ,4BAA4B;CAEzC,OAAO;AACR;;;;;;;AASA,MAAa,uBACZ,MACA,UACA,UACA,OAKI,CAAC,MACU;CACf,MAAM,EAAE,gBAAgB;CACxB,MAAM,iBAAiB,eACnB,QAAwB,yBAAyB,KAAK,WAAW,IAClE,KAAA;CACH,OAAO;EACN;EACA,MAAM;EACN,SAAS;EACT,OAAO,SAAS,QAAQ;EACxB,UAAU,mBAAmB;GAC5B,iBAAiB,KAAK,YAAY,mBAAmB,CAAC,OAAO;GAC7D,aAAa,KAAK,YAAY;GAC9B,aAAa,KAAK,YAAY;GAC9B;EACD,CAAC;EACD,GAAG,YAAY,QAAQ;EACvB,OAAO;GACN,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GAC1C,YAAY,EACX,OAAO;IACN,MAAM;IACN,aAAa;KACZ,GAAI,KAAK,WAAW,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;KACnD,GAAI,KAAK,YAAY,gBAAgB,QAAQ,EAAE,aAAa,MAAM,IAAI,CAAC;KACvE,GAAI,KAAK,YAAY,gBAAgB,QAAQ,EAAE,aAAa,MAAM,IAAI,CAAC;KACvE,GAAI,KAAK,YAAY,kBAClB,EAAE,iBAAiB,KAAK,WAAW,gBAAgB,IACnD,CAAC;IACL;GACD,EACD;EACD;CACD;AACD"}
1
+ {"version":3,"file":"emailRecipients.js","names":[],"sources":["../../src/actions/emailRecipients.ts"],"sourcesContent":["import type { PayloadRequest, TextField } from 'payload'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { localizedIf } from '../fields/localizedIf'\nimport { interpolate } from '../recall/interpolate'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelFor } from '../translations/server'\nimport type {\n\tRecipientResolveArgs,\n\tRecipientSource,\n\tRecipientSourceRegistry,\n} from './recipientSources'\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst TOKEN_RE = /^\\{\\{\\s*([\\w.-]+)\\s*\\}\\}$/\n\n/** A plausible email address (a permissive shape check, not full RFC validation). */\nexport const isPlausibleEmail = (value: string): boolean => EMAIL_RE.test(value.trim())\n\n/** The field name inside a `{{name}}` recipient token, or undefined when the string is not a token. */\nexport const parseFieldToken = (value: string): string | undefined => {\n\tconst match = TOKEN_RE.exec(value.trim())\n\treturn match ? match[1] : undefined\n}\n\nexport const isFieldToken = (value: string): boolean => parseFieldToken(value) !== undefined\n\nconst toList = (value: unknown): string[] =>\n\tArray.isArray(value)\n\t\t? value.filter((entry): entry is string => typeof entry === 'string')\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\n/**\n * The first plausible email in a resolved value, or empty. A recipient entry names a single address,\n * so this drops anything past a separator or CR/LF that a `{{field}}` token might interpolate from\n * visitor input, closing SMTP header injection and extra-recipient injection.\n */\nexport const firstAddress = (value: string): string =>\n\tvalue\n\t\t.split(/[,;\\n\\r]+/)\n\t\t.map((part) => part.trim())\n\t\t.find(isPlausibleEmail) ?? ''\n\n/**\n * Resolve a stored recipient value (a `string[]`, or a legacy single string) to the comma-separated\n * list `payload.sendEmail` accepts: each entry is interpolated (a `{{field}}` token resolves from the\n * submission, a plain email passes through), sanitized to a single address, empties dropped, joined.\n */\nexport const resolveRecipients = (value: unknown, resolve: (name: string) => string): string =>\n\ttoList(value)\n\t\t.map((entry) => firstAddress(interpolate(entry, resolve)))\n\t\t.filter((entry) => entry.length > 0)\n\t\t.join(', ')\n\n/**\n * Async recipient resolution for the email actions, extending `resolveRecipients` with server-resolved\n * sources. A registered source value calls its `resolve` (each returned address reduced to one by\n * `firstAddress`, so a source cannot inject headers or extra recipients either); a `{{token}}`/plain\n * email resolves exactly as before. Returns a clean address list (`[]` when nothing resolves) so the\n * caller can skip an empty send. A thrown resolver propagates, failing the action loudly rather than\n * sending to a shortened list.\n */\nexport const resolveRecipientEntries = async (\n\tvalue: unknown,\n\topts: {\n\t\tresolve: (name: string) => string\n\t\tsources?: Map<string, RecipientSource>\n\t\tsourceArgs?: RecipientResolveArgs\n\t}\n): Promise<string[]> => {\n\tconst out: string[] = []\n\tfor (const entry of toList(value)) {\n\t\tconst source = opts.sources?.get(entry)\n\t\tif (source) {\n\t\t\t// A source only resolves with the run-time args; there are none at authoring/validation time.\n\t\t\tconst resolved = opts.sourceArgs ? await source.resolve(opts.sourceArgs) : []\n\t\t\tfor (const address of resolved) {\n\t\t\t\tconst clean = firstAddress(address)\n\t\t\t\tif (clean) {\n\t\t\t\t\tout.push(clean)\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst clean = firstAddress(interpolate(entry, opts.resolve))\n\t\tif (clean) {\n\t\t\tout.push(clean)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Field `validate` for a recipient list: unset is fine; otherwise every entry must be a valid email\n * or a `{{field}}` token naming an existing field of an allowed token type. When `allowCustom` is\n * false, a non-token entry must additionally be a member of the resolved options (`resolveAllowed`,\n * e.g. the department addresses), matching the client constraint on the server. Fails closed if the\n * options resolver throws (mirroring the `from` field). Reads the form's `fields` off `data`. Like\n * `from`, Payload runs this on every save, so the resolver is consulted each save under\n * `allowCustom: false`; `buildRecipientField` memoizes it per request so all recipient fields share one call.\n */\nexport const validateRecipients =\n\t(opts: {\n\t\ttokenFieldTypes?: string[]\n\t\tallowCustom?: boolean\n\t\tfieldTokens?: boolean\n\t\tresolveAllowed?: (req: PayloadRequest) => Set<string> | Promise<Set<string>>\n\t\t/** Stored values of registered recipient sources; a member is a valid recipient by itself. */\n\t\tsourceValues?: Set<string>\n\t}) =>\n\tasync (\n\t\tvalue: unknown,\n\t\t{ data, req }: { data?: unknown; req: PayloadRequest }\n\t): Promise<string | true> => {\n\t\tconst list = toList(value)\n\t\tif (list.length === 0) {\n\t\t\treturn true\n\t\t}\n\t\tconst fields =\n\t\t\tdata && typeof data === 'object' ? (data as Record<string, unknown>).fields : undefined\n\t\tconst { tokenFieldTypes, allowCustom, fieldTokens, resolveAllowed } = opts\n\t\tconst allowedFields = new Set(\n\t\t\ttokenFieldTypes && tokenFieldTypes.length > 0\n\t\t\t\t? fieldNamesOfType(fields, tokenFieldTypes)\n\t\t\t\t: fieldNames(fields)\n\t\t)\n\t\t// Only resolve the membership set when it is actually enforced (allowCustom explicitly false),\n\t\t// so the default (free-typed) path pays no resolver cost. Compare case-insensitively, matching\n\t\t// the client's dedupe, since email delivery ignores case.\n\t\tlet allowedValues: Set<string> | undefined\n\t\tif (allowCustom === false) {\n\t\t\tif (resolveAllowed) {\n\t\t\t\ttry {\n\t\t\t\t\tallowedValues = await resolveAllowed(req)\n\t\t\t\t} catch {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientOptionsUnavailable)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallowedValues = new Set()\n\t\t\t}\n\t\t}\n\t\tfor (const entry of list) {\n\t\t\t// A registered source value is a valid recipient on its own: checked first, so a same-named form\n\t\t\t// field cannot shadow it and `allowCustom: false` cannot block it (it is not a custom address).\n\t\t\tif (opts.sourceValues?.has(entry)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst token = parseFieldToken(entry)\n\t\t\tif (token) {\n\t\t\t\t// `fieldTokens: false` disables recipient tokens; enforce it on the server, not just the client.\n\t\t\t\tif (fieldTokens === false) {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientNotAllowed)\n\t\t\t\t}\n\t\t\t\tif (!allowedFields.has(token)) {\n\t\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientUnknownField)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!isPlausibleEmail(entry)) {\n\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientInvalid)\n\t\t\t}\n\t\t\tif (allowCustom === false && !allowedValues?.has(entry.trim().toLowerCase())) {\n\t\t\t\treturn asTranslate(req.t)(keys.validationRecipientNotAllowed)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n/** Host-configurable behavior for the recipient fields (plugin option `email.recipients`). */\nexport type RecipientsConfig = {\n\t/** Allow free-typed emails (default true). */\n\tallowCustom?: boolean\n\t/** Offer the form's own fields as recipient tokens (default true). */\n\tfieldTokens?: boolean\n\t/** Field types eligible as tokens (default `['email']`). */\n\ttokenFieldTypes?: string[]\n}\n\nconst RECIPIENTS_FIELD_REF = '@10x-media/form-builder/client#RecipientsSelect'\n\nconst DEPARTMENT_ALLOWED_CACHE = 'formBuilderDepartmentAllowedSet'\n\n/**\n * The department option values as a lowercased Set, memoized on `req.context` so every recipient\n * field validated in one save shares a single `departments` call. Payload validates the fields\n * concurrently, so the in-flight promise is cached synchronously (not the resolved value) to avoid a\n * resolve-per-field race. Lowercased because email delivery ignores case, matching the client dedupe.\n */\nconst resolveDepartmentAllowed = (\n\treq: PayloadRequest,\n\tdepartments: DepartmentEmailsResolver\n): Promise<Set<string>> => {\n\tconst cached = req.context?.[DEPARTMENT_ALLOWED_CACHE]\n\tif (cached instanceof Promise) {\n\t\treturn cached as Promise<Set<string>>\n\t}\n\tconst promise = Promise.resolve()\n\t\t.then(() => departments({ req }))\n\t\t.then((options) => new Set(options.map((option) => option.value.trim().toLowerCase())))\n\tif (req.context) {\n\t\treq.context[DEPARTMENT_ALLOWED_CACHE] = promise\n\t}\n\treturn promise\n}\n\n/**\n * A `text hasMany` field rendered by `RecipientsSelect`, used for every email address list. `endpoint`\n * (when set) supplies preset options (e.g. the host's departments); `recipients` narrows the field's\n * behavior; `width` sets `admin.width` so a pair can share a row; `departments` (when set) backs\n * server-side `allowCustom: false` enforcement with the resolved option values.\n */\n// biome-ignore lint/complexity/useMaxParams: the field identity (name, label, localize) plus its grouped options is the minimal surface\nexport const buildRecipientField = (\n\tname: string,\n\tlabelKey: string,\n\tlocalize: boolean,\n\topts: {\n\t\tendpoint?: string\n\t\trecipients?: RecipientsConfig\n\t\twidth?: string\n\t\tdepartments?: DepartmentEmailsResolver\n\t\tsources?: RecipientSourceRegistry\n\t} = {}\n): TextField => {\n\tconst { departments } = opts\n\tconst resolveAllowed = departments\n\t\t? (req: PayloadRequest) => resolveDepartmentAllowed(req, departments)\n\t\t: undefined\n\tconst sourceList = Object.values(opts.sources ?? {})\n\tconst sourceValues = sourceList.length > 0 ? new Set(sourceList.map((s) => s.value)) : undefined\n\treturn {\n\t\tname,\n\t\ttype: 'text',\n\t\thasMany: true,\n\t\tlabel: labelFor(labelKey),\n\t\tvalidate: validateRecipients({\n\t\t\ttokenFieldTypes: opts.recipients?.tokenFieldTypes ?? ['email'],\n\t\t\tallowCustom: opts.recipients?.allowCustom,\n\t\t\tfieldTokens: opts.recipients?.fieldTokens,\n\t\t\tresolveAllowed,\n\t\t\tsourceValues,\n\t\t}),\n\t\t...localizedIf(localize),\n\t\tadmin: {\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: RECIPIENTS_FIELD_REF,\n\t\t\t\t\tclientProps: {\n\t\t\t\t\t\t// The departments option set is request-scoped, so it loads before the first save.\n\t\t\t\t\t\t...(opts.endpoint ? { endpoint: opts.endpoint, scope: 'request' } : {}),\n\t\t\t\t\t\t...(opts.recipients?.allowCustom === false ? { allowCustom: false } : {}),\n\t\t\t\t\t\t...(opts.recipients?.fieldTokens === false ? { fieldTokens: false } : {}),\n\t\t\t\t\t\t...(opts.recipients?.tokenFieldTypes\n\t\t\t\t\t\t\t? { tokenFieldTypes: opts.recipients.tokenFieldTypes }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(sourceList.length > 0\n\t\t\t\t\t\t\t? { sources: sourceList.map((s) => ({ value: s.value, label: s.label })) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAaA,MAAM,WAAW;AACjB,MAAM,WAAW;;AAGjB,MAAa,oBAAoB,UAA2B,SAAS,KAAK,MAAM,KAAK,CAAC;;AAGtF,MAAa,mBAAmB,UAAsC;CACrE,MAAM,QAAQ,SAAS,KAAK,MAAM,KAAK,CAAC;CACxC,OAAO,QAAQ,MAAM,KAAK,KAAA;AAC3B;AAIA,MAAM,UAAU,UACf,MAAM,QAAQ,KAAK,IAChB,MAAM,QAAQ,UAA2B,OAAO,UAAU,QAAQ,IAClE,OAAO,UAAU,YAAY,MAAM,SAAS,IAC3C,CAAC,KAAK,IACN,CAAC;;;;;;AAON,MAAa,gBAAgB,UAC5B,MACE,MAAM,WAAW,EACjB,KAAK,SAAS,KAAK,KAAK,CAAC,EACzB,KAAK,gBAAgB,KAAK;;;;;;;;;AAqB7B,MAAa,0BAA0B,OACtC,OACA,SAKuB;CACvB,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,SAAS,OAAO,KAAK,GAAG;EAClC,MAAM,SAAS,KAAK,SAAS,IAAI,KAAK;EACtC,IAAI,QAAQ;GAEX,MAAM,WAAW,KAAK,aAAa,MAAM,OAAO,QAAQ,KAAK,UAAU,IAAI,CAAC;GAC5E,KAAK,MAAM,WAAW,UAAU;IAC/B,MAAM,QAAQ,aAAa,OAAO;IAClC,IAAI,OACH,IAAI,KAAK,KAAK;GAEhB;GACA;EACD;EACA,MAAM,QAAQ,aAAa,YAAY,OAAO,KAAK,OAAO,CAAC;EAC3D,IAAI,OACH,IAAI,KAAK,KAAK;CAEhB;CACA,OAAO;AACR;;;;;;;;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;KAAM,EAAE,EAAE,IACvE,CAAC;IACL;GACD,EACD;EACD;CACD;AACD"}
@@ -0,0 +1,27 @@
1
+ import { SubmissionContextArgs } from "./submissionContext.js";
2
+
3
+ //#region src/actions/emailRender.d.ts
4
+ /** The built-in email actions `email.render` runs for. */
5
+ type EmailActionType = 'emailTeam' | 'confirmation';
6
+ /**
7
+ * What `email.render` receives per outgoing email: the finished body `html` (the default pipeline's
8
+ * output, or `richText.serialize`'s when set), the raw `body` it was rendered from, the interpolated
9
+ * `subject`, the `actionType` sending it, and the submission context: `locale` (the submission's
10
+ * own), `form` (the whole document, see `SubmissionForm`), `submissionId`, `values`,
11
+ * `descriptors`, `context`, `payload`, and `req`.
12
+ */
13
+ type EmailRenderArgs = SubmissionContextArgs & {
14
+ html: string; /** The action's stored rich text (or legacy string) body config, before serialization. */
15
+ body: unknown;
16
+ subject: string;
17
+ actionType: EmailActionType;
18
+ };
19
+ /**
20
+ * Host hook producing the final `html` of every built-in email (plugin option `email.render`), e.g.
21
+ * to wrap the body in a branded, localized layout. It runs after the body is serialized, so it only
22
+ * wraps and never has to re-render rich text. A throw fails the action like a send failure does.
23
+ */
24
+ type EmailRender = (args: EmailRenderArgs) => Promise<string> | string;
25
+ //#endregion
26
+ export { EmailActionType, EmailRender, EmailRenderArgs };
27
+ //# sourceMappingURL=emailRender.d.ts.map