@nextlyhq/plugin-form-builder 0.0.2-alpha.4 → 0.0.2-alpha.41

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 (38) hide show
  1. package/README.md +4 -5
  2. package/dist/admin/index.d.ts +123 -331
  3. package/dist/admin/index.js +3809 -3419
  4. package/dist/admin/index.js.map +1 -1
  5. package/dist/chunk-WVI7N3QO.js +559 -0
  6. package/dist/chunk-WVI7N3QO.js.map +1 -0
  7. package/dist/index.d.ts +12 -11
  8. package/dist/index.js +555 -661
  9. package/dist/index.js.map +1 -1
  10. package/dist/{index-C0kBvYjm.d.ts → types-r8uBeB0u.d.ts} +126 -125
  11. package/package.json +28 -30
  12. package/dist/CheckboxFieldEditor-K4T6QX52.js +0 -121
  13. package/dist/CheckboxFieldEditor-K4T6QX52.js.map +0 -1
  14. package/dist/DateFieldEditor-JFJFAVOH.js +0 -187
  15. package/dist/DateFieldEditor-JFJFAVOH.js.map +0 -1
  16. package/dist/EmailFieldEditor-MMOXXL7P.js +0 -138
  17. package/dist/EmailFieldEditor-MMOXXL7P.js.map +0 -1
  18. package/dist/NumberFieldEditor-UISAYR6Z.js +0 -175
  19. package/dist/NumberFieldEditor-UISAYR6Z.js.map +0 -1
  20. package/dist/RadioFieldEditor-6UQFH4WT.js +0 -165
  21. package/dist/RadioFieldEditor-6UQFH4WT.js.map +0 -1
  22. package/dist/SelectFieldEditor-PSO4KHV4.js +0 -213
  23. package/dist/SelectFieldEditor-PSO4KHV4.js.map +0 -1
  24. package/dist/TextFieldEditor-5EU64EA5.js +0 -187
  25. package/dist/TextFieldEditor-5EU64EA5.js.map +0 -1
  26. package/dist/TextareaFieldEditor-773G3LNM.js +0 -190
  27. package/dist/TextareaFieldEditor-773G3LNM.js.map +0 -1
  28. package/dist/admin/index.css +0 -934
  29. package/dist/admin/index.css.map +0 -1
  30. package/dist/chunk-ABNZFTQK.js +0 -586
  31. package/dist/chunk-ABNZFTQK.js.map +0 -1
  32. package/dist/chunk-XTCEPJ7B.js +0 -256
  33. package/dist/chunk-XTCEPJ7B.js.map +0 -1
  34. package/dist/components/index.d.ts +0 -3
  35. package/dist/components/index.js +0 -9
  36. package/dist/components/index.js.map +0 -1
  37. package/dist/styles/form-builder.css +0 -1150
  38. package/dist/styles/submissions-filter.css +0 -75
package/dist/index.js CHANGED
@@ -1,5 +1,36 @@
1
+ import {
2
+ BUILT_IN_FORM_FIELD_TYPES,
3
+ DEFAULT_FORM_SETTINGS,
4
+ DEFAULT_NOTIFICATION_SETTINGS,
5
+ applyFieldDefaults,
6
+ applyFormDefaults,
7
+ createFormConfig,
8
+ downloadFile,
9
+ evaluateConditions,
10
+ evaluateSingleCondition,
11
+ exportAndDownload,
12
+ exportToCSV,
13
+ exportToJSON,
14
+ formatExportValue,
15
+ generateExportFilename,
16
+ getSupportedComparisonOperators,
17
+ isCheckboxFormField,
18
+ isEmailFormField,
19
+ isFileFormField,
20
+ isFormField,
21
+ isFormFieldType,
22
+ isKnownFormField,
23
+ isSelectFormField,
24
+ isTextFormField,
25
+ isValidComparisonOperator,
26
+ normalizeFormSettings,
27
+ pluralize,
28
+ toTitleCase
29
+ } from "./chunk-WVI7N3QO.js";
30
+
1
31
  // src/plugin.ts
2
- import { getCollectionsHandler } from "nextly/runtime";
32
+ import { createRequire } from "module";
33
+ import { definePlugin } from "@nextlyhq/plugin-sdk";
3
34
 
4
35
  // src/collections/forms.ts
5
36
  import {
@@ -90,12 +121,18 @@ function formsCollection(pluginConfig) {
90
121
  description: "Allow the same user/IP to submit this form multiple times"
91
122
  }
92
123
  }),
124
+ checkbox({
125
+ name: "honeypotEnabled",
126
+ label: "Honeypot",
127
+ admin: {
128
+ description: "Per-form honeypot override; unset inherits the plugin default"
129
+ }
130
+ }),
93
131
  checkbox({
94
132
  name: "captchaEnabled",
95
133
  label: "Enable reCAPTCHA",
96
- defaultValue: false,
97
134
  admin: {
98
- description: "Protect this form with Google reCAPTCHA v3"
135
+ description: "Per-form reCAPTCHA override; unset inherits the plugin default"
99
136
  }
100
137
  }),
101
138
  text({
@@ -163,10 +200,10 @@ function formsCollection(pluginConfig) {
163
200
  // ============================================================
164
201
  json({
165
202
  name: "notifications",
166
- label: "Email Integrations",
203
+ label: "Notifications",
167
204
  defaultValue: [],
168
205
  admin: {
169
- description: "Email notification integrations. Managed by the Form Builder UI."
206
+ description: "Email notification rules. Managed by the Form Builder UI."
170
207
  }
171
208
  }),
172
209
  // ============================================================
@@ -252,16 +289,6 @@ function formsCollection(pluginConfig) {
252
289
  }
253
290
  return data;
254
291
  }
255
- ],
256
- // Add virtual submission count field
257
- afterRead: [
258
- (context) => {
259
- const { data } = context;
260
- if (data) {
261
- data.submissionCount = 0;
262
- }
263
- return data;
264
- }
265
292
  ]
266
293
  },
267
294
  // Spread any additional overrides (excluding already used properties)
@@ -317,12 +344,23 @@ function submissionsCollection(pluginConfig) {
317
344
  options: [
318
345
  { label: "New", value: "new" },
319
346
  { label: "Read", value: "read" },
320
- { label: "Archived", value: "archived" }
347
+ { label: "Archived", value: "archived" },
348
+ // Spam is stored and flagged, never silently dropped: a false
349
+ // positive stays reviewable and recoverable ("Not spam" = back to new).
350
+ { label: "Spam", value: "spam" }
321
351
  ],
322
352
  admin: {
323
353
  description: "Track whether this submission has been reviewed"
324
354
  }
325
355
  }),
356
+ text2({
357
+ name: "spamReason",
358
+ label: "Spam Reason",
359
+ admin: {
360
+ readOnly: true,
361
+ description: "Which spam check flagged this submission (empty for clean submissions)"
362
+ }
363
+ }),
326
364
  // ============================================================
327
365
  // Internal Notes
328
366
  // ============================================================
@@ -360,6 +398,24 @@ function submissionsCollection(pluginConfig) {
360
398
  readOnly: true,
361
399
  description: "When the form was submitted"
362
400
  }
401
+ }),
402
+ // Honesty stamps for admin edits of submitted data: a corrected
403
+ // submission must never be indistinguishable from what the visitor sent.
404
+ date({
405
+ name: "editedAt",
406
+ label: "Edited At",
407
+ admin: {
408
+ readOnly: true,
409
+ description: "When an admin last edited the submitted data"
410
+ }
411
+ }),
412
+ text2({
413
+ name: "editedBy",
414
+ label: "Edited By",
415
+ admin: {
416
+ readOnly: true,
417
+ description: "ID of the admin who last edited the submitted data"
418
+ }
363
419
  })
364
420
  ];
365
421
  let finalFields;
