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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +12 -4
  3. package/dist/actions/assertNoBlockCollision.js +18 -0
  4. package/dist/actions/assertNoBlockCollision.js.map +1 -0
  5. package/dist/actions/body/serializeBody.d.ts +16 -14
  6. package/dist/actions/body/serializeBody.js +5 -8
  7. package/dist/actions/body/serializeBody.js.map +1 -1
  8. package/dist/actions/builtin/confirmation.js +2 -1
  9. package/dist/actions/builtin/confirmation.js.map +1 -1
  10. package/dist/actions/builtin/emailAction.d.ts +15 -3
  11. package/dist/actions/builtin/emailAction.js +72 -20
  12. package/dist/actions/builtin/emailAction.js.map +1 -1
  13. package/dist/actions/builtin/emailTeam.js +11 -5
  14. package/dist/actions/builtin/emailTeam.js.map +1 -1
  15. package/dist/actions/defineAction.d.ts +37 -6
  16. package/dist/actions/defineAction.js +14 -1
  17. package/dist/actions/defineAction.js.map +1 -1
  18. package/dist/actions/dispatch.d.ts +12 -0
  19. package/dist/actions/dispatch.js +103 -30
  20. package/dist/actions/dispatch.js.map +1 -1
  21. package/dist/actions/dispatchContext.js +19 -0
  22. package/dist/actions/dispatchContext.js.map +1 -0
  23. package/dist/actions/emailRecipients.js +38 -8
  24. package/dist/actions/emailRecipients.js.map +1 -1
  25. package/dist/actions/emailRender.d.ts +27 -0
  26. package/dist/actions/fromAddresses.d.ts +19 -1
  27. package/dist/actions/fromAddresses.js +66 -9
  28. package/dist/actions/fromAddresses.js.map +1 -1
  29. package/dist/actions/recipientSources.d.ts +23 -0
  30. package/dist/actions/recipientSources.js +11 -0
  31. package/dist/actions/recipientSources.js.map +1 -0
  32. package/dist/actions/registry.js +3 -1
  33. package/dist/actions/registry.js.map +1 -1
  34. package/dist/actions/runActions.d.ts +2 -0
  35. package/dist/actions/runActions.js +13 -8
  36. package/dist/actions/runActions.js.map +1 -1
  37. package/dist/actions/sign.js.map +1 -1
  38. package/dist/actions/submissionContext.d.ts +34 -0
  39. package/dist/actions/task.js +43 -16
  40. package/dist/actions/task.js.map +1 -1
  41. package/dist/aggregation/aggregateResponses.js +3 -4
  42. package/dist/aggregation/aggregateResponses.js.map +1 -1
  43. package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
  44. package/dist/aggregation/resolveResultsRequest.js +69 -26
  45. package/dist/aggregation/resolveResultsRequest.js.map +1 -1
  46. package/dist/calc/computeCalcFields.d.ts +5 -3
  47. package/dist/calc/computeCalcFields.js +4 -3
  48. package/dist/calc/computeCalcFields.js.map +1 -1
  49. package/dist/calc/evaluate.d.ts +26 -3
  50. package/dist/calc/evaluate.js +33 -11
  51. package/dist/calc/evaluate.js.map +1 -1
  52. package/dist/calc/formatCalc.d.ts +11 -0
  53. package/dist/calc/formatCalc.js +35 -0
  54. package/dist/calc/formatCalc.js.map +1 -0
  55. package/dist/calc/formatCalcValue.d.ts +17 -0
  56. package/dist/calc/formatCalcValue.js +17 -0
  57. package/dist/calc/formatCalcValue.js.map +1 -0
  58. package/dist/calc/normalizeCalc.d.ts +17 -3
  59. package/dist/calc/normalizeCalc.js +39 -17
  60. package/dist/calc/normalizeCalc.js.map +1 -1
  61. package/dist/calc/registry.d.ts +43 -0
  62. package/dist/calc/registry.js +27 -0
  63. package/dist/calc/registry.js.map +1 -0
  64. package/dist/calc/resolveCalcContext.d.ts +36 -0
  65. package/dist/calc/resolveCalcContext.js +87 -0
  66. package/dist/calc/resolveCalcContext.js.map +1 -0
  67. package/dist/calc/types.d.ts +19 -4
  68. package/dist/calc/types.js +3 -2
  69. package/dist/calc/types.js.map +1 -1
  70. package/dist/client/ByteSizeField.js +11 -8
  71. package/dist/client/ByteSizeField.js.map +1 -1
  72. package/dist/client/CalcExpressionBuilder.d.ts +20 -0
  73. package/dist/client/CalcExpressionBuilder.js +888 -0
  74. package/dist/client/CalcExpressionBuilder.js.map +1 -0
  75. package/dist/client/ClosePollButton.js +3 -3
  76. package/dist/client/ClosePollButton.js.map +1 -1
  77. package/dist/client/CondensedArray.d.ts +2 -2
  78. package/dist/client/CondensedArray.js +5 -7
  79. package/dist/client/CondensedArray.js.map +1 -1
  80. package/dist/client/ConditionBuilder.js +5 -7
  81. package/dist/client/ConditionBuilder.js.map +1 -1
  82. package/dist/client/ConditionRow.js +3 -3
  83. package/dist/client/ConditionRow.js.map +1 -1
  84. package/dist/client/ConsentBlockLabel.js +2 -2
  85. package/dist/client/ConsentBlockLabel.js.map +1 -1
  86. package/dist/client/ConsentRetentionNotice.d.ts +11 -0
  87. package/dist/client/ConsentRetentionNotice.js +23 -0
  88. package/dist/client/ConsentRetentionNotice.js.map +1 -0
  89. package/dist/client/EndpointOptionsSelect.d.ts +17 -7
  90. package/dist/client/EndpointOptionsSelect.js +18 -14
  91. package/dist/client/EndpointOptionsSelect.js.map +1 -1
  92. package/dist/client/FieldBlockLabel.js +2 -2
  93. package/dist/client/FieldBlockLabel.js.map +1 -1
  94. package/dist/client/FieldNameSelect.d.ts +1 -0
  95. package/dist/client/FieldNameSelect.js +2 -4
  96. package/dist/client/FieldNameSelect.js.map +1 -1
  97. package/dist/client/FlowBuilder.js +31 -23
  98. package/dist/client/FlowBuilder.js.map +1 -1
  99. package/dist/client/FormConditionField.js +0 -1
  100. package/dist/client/FormConditionField.js.map +1 -1
  101. package/dist/client/RecipientsSelect.d.ts +9 -2
  102. package/dist/client/RecipientsSelect.js +31 -10
  103. package/dist/client/RecipientsSelect.js.map +1 -1
  104. package/dist/client/admin.css +345 -72
  105. package/dist/client/endpointOptions.d.ts +11 -0
  106. package/dist/client/endpointOptions.js +17 -8
  107. package/dist/client/endpointOptions.js.map +1 -1
  108. package/dist/collections/formSubmissions.js +145 -51
  109. package/dist/collections/formSubmissions.js.map +1 -1
  110. package/dist/collections/forms.js +170 -65
  111. package/dist/collections/forms.js.map +1 -1
  112. package/dist/collections/formsEndpoints.js +31 -26
  113. package/dist/collections/formsEndpoints.js.map +1 -1
  114. package/dist/collections/settingsFields.d.ts +32 -0
  115. package/dist/collections/settingsFields.js +55 -0
  116. package/dist/collections/settingsFields.js.map +1 -0
  117. package/dist/consent/captureConsent.d.ts +2 -1
  118. package/dist/consent/captureConsent.js +4 -1
  119. package/dist/consent/captureConsent.js.map +1 -1
  120. package/dist/consent/consentSourcesField.d.ts +7 -1
  121. package/dist/consent/consentSourcesField.js +15 -1
  122. package/dist/consent/consentSourcesField.js.map +1 -1
  123. package/dist/consent/effectiveStatement.js +16 -0
  124. package/dist/consent/effectiveStatement.js.map +1 -0
  125. package/dist/consent/resolveConsentSourcesRequest.js +2 -2
  126. package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
  127. package/dist/consent/resolveConsentStatements.js +3 -1
  128. package/dist/consent/resolveConsentStatements.js.map +1 -1
  129. package/dist/consent/resolvePublishedVersionRef.js +1 -0
  130. package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
  131. package/dist/consent/types.d.ts +8 -0
  132. package/dist/context/formContext.d.ts +30 -0
  133. package/dist/context/formContext.js +54 -0
  134. package/dist/context/formContext.js.map +1 -0
  135. package/dist/email/departmentsField.d.ts +6 -1
  136. package/dist/email/departmentsField.js +6 -1
  137. package/dist/email/departmentsField.js.map +1 -1
  138. package/dist/exports/client.d.ts +3 -1
  139. package/dist/exports/client.js +3 -1
  140. package/dist/exports/i18n.d.ts +14 -2
  141. package/dist/exports/i18n.js +14 -2
  142. package/dist/exports/react.d.ts +23 -5
  143. package/dist/exports/react.js +17 -1
  144. package/dist/exports/rsc.d.ts +4 -1
  145. package/dist/exports/rsc.js +7 -4
  146. package/dist/exports/shared.d.ts +21 -0
  147. package/dist/exports/shared.js +18 -0
  148. package/dist/exports/types.d.ts +4 -3
  149. package/dist/fields/buildFieldBlocks.js +2 -1
  150. package/dist/fields/buildFieldBlocks.js.map +1 -1
  151. package/dist/fields/builtin/calculation.d.ts +17 -0
  152. package/dist/fields/builtin/calculation.js +70 -127
  153. package/dist/fields/builtin/calculation.js.map +1 -1
  154. package/dist/fields/builtin/checkbox.js +15 -0
  155. package/dist/fields/builtin/checkbox.js.map +1 -1
  156. package/dist/fields/builtin/consent.js +21 -1
  157. package/dist/fields/builtin/consent.js.map +1 -1
  158. package/dist/fields/builtin/email.js +7 -0
  159. package/dist/fields/builtin/email.js.map +1 -1
  160. package/dist/fields/builtin/index.d.ts +6 -2
  161. package/dist/fields/builtin/index.js +9 -4
  162. package/dist/fields/builtin/index.js.map +1 -1
  163. package/dist/fields/builtin/select.js +20 -1
  164. package/dist/fields/builtin/select.js.map +1 -1
  165. package/dist/fields/builtin/text.js +7 -0
  166. package/dist/fields/builtin/text.js.map +1 -1
  167. package/dist/fields/instanceOptions.js +1 -1
  168. package/dist/fields/instanceOptions.js.map +1 -1
  169. package/dist/fields/sharedConfig.js +15 -11
  170. package/dist/fields/sharedConfig.js.map +1 -1
  171. package/dist/fields/types.d.ts +8 -2
  172. package/dist/form/findFormAtLocale.d.ts +30 -0
  173. package/dist/form/findFormAtLocale.js +88 -0
  174. package/dist/form/findFormAtLocale.js.map +1 -0
  175. package/dist/form/pollState.d.ts +2 -1
  176. package/dist/form/pollState.js.map +1 -1
  177. package/dist/form/toFormDocument.d.ts +18 -6
  178. package/dist/form/toFormDocument.js +3 -1
  179. package/dist/form/toFormDocument.js.map +1 -1
  180. package/dist/form/types.d.ts +9 -1
  181. package/dist/index.d.ts +29 -7
  182. package/dist/index.js +74 -18
  183. package/dist/index.js.map +1 -1
  184. package/dist/options.d.ts +119 -4
  185. package/dist/plugin/collectionSlugs.d.ts +28 -0
  186. package/dist/plugin/collectionSlugs.js +65 -0
  187. package/dist/plugin/collectionSlugs.js.map +1 -0
  188. package/dist/plugin/customState.js +1 -1
  189. package/dist/plugin/customState.js.map +1 -1
  190. package/dist/plugin/registerCollections.js +38 -21
  191. package/dist/plugin/registerCollections.js.map +1 -1
  192. package/dist/poll/closeJob.d.ts +4 -3
  193. package/dist/poll/closeJob.js +13 -10
  194. package/dist/poll/closeJob.js.map +1 -1
  195. package/dist/poll/outcomeBeforeChange.js +2 -2
  196. package/dist/poll/outcomeBeforeChange.js.map +1 -1
  197. package/dist/poll/pollTypeRegistry.js +1 -1
  198. package/dist/poll/resolvePollCloseRequest.js +5 -4
  199. package/dist/poll/resolvePollCloseRequest.js.map +1 -1
  200. package/dist/poll/resolvePollOptionsRequest.js +2 -2
  201. package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
  202. package/dist/poll/resolvePollOutcome.d.ts +6 -0
  203. package/dist/poll/resolvePollOutcome.js +20 -6
  204. package/dist/poll/resolvePollOutcome.js.map +1 -1
  205. package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
  206. package/dist/poll/votes/aggregateFromVotes.js +55 -0
  207. package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
  208. package/dist/poll/votes/answerValues.js +16 -0
  209. package/dist/poll/votes/answerValues.js.map +1 -0
  210. package/dist/poll/votes/bumpPollVote.js +91 -0
  211. package/dist/poll/votes/bumpPollVote.js.map +1 -0
  212. package/dist/poll/votes/recountPollVotes.d.ts +20 -0
  213. package/dist/poll/votes/recountPollVotes.js +63 -0
  214. package/dist/poll/votes/recountPollVotes.js.map +1 -0
  215. package/dist/poll/votes/voteTallyHook.js +76 -0
  216. package/dist/poll/votes/voteTallyHook.js.map +1 -0
  217. package/dist/poll/votes/votesCollection.d.ts +23 -0
  218. package/dist/poll/votes/votesCollection.js +96 -0
  219. package/dist/poll/votes/votesCollection.js.map +1 -0
  220. package/dist/react/Form.d.ts +49 -7
  221. package/dist/react/Form.js +48 -13
  222. package/dist/react/Form.js.map +1 -1
  223. package/dist/react/FormContext.d.ts +8 -1
  224. package/dist/react/FormContext.js.map +1 -1
  225. package/dist/react/FormResults.d.ts +4 -2
  226. package/dist/react/FormResults.js +21 -8
  227. package/dist/react/FormResults.js.map +1 -1
  228. package/dist/react/Poll.d.ts +25 -2
  229. package/dist/react/Poll.js +76 -25
  230. package/dist/react/Poll.js.map +1 -1
  231. package/dist/react/adapters.d.ts +35 -0
  232. package/dist/react/adapters.js +11 -0
  233. package/dist/react/adapters.js.map +1 -0
  234. package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
  235. package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
  236. package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
  237. package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
  238. package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
  239. package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
  240. package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
  241. package/dist/react/captcha/TurnstileCaptcha.js +2 -2
  242. package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
  243. package/dist/react/captcha/useCaptchaScript.js +23 -5
  244. package/dist/react/captcha/useCaptchaScript.js.map +1 -1
  245. package/dist/react/fetchResults.d.ts +6 -3
  246. package/dist/react/fetchResults.js +10 -5
  247. package/dist/react/fetchResults.js.map +1 -1
  248. package/dist/react/primitives/Checkbox.d.ts +4 -2
  249. package/dist/react/primitives/Checkbox.js +3 -2
  250. package/dist/react/primitives/Checkbox.js.map +1 -1
  251. package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
  252. package/dist/react/primitives/ChoiceGroup.js +33 -0
  253. package/dist/react/primitives/ChoiceGroup.js.map +1 -0
  254. package/dist/react/primitives/FieldShell.d.ts +11 -1
  255. package/dist/react/primitives/FieldShell.js +43 -33
  256. package/dist/react/primitives/FieldShell.js.map +1 -1
  257. package/dist/react/primitives/Input.d.ts +3 -1
  258. package/dist/react/primitives/Input.js +2 -1
  259. package/dist/react/primitives/Input.js.map +1 -1
  260. package/dist/react/renderers/calculation.js +6 -1
  261. package/dist/react/renderers/calculation.js.map +1 -1
  262. package/dist/react/renderers/checkbox.js +2 -1
  263. package/dist/react/renderers/checkbox.js.map +1 -1
  264. package/dist/react/renderers/consent.js +8 -3
  265. package/dist/react/renderers/consent.js.map +1 -1
  266. package/dist/react/renderers/email.js +3 -1
  267. package/dist/react/renderers/email.js.map +1 -1
  268. package/dist/react/renderers/repeater.js +5 -0
  269. package/dist/react/renderers/repeater.js.map +1 -1
  270. package/dist/react/renderers/select.js +20 -2
  271. package/dist/react/renderers/select.js.map +1 -1
  272. package/dist/react/renderers/text.js +3 -1
  273. package/dist/react/renderers/text.js.map +1 -1
  274. package/dist/react/state.d.ts +10 -0
  275. package/dist/react/state.js +45 -1
  276. package/dist/react/state.js.map +1 -1
  277. package/dist/react/submitForm.d.ts +20 -3
  278. package/dist/react/submitForm.js +8 -4
  279. package/dist/react/submitForm.js.map +1 -1
  280. package/dist/react/useCalcValues.d.ts +10 -0
  281. package/dist/react/useCalcValues.js +13 -0
  282. package/dist/react/useCalcValues.js.map +1 -0
  283. package/dist/react/useField.js +2 -1
  284. package/dist/react/useField.js.map +1 -1
  285. package/dist/recall/resolver.js +1 -1
  286. package/dist/recall/resolver.js.map +1 -1
  287. package/dist/spam/constants.js +7 -1
  288. package/dist/spam/constants.js.map +1 -1
  289. package/dist/spam/spamGuard.js +2 -1
  290. package/dist/spam/spamGuard.js.map +1 -1
  291. package/dist/submissions/SubmissionAnswersClient.js +14 -14
  292. package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
  293. package/dist/submissions/createSubmission.d.ts +7 -1
  294. package/dist/submissions/createSubmission.js +10 -5
  295. package/dist/submissions/createSubmission.js.map +1 -1
  296. package/dist/submissions/formIdOf.js +13 -0
  297. package/dist/submissions/formIdOf.js.map +1 -0
  298. package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
  299. package/dist/submissions/resolveVotedSubmission.js +51 -0
  300. package/dist/submissions/resolveVotedSubmission.js.map +1 -0
  301. package/dist/submissions/runSubmission.js +6 -5
  302. package/dist/submissions/runSubmission.js.map +1 -1
  303. package/dist/submissions/submissionLocale.js +39 -0
  304. package/dist/submissions/submissionLocale.js.map +1 -0
  305. package/dist/submissions/validateSubmission.js +125 -79
  306. package/dist/submissions/validateSubmission.js.map +1 -1
  307. package/dist/submissions/verifyContext.js +35 -0
  308. package/dist/submissions/verifyContext.js.map +1 -0
  309. package/dist/submissions/voteChange.js +21 -0
  310. package/dist/submissions/voteChange.js.map +1 -0
  311. package/dist/submissions/voteChangeEndpoint.js +110 -0
  312. package/dist/submissions/voteChangeEndpoint.js.map +1 -0
  313. package/dist/submissions/votedCookie.d.ts +10 -4
  314. package/dist/submissions/votedCookie.js +49 -11
  315. package/dist/submissions/votedCookie.js.map +1 -1
  316. package/dist/translations/ar.d.ts +7 -0
  317. package/dist/translations/ar.js +379 -0
  318. package/dist/translations/ar.js.map +1 -0
  319. package/dist/translations/clientRuntimeKeys.d.ts +17 -0
  320. package/dist/translations/clientRuntimeKeys.js +48 -0
  321. package/dist/translations/clientRuntimeKeys.js.map +1 -0
  322. package/dist/translations/de.d.ts +12 -0
  323. package/dist/translations/de.js +78 -3
  324. package/dist/translations/de.js.map +1 -1
  325. package/dist/translations/en.js +78 -3
  326. package/dist/translations/en.js.map +1 -1
  327. package/dist/translations/es.d.ts +7 -0
  328. package/dist/translations/es.js +379 -0
  329. package/dist/translations/es.js.map +1 -0
  330. package/dist/translations/fr.d.ts +7 -0
  331. package/dist/translations/fr.js +379 -0
  332. package/dist/translations/fr.js.map +1 -0
  333. package/dist/translations/id.d.ts +7 -0
  334. package/dist/translations/id.js +379 -0
  335. package/dist/translations/id.js.map +1 -0
  336. package/dist/translations/index.d.ts +23 -6
  337. package/dist/translations/index.js +31 -6
  338. package/dist/translations/index.js.map +1 -1
  339. package/dist/translations/keys.d.ts +76 -1
  340. package/dist/translations/keys.js +76 -1
  341. package/dist/translations/keys.js.map +1 -1
  342. package/dist/translations/ko.d.ts +7 -0
  343. package/dist/translations/ko.js +379 -0
  344. package/dist/translations/ko.js.map +1 -0
  345. package/dist/translations/makeTranslate.d.ts +7 -3
  346. package/dist/translations/makeTranslate.js +12 -3
  347. package/dist/translations/makeTranslate.js.map +1 -1
  348. package/dist/translations/pt.d.ts +7 -0
  349. package/dist/translations/pt.js +379 -0
  350. package/dist/translations/pt.js.map +1 -0
  351. package/dist/translations/ru.d.ts +7 -0
  352. package/dist/translations/ru.js +379 -0
  353. package/dist/translations/ru.js.map +1 -0
  354. package/dist/translations/uk.d.ts +7 -0
  355. package/dist/translations/uk.js +379 -0
  356. package/dist/translations/uk.js.map +1 -0
  357. package/dist/translations/zh.d.ts +7 -0
  358. package/dist/translations/zh.js +379 -0
  359. package/dist/translations/zh.js.map +1 -0
  360. package/dist/validation/builtin/index.js +2 -0
  361. package/dist/validation/builtin/index.js.map +1 -1
  362. package/dist/validation/builtin/integer.js +15 -0
  363. package/dist/validation/builtin/integer.js.map +1 -0
  364. package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
  365. package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
  366. package/package.json +29 -16
  367. package/styles/form-builder.css +84 -0
