payload-canvas 0.5.2 → 0.7.0-next.0

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 (325) hide show
  1. package/README.md +350 -45
  2. package/dist/admin/AiKeyField.d.ts +4 -3
  3. package/dist/admin/AiKeyField.js +3 -3
  4. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  5. package/dist/admin/ArrayRowLabel.js +21 -0
  6. package/dist/admin/BuilderTab.js +1 -1
  7. package/dist/admin/DocumentEditView.d.ts +1 -1
  8. package/dist/admin/DocumentEditView.js +2 -3
  9. package/dist/admin/LayoutField.d.ts +1 -1
  10. package/dist/admin/LayoutField.js +2 -2
  11. package/dist/admin/TemplateConditionsField.d.ts +2 -2
  12. package/dist/admin/TemplateConditionsField.js +2 -2
  13. package/dist/admin/aiKeyField.css +58 -0
  14. package/dist/admin/client.d.ts +1 -0
  15. package/dist/admin/client.js +2 -0
  16. package/dist/admin/diff/LayoutDiff.js +3 -3
  17. package/dist/admin/diff/LayoutJsonDiff.d.ts +1 -1
  18. package/dist/admin/diff/LayoutJsonDiff.js +1 -1
  19. package/dist/admin/diff/layoutDiff.css +180 -0
  20. package/dist/admin/editor/Editor.d.ts +2 -2
  21. package/dist/admin/editor/Editor.js +10 -3
  22. package/dist/admin/editor/Inspector.js +23 -17
  23. package/dist/admin/editor/Library.d.ts +2 -2
  24. package/dist/admin/editor/Library.js +8 -7
  25. package/dist/admin/editor/Outline.js +20 -12
  26. package/dist/admin/editor/Overlay.js +6 -4
  27. package/dist/admin/editor/actions.d.ts +7 -2
  28. package/dist/admin/editor/actions.js +44 -12
  29. package/dist/admin/editor/assistant/AssistantPanel.d.ts +1 -1
  30. package/dist/admin/editor/assistant/AssistantPanel.js +33 -21
  31. package/dist/admin/editor/assistant/{assistant.scss → assistant.css} +322 -315
  32. package/dist/admin/editor/classes/ClassManager.d.ts +1 -1
  33. package/dist/admin/editor/classes/ClassManager.js +1 -1
  34. package/dist/admin/editor/classes/manager.css +258 -0
  35. package/dist/admin/editor/comments/CommentLayer.d.ts +1 -1
  36. package/dist/admin/editor/comments/CommentLayer.js +1 -1
  37. package/dist/admin/editor/comments/CommentsPanel.d.ts +1 -1
  38. package/dist/admin/editor/comments/CommentsPanel.js +1 -1
  39. package/dist/admin/editor/comments/{comments.scss → comments.css} +121 -140
  40. package/dist/admin/editor/comments/controller.d.ts +7 -0
  41. package/dist/admin/editor/comments/controller.js +12 -0
  42. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  43. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  44. package/dist/admin/editor/dnd/{dnd.scss → dnd.css} +78 -80
  45. package/dist/admin/editor/dnd/smooth.js +1 -1
  46. package/dist/admin/editor/{editor.scss → editor.css} +798 -751
  47. package/dist/admin/editor/empty/EmptyStart.d.ts +1 -1
  48. package/dist/admin/editor/empty/EmptyStart.js +3 -3
  49. package/dist/admin/editor/empty/{empty.scss → empty.css} +12 -13
  50. package/dist/admin/editor/fields/ArrayField.js +3 -3
  51. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  52. package/dist/admin/editor/fields/FormBlock.js +167 -0
  53. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  54. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  55. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  56. package/dist/admin/editor/fields/GroupField.js +30 -1
  57. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  58. package/dist/admin/editor/fields/MergeTags.js +62 -0
  59. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  60. package/dist/admin/editor/fields/arrayRows.js +0 -4
  61. package/dist/admin/editor/fields/fields.css +786 -0
  62. package/dist/admin/editor/fields/values.d.ts +0 -2
  63. package/dist/admin/editor/fields/values.js +0 -14
  64. package/dist/admin/editor/generate/GenerateImage.d.ts +1 -1
  65. package/dist/admin/editor/generate/GenerateImage.js +1 -1
  66. package/dist/admin/editor/generate/{generate.scss → generate.css} +83 -82
  67. package/dist/admin/editor/icons.d.ts +3 -0
  68. package/dist/admin/editor/icons.js +3 -0
  69. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  70. package/dist/admin/editor/insert/picker.d.ts +3 -2
  71. package/dist/admin/editor/insert/picker.js +9 -3
  72. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  73. package/dist/admin/editor/layout/layout.css +243 -0
  74. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  75. package/dist/admin/editor/layout/leftTabs.js +18 -0
  76. package/dist/admin/editor/layout/panels.js +1 -1
  77. package/dist/admin/editor/live/PresenceUI.d.ts +1 -1
  78. package/dist/admin/editor/live/PresenceUI.js +2 -2
  79. package/dist/admin/editor/live/{presence.scss → presence.css} +5 -4
  80. package/dist/admin/editor/locale/LocaleField.d.ts +1 -1
  81. package/dist/admin/editor/locale/LocaleField.js +1 -1
  82. package/dist/admin/editor/locale/LocaleSwitcher.d.ts +1 -1
  83. package/dist/admin/editor/locale/LocaleSwitcher.js +1 -1
  84. package/dist/admin/editor/locale/locale.css +153 -0
  85. package/dist/admin/editor/media/ImageEditor.d.ts +9 -3
  86. package/dist/admin/editor/media/ImageEditor.js +17 -11
  87. package/dist/admin/editor/media/{media.scss → media.css} +70 -60
  88. package/dist/admin/editor/media/model.d.ts +10 -1
  89. package/dist/admin/editor/media/model.js +19 -0
  90. package/dist/admin/editor/menu/Menu.d.ts +1 -1
  91. package/dist/admin/editor/menu/Menu.js +1 -1
  92. package/dist/admin/editor/menu/blockMenu.js +3 -3
  93. package/dist/admin/editor/menu/menu.css +132 -0
  94. package/dist/admin/editor/motion/MotionPanel.d.ts +2 -2
  95. package/dist/admin/editor/motion/MotionPanel.js +2 -2
  96. package/dist/admin/editor/motion/{motion.scss → motion.css} +24 -21
  97. package/dist/admin/editor/names.d.ts +9 -0
  98. package/dist/admin/editor/names.js +18 -0
  99. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  100. package/dist/admin/editor/regions/RegionFields.js +122 -0
  101. package/dist/admin/editor/regions/RegionPane.js +5 -3
  102. package/dist/admin/editor/regions/RegionRows.js +2 -2
  103. package/dist/admin/editor/regions/required.d.ts +16 -0
  104. package/dist/admin/editor/regions/required.js +43 -0
  105. package/dist/admin/editor/renderField.d.ts +10 -3
  106. package/dist/admin/editor/renderField.js +87 -33
  107. package/dist/admin/editor/runtime.d.ts +3 -2
  108. package/dist/admin/editor/runtime.js +12 -18
  109. package/dist/admin/editor/sections/ComponentFields.d.ts +1 -1
  110. package/dist/admin/editor/sections/ComponentFields.js +2 -3
  111. package/dist/admin/editor/sections/PropertyControls.d.ts +1 -1
  112. package/dist/admin/editor/sections/PropertyControls.js +1 -1
  113. package/dist/admin/editor/sections/components.css +244 -0
  114. package/dist/admin/editor/sections/variants.css +93 -0
  115. package/dist/admin/editor/sections/variants.d.ts +1 -1
  116. package/dist/admin/editor/sections/variants.js +1 -1
  117. package/dist/admin/editor/styles/ClassBar.d.ts +1 -1
  118. package/dist/admin/editor/styles/ClassBar.js +1 -1
  119. package/dist/admin/editor/styles/StylesPanel.d.ts +1 -1
  120. package/dist/admin/editor/styles/StylesPanel.js +5 -3
  121. package/dist/admin/editor/styles/{classes.scss → classes.css} +128 -125
  122. package/dist/admin/editor/styles/context.js +9 -4
  123. package/dist/admin/editor/styles/{styles.scss → styles.css} +368 -370
  124. package/dist/admin/editor/templates/Bindable.d.ts +1 -1
  125. package/dist/admin/editor/templates/Bindable.js +1 -1
  126. package/dist/admin/editor/templates/binding.js +4 -1
  127. package/dist/admin/editor/templates/{templates.scss → templates.css} +207 -206
  128. package/dist/admin/editor/tooltip/Tooltips.d.ts +1 -1
  129. package/dist/admin/editor/tooltip/Tooltips.js +1 -1
  130. package/dist/admin/editor/tooltip/{tooltip.scss → tooltip.css} +11 -10
  131. package/dist/admin/editor/topbar/ContentModeToggle.d.ts +1 -1
  132. package/dist/admin/editor/topbar/ContentModeToggle.js +2 -2
  133. package/dist/admin/editor/topbar/DocumentActions.js +5 -5
  134. package/dist/admin/editor/topbar/TopBar.d.ts +1 -1
  135. package/dist/admin/editor/topbar/TopBar.js +2 -3
  136. package/dist/admin/editor/topbar/contentMode.css +25 -0
  137. package/dist/admin/editor/topbar/screens/DrawerRouter.d.ts +1 -1
  138. package/dist/admin/editor/topbar/screens/DrawerRouter.js +52 -40
  139. package/dist/admin/editor/topbar/screens/ScreenDrawer.d.ts +1 -1
  140. package/dist/admin/editor/topbar/screens/ScreenDrawer.js +4 -5
  141. package/dist/admin/editor/topbar/screens/drawerRouterSupport.d.ts +5 -5
  142. package/dist/admin/editor/topbar/screens/drawerRouterSupport.js +7 -7
  143. package/dist/admin/editor/topbar/screens/screens.css +139 -0
  144. package/dist/admin/editor/topbar/settingsDrawer.css +33 -0
  145. package/dist/admin/editor/topbar/settingsDrawer.d.ts +1 -1
  146. package/dist/admin/editor/topbar/settingsDrawer.js +3 -3
  147. package/dist/admin/editor/topbar/{topbar.scss → topbar.css} +189 -231
  148. package/dist/admin/editor/ui/Select.d.ts +1 -1
  149. package/dist/admin/editor/ui/Select.js +1 -1
  150. package/dist/admin/editor/ui/Slider.d.ts +1 -1
  151. package/dist/admin/editor/ui/Slider.js +1 -1
  152. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  153. package/dist/admin/editor/ui/Tabs.js +17 -0
  154. package/dist/admin/editor/ui/controls.css +301 -0
  155. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  156. package/dist/admin/forms/SubmissionCells.js +31 -0
  157. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  158. package/dist/admin/forms/SubmissionView.js +106 -0
  159. package/dist/admin/forms/submissionData.d.ts +32 -0
  160. package/dist/admin/forms/submissionData.js +63 -0
  161. package/dist/admin/forms/submissions.css +200 -0
  162. package/dist/admin/layoutField.css +70 -0
  163. package/dist/admin/rsc.d.ts +2 -0
  164. package/dist/admin/rsc.js +5 -0
  165. package/dist/admin/screen/BuilderScreen.d.ts +1 -1
  166. package/dist/admin/screen/BuilderScreen.js +1 -1
  167. package/dist/admin/templateConditions.css +25 -0
  168. package/dist/ai/endpoint.d.ts +5 -0
  169. package/dist/ai/endpoint.js +18 -8
  170. package/dist/ai/images/service.js +2 -2
  171. package/dist/ai/prompt.d.ts +8 -0
  172. package/dist/ai/prompt.js +30 -0
  173. package/dist/ai/settings/index.js +3 -0
  174. package/dist/ai/tools.d.ts +6 -1
  175. package/dist/ai/tools.js +90 -6
  176. package/dist/blocks/builtins/carousel.js +10 -1
  177. package/dist/blocks/index.d.ts +1 -1
  178. package/dist/blocks/index.js +1 -1
  179. package/dist/blocks/payload.d.ts +7 -0
  180. package/dist/blocks/payload.js +16 -2
  181. package/dist/classes/collection.js +1 -0
  182. package/dist/classes/sheet.js +2 -0
  183. package/dist/comments/collection.js +3 -0
  184. package/dist/comments/shared.d.ts +5 -0
  185. package/dist/comments/shared.js +5 -0
  186. package/dist/core/blocks.d.ts +17 -3
  187. package/dist/core/blocks.js +92 -10
  188. package/dist/core/classes.d.ts +5 -0
  189. package/dist/core/classes.js +26 -1
  190. package/dist/core/conditions.d.ts +7 -0
  191. package/dist/core/conditions.js +22 -0
  192. package/dist/core/dropTarget.d.ts +3 -2
  193. package/dist/core/dropTarget.js +7 -1
  194. package/dist/core/fieldHooks.d.ts +1 -1
  195. package/dist/core/index.d.ts +6 -3
  196. package/dist/core/index.js +6 -3
  197. package/dist/core/payloadBlocks.js +25 -3
  198. package/dist/core/references.d.ts +7 -0
  199. package/dist/core/references.js +29 -11
  200. package/dist/core/regions.d.ts +14 -0
  201. package/dist/core/regions.js +17 -1
  202. package/dist/core/rowLabel.d.ts +8 -0
  203. package/dist/core/rowLabel.js +98 -0
  204. package/dist/core/starter.d.ts +10 -0
  205. package/dist/core/starter.js +40 -0
  206. package/dist/core/tree.js +4 -0
  207. package/dist/core/types.d.ts +96 -0
  208. package/dist/core/uniqueProps.d.ts +40 -0
  209. package/dist/core/uniqueProps.js +156 -0
  210. package/dist/core/validate.js +43 -3
  211. package/dist/forms/answers.d.ts +21 -0
  212. package/dist/forms/answers.js +82 -0
  213. package/dist/forms/blocks.d.ts +33 -0
  214. package/dist/forms/blocks.js +178 -0
  215. package/dist/forms/conditions.d.ts +78 -0
  216. package/dist/forms/conditions.js +184 -0
  217. package/dist/forms/emails.d.ts +23 -0
  218. package/dist/forms/emails.js +64 -0
  219. package/dist/forms/fieldConfigs.d.ts +35 -0
  220. package/dist/forms/fieldConfigs.js +167 -0
  221. package/dist/forms/fieldOps.d.ts +78 -0
  222. package/dist/forms/fieldOps.js +378 -0
  223. package/dist/forms/fieldSettings.d.ts +81 -0
  224. package/dist/forms/fieldSettings.js +239 -0
  225. package/dist/forms/files.d.ts +54 -0
  226. package/dist/forms/files.js +128 -0
  227. package/dist/forms/index.d.ts +16 -0
  228. package/dist/forms/index.js +18 -0
  229. package/dist/forms/mergeTags.d.ts +103 -0
  230. package/dist/forms/mergeTags.js +150 -0
  231. package/dist/forms/noScript.d.ts +60 -0
  232. package/dist/forms/noScript.js +109 -0
  233. package/dist/forms/pageForms.d.ts +99 -0
  234. package/dist/forms/pageForms.js +294 -0
  235. package/dist/forms/pageSync.d.ts +91 -0
  236. package/dist/forms/pageSync.js +325 -0
  237. package/dist/forms/rateLimit.d.ts +21 -0
  238. package/dist/forms/rateLimit.js +50 -0
  239. package/dist/forms/settings.d.ts +13 -0
  240. package/dist/forms/settings.js +92 -0
  241. package/dist/forms/spam.d.ts +100 -0
  242. package/dist/forms/spam.js +218 -0
  243. package/dist/forms/spamSettings.d.ts +43 -0
  244. package/dist/forms/spamSettings.js +25 -0
  245. package/dist/forms/submission.d.ts +34 -0
  246. package/dist/forms/submission.js +89 -0
  247. package/dist/forms/submissionsAdmin.d.ts +26 -0
  248. package/dist/forms/submissionsAdmin.js +108 -0
  249. package/dist/forms/summary.d.ts +60 -0
  250. package/dist/forms/summary.js +113 -0
  251. package/dist/forms/uploads.d.ts +41 -0
  252. package/dist/forms/uploads.js +132 -0
  253. package/dist/index.d.ts +8 -2
  254. package/dist/index.js +8 -2
  255. package/dist/live/document.d.ts +12 -0
  256. package/dist/live/document.js +8 -1
  257. package/dist/live/draftAccess.js +1 -1
  258. package/dist/live/endpoints.d.ts +1 -0
  259. package/dist/live/session.js +3 -1
  260. package/dist/live/storage.d.ts +13 -2
  261. package/dist/live/storage.js +18 -7
  262. package/dist/mcp/forms.d.ts +26 -0
  263. package/dist/mcp/forms.js +280 -0
  264. package/dist/mcp/index.d.ts +7 -0
  265. package/dist/mcp/index.js +29 -10
  266. package/dist/mcp/shared.d.ts +1 -0
  267. package/dist/mcp/shared.js +1 -0
  268. package/dist/plugin/forms.d.ts +30 -0
  269. package/dist/plugin/forms.js +63 -0
  270. package/dist/plugin/formsSync.d.ts +138 -0
  271. package/dist/plugin/formsSync.js +345 -0
  272. package/dist/plugin/hook.d.ts +22 -0
  273. package/dist/plugin/hook.js +19 -7
  274. package/dist/plugin/index.d.ts +14 -0
  275. package/dist/plugin/index.js +101 -30
  276. package/dist/plugin/links.d.ts +7 -2
  277. package/dist/plugin/links.js +9 -3
  278. package/dist/plugin/references.d.ts +6 -0
  279. package/dist/plugin/references.js +12 -0
  280. package/dist/plugin/sections.js +3 -0
  281. package/dist/plugin/templates.js +5 -1
  282. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  283. package/dist/react/canvas/BuilderCanvas.js +29 -6
  284. package/dist/react/canvas/inline/candidates.js +2 -2
  285. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  286. package/dist/react/canvas/inline/mapper.js +35 -4
  287. package/dist/react/canvas/inline/rich/editor.js +9 -1
  288. package/dist/react/components/Image.d.ts +1 -1
  289. package/dist/react/components/Image.js +2 -2
  290. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  291. package/dist/react/render/LayoutOutlet.js +9 -4
  292. package/dist/react/render/RenderLayout.js +13 -7
  293. package/dist/react/render/resolve.d.ts +1 -0
  294. package/dist/react/render/resolve.js +7 -1
  295. package/dist/react/render/templates.js +3 -1
  296. package/dist/react/server.js +19 -0
  297. package/dist/react/theme/ThemeStyle.js +1 -1
  298. package/dist/theme/admin/ColorField.d.ts +4 -3
  299. package/dist/theme/admin/ColorField.js +1 -1
  300. package/dist/theme/admin/FontField.d.ts +4 -3
  301. package/dist/theme/admin/FontField.js +1 -1
  302. package/dist/theme/admin/SaveSignal.js +1 -1
  303. package/dist/theme/admin/SliderField.d.ts +1 -1
  304. package/dist/theme/admin/SliderField.js +1 -1
  305. package/dist/theme/admin/Variables.d.ts +4 -3
  306. package/dist/theme/admin/Variables.js +2 -2
  307. package/dist/theme/admin/fields.css +327 -0
  308. package/dist/theme/global.js +2 -0
  309. package/package.json +29 -24
  310. package/dist/admin/aiKeyField.scss +0 -58
  311. package/dist/admin/diff/layoutDiff.scss +0 -181
  312. package/dist/admin/editor/classes/manager.scss +0 -262
  313. package/dist/admin/editor/fields/fields.scss +0 -628
  314. package/dist/admin/editor/layout/layout.scss +0 -240
  315. package/dist/admin/editor/locale/locale.scss +0 -154
  316. package/dist/admin/editor/menu/menu.scss +0 -132
  317. package/dist/admin/editor/sections/components.scss +0 -238
  318. package/dist/admin/editor/sections/variants.scss +0 -90
  319. package/dist/admin/editor/topbar/contentMode.scss +0 -35
  320. package/dist/admin/editor/topbar/screens/screens.scss +0 -134
  321. package/dist/admin/editor/topbar/settingsDrawer.scss +0 -32
  322. package/dist/admin/editor/ui/controls.scss +0 -320
  323. package/dist/admin/layoutField.scss +0 -69
  324. package/dist/admin/templateConditions.scss +0 -24
  325. package/dist/theme/admin/fields.scss +0 -363