@@ -381,10 +437,17 @@ function submissionsCollection(pluginConfig) {
381
437
  order: 51,
382
438
  useAsTitle: "id",
383
439
  description: "View and manage form submissions",
384
- // Custom components for submissions list
440
+ // Submissions are created by visitors submitting forms — a hand-typed
441
+ // "New Submission" would be fiction, so the admin never offers one.
442
+ disableCreate: true,
385
443
  components: {
386
- // Filter dropdown to filter submissions by form
387
- BeforeListTable: "@nextlyhq/plugin-form-builder/admin#SubmissionsFilter"
444
+ // The full submissions experience (per-form columns, status tabs,
445
+ // drawer detail, export) replaces the generic list.
446
+ views: {
447
+ List: {
448
+ Component: "@nextlyhq/plugin-form-builder/admin#SubmissionsView"
449
+ }
450
+ }
388
451
  },
389
452
  ...overrides.admin
390
453
  },
@@ -401,7 +464,9 @@ function submissionsCollection(pluginConfig) {
401
464
  delete: accessOverrides?.delete ?? (({ roles }) => roles.includes("admin") || roles.includes("super-admin"))
402
465
  },
403
466
  hooks: {
404
- // Auto-set submittedAt timestamp on creation
467
+ // Auto-set submittedAt timestamp on creation. (The edit stamp for
468
+ // updates is registered in plugin.ts init — direct registry hooks are
469
+ // the path that runs for every API surface.)
405
470
  beforeValidate: [
406
471
  (context) => {
407
472
  const { data, operation } = context;
@@ -424,9 +489,12 @@ function submissionsCollection(pluginConfig) {
424
489
  }
425
490
 
426
491
  // src/plugin.ts
492
+ var { version: PLUGIN_VERSION } = createRequire(import.meta.url)(
493
+ "../package.json"
494
+ );
427
495
  function resolveConfig(options) {
428
- const formOverrides = options.formOverrides || options.collections?.forms || {};
429
- const submissionOverrides = options.formSubmissionOverrides || options.collections?.submissions || {};
496
+ const formOverrides = options.formOverrides || {};
497
+ const submissionOverrides = options.formSubmissionOverrides || {};
430
498
  return {
431
499
  formOverrides: {
432
500
  ...formOverrides,
@@ -495,41 +563,206 @@ function formBuilder(options = {}) {
495
563
  const resolvedConfig = resolveConfig(options);
496
564
  const formsCol = formsCollection(resolvedConfig);
497
565
  const submissionsCol = submissionsCollection(resolvedConfig);
498
- const plugin = {
566
+ const plugin = definePlugin({
499
567
  name: "@nextlyhq/plugin-form-builder",
500
- version: "0.0.8",
501
- collections: [formsCol, submissionsCol],
568
+ version: PLUGIN_VERSION,
569
+ nextly: ">=0.0.2-alpha.21",
570
+ // Identity metadata for the admin plugins page, mirroring package.json.
571
+ author: "Nextly",
572
+ homepage: "https://nextlyhq.com",
573
+ repository: "https://github.com/nextlyhq/nextly",
574
+ license: "MIT",
575
+ category: "forms",
576
+ tags: ["forms", "submissions", "email-notifications"],
577
+ // Declarative schema: the merged pipeline folds these into the
578
+ // app schema — no manual `setup()` append needed. Just register the plugin.
579
+ contributes: {
580
+ collections: [formsCol, submissionsCol],
581
+ // Custom permission — gates submission export beyond CRUD. The
582
+ // canonical example third-party plugin authors copy.
583
+ permissions: [
584
+ {
585
+ action: "export",
586
+ resource: "submissions",
587
+ label: "Export Submissions",
588
+ description: "Export form submissions as CSV/JSON",
589
+ // No `group`: the admin already files this under the plugin that
590
+ // declared it, so naming the plugin again would nest it inside
591
+ // itself. `group` is for a plugin with enough permissions to sort
592
+ // its own into headings, which one is not.
593
+ //
594
+ // `danger` because the point of the permission is to take
595
+ // submissions — names, emails, whatever a form asked for — out of
596
+ // the site in a file.
597
+ danger: true
598
+ }
599
+ ],
600
+ // HTTP route — exported at
601
+ // /api/plugins/@nextlyhq/plugin-form-builder/submissions/export. Secure by
602
+ // default: gated by the custom `export-submissions` permission. Reads
603
+ // via the secure-by-default service path as the authed user and
604
+ // resolves its OWN slug through `ctx.self`. The canonical
605
+ // contributes.routes example for third-party authors.
606
+ routes: [
607
+ {
608
+ method: "GET",
609
+ path: "/submissions/export",
610
+ requiredPermission: "export-submissions",
611
+ handler: async (req, ctx) => {
612
+ const declaredSlug = resolvedConfig.formSubmissionOverrides.slug;
613
+ const slug = ctx.self.collections[declaredSlug] ?? declaredSlug;
614
+ const url2 = new URL(req.url);
615
+ const format = url2.searchParams.get("format") ?? "json";
616
+ const formId = url2.searchParams.get("form");
617
+ const status = url2.searchParams.get("status");
618
+ const where = {};
619
+ if (formId) where.form = { equals: formId };
620
+ if (status) where.status = { equals: status };
621
+ else where.status = { not_equals: "spam" };
622
+ const opts = { as: "user", user: ctx.user ?? void 0 };
623
+ let form;
624
+ if (format === "csv") {
625
+ if (!formId) {
626
+ return Response.json(
627
+ {
628
+ error: {
629
+ code: "VALIDATION_ERROR",
630
+ message: "CSV export requires a form parameter."
631
+ }
632
+ },
633
+ { status: 400 }
634
+ );
635
+ }
636
+ const formsSlugDeclared = resolvedConfig.formOverrides.slug;
637
+ const formsSlug = ctx.self.collections[formsSlugDeclared] ?? formsSlugDeclared;
638
+ const formResult = await ctx.services.collections.listEntries(
639
+ formsSlug,
640
+ { where: { id: { equals: formId } } },
641
+ opts
642
+ );
643
+ form = formResult.data[0];
644
+ if (!form) {
645
+ return Response.json(
646
+ { error: { code: "NOT_FOUND", message: "Form not found." } },
647
+ { status: 404 }
648
+ );
649
+ }
650
+ }
651
+ const MAX_EXPORT_ROWS = 5e4;
652
+ const items = [];
653
+ const pageSize = 200;
654
+ let truncated = false;
655
+ for (let page = 1; ; page += 1) {
656
+ const result = await ctx.services.collections.listEntries(
657
+ slug,
658
+ { where, pagination: { limit: pageSize, page } },
659
+ opts
660
+ );
661
+ items.push(...result.data);
662
+ const pageWasFull = result.data.length === pageSize;
663
+ if (items.length >= MAX_EXPORT_ROWS) {
664
+ truncated = pageWasFull || items.length > MAX_EXPORT_ROWS;
665
+ items.length = MAX_EXPORT_ROWS;
666
+ break;
667
+ }
668
+ if (!pageWasFull) break;
669
+ }
670
+ const truncationHeaders = truncated ? { "X-Export-Truncated": "true" } : {};
671
+ if (format !== "csv" || !form) {
672
+ return Response.json({ items }, { headers: truncationHeaders });
673
+ }
674
+ const csv = exportToCSV(
675
+ items,
676
+ form
677
+ );
678
+ const filename = generateExportFilename(
679
+ typeof form.slug === "string" ? form.slug : "form",
680
+ "csv"
681
+ );
682
+ return new Response(csv, {
683
+ headers: {
684
+ "Content-Type": "text/csv; charset=utf-8",
685
+ "Content-Disposition": `attachment; filename="${filename}"`,
686
+ ...truncationHeaders
687
+ }
688
+ });
689
+ }
690
+ },
691
+ {
692
+ // The builder UI reads the host's resolved field enable/disable map
693
+ // from here, so the plugin option actually gates the type picker.
694
+ // Options resolve server-side only; this is the one channel the
695
+ // admin client has to them.
696
+ method: "GET",
697
+ path: "/builder-config",
698
+ // Derived from the forms slug like the menu entry: with an
699
+ // overridden slug, users hold read-<slug>, not read-forms.
700
+ requiredPermission: `read-${resolvedConfig.formOverrides.slug}`,
701
+ handler: (_req, ctx) => Promise.resolve(
702
+ Response.json({
703
+ fields: resolvedConfig.fields,
704
+ // Notification defaults the builder surfaces: defaultToEmail
705
+ // seeds a new form's first rule, defaultFrom renders as the
706
+ // inherited sender placeholder.
707
+ notifications: {
708
+ defaultFrom: resolvedConfig.notifications.defaultFrom,
709
+ defaultToEmail: resolvedConfig.notifications.defaultToEmail
710
+ },
711
+ // Spam defaults the Settings tab surfaces, so per-form
712
+ // override selects can show what "inherit" resolves to.
713
+ spamProtection: {
714
+ honeypot: resolvedConfig.spamProtection.honeypot,
715
+ recaptchaEnabled: resolvedConfig.spamProtection.recaptcha?.enabled ?? false
716
+ },
717
+ // Runtime-resolved collection slugs (through ctx.self, so a
718
+ // framework .rename() is honored too) — admin components
719
+ // never hardcode "forms"/"form-submissions".
720
+ slugs: {
721
+ forms: ctx.self.collections[resolvedConfig.formOverrides.slug] ?? resolvedConfig.formOverrides.slug,
722
+ submissions: ctx.self.collections[resolvedConfig.formSubmissionOverrides.slug] ?? resolvedConfig.formSubmissionOverrides.slug
723
+ }
724
+ })
725
+ )
726
+ }
727
+ ]
728
+ },
729
+ // Forms is a first-class destination, not a plugin detail: standalone
730
+ // placement gives it its own main-rail icon after Media, and its
731
+ // sub-sidebar lists the plugin's collections (Forms, Submissions) —
732
+ // no separate menu contribution, so "Forms" exists exactly once.
733
+ // Hosts preferring the Plugins section override placement in config.
734
+ // (The old admin.settings.component that rendered a second full builder
735
+ // at /admin/plugins/<slug> is gone; the collection Edit-view override
736
+ // is the single FormBuilderView mount.)
502
737
  admin: {
738
+ placement: "standalone",
739
+ after: "media",
503
740
  order: 50,
741
+ appearance: { icon: "FileText", label: "Forms" },
504
742
  description: "Create and manage forms with submission tracking"
505
743
  },
506
- // -- Config transformer --------------------------------------------------
507
- // Automatically adds plugin collections so users don't have to spread them.
508
- config(config) {
509
- const existing = config.collections || [];
510
- const formsSlug = resolvedConfig.formOverrides.slug;
511
- const submissionsSlug = resolvedConfig.formSubmissionOverrides.slug;
512
- const toAdd = [];
513
- if (!existing.some((c) => c.slug === formsSlug))
514
- toAdd.push(formsCol);
515
- if (!existing.some((c) => c.slug === submissionsSlug))
516
- toAdd.push(submissionsCol);
517
- return { ...config, collections: [...existing, ...toAdd] };
518
- },
519
744
  // -- Init ----------------------------------------------------------------
520
745
  // Registers an afterCreate hook on submissions to send email notifications.
521
746
  init(nextly) {
522
- const submissionSlug = resolvedConfig.formSubmissionOverrides.slug;
523
- const guardKey = `__formBuilder_afterCreate_${submissionSlug}`;
524
- const g = globalThis;
525
- if (g[guardKey]) return;
526
- g[guardKey] = true;
527
- nextly.infra.logger.info("Form Builder plugin initialized", {
747
+ const declaredSubmissionsSlug = resolvedConfig.formSubmissionOverrides.slug;
748
+ const submissionSlug = nextly.self.collections[declaredSubmissionsSlug] ?? declaredSubmissionsSlug;
749
+ nextly.logger.info("Form Builder plugin initialized", {
528
750
  formsCollection: resolvedConfig.formOverrides.slug,
529
751
  submissionsCollection: submissionSlug,
530
752
  enabledFields: Object.entries(resolvedConfig.fields).filter(([, on]) => on).map(([name]) => name)
531
753
  });
532
754
  nextly.__formBuilderConfig = resolvedConfig;
755
+ if (resolvedConfig.beforeEmail) {
756
+ nextly.filters.add(
757
+ "form-builder.beforeEmail",
758
+ (emails, ctx) => resolvedConfig.beforeEmail({
759
+ emails,
760
+ // Boundary: loose runtime documents → the user's typed contract.
761
+ form: ctx.form,
762
+ submission: ctx.submission
763
+ })
764
+ );
765
+ }
533
766
  nextly.hooks.on(
534
767
  "afterCreate",
535
768
  submissionSlug,
@@ -537,8 +770,42 @@ function formBuilder(options = {}) {
537
770
  await handleSubmissionCreated(context, resolvedConfig, nextly);
538
771
  }
539
772
  );
773
+ nextly.hooks.on("beforeUpdate", submissionSlug, (context) => {
774
+ const ctx = context;
775
+ if (ctx.data && ctx.data.data !== void 0) {
776
+ ctx.data.editedAt = /* @__PURE__ */ new Date();
777
+ ctx.data.editedBy = ctx.user?.id ?? null;
778
+ }
779
+ return ctx.data;
780
+ });
781
+ const declaredFormsSlug = resolvedConfig.formOverrides.slug;
782
+ const formsSlug = nextly.self.collections[declaredFormsSlug] ?? declaredFormsSlug;
783
+ nextly.hooks.on("afterRead", formsSlug, async (context) => {
784
+ const data = context.data;
785
+ const records = Array.isArray(data) ? data : data ? [data] : [];
786
+ await Promise.all(
787
+ records.map(async (record) => {
788
+ const form = record;
789
+ if (typeof form.id !== "string") return;
790
+ try {
791
+ form.submissionCount = await nextly.services.collections.count(
792
+ submissionSlug,
793
+ {
794
+ where: {
795
+ form: { equals: form.id },
796
+ status: { not_equals: "spam" }
797
+ }
798
+ },
799
+ { as: "system" }
800
+ );
801
+ } catch {
802
+ form.submissionCount = 0;
803
+ }
804
+ })
805
+ );
806
+ });
540
807
  }
541
- };
808
+ });
542
809
  return {
543
810
  plugin,
544
811
  collections: [formsCol, submissionsCol],
@@ -574,9 +841,78 @@ function collectAttachmentInputs(fields, submittedData) {
574
841
  }
575
842
  return attachments;
576
843
  }
844
+ function parseJsonColumn(value) {
845
+ if (typeof value === "string") {
846
+ try {
847
+ const parsed = JSON.parse(value);
848
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
849
+ } catch {
850
+ return {};
851
+ }
852
+ }
853
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
854
+ }
855
+ function normalizeAddressList(addresses) {
856
+ if (!Array.isArray(addresses)) return void 0;
857
+ const cleaned = addresses.map((address) => typeof address === "string" ? address.trim() : "").filter(Boolean);
858
+ return cleaned.length > 0 ? cleaned : void 0;
859
+ }
860
+ function buildNotificationEmails(input) {
861
+ const { notifications, submittedData, formName, submissionId, defaultFrom } = input;
862
+ const seen = /* @__PURE__ */ new Set();
863
+ const emails = [];
864
+ const skipped = [];
865
+ for (const notification of notifications) {
866
+ if (!notification.enabled) continue;
867
+ if (!notification.templateSlug) {
868
+ skipped.push({ notificationId: notification.id, reason: "no-template" });
869
+ continue;
870
+ }
871
+ const key = notification.id || JSON.stringify(notification);
872
+ if (seen.has(key)) continue;
873
+ seen.add(key);
874
+ if (notification.condition && !evaluateSingleCondition(notification.condition, submittedData)) {
875
+ skipped.push({
876
+ notificationId: notification.id,
877
+ reason: "condition-unmet"
878
+ });
879
+ continue;
880
+ }
881
+ const to = (notification.recipientType === "field" ? resolveFieldRef(notification.to, submittedData) : notification.to).trim();
882
+ if (!to) {
883
+ skipped.push({
884
+ notificationId: notification.id,
885
+ reason: "empty-recipient"
886
+ });
887
+ continue;
888
+ }
889
+ const cc = normalizeAddressList(notification.cc);
890
+ const bcc = normalizeAddressList(notification.bcc);
891
+ const from = notification.senderEmail?.trim() || defaultFrom?.trim() || void 0;
892
+ const replyTo = notification.replyTo ? resolveFieldRef(notification.replyTo, submittedData).trim() || void 0 : void 0;
893
+ emails.push({
894
+ to,
895
+ templateSlug: notification.templateSlug,
896
+ variables: {
897
+ ...submittedData,
898
+ formName,
899
+ submissionId
900
+ },
901
+ providerId: notification.providerId,
902
+ from,
903
+ replyTo,
904
+ cc,
905
+ bcc,
906
+ notificationId: notification.id
907
+ });
908
+ }
909
+ return { emails, skipped };
910
+ }
577
911
  async function handleSubmissionCreated(context, config, nextly) {
912
+ if (!config.notifications.enabled) return;
578
913
  const submission = context.data;
579
914
  if (!submission) return;
915
+ if (submission.status === "spam") return;
580
916
  const rawFormId = submission.form;
581
917
  let formId = null;
582
918
  if (typeof rawFormId === "string") {
@@ -592,46 +928,59 @@ async function handleSubmissionCreated(context, config, nextly) {
592
928
  if (notifications.length === 0) return;
593
929
  const emailService = nextly.services.email;
594
930
  if (!emailService) return;
595
- const submittedData = submission.data ?? {};
931
+ const submittedData = parseJsonColumn(submission.data);
596
932
  const formFields = Array.isArray(form.fields) ? form.fields : [];
597
933
  const fileAttachments = collectAttachmentInputs(formFields, submittedData);
598
- const seen = /* @__PURE__ */ new Set();
599
- for (const notification of notifications) {
600
- if (!notification.enabled || !notification.templateSlug) continue;
601
- const key = notification.id || `${notification.to}::${notification.templateSlug}`;
602
- if (seen.has(key)) continue;
603
- seen.add(key);
934
+ const { emails, skipped } = buildNotificationEmails({
935
+ notifications,
936
+ submittedData,
937
+ formName: form.name,
938
+ submissionId: submission.id,
939
+ defaultFrom: config.notifications.defaultFrom
940
+ });
941
+ for (const skip of skipped) {
942
+ if (skip.reason === "empty-recipient") {
943
+ nextly.logger.warn?.(
944
+ "Form Builder: empty recipient, skipping notification",
945
+ { notificationId: skip.notificationId, formSlug: form.slug }
946
+ );
947
+ } else {
948
+ nextly.logger.debug?.("Form Builder: notification skipped", {
949
+ notificationId: skip.notificationId,
950
+ formSlug: form.slug,
951
+ reason: skip.reason
952
+ });
953
+ }
954
+ }
955
+ if (emails.length === 0) return;
956
+ const finalEmails = await nextly.filters.apply("form-builder.beforeEmail", emails, { form, submission });
957
+ for (const email2 of finalEmails) {
604
958
  try {
605
- const to = notification.recipientType === "field" ? resolveFieldRef(notification.to, submittedData) : notification.to;
606
- if (!to) {
607
- nextly.infra.logger.warn?.(
608
- "Form Builder: empty recipient, skipping notification",
609
- { notificationId: notification.id, formSlug: form.slug }
610
- );
611
- continue;
612
- }
613
- const cc = Array.isArray(notification.cc) && notification.cc.length ? notification.cc : void 0;
614
- const bcc = Array.isArray(notification.bcc) && notification.bcc.length ? notification.bcc : void 0;
615
959
  await emailService.sendWithTemplate(
616
- notification.templateSlug,
617
- to,
618
- { ...submittedData, formName: form.name, submissionId: submission.id },
960
+ email2.templateSlug,
961
+ email2.to,
962
+ email2.variables,
619
963
  {
620
- providerId: notification.providerId,
621
- cc,
622
- bcc,
964
+ providerId: email2.providerId,
965
+ from: email2.from,
966
+ replyTo: email2.replyTo,
967
+ cc: email2.cc,
968
+ bcc: email2.bcc,
623
969
  attachments: fileAttachments.length > 0 ? fileAttachments : void 0
624
970
  }
625
971
  );
626
- nextly.infra.logger.info?.("Form Builder: notification sent", {
972
+ nextly.logger.info?.("Form Builder: notification sent", {
627
973
  formSlug: form.slug,
628
- to,
629
- templateSlug: notification.templateSlug,
974
+ to: email2.to,
975
+ templateSlug: email2.templateSlug,
976
+ notificationId: email2.notificationId,
630
977
  attachmentCount: fileAttachments.length
631
978
  });
632
979
  } catch (err) {
633
- nextly.infra.logger.error?.("Form Builder: notification failed", {
634
- notificationId: notification.id,
980
+ nextly.logger.error?.("Form Builder: notification failed", {
981
+ to: email2.to,
982
+ templateSlug: email2.templateSlug,
983
+ notificationId: email2.notificationId,
635
984
  error: err instanceof Error ? err.message : String(err)
636
985
  });
637
986
  }
@@ -639,27 +988,14 @@ async function handleSubmissionCreated(context, config, nextly) {
639
988
  }
640
989
  async function fetchParentForm(config, formId, nextly) {
641
990
  try {
642
- const handler = getCollectionsHandler();
643
- if (!handler) {
644
- nextly.infra.logger.warn?.(
645
- "Form Builder: CollectionsHandler unavailable, skipping notifications"
646
- );
647
- return null;
648
- }
649
- const result = await handler.getEntry({
650
- collectionName: config.formOverrides.slug,
651
- entryId: formId,
652
- overrideAccess: true
653
- });
654
- const fromData = result?.data;
655
- if (fromData) return fromData;
656
- const fromDoc = result?.doc;
657
- if (fromDoc && typeof fromDoc === "object") {
658
- return fromDoc;
659
- }
660
- return null;
991
+ const form = await nextly.services.collections.findEntryById(
992
+ config.formOverrides.slug,
993
+ formId,
994
+ { as: "system" }
995
+ );
996
+ return form;
661
997
  } catch (err) {
662
- nextly.infra.logger.error?.("Form Builder: failed to fetch form", {
998
+ nextly.logger.error?.("Form Builder: failed to fetch form", {
663
999
  formId,
664
1000
  error: err instanceof Error ? err.message : String(err)
665
1001
  });
@@ -667,30 +1003,8 @@ async function fetchParentForm(config, formId, nextly) {
667
1003
  }
668
1004
  }
669
1005
 
670
- // src/types.ts
671
- function isFormField(value) {
672
- return typeof value === "object" && value !== null && "type" in value && "name" in value && "label" in value;
673
- }
674
- function isFormFieldType(field, type) {
675
- return field.type === type;
676
- }
677
- function isTextFormField(field) {
678
- return field.type === "text";
679
- }
680
- function isEmailFormField(field) {
681
- return field.type === "email";
682
- }
683
- function isSelectFormField(field) {
684
- return field.type === "select";
685
- }
686
- function isCheckboxFormField(field) {
687
- return field.type === "checkbox";
688
- }
689
- function isFileFormField(field) {
690
- return field.type === "file";
691
- }
692
-
693
1006
  // src/config/validate-form.ts
1007
+ import { isPluginFieldTypeOnSurface } from "nextly";
694
1008
  var RESERVED_FORM_SLUGS = [
695
1009
  // API routes
696
1010
  "api",
@@ -707,21 +1021,7 @@ var RESERVED_FORM_SLUGS = [
707
1021
  var RESERVED_SLUGS_SET = new Set(RESERVED_FORM_SLUGS);
708
1022
  var SLUG_PATTERN = /^[a-z][a-z0-9_-]*$/;
709
1023
  var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
710
- var VALID_FIELD_TYPES = [
711
- "text",
712
- "email",
713
- "number",
714
- "phone",
715
- "url",
716
- "textarea",
717
- "select",
718
- "checkbox",
719
- "radio",
720
- "file",
721
- "date",
722
- "time",
723
- "hidden"
724
- ];
1024
+ var VALID_FIELD_TYPES = BUILT_IN_FORM_FIELD_TYPES;
725
1025
  var VALID_FIELD_TYPES_SET = new Set(VALID_FIELD_TYPES);
726
1026
  function isReservedSlug(slug) {
727
1027
  return RESERVED_SLUGS_SET.has(slug.toLowerCase());
@@ -937,7 +1237,8 @@ function validateField(field, path, errors, seenNames) {
937
1237
  });
938
1238
  return;
939
1239
  }
940
- if (typeof fieldType !== "string" || !VALID_FIELD_TYPES_SET.has(fieldType)) {
1240
+ const isValidType = typeof fieldType === "string" && (VALID_FIELD_TYPES_SET.has(fieldType) || isPluginFieldTypeOnSurface(fieldType, "forms"));
1241
+ if (!isValidType) {
941
1242
  let fieldTypeRepr;
942
1243
  if (typeof fieldType === "object" && fieldType !== null) {
943
1244
  fieldTypeRepr = JSON.stringify(fieldType);
@@ -1065,82 +1366,6 @@ ${errorMessages}`
1065
1366
  }
1066
1367
  }
1067
1368
 
1068
- // src/config/defaults.ts
1069
- var DEFAULT_FORM_SETTINGS = {
1070
- submitButtonText: "Submit",
1071
- confirmationType: "message",
1072
- successMessage: "Thank you for your submission!",
1073
- allowMultipleSubmissions: true
1074
- };
1075
- var DEFAULT_NOTIFICATION_SETTINGS = {
1076
- enabled: true,
1077
- replyTo: true
1078
- };
1079
- function toTitleCase(str) {
1080
- return str.replace(/[-_]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
1081
- }
1082
- function pluralize(singular) {
1083
- if (singular.endsWith("y") && !/[aeiou]y$/i.test(singular)) {
1084
- return singular.slice(0, -1) + "ies";
1085
- }
1086
- if (singular.endsWith("s") || singular.endsWith("x") || singular.endsWith("z") || singular.endsWith("ch") || singular.endsWith("sh")) {
1087
- return singular + "es";
1088
- }
1089
- return singular + "s";
1090
- }
1091
- function applyFormDefaults(config) {
1092
- const singularLabel = config.labels?.singular || toTitleCase(config.slug);
1093
- return {
1094
- ...config,
1095
- // Generate labels from slug if not provided
1096
- labels: {
1097
- singular: singularLabel,
1098
- plural: config.labels?.plural || pluralize(singularLabel)
1099
- },
1100
- // Apply settings defaults
1101
- settings: {
1102
- submitButtonText: config.settings?.submitButtonText || DEFAULT_FORM_SETTINGS.submitButtonText,
1103
- confirmationType: config.settings?.confirmationType || DEFAULT_FORM_SETTINGS.confirmationType,
1104
- successMessage: config.settings?.successMessage || DEFAULT_FORM_SETTINGS.successMessage,
1105
- allowMultipleSubmissions: config.settings?.allowMultipleSubmissions ?? DEFAULT_FORM_SETTINGS.allowMultipleSubmissions,
1106
- // Preserve other settings that don't have defaults
1107
- redirectUrl: config.settings?.redirectUrl,
1108
- redirectRelation: config.settings?.redirectRelation,
1109
- captcha: config.settings?.captcha
1110
- },
1111
- // Apply notification defaults if notifications are configured
1112
- notifications: config.notifications ? {
1113
- enabled: config.notifications.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.enabled,
1114
- recipients: config.notifications.recipients || [],
1115
- subject: config.notifications.subject || `New submission for ${singularLabel}`,
1116
- replyTo: config.notifications.replyTo ?? DEFAULT_NOTIFICATION_SETTINGS.replyTo,
1117
- template: config.notifications.template
1118
- } : void 0,
1119
- // Apply access defaults
1120
- access: {
1121
- // Default: anyone can submit the form
1122
- submit: config.access?.submit || (() => true),
1123
- // Default: only authenticated users can view submissions
1124
- read: config.access?.read || (({ req }) => !!req.user)
1125
- }
1126
- };
1127
- }
1128
- function applyFieldDefaults(field) {
1129
- const label = field.label || (field.name ? toTitleCase(field.name.replace(/([A-Z])/g, " $1").trim()) : "");
1130
- return {
1131
- ...field,
1132
- label,
1133
- required: field.required ?? false
1134
- };
1135
- }
1136
- function createFormConfig(slug, fields, options) {
1137
- return applyFormDefaults({
1138
- slug,
1139
- fields,
1140
- ...options
1141
- });
1142
- }
1143
-
1144
1369
  // src/config/field-helpers.ts
1145
1370
  var option = (label, value) => ({
1146
1371
  label,
@@ -1199,189 +1424,18 @@ var hidden = (config) => ({
1199
1424
  type: "hidden"
1200
1425
  });
1201
1426
 
1202
- // src/utils/evaluate-conditions.ts
1203
- function isEmptyValue(value) {
1204
- if (value === void 0 || value === null) {
1205
- return true;
1206
- }
1207
- if (typeof value === "string" && value.trim() === "") {
1208
- return true;
1209
- }
1210
- if (Array.isArray(value) && value.length === 0) {
1211
- return true;
1212
- }
1213
- return false;
1214
- }
1215
- function toNumber(value) {
1216
- if (typeof value === "number") {
1217
- return value;
1218
- }
1219
- if (typeof value === "string") {
1220
- const trimmed = value.trim();
1221
- if (trimmed === "") {
1222
- return NaN;
1223
- }
1224
- return Number(trimmed);
1225
- }
1226
- return NaN;
1227
- }
1228
- function toString(value) {
1229
- if (value === void 0 || value === null) {
1230
- return "";
1231
- }
1232
- if (typeof value === "string") {
1233
- return value;
1234
- }
1235
- if (Array.isArray(value)) {
1236
- return value.join(", ");
1237
- }
1238
- if (typeof value === "object") {
1239
- return JSON.stringify(value);
1240
- }
1241
- return String(value);
1242
- }
1243
- function compareValues(operator, fieldValue, conditionValue) {
1244
- switch (operator) {
1245
- case "equals": {
1246
- if (Array.isArray(fieldValue)) {
1247
- if (Array.isArray(conditionValue)) {
1248
- if (fieldValue.length !== conditionValue.length) {
1249
- return false;
1250
- }
1251
- return fieldValue.every((v, i) => v === conditionValue[i]);
1252
- }
1253
- return fieldValue.includes(conditionValue);
1254
- }
1255
- return toString(fieldValue) === toString(conditionValue);
1256
- }
1257
- case "notEquals": {
1258
- if (Array.isArray(fieldValue)) {
1259
- if (Array.isArray(conditionValue)) {
1260
- if (fieldValue.length !== conditionValue.length) {
1261
- return true;
1262
- }
1263
- return !fieldValue.every((v, i) => v === conditionValue[i]);
1264
- }
1265
- return !fieldValue.includes(conditionValue);
1266
- }
1267
- return toString(fieldValue) !== toString(conditionValue);
1268
- }
1269
- case "contains": {
1270
- const fieldStr = toString(fieldValue).toLowerCase();
1271
- const conditionStr = toString(conditionValue).toLowerCase();
1272
- if (Array.isArray(fieldValue)) {
1273
- return fieldValue.some(
1274
- (v) => toString(v).toLowerCase().includes(conditionStr)
1275
- );
1276
- }
1277
- return fieldStr.includes(conditionStr);
1278
- }
1279
- case "isEmpty": {
1280
- return isEmptyValue(fieldValue);
1281
- }
1282
- case "isNotEmpty": {
1283
- return !isEmptyValue(fieldValue);
1284
- }
1285
- case "greaterThan": {
1286
- const fieldNum = toNumber(fieldValue);
1287
- const conditionNum = toNumber(conditionValue);
1288
- if (!Number.isNaN(fieldNum) && !Number.isNaN(conditionNum)) {
1289
- return fieldNum > conditionNum;
1290
- }
1291
- return toString(fieldValue) > toString(conditionValue);
1292
- }
1293
- case "lessThan": {
1294
- const fieldNum = toNumber(fieldValue);
1295
- const conditionNum = toNumber(conditionValue);
1296
- if (!Number.isNaN(fieldNum) && !Number.isNaN(conditionNum)) {
1297
- return fieldNum < conditionNum;
1298
- }
1299
- return toString(fieldValue) < toString(conditionValue);
1300
- }
1301
- default: {
1302
- console.warn(
1303
- `[evaluateConditions] Unknown comparison operator: ${String(operator)}`
1304
- );
1305
- return false;
1306
- }
1307
- }
1308
- }
1309
- function evaluateSingleCondition(condition, formData) {
1310
- const { field, comparison, value: conditionValue } = condition;
1311
- const fieldValue = getNestedValue(formData, field);
1312
- return compareValues(comparison, fieldValue, conditionValue);
1313
- }
1314
- function getNestedValue(obj, path) {
1315
- if (!path) {
1316
- return void 0;
1317
- }
1318
- if (!path.includes(".")) {
1319
- return obj[path];
1320
- }
1321
- const parts = path.split(".");
1322
- let current = obj;
1323
- for (const part of parts) {
1324
- if (current === void 0 || current === null) {
1325
- return void 0;
1326
- }
1327
- if (typeof current !== "object") {
1328
- return void 0;
1329
- }
1330
- current = current[part];
1331
- }
1332
- return current;
1333
- }
1334
- function evaluateConditions(logic, formData) {
1335
- if (!logic || !logic.enabled) {
1336
- return true;
1337
- }
1338
- const { action, operator, conditions } = logic;
1339
- if (!conditions || conditions.length === 0) {
1340
- return true;
1341
- }
1342
- const results = conditions.map(
1343
- (condition) => evaluateSingleCondition(condition, formData)
1344
- );
1345
- let conditionsMet;
1346
- if (operator === "OR") {
1347
- conditionsMet = results.some((result) => result);
1348
- } else {
1349
- conditionsMet = results.every((result) => result);
1350
- }
1351
- if (action === "hide") {
1352
- return !conditionsMet;
1353
- }
1354
- return conditionsMet;
1355
- }
1356
- function isValidComparisonOperator(operator) {
1357
- const validOperators = [
1358
- "equals",
1359
- "notEquals",
1360
- "contains",
1361
- "isEmpty",
1362
- "isNotEmpty",
1363
- "greaterThan",
1364
- "lessThan"
1365
- ];
1366
- return validOperators.includes(operator);
1367
- }
1368
- function getSupportedComparisonOperators() {
1369
- return [
1370
- "equals",
1371
- "notEquals",
1372
- "contains",
1373
- "isEmpty",
1374
- "isNotEmpty",
1375
- "greaterThan",
1376
- "lessThan"
1377
- ];
1378
- }
1379
-
1380
1427
  // src/utils/generate-schema.ts
1381
1428
  import { z } from "zod";
1382
1429
  function generateZodSchema(fields) {
1383
1430
  const schemaShape = {};
1384
1431
  for (const field of fields) {
1432
+ if (!isKnownFormField(field)) {
1433
+ schemaShape[field.name] = field.required ? z.unknown().refine(
1434
+ (value) => value !== void 0 && value !== null && value !== "",
1435
+ { message: `${field.label || field.name} is required` }
1436
+ ) : z.unknown();
1437
+ continue;
1438
+ }
1385
1439
  if (field.type === "hidden" && !field.required) {
1386
1440
  schemaShape[field.name] = z.string().optional();
1387
1441
  continue;
@@ -1459,8 +1513,7 @@ function generateEmailSchema(field) {
1459
1513
  }
1460
1514
  function generateNumberSchema(field) {
1461
1515
  let schema = z.number({
1462
- required_error: field.validation?.errorMessage || "This field is required",
1463
- invalid_type_error: "Must be a number"
1516
+ error: (issue) => issue.input === void 0 ? field.validation?.errorMessage || "This field is required" : "Must be a number"
1464
1517
  });
1465
1518
  if (field.validation?.min !== void 0) {
1466
1519
  schema = schema.min(
@@ -1533,9 +1586,7 @@ function generateSelectSchema(field) {
1533
1586
  return schema2.optional();
1534
1587
  }
1535
1588
  const schema = z.enum(validValues, {
1536
- errorMap: () => ({
1537
- message: field.validation?.errorMessage || "Please select a valid option"
1538
- })
1589
+ error: () => field.validation?.errorMessage || "Please select a valid option"
1539
1590
  });
1540
1591
  if (field.required) {
1541
1592
  return schema;
@@ -1554,9 +1605,7 @@ function generateCheckboxSchema(field) {
1554
1605
  function generateRadioSchema(field) {
1555
1606
  const validValues = field.options.map((opt) => opt.value);
1556
1607
  const schema = z.enum(validValues, {
1557
- errorMap: () => ({
1558
- message: field.validation?.errorMessage || "Please select an option"
1559
- })
1608
+ error: () => field.validation?.errorMessage || "Please select an option"
1560
1609
  });
1561
1610
  if (field.required) {
1562
1611
  return schema;
@@ -1633,7 +1682,7 @@ function transformFormData(data, fields) {
1633
1682
  if (value === void 0) {
1634
1683
  continue;
1635
1684
  }
1636
- transformed[field.name] = transformFieldValue(value, field);
1685
+ transformed[field.name] = isKnownFormField(field) ? transformFieldValue(value, field) : value;
1637
1686
  }
1638
1687
  return transformed;
1639
1688
  }
@@ -1684,7 +1733,7 @@ function getValidationErrors(result) {
1684
1733
  return {};
1685
1734
  }
1686
1735
  const errors = {};
1687
- for (const error of result.error.errors) {
1736
+ for (const error of result.error.issues) {
1688
1737
  const path = error.path.join(".");
1689
1738
  if (!errors[path]) {
1690
1739
  errors[path] = error.message;
@@ -1693,203 +1742,6 @@ function getValidationErrors(result) {
1693
1742
  return errors;
1694
1743
  }
1695
1744
 
1696
- // src/utils/export-formats.ts
1697
- var UTF8_BOM = "\uFEFF";
1698
- function safeString(value) {
1699
- if (typeof value === "object" && value !== null) {
1700
- return JSON.stringify(value);
1701
- }
1702
- return String(value);
1703
- }
1704
- function formatExportValue(value, field) {
1705
- if (value === null || value === void 0) {
1706
- return "";
1707
- }
1708
- if (field) {
1709
- switch (field.type) {
1710
- case "checkbox":
1711
- return value ? "Yes" : "No";
1712
- case "select":
1713
- if (Array.isArray(value)) {
1714
- return value.join(", ");
1715
- }
1716
- return safeString(value);
1717
- case "file":
1718
- if (Array.isArray(value)) {
1719
- return value.map((v) => safeString(v)).join(", ");
1720
- }
1721
- return safeString(value);
1722
- case "date":
1723
- if (value instanceof Date) {
1724
- return value.toISOString().split("T")[0];
1725
- }
1726
- if (typeof value === "string") {
1727
- const parsed = new Date(value);
1728
- if (!isNaN(parsed.getTime())) {
1729
- return parsed.toISOString().split("T")[0];
1730
- }
1731
- }
1732
- return safeString(value);
1733
- case "time":
1734
- return safeString(value);
1735
- case "hidden":
1736
- return safeString(value);
1737
- default:
1738
- break;
1739
- }
1740
- }
1741
- if (Array.isArray(value)) {
1742
- return value.join(", ");
1743
- }
1744
- if (typeof value === "boolean") {
1745
- return value ? "Yes" : "No";
1746
- }
1747
- if (value instanceof Date) {
1748
- return value.toISOString();
1749
- }
1750
- return safeString(value);
1751
- }
1752
- function formatDate(date3, format = "iso") {
1753
- if (!date3) return "";
1754
- const d = typeof date3 === "string" ? new Date(date3) : date3;
1755
- if (isNaN(d.getTime())) {
1756
- return "";
1757
- }
1758
- return format === "iso" ? d.toISOString() : d.toLocaleString();
1759
- }
1760
- function escapeCSVValue(value, delimiter = ",") {
1761
- const needsQuoting = value.includes(delimiter) || value.includes('"') || value.includes("\n") || value.includes("\r");
1762
- if (!needsQuoting) {
1763
- return value;
1764
- }
1765
- const escaped = value.replace(/"/g, '""');
1766
- return `"${escaped}"`;
1767
- }
1768
- function exportToCSV(submissions, form, options = {}) {
1769
- const {
1770
- includeMetadata = true,
1771
- delimiter = ",",
1772
- includeBOM = true,
1773
- dateFormat = "iso"
1774
- } = options;
1775
- const exportableFields = form.fields;
1776
- const headers = [];
1777
- for (const field of exportableFields) {
1778
- headers.push(field.label);
1779
- }
1780
- if (includeMetadata) {
1781
- headers.push("ID", "Status", "Submitted At", "IP Address", "User Agent");
1782
- }
1783
- const rows = [];
1784
- for (const submission of submissions) {
1785
- const row = [];
1786
- const data = submission.data;
1787
- for (const field of exportableFields) {
1788
- const value = data[field.name];
1789
- const formatted = formatExportValue(value, field);
1790
- row.push(escapeCSVValue(formatted, delimiter));
1791
- }
1792
- if (includeMetadata) {
1793
- row.push(escapeCSVValue(submission.id, delimiter));
1794
- row.push(escapeCSVValue(submission.status, delimiter));
1795
- row.push(
1796
- escapeCSVValue(
1797
- formatDate(submission.submittedAt, dateFormat),
1798
- delimiter
1799
- )
1800
- );
1801
- row.push(escapeCSVValue(submission.ipAddress || "", delimiter));
1802
- row.push(escapeCSVValue(submission.userAgent || "", delimiter));
1803
- }
1804
- rows.push(row);
1805
- }
1806
- const escapedHeaders = headers.map((h) => escapeCSVValue(h, delimiter));
1807
- const lines = [
1808
- escapedHeaders.join(delimiter),
1809
- ...rows.map((row) => row.join(delimiter))
1810
- ];
1811
- const csvContent = lines.join("\r\n");
1812
- return includeBOM ? UTF8_BOM + csvContent : csvContent;
1813
- }
1814
- function exportToJSON(submissions, form, options = {}) {
1815
- const {
1816
- includeMetadata = true,
1817
- includeFormDefinition = true,
1818
- indent = 2
1819
- } = options;
1820
- const exportableFields = form.fields;
1821
- const formDefinition = includeFormDefinition ? {
1822
- id: form.id,
1823
- name: form.name,
1824
- slug: form.slug,
1825
- fields: exportableFields.map((f) => ({
1826
- name: f.name,
1827
- label: f.label,
1828
- type: f.type
1829
- }))
1830
- } : void 0;
1831
- const exportedSubmissions = submissions.map((submission) => {
1832
- const data = submission.data;
1833
- const fieldData = {};
1834
- for (const field of exportableFields) {
1835
- const value = data[field.name];
1836
- fieldData[field.name] = value;
1837
- }
1838
- if (includeMetadata) {
1839
- return {
1840
- ...fieldData,
1841
- _metadata: {
1842
- id: submission.id,
1843
- status: submission.status,
1844
- submittedAt: submission.submittedAt,
1845
- ipAddress: submission.ipAddress || null,
1846
- userAgent: submission.userAgent || null,
1847
- createdAt: submission.createdAt,
1848
- updatedAt: submission.updatedAt
1849
- }
1850
- };
1851
- }
1852
- return fieldData;
1853
- });
1854
- const exportData = {
1855
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1856
- totalSubmissions: submissions.length,
1857
- submissions: exportedSubmissions
1858
- };
1859
- if (formDefinition) {
1860
- exportData.form = formDefinition;
1861
- }
1862
- return JSON.stringify(exportData, null, indent);
1863
- }
1864
- function downloadFile(content, filename, mimeType) {
1865
- if (typeof window === "undefined" || typeof document === "undefined") {
1866
- throw new Error("downloadFile is only available in browser environments");
1867
- }
1868
- const blob = new Blob([content], { type: mimeType });
1869
- const url2 = URL.createObjectURL(blob);
1870
- const link = document.createElement("a");
1871
- link.href = url2;
1872
- link.download = filename;
1873
- document.body.appendChild(link);
1874
- link.click();
1875
- document.body.removeChild(link);
1876
- URL.revokeObjectURL(url2);
1877
- }
1878
- function generateExportFilename(formSlug, format) {
1879
- const date3 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1880
- return `${formSlug}-submissions-${date3}.${format}`;
1881
- }
1882
- function exportAndDownload(submissions, form, format, options) {
1883
- const filename = generateExportFilename(form.slug, format);
1884
- if (format === "csv") {
1885
- const content = exportToCSV(submissions, form, options);
1886
- downloadFile(content, filename, "text/csv;charset=utf-8");
1887
- } else {
1888
- const content = exportToJSON(submissions, form, options);
1889
- downloadFile(content, filename, "application/json");
1890
- }
1891
- }
1892
-
1893
1745
  // src/handlers/spam-detection.ts
1894
1746
  var rateLimitStore = /* @__PURE__ */ new Map();
1895
1747
  async function checkSpam(options) {
@@ -2007,7 +1859,7 @@ async function submitForm(options, context) {
2007
1859
  const { formSlug, data, metadata } = options;
2008
1860
  const { pluginContext, pluginConfig } = context;
2009
1861
  const { collections } = pluginContext.services;
2010
- const { logger } = pluginContext.infra;
1862
+ const { logger } = pluginContext;
2011
1863
  try {
2012
1864
  const form = await fetchFormBySlug(formSlug, pluginConfig, pluginContext);
2013
1865
  if (!form) {
@@ -2029,46 +1881,95 @@ async function submitForm(options, context) {
2029
1881
  error: "This form is not currently accepting submissions"
2030
1882
  };
2031
1883
  }
2032
- const transformedData = transformFormData(data, form.fields);
2033
- const schema = generateZodSchema(form.fields);
2034
- const validationResult = schema.safeParse(transformedData);
2035
- if (!validationResult.success) {
2036
- const validationErrors = getValidationErrors(validationResult);
2037
- logger.debug?.("Form validation failed", {
2038
- formSlug,
2039
- errors: validationErrors
2040
- });
2041
- return {
2042
- success: false,
2043
- error: "Validation failed",
2044
- validationErrors
2045
- };
1884
+ const settings = normalizeFormSettings(form.settings);
1885
+ if (settings.allowMultipleSubmissions === false && !metadata?.ipAddress) {
1886
+ logger.warn?.(
1887
+ "Single-submission form received a submission without an IP \u2014 the restriction cannot apply",
1888
+ { formSlug }
1889
+ );
1890
+ }
1891
+ if (settings.allowMultipleSubmissions === false && metadata?.ipAddress) {
1892
+ const existing = await collections.count(
1893
+ pluginConfig.formSubmissionOverrides.slug,
1894
+ {
1895
+ where: {
1896
+ form: { equals: form.id },
1897
+ ipAddress: { equals: metadata.ipAddress },
1898
+ status: { not_equals: "spam" }
1899
+ }
1900
+ },
1901
+ { as: "system" }
1902
+ );
1903
+ if (existing > 0) {
1904
+ logger.info?.("Repeat submission rejected (single-submission form)", {
1905
+ formSlug,
1906
+ ipAddress: metadata.ipAddress
1907
+ });
1908
+ return {
1909
+ success: false,
1910
+ error: "You have already submitted this form."
1911
+ };
1912
+ }
2046
1913
  }
2047
- sanitizeSubmissionData(validationResult.data, form.fields);
1914
+ const declaredFieldNames = new Set(form.fields.map((field) => field.name));
1915
+ const undeclaredData = Object.fromEntries(
1916
+ Object.entries(data).filter(([key]) => !declaredFieldNames.has(key))
1917
+ );
2048
1918
  const spamResult = await checkSpam({
2049
- data: transformedData,
1919
+ data: undeclaredData,
2050
1920
  ipAddress: metadata?.ipAddress,
2051
1921
  formSlug,
2052
1922
  config: {
2053
- honeypot: pluginConfig.spamProtection.honeypot,
1923
+ // Per-form overrides win where set; blank inherits the plugin config.
1924
+ honeypot: settings.honeypotEnabled ?? pluginConfig.spamProtection.honeypot,
2054
1925
  rateLimit: pluginConfig.spamProtection.rateLimit,
2055
- recaptcha: pluginConfig.spamProtection.recaptcha
1926
+ recaptcha: {
1927
+ ...pluginConfig.spamProtection.recaptcha,
1928
+ enabled: settings.captchaEnabled ?? pluginConfig.spamProtection.recaptcha?.enabled ?? false
1929
+ }
2056
1930
  }
2057
1931
  });
2058
- if (spamResult.isSpam) {
2059
- logger.info?.("Spam submission detected and rejected", {
1932
+ if (spamResult.isSpam && spamResult.reason === "rate_limit") {
1933
+ logger.info?.("Spam submission rejected (rate limit)", {
1934
+ formSlug,
1935
+ ipAddress: metadata?.ipAddress
1936
+ });
1937
+ return { success: true };
1938
+ }
1939
+ const isContentSpam = spamResult.isSpam;
1940
+ const transformedData = transformFormData(data, form.fields);
1941
+ let storedData;
1942
+ if (isContentSpam) {
1943
+ logger.info?.("Spam submission detected \u2014 storing flagged", {
2060
1944
  formSlug,
2061
1945
  reason: spamResult.reason,
2062
1946
  ipAddress: metadata?.ipAddress
2063
1947
  });
2064
- return {
2065
- success: true
2066
- };
1948
+ sanitizeSubmissionData(transformedData, form.fields);
1949
+ storedData = transformedData;
1950
+ } else {
1951
+ const schema = generateZodSchema(form.fields);
1952
+ const validationResult = schema.safeParse(transformedData);
1953
+ if (!validationResult.success) {
1954
+ const validationErrors = getValidationErrors(validationResult);
1955
+ logger.debug?.("Form validation failed", {
1956
+ formSlug,
1957
+ errors: validationErrors
1958
+ });
1959
+ return {
1960
+ success: false,
1961
+ error: "Validation failed",
1962
+ validationErrors
1963
+ };
1964
+ }
1965
+ sanitizeSubmissionData(validationResult.data, form.fields);
1966
+ storedData = validationResult.data;
2067
1967
  }
2068
1968
  const submissionData = {
2069
1969
  form: form.id,
2070
- data: validationResult.data,
2071
- status: "new",
1970
+ data: storedData,
1971
+ status: isContentSpam ? "spam" : "new",
1972
+ spamReason: isContentSpam ? spamResult.reason ?? null : null,
2072
1973
  ipAddress: metadata?.ipAddress || null,
2073
1974
  userAgent: metadata?.userAgent || null,
2074
1975
  submittedAt: /* @__PURE__ */ new Date()
@@ -2076,14 +1977,19 @@ async function submitForm(options, context) {
2076
1977
  const submission = await collections.createEntry(
2077
1978
  pluginConfig.formSubmissionOverrides.slug,
2078
1979
  submissionData,
2079
- {}
2080
- // Empty context - submission creation is public
1980
+ // Public form submission — create as system. No ambient user; an
1981
+ // empty context already resolves to system, but be explicit.
1982
+ { as: "system" }
2081
1983
  );
2082
1984
  logger.info?.("Form submission created successfully", {
2083
1985
  formSlug,
2084
- submissionId: submission.id
1986
+ submissionId: submission.id,
1987
+ flaggedAsSpam: isContentSpam
2085
1988
  });
2086
1989
  const redirect = determineRedirectUrl(form);
1990
+ if (isContentSpam) {
1991
+ return { success: true, redirect };
1992
+ }
2087
1993
  return {
2088
1994
  success: true,
2089
1995
  submission,
@@ -2105,19 +2011,10 @@ async function fetchFormBySlug(slug, pluginConfig, pluginContext) {
2105
2011
  const { collections } = pluginContext.services;
2106
2012
  const result = await collections.listEntries(
2107
2013
  pluginConfig.formOverrides.slug,
2108
- {
2109
- pagination: { limit: 100 }
2110
- // Fetch enough to find the form
2111
- },
2112
- {}
2113
- // Empty context for public access
2114
- );
2115
- if (!result.data || result.data.length === 0) {
2116
- return null;
2117
- }
2118
- const form = result.data.find(
2119
- (entry) => entry.slug === slug
2014
+ { where: { slug: { equals: slug } }, pagination: { limit: 1 } },
2015
+ { as: "system" }
2120
2016
  );
2017
+ const form = result.data?.[0];
2121
2018
  return form ? form : null;
2122
2019
  } catch {
2123
2020
  return null;
@@ -2191,33 +2088,28 @@ async function getFormSubmissionStats(formSlug, context) {
2191
2088
  return null;
2192
2089
  }
2193
2090
  try {
2194
- const result = await collections.listEntries(
2195
- pluginConfig.formSubmissionOverrides.slug,
2196
- {
2197
- pagination: { limit: 1e3 }
2198
- // Reasonable limit for stats
2199
- },
2200
- {}
2201
- );
2202
- if (!result.data) {
2203
- return { total: 0, new: 0, read: 0, archived: 0 };
2204
- }
2205
- const submissions = result.data.filter(
2206
- (entry) => entry.form === form.id
2207
- );
2208
- const stats = {
2209
- total: submissions.length,
2210
- new: 0,
2211
- read: 0,
2212
- archived: 0
2213
- };
2214
- for (const sub of submissions) {
2215
- const status = sub.status;
2216
- if (status === "new") stats.new++;
2217
- else if (status === "read") stats.read++;
2218
- else if (status === "archived") stats.archived++;
2219
- }
2220
- return stats;
2091
+ const submissionsSlug = pluginConfig.formSubmissionOverrides.slug;
2092
+ const sys = { as: "system" };
2093
+ const base = { form: { equals: form.id } };
2094
+ const [total, newCount, read, archived] = await Promise.all([
2095
+ collections.count(submissionsSlug, { where: base }, sys),
2096
+ collections.count(
2097
+ submissionsSlug,
2098
+ { where: { ...base, status: { equals: "new" } } },
2099
+ sys
2100
+ ),
2101
+ collections.count(
2102
+ submissionsSlug,
2103
+ { where: { ...base, status: { equals: "read" } } },
2104
+ sys
2105
+ ),
2106
+ collections.count(
2107
+ submissionsSlug,
2108
+ { where: { ...base, status: { equals: "archived" } } },
2109
+ sys
2110
+ )
2111
+ ]);
2112
+ return { total, new: newCount, read, archived };
2221
2113
  } catch {
2222
2114
  return null;
2223
2115
  }
@@ -2404,6 +2296,7 @@ function getSupportedWebhookEvents() {
2404
2296
  // src/index.ts
2405
2297
  var formBuilderPlugin = formBuilder().plugin;
2406
2298
  export {
2299
+ BUILT_IN_FORM_FIELD_TYPES,
2407
2300
  DEFAULT_FORM_SETTINGS,
2408
2301
  DEFAULT_NOTIFICATION_SETTINGS,
2409
2302
  RESERVED_FORM_SLUGS,
@@ -2443,6 +2336,7 @@ export {
2443
2336
  isFormAcceptingSubmissions,
2444
2337
  isFormField,
2445
2338
  isFormFieldType,
2339
+ isKnownFormField,
2446
2340
  isRateLimited,
2447
2341
  isSelectFormField,
2448
2342
  isTextFormField,