@@ -0,0 +1,55 @@
1
+ import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
2
+ import "./votesCollection.js";
3
+ //#region src/poll/votes/aggregateFromVotes.ts
4
+ const round1 = (n) => Math.round(n * 10) / 10;
5
+ /**
6
+ * Poll results from the tally store: one find over the form's rows for the field (O(options),
7
+ * no scan, no truncation), buckets zero-seeded from the effective options so order and labels
8
+ * match the scan-based shape. Counts sum across shard rows (see VOTE_SHARDS). `total` comes
9
+ * from the respondents rows, keeping the percentage denominator exact for multi-value answers.
10
+ */
11
+ const aggregateFromVotes = async (args) => {
12
+ const { payload, formId, field, meta, options, req } = args;
13
+ const { docs } = await payload.find({
14
+ collection: pluginSlugsOf(payload).pollVotes,
15
+ where: { and: [{ form: { equals: String(formId) } }, { field: { equals: field } }] },
16
+ limit: 1e5,
17
+ pagination: false,
18
+ depth: 0,
19
+ overrideAccess: true,
20
+ req
21
+ });
22
+ const counts = /* @__PURE__ */ new Map();
23
+ let total = 0;
24
+ for (const doc of docs) {
25
+ const value = doc.value == null ? "" : String(doc.value);
26
+ const count = typeof doc.count === "number" ? doc.count : 0;
27
+ if (value === "") total += count;
28
+ else counts.set(value, (counts.get(value) ?? 0) + count);
29
+ }
30
+ total = Math.max(0, total);
31
+ const optionValues = new Set(options.map((option) => option.value));
32
+ const leftovers = [...counts.keys()].filter((value) => !optionValues.has(value)).sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0));
33
+ const labelByValue = new Map(options.map((option) => [option.value, option.label]));
34
+ const buckets = [...options.map((option) => option.value), ...leftovers].map((value) => {
35
+ const count = Math.max(0, counts.get(value) ?? 0);
36
+ return {
37
+ value,
38
+ label: labelByValue.get(value) ?? value,
39
+ count,
40
+ percentage: total > 0 ? round1(count / total * 100) : 0
41
+ };
42
+ });
43
+ return {
44
+ field,
45
+ label: meta?.label,
46
+ fieldType: meta?.fieldType,
47
+ total,
48
+ buckets,
49
+ truncated: false
50
+ };
51
+ };
52
+ //#endregion
53
+ export { aggregateFromVotes };
54
+
55
+ //# sourceMappingURL=aggregateFromVotes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregateFromVotes.js","names":[],"sources":["../../../src/poll/votes/aggregateFromVotes.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { FieldAggregation } from '../../aggregation/types'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { RESPONDENTS_VALUE } from './votesCollection'\n\ntype VoteRow = { field?: unknown; value?: unknown; count?: unknown }\n\nconst round1 = (n: number): number => Math.round(n * 10) / 10\n\n/**\n * Poll results from the tally store: one find over the form's rows for the field (O(options),\n * no scan, no truncation), buckets zero-seeded from the effective options so order and labels\n * match the scan-based shape. Counts sum across shard rows (see VOTE_SHARDS). `total` comes\n * from the respondents rows, keeping the percentage denominator exact for multi-value answers.\n */\nexport const aggregateFromVotes = async (args: {\n\tpayload: Payload\n\tformId: number | string\n\tfield: string\n\tmeta?: { label?: string; fieldType?: string }\n\toptions: { value: string; label: string }[]\n\treq?: PayloadRequest\n}): Promise<FieldAggregation> => {\n\tconst { payload, formId, field, meta, options, req } = args\n\tconst { docs } = await payload.find({\n\t\tcollection: pluginSlugsOf(payload).pollVotes,\n\t\twhere: { and: [{ form: { equals: String(formId) } }, { field: { equals: field } }] },\n\t\tlimit: 100_000,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\n\tconst counts = new Map<string, number>()\n\tlet total = 0\n\tfor (const doc of docs as VoteRow[]) {\n\t\tconst value = doc.value == null ? RESPONDENTS_VALUE : String(doc.value)\n\t\tconst count = typeof doc.count === 'number' ? doc.count : 0\n\t\tif (value === RESPONDENTS_VALUE) {\n\t\t\ttotal += count\n\t\t} else {\n\t\t\tcounts.set(value, (counts.get(value) ?? 0) + count)\n\t\t}\n\t}\n\n\t// Clamp at read: a concurrent double-change can transiently double-decrement one value (see\n\t// the tally hook's drift note), and a negative bucket count must never surface to a reader.\n\ttotal = Math.max(0, total)\n\n\tconst optionValues = new Set(options.map((option) => option.value))\n\tconst leftovers = [...counts.keys()]\n\t\t.filter((value) => !optionValues.has(value))\n\t\t.sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0))\n\tconst labelByValue = new Map(options.map((option) => [option.value, option.label]))\n\n\tconst buckets = [...options.map((option) => option.value), ...leftovers].map((value) => {\n\t\tconst count = Math.max(0, counts.get(value) ?? 0)\n\t\treturn {\n\t\t\tvalue,\n\t\t\tlabel: labelByValue.get(value) ?? value,\n\t\t\tcount,\n\t\t\tpercentage: total > 0 ? round1((count / total) * 100) : 0,\n\t\t}\n\t})\n\n\treturn {\n\t\tfield,\n\t\tlabel: meta?.label,\n\t\tfieldType: meta?.fieldType,\n\t\ttotal,\n\t\tbuckets,\n\t\ttruncated: false,\n\t}\n}\n"],"mappings":";;;AAOA,MAAM,UAAU,MAAsB,KAAK,MAAM,IAAI,EAAE,IAAI;;;;;;;AAQ3D,MAAa,qBAAqB,OAAO,SAOR;CAChC,MAAM,EAAE,SAAS,QAAQ,OAAO,MAAM,SAAS,QAAQ;CACvD,MAAM,EAAE,SAAS,MAAM,QAAQ,KAAK;EACnC,YAAY,cAAc,OAAO,EAAE;EACnC,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,MAAM,EAAE,CAAC,EAAE;EACnF,OAAO;EACP,YAAY;EACZ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC;CAED,MAAM,yBAAS,IAAI,IAAoB;CACvC,IAAI,QAAQ;CACZ,KAAK,MAAM,OAAO,MAAmB;EACpC,MAAM,QAAQ,IAAI,SAAS,OAAA,KAA2B,OAAO,IAAI,KAAK;EACtE,MAAM,QAAQ,OAAO,IAAI,UAAU,WAAW,IAAI,QAAQ;EAC1D,IAAI,UAAA,IACH,SAAS;OAET,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,KAAK;CAEpD;CAIA,QAAQ,KAAK,IAAI,GAAG,KAAK;CAEzB,MAAM,eAAe,IAAI,IAAI,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;CAClE,MAAM,YAAY,CAAC,GAAG,OAAO,KAAK,CAAC,EACjC,QAAQ,UAAU,CAAC,aAAa,IAAI,KAAK,CAAC,EAC1C,MAAM,GAAG,OAAO,OAAO,IAAI,CAAC,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,EAAE;CAC5D,MAAM,eAAe,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC;CAElF,MAAM,UAAU,CAAC,GAAG,QAAQ,KAAK,WAAW,OAAO,KAAK,GAAG,GAAG,SAAS,EAAE,KAAK,UAAU;EACvF,MAAM,QAAQ,KAAK,IAAI,GAAG,OAAO,IAAI,KAAK,KAAK,CAAC;EAChD,OAAO;GACN;GACA,OAAO,aAAa,IAAI,KAAK,KAAK;GAClC;GACA,YAAY,QAAQ,IAAI,OAAQ,QAAQ,QAAS,GAAG,IAAI;EACzD;CACD,CAAC;CAED,OAAO;EACN;EACA,OAAO,MAAM;EACb,WAAW,MAAM;EACjB;EACA;EACA,WAAW;CACZ;AACD"}
@@ -0,0 +1,16 @@
1
+ //#region src/poll/votes/answerValues.ts
2
+ /**
3
+ * A submission's answer(s) for one field as normalized non-empty strings: the shape both the vote
4
+ * tally and the voted-pick resolver count by (a multi-select answer contributes one entry per
5
+ * selected value).
6
+ */
7
+ const answerValues = (values, field) => {
8
+ if (!Array.isArray(values)) return [];
9
+ const entry = values.find((row) => row.field === field);
10
+ if (entry == null) return [];
11
+ return (Array.isArray(entry.value) ? entry.value : [entry.value]).filter((value) => value != null && value !== "").map((value) => String(value));
12
+ };
13
+ //#endregion
14
+ export { answerValues };
15
+
16
+ //# sourceMappingURL=answerValues.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answerValues.js","names":[],"sources":["../../../src/poll/votes/answerValues.ts"],"sourcesContent":["import type { SubmissionValue } from '../../submissions/types'\n\n/**\n * A submission's answer(s) for one field as normalized non-empty strings: the shape both the vote\n * tally and the voted-pick resolver count by (a multi-select answer contributes one entry per\n * selected value).\n */\nexport const answerValues = (values: unknown, field: string): string[] => {\n\tif (!Array.isArray(values)) return []\n\tconst entry = (values as SubmissionValue[]).find((row) => row.field === field)\n\tif (entry == null) return []\n\tconst raw = Array.isArray(entry.value) ? entry.value : [entry.value]\n\treturn raw.filter((value) => value != null && value !== '').map((value) => String(value))\n}\n"],"mappings":";;;;;;AAOA,MAAa,gBAAgB,QAAiB,UAA4B;CACzE,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC;CACpC,MAAM,QAAS,OAA6B,MAAM,QAAQ,IAAI,UAAU,KAAK;CAC7E,IAAI,SAAS,MAAM,OAAO,CAAC;CAE3B,QADY,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,GACxD,QAAQ,UAAU,SAAS,QAAQ,UAAU,EAAE,EAAE,KAAK,UAAU,OAAO,KAAK,CAAC;AACzF"}
@@ -0,0 +1,91 @@
1
+ import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
2
+ import "./votesCollection.js";
3
+ import toSnakeCase from "to-snake-case";
4
+ //#region src/poll/votes/bumpPollVote.ts
5
+ /**
6
+ * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,
7
+ * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even
8
+ * though this branch is unreachable there. The function-built specifier is opaque to their
9
+ * analyzers, the ignore comments cover bundlers that would still warn, and the type-only
10
+ * reference above erases at compile time, so the package is touched only when the Postgres
11
+ * branch actually runs.
12
+ */
13
+ const importPostgresSql = () => {
14
+ return import(
15
+ /* webpackIgnore: true */
16
+ /* turbopackIgnore: true */
17
+ /* @vite-ignore */
18
+ ["@payloadcms", "db-postgres"].join("/")
19
+ );
20
+ };
21
+ /**
22
+ * Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment
23
+ * statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique
24
+ * compound index makes concurrent bumps for the same key safe without read-modify-write races.
25
+ * The shard column is internal: transactional Mongo bumps pick a random shard in
26
+ * [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);
27
+ * Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.
28
+ *
29
+ * When `transactionID` names an open Payload transaction, the write joins it: a bump failure
30
+ * thrown from the submission hook rolls back the submission create (no undercount), and an
31
+ * aborted create rolls back the joined bump (no overcount). Residual risk on transactional
32
+ * Mongo: two concurrent bumps that land on the same shard still abort one transaction
33
+ * (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,
34
+ * so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.
35
+ * Mongo with transactions disabled) the write lands on the root handle immediately; a later
36
+ * recount from stored submissions is the healer for any drift that window allows.
37
+ */
38
+ async function bumpPollVote(payload, key, by, transactionID) {
39
+ const slug = pluginSlugsOf(payload).pollVotes;
40
+ if (payload.db.name === "mongoose") {
41
+ const db = payload.db;
42
+ const model = db.collections[slug];
43
+ if (!model) throw new Error(`form-builder: mongoose collection "${slug}" not found`);
44
+ const session = transactionID !== void 0 ? db.sessions?.[transactionID] : void 0;
45
+ const shard = session ? Math.floor(Math.random() * 8) : 0;
46
+ const shardedKey = {
47
+ ...key,
48
+ shard
49
+ };
50
+ const update = {
51
+ $inc: { count: by },
52
+ $setOnInsert: shardedKey
53
+ };
54
+ const options = session ? {
55
+ upsert: true,
56
+ session
57
+ } : { upsert: true };
58
+ try {
59
+ await model.collection.updateOne(shardedKey, update, options);
60
+ } catch (error) {
61
+ const duplicate = error?.code === 11e3;
62
+ if (session || !duplicate) throw error;
63
+ await model.collection.updateOne(shardedKey, update, options);
64
+ }
65
+ return;
66
+ }
67
+ const { sql } = await importPostgresSql();
68
+ const db = payload.db;
69
+ const tableKey = toSnakeCase(slug);
70
+ const tableName = db.tableNameMap.get(tableKey);
71
+ if (!tableName) throw new Error(`form-builder: drizzle table "${tableKey}" not found`);
72
+ const table = db.tables[tableName];
73
+ if (!table) throw new Error(`form-builder: drizzle table object for "${tableName}" not found`);
74
+ await ((transactionID !== void 0 ? db.sessions?.[transactionID]?.db : void 0) ?? db.drizzle).insert(table).values({
75
+ ...key,
76
+ shard: 0,
77
+ count: by
78
+ }).onConflictDoUpdate({
79
+ target: [
80
+ table.form,
81
+ table.field,
82
+ table.value,
83
+ table.shard
84
+ ],
85
+ set: { count: sql`${table.count} + ${by}` }
86
+ });
87
+ }
88
+ //#endregion
89
+ export { bumpPollVote };
90
+
91
+ //# sourceMappingURL=bumpPollVote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bumpPollVote.js","names":[],"sources":["../../../src/poll/votes/bumpPollVote.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport toSnakeCase from 'to-snake-case'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { VOTE_SHARDS } from './votesCollection'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n\tsessions?: Record<number | string, unknown>\n}\ntype PgInsert = {\n\tinsert: (t: unknown) => {\n\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t}\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: PgInsert\n\tsessions?: Record<number | string, { db: PgInsert }>\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\n/**\n * Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment\n * statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique\n * compound index makes concurrent bumps for the same key safe without read-modify-write races.\n * The shard column is internal: transactional Mongo bumps pick a random shard in\n * [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);\n * Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.\n *\n * When `transactionID` names an open Payload transaction, the write joins it: a bump failure\n * thrown from the submission hook rolls back the submission create (no undercount), and an\n * aborted create rolls back the joined bump (no overcount). Residual risk on transactional\n * Mongo: two concurrent bumps that land on the same shard still abort one transaction\n * (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,\n * so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.\n * Mongo with transactions disabled) the write lands on the root handle immediately; a later\n * recount from stored submissions is the healer for any drift that window allows.\n */\n// biome-ignore lint/complexity/useMaxParams: write primitive signature (payload, key, by, transactionID)\nexport async function bumpPollVote(\n\tpayload: Payload,\n\tkey: { form: string; field: string; value: string },\n\tby: number,\n\ttransactionID?: number | string\n): Promise<void> {\n\tconst slug = pluginSlugsOf(payload).pollVotes\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[slug]\n\t\tif (!model) throw new Error(`form-builder: mongoose collection \"${slug}\" not found`)\n\t\tconst session = transactionID !== undefined ? db.sessions?.[transactionID] : undefined\n\t\tconst shard = session ? Math.floor(Math.random() * VOTE_SHARDS) : 0\n\t\tconst shardedKey = { ...key, shard }\n\t\tconst update = { $inc: { count: by }, $setOnInsert: shardedKey }\n\t\tconst options = session ? { upsert: true, session } : { upsert: true }\n\t\ttry {\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t} catch (error) {\n\t\t\t// Concurrent first inserts for a new key can race the upsert into E11000; outside a\n\t\t\t// transaction the row now exists, so one retry takes the $inc branch. Inside a\n\t\t\t// transaction the error propagates and Payload's rollback/retry semantics apply.\n\t\t\tconst duplicate = (error as { code?: unknown } | null)?.code === 11000\n\t\t\tif (session || !duplicate) throw error\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t}\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\t// Payload keys every collection's table by its snake-cased slug, whatever `dbName` renames it to.\n\tconst tableKey = toSnakeCase(slug)\n\tconst tableName = db.tableNameMap.get(tableKey)\n\tif (!tableName) throw new Error(`form-builder: drizzle table \"${tableKey}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`form-builder: drizzle table object for \"${tableName}\" not found`)\n\tconst txn = transactionID !== undefined ? db.sessions?.[transactionID]?.db : undefined\n\tawait (txn ?? db.drizzle)\n\t\t.insert(table)\n\t\t.values({ ...key, shard: 0, count: by })\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: [table.form, table.field, table.value, table.shard],\n\t\t\tset: { count: sql`${table.count} + ${by}` },\n\t\t})\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;;;;;;;;;;;;;;;;;;AA2CA,eAAsB,aACrB,SACA,KACA,IACA,eACgB;CAChB,MAAM,OAAO,cAAc,OAAO,EAAE;CACpC,IAAI,QAAQ,GAAG,SAAS,YAAY;EACnC,MAAM,KAAK,QAAQ;EACnB,MAAM,QAAQ,GAAG,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,sCAAsC,KAAK,YAAY;EACnF,MAAM,UAAU,kBAAkB,KAAA,IAAY,GAAG,WAAW,iBAAiB,KAAA;EAC7E,MAAM,QAAQ,UAAU,KAAK,MAAM,KAAK,OAAO,IAAA,CAAe,IAAI;EAClE,MAAM,aAAa;GAAE,GAAG;GAAK;EAAM;EACnC,MAAM,SAAS;GAAE,MAAM,EAAE,OAAO,GAAG;GAAG,cAAc;EAAW;EAC/D,MAAM,UAAU,UAAU;GAAE,QAAQ;GAAM;EAAQ,IAAI,EAAE,QAAQ,KAAK;EACrE,IAAI;GACH,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D,SAAS,OAAO;GAIf,MAAM,YAAa,OAAqC,SAAS;GACjE,IAAI,WAAW,CAAC,WAAW,MAAM;GACjC,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,kBAAkB;CACxC,MAAM,KAAK,QAAQ;CAEnB,MAAM,WAAW,YAAY,IAAI;CACjC,MAAM,YAAY,GAAG,aAAa,IAAI,QAAQ;CAC9C,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,gCAAgC,SAAS,YAAY;CACrF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,2CAA2C,UAAU,YAAY;CAE7F,QADY,kBAAkB,KAAA,IAAY,GAAG,WAAW,gBAAgB,KAAK,KAAA,MAC/D,GAAG,SACf,OAAO,KAAK,EACZ,OAAO;EAAE,GAAG;EAAK,OAAO;EAAG,OAAO;CAAG,CAAC,EACtC,mBAAmB;EACnB,QAAQ;GAAC,MAAM;GAAM,MAAM;GAAO,MAAM;GAAO,MAAM;EAAK;EAC1D,KAAK,EAAE,OAAO,GAAG,GAAG,MAAM,MAAM,KAAK,KAAK;CAC3C,CAAC;AACH"}
@@ -0,0 +1,20 @@
1
+ import { Payload, PayloadRequest } from "payload";
2
+
3
+ //#region src/poll/votes/recountPollVotes.d.ts
4
+ /**
5
+ * Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
6
+ * changes, or backfill after enabling a poll late). Scans first and refuses a truncated
7
+ * aggregation, then deletes the form's tally rows for the results field and replays the scan
8
+ * into fresh rows, so the store is never left holding a knowingly partial count. Writes join
9
+ * the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
10
+ * its submissions are pruned, so the tally store is the only record of its votes and a rebuild
11
+ * would wipe them.
12
+ */
13
+ declare const recountPollVotes: (args: {
14
+ payload: Payload;
15
+ formId: number | string;
16
+ req?: PayloadRequest;
17
+ }) => Promise<void>;
18
+ //#endregion
19
+ export { recountPollVotes };
20
+ //# sourceMappingURL=recountPollVotes.d.ts.map
@@ -0,0 +1,63 @@
1
+ import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
2
+ import { pollConfigOf } from "../../form/pollState.js";
3
+ import "./votesCollection.js";
4
+ import { bumpPollVote } from "./bumpPollVote.js";
5
+ import { transactionIDOf } from "./voteTallyHook.js";
6
+ import { aggregateFieldResponses } from "../../aggregation/aggregateResponses.js";
7
+ //#region src/poll/votes/recountPollVotes.ts
8
+ const RECOUNT_MAX_SUBMISSIONS = 1e5;
9
+ /**
10
+ * Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
11
+ * changes, or backfill after enabling a poll late). Scans first and refuses a truncated
12
+ * aggregation, then deletes the form's tally rows for the results field and replays the scan
13
+ * into fresh rows, so the store is never left holding a knowingly partial count. Writes join
14
+ * the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
15
+ * its submissions are pruned, so the tally store is the only record of its votes and a rebuild
16
+ * would wipe them.
17
+ */
18
+ const recountPollVotes = async (args) => {
19
+ const { payload, formId, req } = args;
20
+ const form = await payload.findByID({
21
+ collection: pluginSlugsOf(payload).forms,
22
+ id: formId,
23
+ depth: 0,
24
+ overrideAccess: true,
25
+ req
26
+ }).catch(() => null);
27
+ const poll = form ? pollConfigOf(form.poll) : void 0;
28
+ const resultsField = typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
29
+ if (!resultsField) return;
30
+ if (form?.persistSubmissions === false) throw new Error(`form-builder: recountPollVotes cannot rebuild form "${String(formId)}": it does not persist submissions, so the tally store is the only record of its votes.`);
31
+ const aggregation = await aggregateFieldResponses({
32
+ payload,
33
+ formId,
34
+ field: resultsField,
35
+ req,
36
+ maxSubmissions: RECOUNT_MAX_SUBMISSIONS
37
+ });
38
+ if (aggregation?.truncated) throw new Error(`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`);
39
+ await payload.delete({
40
+ collection: pluginSlugsOf(payload).pollVotes,
41
+ where: { and: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }] },
42
+ overrideAccess: true,
43
+ req
44
+ });
45
+ if (!aggregation) return;
46
+ const transactionID = transactionIDOf(req?.transactionID);
47
+ const base = {
48
+ form: String(formId),
49
+ field: resultsField
50
+ };
51
+ for (const bucket of aggregation.buckets) if (bucket.count > 0) await bumpPollVote(payload, {
52
+ ...base,
53
+ value: bucket.value
54
+ }, bucket.count, transactionID);
55
+ if (aggregation.total > 0) await bumpPollVote(payload, {
56
+ ...base,
57
+ value: ""
58
+ }, aggregation.total, transactionID);
59
+ };
60
+ //#endregion
61
+ export { recountPollVotes };
62
+
63
+ //# sourceMappingURL=recountPollVotes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recountPollVotes.js","names":[],"sources":["../../../src/poll/votes/recountPollVotes.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { aggregateFieldResponses } from '../../aggregation/aggregateResponses'\nimport { pollConfigOf } from '../../form/pollState'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { bumpPollVote } from './bumpPollVote'\nimport { RESPONDENTS_VALUE } from './votesCollection'\nimport { transactionIDOf } from './voteTallyHook'\n\nconst RECOUNT_MAX_SUBMISSIONS = 100_000\n\n/**\n * Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB\n * changes, or backfill after enabling a poll late). Scans first and refuses a truncated\n * aggregation, then deletes the form's tally rows for the results field and replays the scan\n * into fresh rows, so the store is never left holding a knowingly partial count. Writes join\n * the request's transaction when one is open. Refuses a form with `persistSubmissions` off:\n * its submissions are pruned, so the tally store is the only record of its votes and a rebuild\n * would wipe them.\n */\nexport const recountPollVotes = async (args: {\n\tpayload: Payload\n\tformId: number | string\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, formId, req } = args\n\tconst form = await payload\n\t\t.findByID({\n\t\t\tcollection: pluginSlugsOf(payload).forms,\n\t\t\tid: formId,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\t.catch(() => null)\n\tconst poll = form ? pollConfigOf(form.poll) : undefined\n\tconst resultsField =\n\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t? poll.resultsField\n\t\t\t: undefined\n\tif (!resultsField) {\n\t\treturn\n\t}\n\tif (form?.persistSubmissions === false) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recountPollVotes cannot rebuild form \"${String(formId)}\": it does not persist submissions, so the tally store is the only record of its votes.`\n\t\t)\n\t}\n\tconst aggregation = await aggregateFieldResponses({\n\t\tpayload,\n\t\tformId,\n\t\tfield: resultsField,\n\t\treq,\n\t\tmaxSubmissions: RECOUNT_MAX_SUBMISSIONS,\n\t})\n\tif (aggregation?.truncated) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`\n\t\t)\n\t}\n\tawait payload.delete({\n\t\tcollection: pluginSlugsOf(payload).pollVotes,\n\t\twhere: {\n\t\t\tand: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }],\n\t\t},\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\tif (!aggregation) {\n\t\treturn\n\t}\n\tconst transactionID = transactionIDOf(req?.transactionID)\n\tconst base = { form: String(formId), field: resultsField }\n\tfor (const bucket of aggregation.buckets) {\n\t\tif (bucket.count > 0) {\n\t\t\tawait bumpPollVote(payload, { ...base, value: bucket.value }, bucket.count, transactionID)\n\t\t}\n\t}\n\tif (aggregation.total > 0) {\n\t\tawait bumpPollVote(\n\t\t\tpayload,\n\t\t\t{ ...base, value: RESPONDENTS_VALUE },\n\t\t\taggregation.total,\n\t\t\ttransactionID\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;AAQA,MAAM,0BAA0B;;;;;;;;;;AAWhC,MAAa,mBAAmB,OAAO,SAIlB;CACpB,MAAM,EAAE,SAAS,QAAQ,QAAQ;CACjC,MAAM,OAAO,MAAM,QACjB,SAAS;EACT,YAAY,cAAc,OAAO,EAAE;EACnC,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC,EACA,YAAY,IAAI;CAClB,MAAM,OAAO,OAAO,aAAa,KAAK,IAAI,IAAI,KAAA;CAC9C,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SAAS,IAClE,KAAK,eACL,KAAA;CACJ,IAAI,CAAC,cACJ;CAED,IAAI,MAAM,uBAAuB,OAChC,MAAM,IAAI,MACT,uDAAuD,OAAO,MAAM,EAAE,wFACvE;CAED,MAAM,cAAc,MAAM,wBAAwB;EACjD;EACA;EACA,OAAO;EACP;EACA,gBAAgB;CACjB,CAAC;CACD,IAAI,aAAa,WAChB,MAAM,IAAI,MACT,kCAAkC,OAAO,MAAM,EAAE,sBAAsB,wBAAwB,2EAChG;CAED,MAAM,QAAQ,OAAO;EACpB,YAAY,cAAc,OAAO,EAAE;EACnC,OAAO,EACN,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,aAAa,EAAE,CAAC,EAChF;EACA,gBAAgB;EAChB;CACD,CAAC;CACD,IAAI,CAAC,aACJ;CAED,MAAM,gBAAgB,gBAAgB,KAAK,aAAa;CACxD,MAAM,OAAO;EAAE,MAAM,OAAO,MAAM;EAAG,OAAO;CAAa;CACzD,KAAK,MAAM,UAAU,YAAY,SAChC,IAAI,OAAO,QAAQ,GAClB,MAAM,aAAa,SAAS;EAAE,GAAG;EAAM,OAAO,OAAO;CAAM,GAAG,OAAO,OAAO,aAAa;CAG3F,IAAI,YAAY,QAAQ,GACvB,MAAM,aACL,SACA;EAAE,GAAG;EAAM,OAAA;CAAyB,GACpC,YAAY,OACZ,aACD;AAEF"}
@@ -0,0 +1,76 @@
1
+ import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
2
+ import { pollConfigOf } from "../../form/pollState.js";
3
+ import { formIdOf } from "../../submissions/formIdOf.js";
4
+ import { answerValues } from "./answerValues.js";
5
+ import "./votesCollection.js";
6
+ import { bumpPollVote } from "./bumpPollVote.js";
7
+ //#region src/poll/votes/voteTallyHook.ts
8
+ const isComplete = (doc) => doc.status == null || doc.status === "complete";
9
+ /** Narrow a request's loosely typed `transactionID` to the value `bumpPollVote` accepts. */
10
+ const transactionIDOf = (transactionID) => typeof transactionID === "number" || typeof transactionID === "string" ? transactionID : void 0;
11
+ /**
12
+ * Vote counting: a submission entering `complete` bumps one tally per answer value for the poll
13
+ * results field, plus the shared respondents row. Votes are permanent by default: no decrement on
14
+ * delete, edit, or prune, which is what lets a pruned submission's vote survive. The one
15
+ * exception is an `allowChange` poll, where an update of an already-complete submission moves the
16
+ * tally with the changed answer (decrement removed values, increment added ones, respondents
17
+ * untouched); delete and prune stay permanent even then. Two concurrent changes of the same
18
+ * submission can each read the same previous answer and double-adjust; the client's double-submit
19
+ * guard makes that rare and `recountPollVotes` is the healer, matching `bumpPollVote`'s residual
20
+ * drift note. Bump failures propagate so the enclosing transaction rolls the submission back
21
+ * rather than silently undercounting; registered before the swallow-all dispatch hook.
22
+ */
23
+ const makeVoteTallyHook = () => async ({ doc, previousDoc, operation, req }) => {
24
+ if (operation !== "create" && operation !== "update") return doc;
25
+ const entering = operation === "create" && isComplete(doc) || operation === "update" && isComplete(doc) && !isComplete(previousDoc ?? {});
26
+ const changing = operation === "update" && isComplete(doc) && isComplete(previousDoc ?? {}) && !entering;
27
+ if (!entering && !changing) return doc;
28
+ const formId = formIdOf(doc.form);
29
+ if (formId == null) return doc;
30
+ const form = await req.payload.findByID({
31
+ collection: pluginSlugsOf(req.payload).forms,
32
+ id: formId,
33
+ depth: 0,
34
+ overrideAccess: true,
35
+ req
36
+ }).catch(() => null);
37
+ const poll = form?.pollEnabled === true ? pollConfigOf(form.poll) : void 0;
38
+ const resultsField = typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
39
+ if (!resultsField) return doc;
40
+ const transactionID = transactionIDOf(req.transactionID);
41
+ const base = {
42
+ form: String(formId),
43
+ field: resultsField
44
+ };
45
+ if (changing) {
46
+ if (poll?.allowChange !== true) return doc;
47
+ const previous = answerValues(previousDoc?.values, resultsField);
48
+ const next = answerValues(doc.values, resultsField);
49
+ const removed = previous.filter((value) => !next.includes(value));
50
+ const added = next.filter((value) => !previous.includes(value));
51
+ for (const value of removed) await bumpPollVote(req.payload, {
52
+ ...base,
53
+ value
54
+ }, -1, transactionID);
55
+ for (const value of added) await bumpPollVote(req.payload, {
56
+ ...base,
57
+ value
58
+ }, 1, transactionID);
59
+ return doc;
60
+ }
61
+ const votes = answerValues(doc.values, resultsField);
62
+ if (votes.length === 0) return doc;
63
+ for (const value of votes) await bumpPollVote(req.payload, {
64
+ ...base,
65
+ value
66
+ }, 1, transactionID);
67
+ await bumpPollVote(req.payload, {
68
+ ...base,
69
+ value: ""
70
+ }, 1, transactionID);
71
+ return doc;
72
+ };
73
+ //#endregion
74
+ export { makeVoteTallyHook, transactionIDOf };
75
+
76
+ //# sourceMappingURL=voteTallyHook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voteTallyHook.js","names":[],"sources":["../../../src/poll/votes/voteTallyHook.ts"],"sourcesContent":["import type { CollectionAfterChangeHook } from 'payload'\nimport { pollConfigOf } from '../../form/pollState'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { formIdOf } from '../../submissions/formIdOf'\nimport { answerValues } from './answerValues'\nimport { bumpPollVote } from './bumpPollVote'\nimport { RESPONDENTS_VALUE } from './votesCollection'\n\nconst isComplete = (doc: { status?: unknown }): boolean =>\n\tdoc.status == null || doc.status === 'complete'\n\n/** Narrow a request's loosely typed `transactionID` to the value `bumpPollVote` accepts. */\nexport const transactionIDOf = (transactionID: unknown): number | string | undefined =>\n\ttypeof transactionID === 'number' || typeof transactionID === 'string' ? transactionID : undefined\n\n/**\n * Vote counting: a submission entering `complete` bumps one tally per answer value for the poll\n * results field, plus the shared respondents row. Votes are permanent by default: no decrement on\n * delete, edit, or prune, which is what lets a pruned submission's vote survive. The one\n * exception is an `allowChange` poll, where an update of an already-complete submission moves the\n * tally with the changed answer (decrement removed values, increment added ones, respondents\n * untouched); delete and prune stay permanent even then. Two concurrent changes of the same\n * submission can each read the same previous answer and double-adjust; the client's double-submit\n * guard makes that rare and `recountPollVotes` is the healer, matching `bumpPollVote`'s residual\n * drift note. Bump failures propagate so the enclosing transaction rolls the submission back\n * rather than silently undercounting; registered before the swallow-all dispatch hook.\n */\nexport const makeVoteTallyHook =\n\t(): CollectionAfterChangeHook =>\n\tasync ({ doc, previousDoc, operation, req }) => {\n\t\tif (operation !== 'create' && operation !== 'update') return doc\n\t\tconst entering =\n\t\t\t(operation === 'create' && isComplete(doc)) ||\n\t\t\t(operation === 'update' && isComplete(doc) && !isComplete(previousDoc ?? {}))\n\t\tconst changing =\n\t\t\toperation === 'update' && isComplete(doc) && isComplete(previousDoc ?? {}) && !entering\n\t\tif (!entering && !changing) return doc\n\t\tconst formId = formIdOf(doc.form)\n\t\tif (formId == null) return doc\n\t\tconst form = await req.payload\n\t\t\t.findByID({\n\t\t\t\tcollection: pluginSlugsOf(req.payload).forms,\n\t\t\t\tid: formId,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t\t.catch(() => null)\n\t\tconst poll = form?.pollEnabled === true ? pollConfigOf(form.poll) : undefined\n\t\tconst resultsField =\n\t\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (!resultsField) return doc\n\t\tconst transactionID = transactionIDOf(req.transactionID)\n\t\tconst base = { form: String(formId), field: resultsField }\n\t\tif (changing) {\n\t\t\tif (poll?.allowChange !== true) return doc\n\t\t\tconst previous = answerValues(previousDoc?.values, resultsField)\n\t\t\tconst next = answerValues(doc.values, resultsField)\n\t\t\tconst removed = previous.filter((value) => !next.includes(value))\n\t\t\tconst added = next.filter((value) => !previous.includes(value))\n\t\t\tfor (const value of removed) {\n\t\t\t\tawait bumpPollVote(req.payload, { ...base, value }, -1, transactionID)\n\t\t\t}\n\t\t\tfor (const value of added) {\n\t\t\t\tawait bumpPollVote(req.payload, { ...base, value }, 1, transactionID)\n\t\t\t}\n\t\t\treturn doc\n\t\t}\n\t\tconst votes = answerValues(doc.values, resultsField)\n\t\tif (votes.length === 0) return doc\n\t\tfor (const value of votes) {\n\t\t\tawait bumpPollVote(req.payload, { ...base, value }, 1, transactionID)\n\t\t}\n\t\tawait bumpPollVote(req.payload, { ...base, value: RESPONDENTS_VALUE }, 1, transactionID)\n\t\treturn doc\n\t}\n"],"mappings":";;;;;;;AAQA,MAAM,cAAc,QACnB,IAAI,UAAU,QAAQ,IAAI,WAAW;;AAGtC,MAAa,mBAAmB,kBAC/B,OAAO,kBAAkB,YAAY,OAAO,kBAAkB,WAAW,gBAAgB,KAAA;;;;;;;;;;;;;AAc1F,MAAa,0BAEZ,OAAO,EAAE,KAAK,aAAa,WAAW,UAAU;CAC/C,IAAI,cAAc,YAAY,cAAc,UAAU,OAAO;CAC7D,MAAM,WACJ,cAAc,YAAY,WAAW,GAAG,KACxC,cAAc,YAAY,WAAW,GAAG,KAAK,CAAC,WAAW,eAAe,CAAC,CAAC;CAC5E,MAAM,WACL,cAAc,YAAY,WAAW,GAAG,KAAK,WAAW,eAAe,CAAC,CAAC,KAAK,CAAC;CAChF,IAAI,CAAC,YAAY,CAAC,UAAU,OAAO;CACnC,MAAM,SAAS,SAAS,IAAI,IAAI;CAChC,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,OAAO,MAAM,IAAI,QACrB,SAAS;EACT,YAAY,cAAc,IAAI,OAAO,EAAE;EACvC,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC,EACA,YAAY,IAAI;CAClB,MAAM,OAAO,MAAM,gBAAgB,OAAO,aAAa,KAAK,IAAI,IAAI,KAAA;CACpE,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SAAS,IAClE,KAAK,eACL,KAAA;CACJ,IAAI,CAAC,cAAc,OAAO;CAC1B,MAAM,gBAAgB,gBAAgB,IAAI,aAAa;CACvD,MAAM,OAAO;EAAE,MAAM,OAAO,MAAM;EAAG,OAAO;CAAa;CACzD,IAAI,UAAU;EACb,IAAI,MAAM,gBAAgB,MAAM,OAAO;EACvC,MAAM,WAAW,aAAa,aAAa,QAAQ,YAAY;EAC/D,MAAM,OAAO,aAAa,IAAI,QAAQ,YAAY;EAClD,MAAM,UAAU,SAAS,QAAQ,UAAU,CAAC,KAAK,SAAS,KAAK,CAAC;EAChE,MAAM,QAAQ,KAAK,QAAQ,UAAU,CAAC,SAAS,SAAS,KAAK,CAAC;EAC9D,KAAK,MAAM,SAAS,SACnB,MAAM,aAAa,IAAI,SAAS;GAAE,GAAG;GAAM;EAAM,GAAG,IAAI,aAAa;EAEtE,KAAK,MAAM,SAAS,OACnB,MAAM,aAAa,IAAI,SAAS;GAAE,GAAG;GAAM;EAAM,GAAG,GAAG,aAAa;EAErE,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,QAAQ,YAAY;CACnD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,KAAK,MAAM,SAAS,OACnB,MAAM,aAAa,IAAI,SAAS;EAAE,GAAG;EAAM;CAAM,GAAG,GAAG,aAAa;CAErE,MAAM,aAAa,IAAI,SAAS;EAAE,GAAG;EAAM,OAAA;CAAyB,GAAG,GAAG,aAAa;CACvF,OAAO;AACR"}
@@ -0,0 +1,23 @@
1
+ import { CollectionConfig } from "payload";
2
+
3
+ //#region src/poll/votes/votesCollection.d.ts
4
+ /**
5
+ * Default slug of the tally collection. A host may rename it via `poll.votes.overrides.slug`;
6
+ * read the live slug with `collectionSlugsOf(payload).pollVotes`.
7
+ */
8
+ declare const POLL_VOTES_SLUG: "form-poll-votes";
9
+ /** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */
10
+ declare const RESPONDENTS_VALUE = "";
11
+ /**
12
+ * Shard count for hot tally counters. Mongo aborts one of two transactions that write the same
13
+ * document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the
14
+ * same (form, field, value) would deterministically fail one submission. Spreading each
15
+ * transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards
16
+ * with high probability, so transactions stop contending. Postgres row locks serialize
17
+ * ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so
18
+ * both always use shard 0. Reads sum counts across shards.
19
+ */
20
+ declare const VOTE_SHARDS = 8;
21
+ //#endregion
22
+ export { POLL_VOTES_SLUG, RESPONDENTS_VALUE, VOTE_SHARDS };
23
+ //# sourceMappingURL=votesCollection.d.ts.map
@@ -0,0 +1,96 @@
1
+ import { keys } from "../../translations/keys.js";
2
+ import { labelForKey } from "../../translations/server.js";
3
+ import { DEFAULT_COLLECTION_SLUGS } from "../../plugin/collectionSlugs.js";
4
+ import { isLoggedIn } from "../../plugin/access.js";
5
+ //#region src/poll/votes/votesCollection.ts
6
+ /**
7
+ * Default slug of the tally collection. A host may rename it via `poll.votes.overrides.slug`;
8
+ * read the live slug with `collectionSlugsOf(payload).pollVotes`.
9
+ */
10
+ const POLL_VOTES_SLUG = DEFAULT_COLLECTION_SLUGS.pollVotes;
11
+ /** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */
12
+ const RESPONDENTS_VALUE = "";
13
+ /**
14
+ * Shard count for hot tally counters. Mongo aborts one of two transactions that write the same
15
+ * document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the
16
+ * same (form, field, value) would deterministically fail one submission. Spreading each
17
+ * transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards
18
+ * with high probability, so transactions stop contending. Postgres row locks serialize
19
+ * ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so
20
+ * both always use shard 0. Reads sum counts across shards.
21
+ */
22
+ const VOTE_SHARDS = 8;
23
+ /**
24
+ * Append-only aggregate tallies: up to VOTE_SHARDS rows per (form, field, value) with running
25
+ * counts that readers sum, plus respondents rows per (form, field) under RESPONDENTS_VALUE.
26
+ * Rows carry no per-voter data and are written via atomic upsert-increments (see bumpPollVote),
27
+ * made concurrency-safe by the unique compound index. Ids are stored as strings for cross-DB
28
+ * parity.
29
+ *
30
+ * `indexes` is intentionally not part of the override surface: the unique compound index is
31
+ * load-bearing for the atomic upsert-increment, so it is fixed rather than spread with the rest.
32
+ */
33
+ const buildPollVotesCollection = (args) => {
34
+ const defaultFields = [
35
+ {
36
+ name: "form",
37
+ type: "text",
38
+ required: true,
39
+ index: true
40
+ },
41
+ {
42
+ name: "field",
43
+ type: "text",
44
+ required: true
45
+ },
46
+ {
47
+ name: "value",
48
+ type: "text"
49
+ },
50
+ {
51
+ name: "shard",
52
+ type: "number",
53
+ required: true,
54
+ defaultValue: 0
55
+ },
56
+ {
57
+ name: "count",
58
+ type: "number",
59
+ required: true,
60
+ defaultValue: 0
61
+ }
62
+ ];
63
+ return {
64
+ versions: false,
65
+ authorship: false,
66
+ ...args.overrides ?? {},
67
+ slug: args.slug ?? POLL_VOTES_SLUG,
68
+ labels: {
69
+ singular: labelForKey(keys.collectionPollVoteSingular),
70
+ plural: labelForKey(keys.collectionPollVotePlural),
71
+ ...args.overrides?.labels ?? {}
72
+ },
73
+ admin: {
74
+ hidden: true,
75
+ ...args.overrides?.admin ?? {}
76
+ },
77
+ access: {
78
+ read: isLoggedIn,
79
+ ...args.overrides?.access ?? {}
80
+ },
81
+ indexes: [{
82
+ fields: [
83
+ "form",
84
+ "field",
85
+ "value",
86
+ "shard"
87
+ ],
88
+ unique: true
89
+ }],
90
+ fields: args.overrides?.fields ? args.overrides.fields({ defaultFields }) : defaultFields
91
+ };
92
+ };
93
+ //#endregion
94
+ export { POLL_VOTES_SLUG, RESPONDENTS_VALUE, VOTE_SHARDS, buildPollVotesCollection };
95
+
96
+ //# sourceMappingURL=votesCollection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"votesCollection.js","names":[],"sources":["../../../src/poll/votes/votesCollection.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\nimport { isLoggedIn } from '../../plugin/access'\nimport type { CollectionOverrides } from '../../plugin/collectionOverrides'\nimport { DEFAULT_COLLECTION_SLUGS } from '../../plugin/collectionSlugs'\nimport { keys } from '../../translations/keys'\nimport { labelForKey } from '../../translations/server'\n\n/**\n * Default slug of the tally collection. A host may rename it via `poll.votes.overrides.slug`;\n * read the live slug with `collectionSlugsOf(payload).pollVotes`.\n */\nexport const POLL_VOTES_SLUG = DEFAULT_COLLECTION_SLUGS.pollVotes\n\n/** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */\nexport const RESPONDENTS_VALUE = ''\n\n/**\n * Shard count for hot tally counters. Mongo aborts one of two transactions that write the same\n * document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the\n * same (form, field, value) would deterministically fail one submission. Spreading each\n * transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards\n * with high probability, so transactions stop contending. Postgres row locks serialize\n * ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so\n * both always use shard 0. Reads sum counts across shards.\n */\nexport const VOTE_SHARDS = 8\n\n/**\n * Append-only aggregate tallies: up to VOTE_SHARDS rows per (form, field, value) with running\n * counts that readers sum, plus respondents rows per (form, field) under RESPONDENTS_VALUE.\n * Rows carry no per-voter data and are written via atomic upsert-increments (see bumpPollVote),\n * made concurrency-safe by the unique compound index. Ids are stored as strings for cross-DB\n * parity.\n *\n * `indexes` is intentionally not part of the override surface: the unique compound index is\n * load-bearing for the atomic upsert-increment, so it is fixed rather than spread with the rest.\n */\nexport const buildPollVotesCollection = (args: {\n\toverrides?: CollectionOverrides\n\t/** The resolved tally slug (`poll.votes.overrides.slug`); the default when omitted. */\n\tslug?: string\n}): CollectionConfig => {\n\tconst defaultFields: CollectionConfig['fields'] = [\n\t\t{ name: 'form', type: 'text', required: true, index: true },\n\t\t{ name: 'field', type: 'text', required: true },\n\t\t{ name: 'value', type: 'text' },\n\t\t{ name: 'shard', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'count', type: 'number', required: true, defaultValue: 0 },\n\t]\n\n\treturn {\n\t\t// A system-maintained tally: no history, no core authorship (both default on in Payload 4).\n\t\tversions: false,\n\t\tauthorship: false,\n\t\t...(args.overrides ?? {}),\n\t\tslug: args.slug ?? POLL_VOTES_SLUG,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.collectionPollVoteSingular),\n\t\t\tplural: labelForKey(keys.collectionPollVotePlural),\n\t\t\t...(args.overrides?.labels ?? {}),\n\t\t},\n\t\tadmin: { hidden: true, ...(args.overrides?.admin ?? {}) },\n\t\taccess: { read: isLoggedIn, ...(args.overrides?.access ?? {}) },\n\t\tindexes: [{ fields: ['form', 'field', 'value', 'shard'], unique: true }],\n\t\tfields: args.overrides?.fields ? args.overrides.fields({ defaultFields }) : defaultFields,\n\t}\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,kBAAkB,yBAAyB;;AAGxD,MAAa,oBAAoB;;;;;;;;;;AAWjC,MAAa,cAAc;;;;;;;;;;;AAY3B,MAAa,4BAA4B,SAIjB;CACvB,MAAM,gBAA4C;EACjD;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAS,MAAM;GAAQ,UAAU;EAAK;EAC9C;GAAE,MAAM;GAAS,MAAM;EAAO;EAC9B;GAAE,MAAM;GAAS,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACjE;GAAE,MAAM;GAAS,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;CAClE;CAEA,OAAO;EAEN,UAAU;EACV,YAAY;EACZ,GAAI,KAAK,aAAa,CAAC;EACvB,MAAM,KAAK,QAAQ;EACnB,QAAQ;GACP,UAAU,YAAY,KAAK,0BAA0B;GACrD,QAAQ,YAAY,KAAK,wBAAwB;GACjD,GAAI,KAAK,WAAW,UAAU,CAAC;EAChC;EACA,OAAO;GAAE,QAAQ;GAAM,GAAI,KAAK,WAAW,SAAS,CAAC;EAAG;EACxD,QAAQ;GAAE,MAAM;GAAY,GAAI,KAAK,WAAW,UAAU,CAAC;EAAG;EAC9D,SAAS,CAAC;GAAE,QAAQ;IAAC;IAAQ;IAAS;IAAS;GAAO;GAAG,QAAQ;EAAK,CAAC;EACvE,QAAQ,KAAK,WAAW,SAAS,KAAK,UAAU,OAAO,EAAE,cAAc,CAAC,IAAI;CAC7E;AACD"}
@@ -1,8 +1,11 @@
1
+ import { SubmissionValue } from "../submissions/types.js";
1
2
  import { AnyFormFieldDefinition } from "../fields/types.js";