@@ -0,0 +1,325 @@
1
+ // The mapping between a "Build here" Form block on a page and its document in the form-builder
2
+ // plugin's forms collection, both ways. Publishing the page writes the block into the document
3
+ // (`formDataFromBlock`); "Move into this page" turns a saved form into the block's own content
4
+ // (`formBlockFromDoc`). Each document remembers the block it was made from (`source`: collection,
5
+ // document id, block id), so a copied page or a duplicated block gets a new document instead of
6
+ // changing the original's. Pure, client-safe.
7
+ import { isRichText, plainToRichText } from '../core/bindings.js';
8
+ import { createId } from '../core/ids.js';
9
+ import { isPlainObject } from '../core/tree.js';
10
+ import { formFieldSlug, formFieldType } from './blocks.js';
11
+ import { FORM_FIELD_CLASS_KEY, FORM_FIELD_PARTS_KEY } from './fieldSettings.js';
12
+ import { FORM_BLOCK, FORM_SLOT, FORM_SUBMIT_BLOCK, formBlockFields, formBlockMode, formIdOf, formSettingNames, formSubmitBlocks } from './pageForms.js';
13
+ /** Name of the hidden group on the forms collection that names the block a form was made from. */
14
+ export const FORM_SOURCE_FIELD = 'source';
15
+ /** The message after a sent form when the Form block has none: the same text the site shows then. */
16
+ export const DEFAULT_CONFIRMATION = 'Thank you. We will reply soon.';
17
+ /** The keys of a field row that are not the field's props. */
18
+ const ROW_KEYS = new Set(['id', 'blockType', 'blockName', FORM_FIELD_CLASS_KEY, FORM_FIELD_PARTS_KEY]);
19
+ /** The "Build here" Form blocks of a layout, in tree order (also inside other blocks). */
20
+ export function pageFormBlocks(layout) {
21
+ const out = [];
22
+ const visit = (list) => {
23
+ for (const block of list) {
24
+ if (block.type === FORM_BLOCK) {
25
+ if (formBlockMode(block.props, block.slots) === 'build')
26
+ out.push(block);
27
+ continue;
28
+ }
29
+ for (const children of Object.values(block.slots ?? {}))
30
+ visit(children);
31
+ }
32
+ };
33
+ visit(layout.blocks);
34
+ return out;
35
+ }
36
+ /** One field block as a row of the plugin's `fields` blocks field. Classes go to the class keys. */
37
+ export function fieldRowOf(block) {
38
+ const row = { id: block.id, blockType: formFieldSlug(block.type) };
39
+ for (const [key, value] of Object.entries(block.props ?? {})) {
40
+ if (!ROW_KEYS.has(key) && value !== undefined)
41
+ row[key] = value;
42
+ }
43
+ row.blockName = block.label ?? null;
44
+ row[FORM_FIELD_CLASS_KEY] = block.className?.trim() ? block.className : null;
45
+ row[FORM_FIELD_PARTS_KEY] = block.partClassName && Object.keys(block.partClassName).length > 0 ? block.partClassName : null;
46
+ return row;
47
+ }
48
+ /** One row of the plugin's `fields` blocks field as a field block. */
49
+ export function fieldBlockOf(row) {
50
+ if (typeof row.blockType !== 'string' || !row.blockType)
51
+ return null;
52
+ const id = typeof row.id === 'string' || typeof row.id === 'number' ? String(row.id) : createId();
53
+ const block = { id, type: formFieldType(row.blockType) };
54
+ const props = {};
55
+ for (const [key, value] of Object.entries(row)) {
56
+ if (!ROW_KEYS.has(key) && value !== null && value !== undefined)
57
+ props[key] = value;
58
+ }
59
+ if (Object.keys(props).length > 0)
60
+ block.props = props;
61
+ if (typeof row.blockName === 'string' && row.blockName.trim())
62
+ block.label = row.blockName;
63
+ const className = row[FORM_FIELD_CLASS_KEY];
64
+ if (typeof className === 'string' && className.trim())
65
+ block.className = className;
66
+ const parts = row[FORM_FIELD_PARTS_KEY];
67
+ if (isPlainObject(parts)) {
68
+ const kept = Object.fromEntries(Object.entries(parts).filter((entry) => typeof entry[1] === 'string' && entry[1].trim() !== ''));
69
+ if (Object.keys(kept).length > 0)
70
+ block.partClassName = kept;
71
+ }
72
+ return block;
73
+ }
74
+ /**
75
+ * The forms document data of a "Build here" Form block: its fields in tree order (as the plugin's
76
+ * rows, row id = block id) and its settings. Empty settings stay out, so the collection's defaults
77
+ * apply. The title falls back to `fallbackTitle`; the submit button label to the first Submit
78
+ * button block's label.
79
+ */
80
+ export function formDataFromBlock(form, options) {
81
+ const props = form.props ?? {};
82
+ const data = {};
83
+ for (const key of options.settings) {
84
+ const value = props[key];
85
+ if (value !== undefined && value !== null && value !== '')
86
+ data[key] = value;
87
+ }
88
+ const title = typeof props.title === 'string' ? props.title.trim() : '';
89
+ data.title = title || options.fallbackTitle;
90
+ if (options.settings.includes('submitButtonLabel') && !data.submitButtonLabel) {
91
+ const label = formSubmitBlocks(form).map((b) => b.props?.label).find((l) => typeof l === 'string' && l.trim() !== '');
92
+ if (label)
93
+ data.submitButtonLabel = label;
94
+ }
95
+ // The form-builder plugin requires a message unless the form redirects: the site's default text.
96
+ if (options.settings.includes('confirmationMessage') && data.confirmationType !== 'redirect' && !data.confirmationMessage) {
97
+ data.confirmationMessage = plainToRichText(DEFAULT_CONFIRMATION);
98
+ }
99
+ data.fields = formBlockFields(form).map(fieldRowOf);
100
+ return data;
101
+ }
102
+ /**
103
+ * The Form block's content made from a forms document ("Move into this page"): the settings as
104
+ * props, "build" mode, the form's id kept, and the fields (row id = block id) followed by a Submit
105
+ * button. `fields` are the forms collection's fields: the values of virtual fields (the spam settings'
106
+ * Turnstile site key, which Payload computes on read) never become block props. `settings`: the
107
+ * setting names, by default all of them (`formSettingNames`).
108
+ */
109
+ export function formBlockFromDoc(stored, fields, settings = formSettingNames(fields)) {
110
+ const doc = withoutVirtualFields(stored, fields);
111
+ const props = { mode: 'build' };
112
+ const id = formIdOf(doc);
113
+ if (id !== null)
114
+ props.form = id;
115
+ for (const key of settings) {
116
+ const value = withoutRowIds(doc[key]);
117
+ if (value !== undefined && value !== null && value !== '')
118
+ props[key] = value;
119
+ }
120
+ const rows = Array.isArray(doc.fields) ? doc.fields.filter(isPlainObject) : [];
121
+ const fieldBlocks = rows.flatMap((row) => {
122
+ const block = fieldBlockOf(row);
123
+ return block ? [block] : [];
124
+ });
125
+ return { props, children: [...fieldBlocks, { id: createId(), type: FORM_SUBMIT_BLOCK }] };
126
+ }
127
+ /** The document without the values of virtual fields, also inside named groups (read-only values Payload computes on read). */
128
+ export function withoutVirtualFields(doc, fields) {
129
+ const out = { ...doc };
130
+ for (const field of fields) {
131
+ if (!('name' in field) || !field.name) {
132
+ if ('fields' in field && Array.isArray(field.fields))
133
+ Object.assign(out, withoutVirtualFields(out, field.fields));
134
+ continue;
135
+ }
136
+ if ('virtual' in field && field.virtual) {
137
+ delete out[field.name];
138
+ continue;
139
+ }
140
+ const value = out[field.name];
141
+ if (field.type === 'group' && value && typeof value === 'object' && !Array.isArray(value)) {
142
+ out[field.name] = withoutVirtualFields(value, field.fields);
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+ /** A value without Payload's `id` keys in array rows (emails), except where a row needs it. */
148
+ function withoutRowIds(value) {
149
+ if (Array.isArray(value))
150
+ return value.map((row) => (isPlainObject(row) ? Object.fromEntries(Object.entries(row).filter(([k]) => k !== 'id').map(([k, v]) => [k, withoutRowIds(v)])) : row));
151
+ return value;
152
+ }
153
+ /** A value with empty values (`null`, `undefined`, `''`, empty objects) and the ids of settings rows left out, for hashing. */
154
+ function canonical(value, keepIds) {
155
+ // Field rows keep their ids (they name the blocks); rows of settings lists (emails) do not.
156
+ if (Array.isArray(value))
157
+ return value.map((item) => canonical(item, keepIds && isPlainObject(item) && 'blockType' in item));
158
+ if (!isPlainObject(value))
159
+ return value;
160
+ const out = {};
161
+ for (const key of Object.keys(value).toSorted()) {
162
+ if (key === 'id' && !keepIds)
163
+ continue;
164
+ const item = canonical(value[key], false);
165
+ if (item === null || item === undefined || item === '')
166
+ continue;
167
+ if (isPlainObject(item) && Object.keys(item).length === 0)
168
+ continue;
169
+ out[key] = item;
170
+ }
171
+ return out;
172
+ }
173
+ /**
174
+ * A short hash of the form data a Form block writes (`formDataFromBlock`), stored on the form as
175
+ * `source.hash`. The next publish writes the form only when the hash differs, so Payload's own
176
+ * defaults in the stored document (empty condition groups, a default redirect) never count as a
177
+ * change. Keys are sorted and empty values left out; FNV-1a over the JSON.
178
+ */
179
+ export function formDataHash(data) {
180
+ const text = JSON.stringify(canonical(data, true));
181
+ let hash = 0x811c9dc5;
182
+ for (let i = 0; i < text.length; i++) {
183
+ hash ^= text.charCodeAt(i);
184
+ hash = Math.imul(hash, 0x01000193) >>> 0;
185
+ }
186
+ return `${hash.toString(36)}-${text.length.toString(36)}`;
187
+ }
188
+ /**
189
+ * The data that clears the settings `stored` has and `next` lacks, so Payload removes them (an
190
+ * update keeps keys it is not sent): `[]` for a list (emails), `null` for text and rich text.
191
+ * Groups (redirect, spam protection) stay: Payload's field hooks expect a group value.
192
+ */
193
+ export function clearedSettings(stored, next, settings) {
194
+ const out = {};
195
+ for (const key of settings) {
196
+ if (key === 'title' || key in next)
197
+ continue;
198
+ const value = stored[key];
199
+ if (value === undefined || value === null || value === '')
200
+ continue;
201
+ if (Array.isArray(value)) {
202
+ if (value.length > 0)
203
+ out[key] = [];
204
+ }
205
+ else if (!isPlainObject(value) || isRichText(value))
206
+ out[key] = null;
207
+ }
208
+ return out;
209
+ }
210
+ /** The source of a stored form, or null when it has none. */
211
+ export function formSourceOf(doc) {
212
+ const source = doc[FORM_SOURCE_FIELD];
213
+ if (!isPlainObject(source))
214
+ return null;
215
+ const { collection, document, block, hash } = source;
216
+ if (typeof collection !== 'string' || !collection || typeof document !== 'string' || !document || typeof block !== 'string' || !block)
217
+ return null;
218
+ return { collection, document, block, ...(typeof hash === 'string' && hash ? { hash } : {}) };
219
+ }
220
+ /** True when a stored form was made from this block of this document. */
221
+ export function isFormOf(doc, source) {
222
+ const own = formSourceOf(doc);
223
+ return own !== null && own.collection === source.collection && own.document === source.document && own.block === source.block;
224
+ }
225
+ /**
226
+ * The layout with `props.form` of each Form block in `ids` (block id -> form id) set, and its
227
+ * `mode` set to "build" (a block without a mode that names a form would read as "saved"). Returns
228
+ * the same layout when nothing changes.
229
+ */
230
+ export function withFormIds(layout, ids) {
231
+ let changed = false;
232
+ const visit = (list) => list.map((block) => {
233
+ let next = block;
234
+ const id = ids.get(block.id);
235
+ if (block.type === FORM_BLOCK && id !== undefined && (formIdOf(block.props?.form) !== id || block.props?.mode !== 'build')) {
236
+ next = { ...block, props: { ...block.props, mode: 'build', form: id } };
237
+ changed = true;
238
+ }
239
+ if (next.slots) {
240
+ const slots = Object.fromEntries(Object.entries(next.slots).map(([name, children]) => [name, visit(children)]));
241
+ if (Object.entries(slots).some(([name, children]) => children !== next.slots?.[name]))
242
+ next = { ...next, slots };
243
+ }
244
+ return next;
245
+ });
246
+ const blocks = visit(layout.blocks);
247
+ return changed ? { ...layout, blocks } : layout;
248
+ }
249
+ /** The children slot of a Form block. */
250
+ export const formChildren = (form) => form.slots?.[FORM_SLOT] ?? [];
251
+ /**
252
+ * The layout with each "Use a saved form" Form block whose `form` is a loaded document holding
253
+ * that form's fields as its children (then a Submit button), so the site renders a saved form with
254
+ * the same field blocks as a form built on the page, and the page's CSS covers the fields' classes.
255
+ * The site runs it after loading the layout's documents (`loadLayoutData`). Returns the same layout
256
+ * when there is no such block.
257
+ */
258
+ export function withSavedFormFields(layout) {
259
+ let changed = false;
260
+ const visit = (list) => list.map((block) => {
261
+ if (block.type === FORM_BLOCK && formBlockMode(block.props, block.slots) === 'saved' && isPlainObject(block.props?.form)) {
262
+ const doc = block.props.form;
263
+ const rows = Array.isArray(doc.fields) ? doc.fields.filter(isPlainObject) : [];
264
+ const fields = rows.flatMap((row) => {
265
+ const field = fieldBlockOf(row);
266
+ return field ? [{ ...field, id: `${block.id}-${field.id}` }] : [];
267
+ });
268
+ changed = true;
269
+ // `mode` stays "saved" now that the block holds the form's fields.
270
+ return { ...block, props: { ...block.props, mode: 'saved' }, slots: { ...block.slots, [FORM_SLOT]: [...fields, { id: `${block.id}-submit`, type: FORM_SUBMIT_BLOCK }] } };
271
+ }
272
+ if (!block.slots)
273
+ return block;
274
+ return { ...block, slots: Object.fromEntries(Object.entries(block.slots).map(([name, children]) => [name, visit(children)])) };
275
+ });
276
+ const blocks = visit(layout.blocks);
277
+ return changed ? { ...layout, blocks } : layout;
278
+ }
279
+ /** The ids of the forms the "Use a saved form" Form blocks of `layouts` show, without repeats. */
280
+ export function savedFormIds(layouts) {
281
+ const out = new Map();
282
+ const visit = (list) => {
283
+ for (const block of list) {
284
+ if (block.type === FORM_BLOCK && formBlockMode(block.props, block.slots) === 'saved') {
285
+ const id = formIdOf(block.props?.form);
286
+ if (id !== null)
287
+ out.set(String(id), id);
288
+ }
289
+ for (const children of Object.values(block.slots ?? {}))
290
+ visit(children);
291
+ }
292
+ };
293
+ for (const layout of layouts)
294
+ visit(layout.blocks);
295
+ return [...out.values()];
296
+ }
297
+ /** Every class of the fields of saved forms (their own classes and part classes), split on spaces. */
298
+ export function savedFormsClasses(docs) {
299
+ const out = new Set();
300
+ for (const doc of docs) {
301
+ for (const row of Array.isArray(doc.fields) ? doc.fields : []) {
302
+ const block = isPlainObject(row) ? fieldBlockOf(row) : null;
303
+ for (const value of [block?.className, ...Object.values(block?.partClassName ?? {})]) {
304
+ for (const name of (value ?? '').split(/\s+/))
305
+ if (name)
306
+ out.add(name);
307
+ }
308
+ }
309
+ }
310
+ return [...out];
311
+ }
312
+ /**
313
+ * The look a Form block takes on when a saved form moves into it ("Move into this page"): the
314
+ * Form block's default layout classes when its own classes lay out nothing (a block that was only
315
+ * a box around the saved form), and the default classes of each part it has none for.
316
+ */
317
+ export function movedFormLook(block, def) {
318
+ const own = (block.className ?? '').split(/\s+/);
319
+ const laysOut = own.some((name) => /^(flex|grid|inline-flex|inline-grid)$/.test(name));
320
+ const parts = Object.fromEntries(Object.entries(def?.parts ?? {}).flatMap(([name, part]) => (part.defaultClassName && !block.partClassName?.[name] ? [[name, part.defaultClassName]] : [])));
321
+ return {
322
+ ...(def?.defaultClassName && !laysOut ? { addClassName: def.defaultClassName } : {}),
323
+ ...(Object.keys(parts).length > 0 ? { partClassName: parts } : {}),
324
+ };
325
+ }
@@ -0,0 +1,21 @@
1
+ import type { KVAdapter } from 'payload';
2
+ /** The part of Payload's key-value store the counter uses. */
3
+ export type CountStore = Pick<KVAdapter, 'get' | 'set' | 'delete'>;
4
+ /** A store in server memory: the fallback when there is no `payload.kv` (unit tests). */
5
+ export declare function memoryStore(): CountStore;
6
+ export type TakeResult = {
7
+ ok: true;
8
+ count: number;
9
+ } | {
10
+ ok: false;
11
+ retryAfterSeconds: number;
12
+ };
13
+ export declare class WindowCounter {
14
+ #private;
15
+ constructor(now?: () => number);
16
+ /**
17
+ * Counts one event for `key`, or refuses it when the key already had `max` events in the window.
18
+ * `max` 0 (or a window of 0) turns the limit off: every event is allowed and nothing is stored.
19
+ */
20
+ take(store: CountStore, key: string, max: number, windowMs: number): Promise<TakeResult>;
21
+ }
@@ -0,0 +1,50 @@
1
+ // A sliding-window counter: at most `max` events per key in the last `windowMs`. The times live in
2
+ // a store (`payload.kv` by default), so the count survives a restart and all app servers share it.
3
+ // Calls for one key run one after another inside one server process.
4
+ /** A store in server memory: the fallback when there is no `payload.kv` (unit tests). */
5
+ export function memoryStore() {
6
+ const values = new Map();
7
+ return {
8
+ get: async (key) => (values.has(key) ? structuredClone(values.get(key)) : null),
9
+ set: async (key, value) => void values.set(key, structuredClone(value)),
10
+ delete: async (key) => void values.delete(key),
11
+ };
12
+ }
13
+ export class WindowCounter {
14
+ #now;
15
+ #queues = new Map();
16
+ constructor(now = Date.now) {
17
+ this.#now = now;
18
+ }
19
+ /** Runs `task` after the earlier tasks for the same key. */
20
+ #serial(key, task) {
21
+ const result = (this.#queues.get(key) ?? Promise.resolve()).then(task);
22
+ const tail = result.catch(() => undefined);
23
+ this.#queues.set(key, tail);
24
+ void tail.then(() => {
25
+ if (this.#queues.get(key) === tail)
26
+ this.#queues.delete(key);
27
+ });
28
+ return result;
29
+ }
30
+ /**
31
+ * Counts one event for `key`, or refuses it when the key already had `max` events in the window.
32
+ * `max` 0 (or a window of 0) turns the limit off: every event is allowed and nothing is stored.
33
+ */
34
+ take(store, key, max, windowMs) {
35
+ if (!(max > 0) || !(windowMs > 0))
36
+ return Promise.resolve({ ok: true, count: 0 });
37
+ return this.#serial(key, async () => {
38
+ const now = this.#now();
39
+ const value = await store.get(key);
40
+ const recent = (Array.isArray(value?.at) ? value.at : []).filter((t) => typeof t === 'number' && t > now - windowMs).toSorted((a, b) => a - b);
41
+ if (recent.length >= max) {
42
+ const oldest = recent[recent.length - max];
43
+ return { ok: false, retryAfterSeconds: Math.max(1, Math.ceil((oldest + windowMs - now) / 1000)) };
44
+ }
45
+ const next = [...recent, now];
46
+ await store.set(key, { at: next });
47
+ return { ok: true, count: next.length };
48
+ });
49
+ }
50
+ }
@@ -0,0 +1,13 @@
1
+ /** The settings format for agents. */
2
+ export declare const FORM_SETTINGS_GUIDE: string;
3
+ /** A form's settings with rich text as plain text and without Payload's row ids. */
4
+ export declare function formSettingsView(doc: Record<string, unknown>, keys: readonly string[]): Record<string, unknown>;
5
+ /**
6
+ * The changes for the regions' fields endpoint (`writeRegionFields`): one per top-level setting.
7
+ * A group (redirect, spamProtection) merges into its stored value; other values replace.
8
+ * `allowed` are the settings the form has. Returns an error string for an unknown key.
9
+ */
10
+ export declare function formSettingsChanges(input: Record<string, unknown>, allowed: readonly string[], stored: Record<string, unknown>): Array<{
11
+ path: string;
12
+ value: unknown;
13
+ }> | string;
@@ -0,0 +1,92 @@
1
+ // A form's settings for AI agents: the form-builder plugin's fields outside `fields` (title,
2
+ // submit button, confirmation, redirect, emails) and the site's own settings groups (spam
3
+ // protection). Agents read and write rich text as plain text. Pure: no Payload, no I/O.
4
+ import { isRichText, plainToRichText, richTextToPlain } from '../core/bindings.js';
5
+ import { isPlainObject } from '../core/tree.js';
6
+ /** The settings format for agents. */
7
+ export const FORM_SETTINGS_GUIDE = [
8
+ 'FORM SETTINGS (updateFormSettings, getForm `settings`). Send only the keys you change:',
9
+ '- title (text, required): the form\'s name in the admin.',
10
+ '- submitButtonLabel (text): the label of the send button.',
11
+ '- confirmationType: "message" (show confirmationMessage after sending) or "redirect" (go to `redirect`).',
12
+ '- confirmationMessage (plain text, one paragraph per line; stored as rich text).',
13
+ '- redirect: { type: "reference", reference: { relationTo: "pages", value: <page id> } } or { type: "custom", url: "/thanks" }. Needed when confirmationType is "redirect".',
14
+ '- emails: the emails sent for each submission. A list that REPLACES all emails: [{ emailTo, cc?, bcc?, replyTo?, emailFrom?, subject, message }]. message is plain text. {{field_name}} in a text puts that answer in (e.g. emailTo "{{email}}" sends to the visitor, replyTo "{{email}}" lets you reply to them); {{*}} lists every answer.',
15
+ '- Other groups this site adds (e.g. spamProtection) take the shape getForm shows; a group merges its keys.',
16
+ ].join('\n');
17
+ /** Keys whose values are rich text in Payload and plain text for agents. */
18
+ const RICH_TEXT_KEYS = new Set(['confirmationMessage', 'message']);
19
+ /** A form's settings with rich text as plain text and without Payload's row ids. */
20
+ export function formSettingsView(doc, keys) {
21
+ const out = {};
22
+ for (const key of keys) {
23
+ if (!(key in doc))
24
+ continue;
25
+ const value = plainValue(key, doc[key]);
26
+ if (value !== undefined)
27
+ out[key] = value;
28
+ }
29
+ return out;
30
+ }
31
+ function plainValue(key, value) {
32
+ if (value === null || value === undefined)
33
+ return undefined;
34
+ if (RICH_TEXT_KEYS.has(key) && isRichText(value))
35
+ return richTextToPlain(value);
36
+ if (Array.isArray(value)) {
37
+ return value.map((row) => {
38
+ if (!isPlainObject(row))
39
+ return row;
40
+ const out = {};
41
+ for (const [k, v] of Object.entries(row)) {
42
+ if (k === 'id')
43
+ continue;
44
+ const plain = plainValue(k, v);
45
+ if (plain !== undefined)
46
+ out[k] = plain;
47
+ }
48
+ return out;
49
+ });
50
+ }
51
+ if (isPlainObject(value) && !isRichText(value)) {
52
+ const out = {};
53
+ for (const [k, v] of Object.entries(value)) {
54
+ const plain = plainValue(k, v);
55
+ if (plain !== undefined)
56
+ out[k] = plain;
57
+ }
58
+ return out;
59
+ }
60
+ return value;
61
+ }
62
+ /** The stored value of a setting an agent sent: plain text becomes rich text where Payload stores rich text. */
63
+ function storedValue(key, value) {
64
+ if (RICH_TEXT_KEYS.has(key) && typeof value === 'string')
65
+ return plainToRichText(value);
66
+ if (Array.isArray(value)) {
67
+ return value.map((row) => (isPlainObject(row) ? Object.fromEntries(Object.entries(row).map(([k, v]) => [k, storedValue(k, v)])) : row));
68
+ }
69
+ return value;
70
+ }
71
+ /**
72
+ * The changes for the regions' fields endpoint (`writeRegionFields`): one per top-level setting.
73
+ * A group (redirect, spamProtection) merges into its stored value; other values replace.
74
+ * `allowed` are the settings the form has. Returns an error string for an unknown key.
75
+ */
76
+ export function formSettingsChanges(input, allowed, stored) {
77
+ const changes = [];
78
+ for (const [key, raw] of Object.entries(input)) {
79
+ if (raw === undefined)
80
+ continue;
81
+ if (!allowed.includes(key))
82
+ return `"${key}" is not a setting of this form. Settings: ${allowed.join(', ')}.`;
83
+ let value = storedValue(key, raw);
84
+ const before = stored[key];
85
+ if (isPlainObject(value) && isPlainObject(before) && !isRichText(value))
86
+ value = { ...before, ...value };
87
+ changes.push({ path: key, value });
88
+ }
89
+ if (changes.length === 0)
90
+ return 'Send at least one setting to change.';
91
+ return changes;
92
+ }
@@ -0,0 +1,100 @@
1
+ import { type CollectionBeforeValidateHook, type Field, type PayloadRequest } from 'payload';
2
+ import { WindowCounter, type CountStore } from './rateLimit.js';
3
+ import { type FormSpamSettings, type FormSpamValues } from './spamSettings.js';
4
+ type Env = Record<string, string | undefined>;
5
+ /** The Turnstile keys from `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`. Null unless both are set. */
6
+ export declare function turnstileKeys(env?: Env): {
7
+ siteKey: string;
8
+ secretKey: string;
9
+ } | null;
10
+ export type SpamProtectionFieldOptions = {
11
+ /** Where the Turnstile keys come from. Default `process.env`. */
12
+ env?: Env;
13
+ };
14
+ /**
15
+ * The `spamProtection` group for the form-builder plugin's forms collection:
16
+ * `formOverrides: { fields: ({ defaultFields }) => [...defaultFields, spamProtectionField()] }`.
17
+ * `turnstileSiteKey` is virtual and hidden: on read it holds the site key when the form uses
18
+ * Turnstile and both keys are set, so the site's form knows whether to show the widget.
19
+ */
20
+ export declare function spamProtectionField(options?: SpamProtectionFieldOptions): Field;
21
+ export type SpamReason = 'honeypot' | 'too-fast' | 'turnstile' | 'rate-limit';
22
+ /** True when the honeypot input has a value. */
23
+ export declare function honeypotFilled(values: FormSpamValues | null | undefined): boolean;
24
+ /**
25
+ * True when the form was sent faster than the form allows. A missing time counts as too fast. A
26
+ * heuristic only: the visitor's browser measures the time, so a bot can send any value. The real
27
+ * checks are the honeypot, the rate limit and Turnstile.
28
+ */
29
+ export declare function filledTooFast(values: FormSpamValues | null | undefined, settings: FormSpamSettings): boolean;
30
+ /**
31
+ * The request header that holds the visitor's IP, set by a proxy the server trusts:
32
+ * - `x-forwarded-for`: behind one reverse proxy (nginx, Caddy, Traefik) that appends the address it
33
+ * sees. The rightmost entry is used: the visitor can write the entries before it.
34
+ * - `x-real-ip`: a proxy that sets this header to the address it sees.
35
+ * - `cf-connecting-ip`: behind Cloudflare, when only Cloudflare can reach the server.
36
+ */
37
+ export type TrustedIpHeader = 'x-forwarded-for' | 'x-real-ip' | 'cf-connecting-ip';
38
+ /**
39
+ * The visitor's IP from the trusted header, or null. No header is trusted by default: any visitor
40
+ * can send these headers, and a proxy that the server does not sit behind does not fix them.
41
+ */
42
+ export declare function clientIp(headers: Pick<Headers, 'get'> | null | undefined, trusted: TrustedIpHeader | null | undefined): string | null;
43
+ /** Asks Cloudflare whether a Turnstile token is valid. A network error or a bad answer counts as invalid. */
44
+ export declare function verifyTurnstile(args: {
45
+ token: string | null | undefined;
46
+ secretKey: string;
47
+ ip?: string | null;
48
+ fetch?: typeof fetch;
49
+ }): Promise<boolean>;
50
+ export type FormSpamProtectionOptions = {
51
+ /** Slug of the forms collection. Default "forms". */
52
+ forms?: string;
53
+ /** Where the Turnstile keys come from. Default `process.env`. */
54
+ env?: Env;
55
+ /** For tests: the fetch that calls Turnstile, the clock, the rate-limit store. */
56
+ fetch?: typeof fetch;
57
+ now?: () => number;
58
+ store?: CountStore;
59
+ /**
60
+ * The header that holds the visitor's IP (see `TrustedIpHeader`). Default: none, so the rate
61
+ * limit is off. Set it to what the proxy in front of the server sets.
62
+ */
63
+ trustedIpHeader?: TrustedIpHeader;
64
+ /** The visitor's IP, for other setups. Wins over `trustedIpHeader`. Without an IP the rate limit does not apply. */
65
+ ipOf?: (req: PayloadRequest) => string | null;
66
+ };
67
+ /**
68
+ * `context` flag of a submission the site's no-JavaScript route sends (a native form post). The
69
+ * fill time cannot be measured without JavaScript: that check passes. A form that uses Turnstile
70
+ * is refused (the check needs the widget). Only server code can set `context`.
71
+ */
72
+ export declare const FORM_NO_SCRIPT_CONTEXT = "builderFormNoScript";
73
+ /** The message for a form with Turnstile sent without JavaScript. */
74
+ export declare const TURNSTILE_NEEDS_SCRIPT_MESSAGE = "This form needs JavaScript for its spam check. Turn on JavaScript and send it again.";
75
+ type CheckArgs = {
76
+ values: FormSpamValues | null | undefined;
77
+ settings: FormSpamSettings;
78
+ ip: string | null;
79
+ formId: string | number | null;
80
+ env: Env;
81
+ fetch?: typeof fetch;
82
+ store: CountStore;
83
+ counter: WindowCounter;
84
+ };
85
+ /** Runs the checks, cheapest first. The rate limit counts only submissions that pass the others. */
86
+ export declare function checkSubmission(args: CheckArgs): Promise<{
87
+ ok: true;
88
+ } | {
89
+ ok: false;
90
+ reason: SpamReason;
91
+ }>;
92
+ /**
93
+ * The submissions hook. Put it first in the form-builder plugin's submissions hooks:
94
+ * `formSubmissionOverrides: { hooks: { beforeValidate: [formSpamProtection(), formSubmissionConditions()] } }`.
95
+ * Runs on create only. The site's form sends `{ form, submissionData, spam }`; `spam` is always
96
+ * removed from the data, so it is never stored. Server code (Local API) and signed-in admin users
97
+ * who send no `spam` values (the admin's create view) are not checked.
98
+ */
99
+ export declare function formSpamProtection(options?: FormSpamProtectionOptions): CollectionBeforeValidateHook;
100
+ export {};