2
3
  import { BodyConverter } from "../actions/body/converters.js";
3
4
  import { FormButtonSettings, FormDocument, FormPollSettings, FormResponseSettings } from "../form/types.js";
5
+ import { FormAdapters } from "./adapters.js";
4
6
  import { RendererTranslate } from "./contract.js";
5
7
  import { FormEventSink } from "../events/types.js";
8
+ import { FormBuilderCollectionSlugs } from "../plugin/collectionSlugs.js";
6
9
  import { AnyValidationRuleDefinition } from "../validation/types.js";
7
10
  import { BackButtonRenderProps, NextButtonRenderProps, SubmitButtonRenderProps } from "./FormControls.js";
8
11
  import { FormPresentation } from "./presentation/types.js";
@@ -25,14 +28,22 @@ type FormSuccessResponse = {
25
28
  };
26
29
  /** The second argument to `onSuccess`: the resolved success response (an object, so it can grow). */
27
30
  type FormSuccessResult = {
28
- response?: FormSuccessResponse;
31
+ response?: FormSuccessResponse; /** The submitted answers (reserved keys like the honeypot and captcha token excluded), e.g. for `<Poll>` to track the voter's pick. */
32
+ values?: SubmissionValue[];
29
33
  };
34
+ /**
35
+ * The plugin's collection slugs as the browser needs them, for a host that renamed them through
36
+ * `overrides.forms.slug` / `overrides.formSubmissions.slug`. Pass the same values the server was
37
+ * given; each omitted key keeps its default.
38
+ */
39
+ type FormCollections = Partial<Pick<FormBuilderCollectionSlugs, 'forms' | 'formSubmissions'>>;
30
40
  type FormProps = {
31
41
  form: FormDocument;
32
42
  fieldTypes?: AnyFormFieldDefinition[];
33
43
  rules?: AnyValidationRuleDefinition[];
34
44
  renderers?: RenderersConfig;
35
- apiRoute?: string;
45
+ apiRoute?: string; /** Renamed plugin collections: submits post to `formSubmissions`, `<Poll>` reads results from `forms`. */
46
+ collections?: FormCollections;
36
47
  onSubmit?: SubmitHandler;
37
48
  /**
38
49
  * Called after a successful submission with the submission id and the resolved success response
@@ -52,9 +63,23 @@ type FormProps = {
52
63
  * and keep the form usable.
53
64
  */
54
65
  successBehavior?: 'replace' | 'reset';
66
+ /**
67
+ * Client halves of the plugin's registered `calc.functions` (same keys), used for the live calc
68
+ * preview only; the server always recomputes authoritatively at submit with the registry's own
69
+ * functions.
70
+ */
71
+ calcFunctions?: Record<string, (args: number[]) => number>;
55
72
  events?: FormEventSink;
56
- t?: RendererTranslate;
73
+ t?: RendererTranslate; /** The visitor's locale for renderer strings and value formatting, e.g. `en-US` (`'en'` when absent). */
57
74
  locale?: string;
75
+ /**
76
+ * The Payload content locale to submit under, one of the host's `localization` codes (`en`, `de`),
77
+ * sent as `?locale=` so the server stores it on the submission and the post-submit actions
78
+ * (confirmation emails included) render in it. A `<Poll>` also reads its results in it. Separate
79
+ * from `locale` because a formatting tag like `en-US` is usually not a content locale code.
80
+ * Absent, the submission takes the host's default locale.
81
+ */
82
+ submissionLocale?: string;
58
83
  layout?: boolean; /** Submit button label. Precedence: this prop, then the form's `buttons.submitLabel`, then the translated default. */
59
84
  submitLabel?: string; /** "Next" button label for multi-step forms. Precedence: this prop, then the form's `buttons.nextLabel`, then the translated default. */
60
85
  nextLabel?: string; /** "Back" button label for multi-step forms. Precedence: this prop, then the form's `buttons.prevLabel`, then the translated default. */
@@ -74,7 +99,13 @@ type FormProps = {
74
99
  honeypot?: false | {
75
100
  name?: string;
76
101
  }; /** A token from your captcha widget; verified server-side when a captcha provider is configured. */
77
- captchaToken?: string; /** Custom layout: render fields with `useField`/`useFormState` instead of the auto-rendered field loop. */
102
+ captchaToken?: string;
103
+ /**
104
+ * A signed form-context token from `signFormContext` (server/RSC), tying this render to a document
105
+ * (e.g. the profile page it is on). Carried alongside the answers, verified server-side, and
106
+ * available to `email.recipientSources`; it is never stored as an answer.
107
+ */
108
+ context?: string; /** Custom layout: render fields with `useField`/`useFormState` instead of the auto-rendered field loop. */
78
109
  children?: ReactNode; /** Chrome rendered inside the form, above the fields, in default mode (e.g. `<FormSteps />`). */
79
110
  header?: ReactNode; /** Additional CSS class names applied to the root `<form>` element (and the success node). */
80
111
  className?: string; /** Replace the default submit button entirely. Receives the resolved label and submitting state. */
@@ -84,6 +115,12 @@ type FormProps = {
84
115
  submitButtonClassName?: string; /** CSS class forwarded to the default "Next" `<button>`. Ignored when `renderNext` is provided. */
85
116
  nextButtonClassName?: string; /** CSS class forwarded to the default "Back" `<button>`. Ignored when `renderBack` is provided. */
86
117
  backButtonClassName?: string;
118
+ /**
119
+ * Host-owned effects (navigation, vote persistence, script loading). Each member defaults to
120
+ * the built-in DOM behavior; see {@link FormAdapters}. Pass a stable reference (module scope or
121
+ * `useMemo`), matching the other injectable props.
122
+ */
123
+ adapters?: FormAdapters;
87
124
  };
88
125
  /** The headless form controller: state, progressive client validation, conditional visibility, submission, events. */
89
126
  declare const Form: ({
@@ -92,14 +129,17 @@ declare const Form: ({
92
129
  rules,
93
130
  renderers,
94
131
  apiRoute,
132
+ collections,
95
133
  onSubmit,
96
134
  onSuccess,
97
135
  onError,
98
136
  converters,
99
137
  successBehavior,
138
+ calcFunctions,
100
139
  events,
101
140
  t,
102
- locale,
141
+ locale: localeProp,
142
+ submissionLocale,
103
143
  layout,
104
144
  submitLabel,
105
145
  nextLabel,
@@ -113,6 +153,7 @@ declare const Form: ({
113
153
  initialValues,
114
154
  honeypot,
115
155
  captchaToken,
156
+ context,
116
157
  children,
117
158
  header,
118
159
  className,
@@ -121,8 +162,9 @@ declare const Form: ({
121
162
  renderBack,
122
163
  submitButtonClassName,
123
164
  nextButtonClassName,
124
- backButtonClassName
165
+ backButtonClassName,
166
+ adapters
125
167
  }: FormProps) => import("react/jsx-runtime").JSX.Element;
126
168
  //#endregion
127
- export { Form, FormProps, FormSuccessResponse, FormSuccessResult };
169
+ export { Form, FormCollections, FormProps, FormSuccessResponse, FormSuccessResult };
128
170
  //# sourceMappingURL=Form.d.ts.map