@10x-media/form-builder 0.1.0-beta.25 → 0.1.0-beta.26

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 (63) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/actions/body/serializeBody.d.ts +10 -14
  3. package/dist/actions/body/serializeBody.js +5 -10
  4. package/dist/actions/body/serializeBody.js.map +1 -1
  5. package/dist/actions/builtin/emailAction.d.ts +7 -0
  6. package/dist/actions/builtin/emailAction.js +14 -7
  7. package/dist/actions/builtin/emailAction.js.map +1 -1
  8. package/dist/actions/defineAction.d.ts +2 -4
  9. package/dist/actions/defineAction.js.map +1 -1
  10. package/dist/actions/emailRender.d.ts +5 -5
  11. package/dist/actions/fromAddresses.d.ts +3 -1
  12. package/dist/actions/fromAddresses.js.map +1 -1
  13. package/dist/actions/recipientSources.d.ts +6 -17
  14. package/dist/actions/recipientSources.js.map +1 -1
  15. package/dist/actions/submissionContext.d.ts +34 -0
  16. package/dist/actions/task.js +10 -13
  17. package/dist/actions/task.js.map +1 -1
  18. package/dist/aggregation/aggregateResponses.js +1 -1
  19. package/dist/aggregation/resolveResultsRequest.js +38 -24
  20. package/dist/aggregation/resolveResultsRequest.js.map +1 -1
  21. package/dist/client/EndpointOptionsSelect.d.ts +1 -0
  22. package/dist/client/EndpointOptionsSelect.js +1 -0
  23. package/dist/client/EndpointOptionsSelect.js.map +1 -1
  24. package/dist/client/FieldNameSelect.d.ts +1 -0
  25. package/dist/client/FieldNameSelect.js +1 -0
  26. package/dist/client/FieldNameSelect.js.map +1 -1
  27. package/dist/client/RecipientsSelect.d.ts +1 -0
  28. package/dist/client/RecipientsSelect.js +1 -0
  29. package/dist/client/RecipientsSelect.js.map +1 -1
  30. package/dist/collections/formSubmissions.js +3 -3
  31. package/dist/collections/forms.js +2 -2
  32. package/dist/exports/rsc.d.ts +1 -1
  33. package/dist/exports/rsc.js +3 -3
  34. package/dist/form/findFormAtLocale.d.ts +30 -0
  35. package/dist/form/findFormAtLocale.js +88 -0
  36. package/dist/form/findFormAtLocale.js.map +1 -0
  37. package/dist/index.d.ts +4 -2
  38. package/dist/index.js +15 -12
  39. package/dist/index.js.map +1 -1
  40. package/dist/options.d.ts +24 -1
  41. package/dist/plugin/registerCollections.js +2 -2
  42. package/dist/poll/resolvePollOutcome.js +1 -1
  43. package/dist/poll/votes/recountPollVotes.js +2 -2
  44. package/dist/poll/votes/voteTallyHook.js +2 -2
  45. package/dist/react/Form.d.ts +9 -5
  46. package/dist/react/Form.js +8 -9
  47. package/dist/react/Form.js.map +1 -1
  48. package/dist/react/Poll.js +4 -2
  49. package/dist/react/Poll.js.map +1 -1
  50. package/dist/react/fetchResults.d.ts +2 -1
  51. package/dist/react/fetchResults.js +5 -2
  52. package/dist/react/fetchResults.js.map +1 -1
  53. package/dist/react/submitForm.d.ts +4 -4
  54. package/dist/react/submitForm.js.map +1 -1
  55. package/dist/submissions/createSubmission.d.ts +6 -0
  56. package/dist/submissions/createSubmission.js +7 -2
  57. package/dist/submissions/createSubmission.js.map +1 -1
  58. package/dist/submissions/submissionLocale.js +27 -6
  59. package/dist/submissions/submissionLocale.js.map +1 -1
  60. package/dist/submissions/validateSubmission.js +108 -101
  61. package/dist/submissions/validateSubmission.js.map +1 -1
  62. package/dist/submissions/voteChangeEndpoint.js +1 -1
  63. package/package.json +3 -3
@@ -1,10 +1,11 @@
1
1
  import { isPollClosed, pollConfigOf } from "../form/pollState.js";
2
- import { aggregateFormResponses, fieldHasOptions } from "./aggregateResponses.js";
2
+ import { resolveSubmissionLocale } from "../submissions/submissionLocale.js";
3
3
  import { resolveEffectivePollOptions } from "../poll/effectivePollOptions.js";
4
+ import { aggregateFormResponses, fieldHasOptions } from "./aggregateResponses.js";
4
5
  import { aggregateFromVotes } from "../poll/votes/aggregateFromVotes.js";
5
6
  import { resolvePollOutcome } from "../poll/resolvePollOutcome.js";
6
7
  import { shouldAutoResolvePoll } from "../poll/closeJob.js";
7
- import { FORMS_SLUG } from "../collections/forms.js";
8
+ import { findFormAtLocale, missingFormOnReadError } from "../form/findFormAtLocale.js";
8
9
  //#region src/aggregation/resolveResultsRequest.ts
9
10
  const forbidden = {
10
11
  status: 403,
@@ -19,34 +20,19 @@ const tallyMetaOf = (instance, field) => ({
19
20
  label: typeof instance?.label === "string" && instance.label.length > 0 ? instance.label : field,
20
21
  fieldType: instance?.blockType
21
22
  });
22
- /**
23
- * Authorize and resolve a poll/survey results request. Authed callers may aggregate any field (or all
24
- * enumerable fields) and bypass the `access` seam; for a poll-enabled form they also get the results
25
- * field's effective options injected so sourced/resolver-backed polls render labels (best-effort, a
26
- * resolve failure degrades to raw values rather than blocking the trusted read). Anonymous callers are
27
- * allowed only when the form's poll is enabled, the poll's `resultsVisibility` permits it (`afterVote`:
28
- * any time; `afterClose`: only once `closesAt` has passed), and the optional host `access` seam
29
- * approves; and then only for the configured `poll.resultsField`, and only if that field is enumerable
30
- * so a misconfigured `resultsField` pointing at a free-text or PII field can never be dumped publicly. A
31
- * static poll is enumerable through its authored options; a poll whose options come from an
32
- * `optionSource` or the field type's own `resolveOptions` resolves them here (registry via
33
- * `config.custom`, per-request cache), gated by `eligibleTypes` and enumerable only when resolution
34
- * yields any, with the resolved options driving bucket order and labels. Resolution failure fails
35
- * closed (503) on the anonymous path. Returns only aggregate counts, never raw submissions.
36
- */
37
- const resolveFormResultsRequest = async (args) => {
23
+ const resolveAtLocale = async (args, locale) => {
38
24
  const { payload, formId, field, isAuthed, req, access, eligibleTypes, pollVotesEnabled } = args;
39
25
  if (formId == null) return {
40
26
  status: 400,
41
27
  body: { errors: [{ message: "Missing form id" }] }
42
28
  };
43
- const form = await payload.findByID({
44
- collection: FORMS_SLUG,
29
+ const form = await findFormAtLocale({
30
+ payload,
45
31
  id: formId,
46
- depth: 0,
47
- overrideAccess: true,
48
- req
49
- }).catch(() => null);
32
+ locale,
33
+ req,
34
+ overrideAccess: true
35
+ }).catch(missingFormOnReadError);
50
36
  if (!form) return {
51
37
  status: 404,
52
38
  body: { errors: [{ message: "Not found" }] }
@@ -136,6 +122,34 @@ const resolveFormResultsRequest = async (args) => {
136
122
  }) }
137
123
  };
138
124
  };
125
+ /**
126
+ * Authorize and resolve a poll/survey results request. Authed callers may aggregate any field (or all
127
+ * enumerable fields) and bypass the `access` seam; for a poll-enabled form they also get the results
128
+ * field's effective options injected so sourced/resolver-backed polls render labels (best-effort, a
129
+ * resolve failure degrades to raw values rather than blocking the trusted read). Anonymous callers are
130
+ * allowed only when the form's poll is enabled, the poll's `resultsVisibility` permits it (`afterVote`:
131
+ * any time; `afterClose`: only once `closesAt` has passed), and the optional host `access` seam
132
+ * approves; and then only for the configured `poll.resultsField`, and only if that field is enumerable
133
+ * so a misconfigured `resultsField` pointing at a free-text or PII field can never be dumped publicly. A
134
+ * static poll is enumerable through its authored options; a poll whose options come from an
135
+ * `optionSource` or the field type's own `resolveOptions` resolves them here (registry via
136
+ * `config.custom`, per-request cache), gated by `eligibleTypes` and enumerable only when resolution
137
+ * yields any, with the resolved options driving bucket order and labels. Resolution failure fails
138
+ * closed (503) on the anonymous path. Returns only aggregate counts, never raw submissions.
139
+ */
140
+ const resolveFormResultsRequest = async (args) => {
141
+ const { payload, req } = args;
142
+ const { localization } = payload.config;
143
+ const locale = resolveSubmissionLocale(req?.locale, localization);
144
+ if (!req || !localization) return resolveAtLocale(args, locale);
145
+ const previousLocale = req.locale;
146
+ req.locale = locale;
147
+ try {
148
+ return await resolveAtLocale(args, locale);
149
+ } finally {
150
+ req.locale = previousLocale;
151
+ }
152
+ };
139
153
  //#endregion
140
154
  export { resolveFormResultsRequest };
141
155
 
@@ -1 +1 @@
1
- {"version":3,"file":"resolveResultsRequest.js","names":[],"sources":["../../src/aggregation/resolveResultsRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { type PollFormLike, shouldAutoResolvePoll } from '../poll/closeJob'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport { resolveEffectivePollOptions } from '../poll/effectivePollOptions'\nimport { resolvePollOutcome } from '../poll/resolvePollOutcome'\nimport { aggregateFromVotes } from '../poll/votes/aggregateFromVotes'\nimport type { FormFieldInstance } from '../submissions/types'\nimport { aggregateFormResponses, fieldHasOptions } from './aggregateResponses'\nimport type { FieldAggregation } from './types'\n\nexport type FormResultsAccessArgs = {\n\treq: PayloadRequest\n\t/** The loaded forms document (depth 0). Untyped beyond `id`: hosts read their own fields (e.g. `form.tenant`). */\n\tform: { id: number | string } & Record<string, unknown>\n}\n\n/**\n * Host seam gating anonymous results reads, evaluated after the form is loaded and before anything\n * is aggregated. Multi-tenant recipe: compare `form.tenant` against the tenant derived from `req`\n * (host header, cookie, or auth context) and return `false` for a cross-tenant read. Authenticated\n * callers bypass this seam (they are admin-trusted, like the rest of the results endpoint).\n */\nexport type FormResultsAccess = (args: FormResultsAccessArgs) => boolean | Promise<boolean>\n\nexport type ResolveResultsRequestArgs = {\n\tpayload: Payload\n\tformId: number | string | undefined\n\t/** The requested field (query param). */\n\tfield?: string\n\t/** Whether the caller is authenticated (an admin/user). */\n\tisAuthed: boolean\n\treq?: PayloadRequest\n\t/** Optional host seam for anonymous reads; absent means plugin-default gating only. */\n\taccess?: FormResultsAccess\n\t/**\n\t * Poll-eligible field types (registry-derived). When set, an anonymous read of an\n\t * option-source poll also requires the results field's instance to be one of these types,\n\t * so legacy or db-written docs pointing at a free-text field can never expose stored\n\t * answers as leftover result buckets.\n\t */\n\teligibleTypes?: readonly string[]\n\t/**\n\t * Whether the hidden tally store backs poll reads. When true, the poll results field is served\n\t * from `aggregateFromVotes` (anonymous reads, and an authed read naming exactly that field)\n\t * instead of the submission scan; every authorization gate stays identical either way.\n\t */\n\tpollVotesEnabled?: boolean\n}\n\nexport type ResolveResultsRequestResult = {\n\tstatus: number\n\tbody: { results: FieldAggregation[] } | { errors: { message: string }[] }\n}\n\nconst forbidden: ResolveResultsRequestResult = {\n\tstatus: 403,\n\tbody: { errors: [{ message: 'Forbidden' }] },\n}\n\n// 503 over 403 for a failed option-source resolve: the form and its poll config are already\n// publicly readable, so \"temporarily unavailable\" leaks nothing new, matches the submission\n// path's precedent, and does not mislabel a transient server fault as an authorization denial.\nconst unavailable: ResolveResultsRequestResult = {\n\tstatus: 503,\n\tbody: { errors: [{ message: 'Poll options unavailable' }] },\n}\n\n/** Scan-shape parity for a tally-served field: label from the live instance, else the field name. */\nconst tallyMetaOf = (\n\tinstance: FormFieldInstance | undefined,\n\tfield: string\n): { label: string; fieldType?: string } => ({\n\tlabel: typeof instance?.label === 'string' && instance.label.length > 0 ? instance.label : field,\n\tfieldType: instance?.blockType,\n})\n\n/**\n * Authorize and resolve a poll/survey results request. Authed callers may aggregate any field (or all\n * enumerable fields) and bypass the `access` seam; for a poll-enabled form they also get the results\n * field's effective options injected so sourced/resolver-backed polls render labels (best-effort, a\n * resolve failure degrades to raw values rather than blocking the trusted read). Anonymous callers are\n * allowed only when the form's poll is enabled, the poll's `resultsVisibility` permits it (`afterVote`:\n * any time; `afterClose`: only once `closesAt` has passed), and the optional host `access` seam\n * approves; and then only for the configured `poll.resultsField`, and only if that field is enumerable\n * so a misconfigured `resultsField` pointing at a free-text or PII field can never be dumped publicly. A\n * static poll is enumerable through its authored options; a poll whose options come from an\n * `optionSource` or the field type's own `resolveOptions` resolves them here (registry via\n * `config.custom`, per-request cache), gated by `eligibleTypes` and enumerable only when resolution\n * yields any, with the resolved options driving bucket order and labels. Resolution failure fails\n * closed (503) on the anonymous path. Returns only aggregate counts, never raw submissions.\n */\nexport const resolveFormResultsRequest = async (\n\targs: ResolveResultsRequestArgs\n): Promise<ResolveResultsRequestResult> => {\n\tconst { payload, formId, field, isAuthed, req, access, eligibleTypes, pollVotesEnabled } = args\n\tif (formId == null) {\n\t\treturn { status: 400, body: { errors: [{ message: 'Missing form id' }] } }\n\t}\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\n\t// No-runner safety net: when a closed poll's `mostVoted`/`source` outcome was never auto-resolved\n\t// (no wired job runner fired the close task), a results read heals it. Idempotent and gate-neutral,\n\t// it runs on the already-loaded form via overrideAccess and writes only through the outcome hook, so\n\t// it cannot relax the anonymous authorization below. A failure degrades silently to the normal path.\n\tif (shouldAutoResolvePoll(form as PollFormLike)) {\n\t\tawait resolvePollOutcome({ payload, formId, req, pollVotesEnabled }).catch(() => undefined)\n\t}\n\n\tlet fields: string[] | undefined\n\tlet resolvedOptions: Record<string, { value: string; label: string }[]> | undefined\n\tif (isAuthed) {\n\t\tfields = field ? [field] : undefined\n\t\t// Label a poll's results field for admins: resolve its effective options (a source, the\n\t\t// field type's own resolver, or authored options) and inject them so a sourced/resolved poll\n\t\t// shows labels instead of raw stored values, and so an all-fields read still surfaces a\n\t\t// resolver-backed field that carries no authored options. Best-effort: a resolver/source\n\t\t// failure degrades to raw values rather than blocking the trusted read (the anonymous path\n\t\t// below fails closed instead). Only run when the read would actually surface the results field.\n\t\tconst poll = pollConfigOf(form.poll)\n\t\tconst resultsField =\n\t\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (form.pollEnabled === true && resultsField && (!field || field === resultsField)) {\n\t\t\tconst options: PollOption[] = await resolveEffectivePollOptions({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tform,\n\t\t\t}).catch(() => [])\n\t\t\tif (options.length > 0) {\n\t\t\t\tresolvedOptions = { [resultsField]: options }\n\t\t\t}\n\t\t\t// Only the explicit single-field poll read switches to the tally store; an all-fields\n\t\t\t// (or multi-field) read keeps the scan, which is the only source for non-poll fields.\n\t\t\tif (pollVotesEnabled === true && field === resultsField) {\n\t\t\t\tconst instances = Array.isArray(form.fields) ? (form.fields as FormFieldInstance[]) : []\n\t\t\t\tconst instance = instances.find((entry) => entry.name === resultsField)\n\t\t\t\tconst aggregation = await aggregateFromVotes({\n\t\t\t\t\tpayload,\n\t\t\t\t\tformId,\n\t\t\t\t\tfield: resultsField,\n\t\t\t\t\tmeta: tallyMetaOf(instance, resultsField),\n\t\t\t\t\toptions: resolvedOptions?.[resultsField] ?? [],\n\t\t\t\t\treq,\n\t\t\t\t})\n\t\t\t\treturn { status: 200, body: { results: [aggregation] } }\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst poll = pollConfigOf(form.poll)\n\t\tif (form.pollEnabled !== true || !poll) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (poll.resultsVisibility === 'afterClose' && !isPollClosed(poll)) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (access) {\n\t\t\t// No req means the seam cannot be evaluated; fail closed rather than skip a configured gate.\n\t\t\t// The concrete generated Form doc has no index signature; the seam's Record<string, unknown>\n\t\t\t// is the ergonomic host-facing contract, so widen the doc to it here.\n\t\t\tconst allowed = req\n\t\t\t\t? await access({ req, form: form as unknown as FormResultsAccessArgs['form'] })\n\t\t\t\t: false\n\t\t\tif (!allowed) {\n\t\t\t\treturn forbidden\n\t\t\t}\n\t\t}\n\t\tconst publicField =\n\t\t\ttypeof poll.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (!publicField) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (field && field !== publicField) {\n\t\t\treturn forbidden\n\t\t}\n\t\tconst instances = Array.isArray(form.fields) ? (form.fields as FormFieldInstance[]) : []\n\t\tconst instance = instances.find((entry) => entry.name === publicField)\n\t\tif (!instance) {\n\t\t\treturn forbidden\n\t\t}\n\t\tconst hasSource = typeof poll.optionSource === 'string' && poll.optionSource.length > 0\n\t\tconst authored = fieldHasOptions(instance)\n\t\t// Options that don't come from the author's own literal `options` list (a source or a\n\t\t// field-typed resolver) require the results field to be a poll-eligible type, so a legacy or\n\t\t// db-written doc pointing `resultsField` at a free-text field can never dump raw answers as\n\t\t// leftover buckets. A static authored poll is a choice field already, so it keeps serving.\n\t\tif ((hasSource || !authored) && eligibleTypes && !eligibleTypes.includes(instance.blockType)) {\n\t\t\treturn forbidden\n\t\t}\n\t\tlet options: PollOption[]\n\t\ttry {\n\t\t\toptions = await resolveEffectivePollOptions({ payload, req, form })\n\t\t} catch {\n\t\t\treturn unavailable\n\t\t}\n\t\tif (options.length === 0) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (pollVotesEnabled === true) {\n\t\t\tconst aggregation = await aggregateFromVotes({\n\t\t\t\tpayload,\n\t\t\t\tformId,\n\t\t\t\tfield: publicField,\n\t\t\t\tmeta: tallyMetaOf(instance, publicField),\n\t\t\t\toptions,\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn { status: 200, body: { results: [aggregation] } }\n\t\t}\n\t\tresolvedOptions = { [publicField]: options }\n\t\tfields = [publicField]\n\t}\n\n\tconst results = await aggregateFormResponses({ payload, formId, fields, req, resolvedOptions })\n\treturn { status: 200, body: { results } }\n}\n"],"mappings":";;;;;;;;AAwDA,MAAM,YAAyC;CAC9C,QAAQ;CACR,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;AAC5C;AAKA,MAAM,cAA2C;CAChD,QAAQ;CACR,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,2BAA2B,CAAC,EAAE;AAC3D;;AAGA,MAAM,eACL,UACA,WAC4C;CAC5C,OAAO,OAAO,UAAU,UAAU,YAAY,SAAS,MAAM,SAAS,IAAI,SAAS,QAAQ;CAC3F,WAAW,UAAU;AACtB;;;;;;;;;;;;;;;;AAiBA,MAAa,4BAA4B,OACxC,SAC0C;CAC1C,MAAM,EAAE,SAAS,QAAQ,OAAO,UAAU,KAAK,QAAQ,eAAe,qBAAqB;CAC3F,IAAI,UAAU,MACb,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE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,OAAO;EAER,IAAI,KAAK,sBAAsB,gBAAgB,CAAC,aAAa,IAAI,GAChE,OAAO;EAER,IAAI;OAOC,EAHY,MACb,MAAM,OAAO;IAAE;IAAW;GAAiD,CAAC,IAC5E,QAEF,OAAO;EAAA;EAGT,MAAM,cACL,OAAO,KAAK,iBAAiB,YAAY,KAAK,aAAa,SAAS,IACjE,KAAK,eACL,KAAA;EACJ,IAAI,CAAC,aACJ,OAAO;EAER,IAAI,SAAS,UAAU,aACtB,OAAO;EAGR,MAAM,YADY,MAAM,QAAQ,KAAK,MAAM,IAAK,KAAK,SAAiC,CAAC,GAC5D,MAAM,UAAU,MAAM,SAAS,WAAW;EACrE,IAAI,CAAC,UACJ,OAAO;EAER,MAAM,YAAY,OAAO,KAAK,iBAAiB,YAAY,KAAK,aAAa,SAAS;EACtF,MAAM,WAAW,gBAAgB,QAAQ;EAKzC,KAAK,aAAa,CAAC,aAAa,iBAAiB,CAAC,cAAc,SAAS,SAAS,SAAS,GAC1F,OAAO;EAER,IAAI;EACJ,IAAI;GACH,UAAU,MAAM,4BAA4B;IAAE;IAAS;IAAK;GAAK,CAAC;EACnE,QAAQ;GACP,OAAO;EACR;EACA,IAAI,QAAQ,WAAW,GACtB,OAAO;EAER,IAAI,qBAAqB,MASxB,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,SAAS,CAAC,MARd,mBAAmB;IAC5C;IACA;IACA,OAAO;IACP,MAAM,YAAY,UAAU,WAAW;IACvC;IACA;GACD,CAAC,CACkD,EAAE;EAAE;EAExD,kBAAkB,GAAG,cAAc,QAAQ;EAC3C,SAAS,CAAC,WAAW;CACtB;CAGA,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,SAAA,MADR,uBAAuB;GAAE;GAAS;GAAQ;GAAQ;GAAK;EAAgB,CAAC,EACxD;CAAE;AACzC"}
1
+ {"version":3,"file":"resolveResultsRequest.js","names":[],"sources":["../../src/aggregation/resolveResultsRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest, TypedLocale } from 'payload'\nimport { findFormAtLocale, missingFormOnReadError } from '../form/findFormAtLocale'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { type PollFormLike, shouldAutoResolvePoll } from '../poll/closeJob'\nimport type { PollOption } from '../poll/definePollOptionSource'\nimport { resolveEffectivePollOptions } from '../poll/effectivePollOptions'\nimport { resolvePollOutcome } from '../poll/resolvePollOutcome'\nimport { aggregateFromVotes } from '../poll/votes/aggregateFromVotes'\nimport { resolveSubmissionLocale } from '../submissions/submissionLocale'\nimport type { FormFieldInstance } from '../submissions/types'\nimport { aggregateFormResponses, fieldHasOptions } from './aggregateResponses'\nimport type { FieldAggregation } from './types'\n\nexport type FormResultsAccessArgs = {\n\treq: PayloadRequest\n\t/** The loaded forms document (depth 0). Untyped beyond `id`: hosts read their own fields (e.g. `form.tenant`). */\n\tform: { id: number | string } & Record<string, unknown>\n}\n\n/**\n * Host seam gating anonymous results reads, evaluated after the form is loaded and before anything\n * is aggregated. Multi-tenant recipe: compare `form.tenant` against the tenant derived from `req`\n * (host header, cookie, or auth context) and return `false` for a cross-tenant read. Authenticated\n * callers bypass this seam (they are admin-trusted, like the rest of the results endpoint).\n */\nexport type FormResultsAccess = (args: FormResultsAccessArgs) => boolean | Promise<boolean>\n\nexport type ResolveResultsRequestArgs = {\n\tpayload: Payload\n\tformId: number | string | undefined\n\t/** The requested field (query param). */\n\tfield?: string\n\t/** Whether the caller is authenticated (an admin/user). */\n\tisAuthed: boolean\n\treq?: PayloadRequest\n\t/** Optional host seam for anonymous reads; absent means plugin-default gating only. */\n\taccess?: FormResultsAccess\n\t/**\n\t * Poll-eligible field types (registry-derived). When set, an anonymous read of an\n\t * option-source poll also requires the results field's instance to be one of these types,\n\t * so legacy or db-written docs pointing at a free-text field can never expose stored\n\t * answers as leftover result buckets.\n\t */\n\teligibleTypes?: readonly string[]\n\t/**\n\t * Whether the hidden tally store backs poll reads. When true, the poll results field is served\n\t * from `aggregateFromVotes` (anonymous reads, and an authed read naming exactly that field)\n\t * instead of the submission scan; every authorization gate stays identical either way.\n\t */\n\tpollVotesEnabled?: boolean\n}\n\nexport type ResolveResultsRequestResult = {\n\tstatus: number\n\tbody: { results: FieldAggregation[] } | { errors: { message: string }[] }\n}\n\nconst forbidden: ResolveResultsRequestResult = {\n\tstatus: 403,\n\tbody: { errors: [{ message: 'Forbidden' }] },\n}\n\n// 503 over 403 for a failed option-source resolve: the form and its poll config are already\n// publicly readable, so \"temporarily unavailable\" leaks nothing new, matches the submission\n// path's precedent, and does not mislabel a transient server fault as an authorization denial.\nconst unavailable: ResolveResultsRequestResult = {\n\tstatus: 503,\n\tbody: { errors: [{ message: 'Poll options unavailable' }] },\n}\n\n/** Scan-shape parity for a tally-served field: label from the live instance, else the field name. */\nconst tallyMetaOf = (\n\tinstance: FormFieldInstance | undefined,\n\tfield: string\n): { label: string; fieldType?: string } => ({\n\tlabel: typeof instance?.label === 'string' && instance.label.length > 0 ? instance.label : field,\n\tfieldType: instance?.blockType,\n})\n\nconst resolveAtLocale = async (\n\targs: ResolveResultsRequestArgs,\n\tlocale: string\n): Promise<ResolveResultsRequestResult> => {\n\tconst { payload, formId, field, isAuthed, req, access, eligibleTypes, pollVotesEnabled } = args\n\tif (formId == null) {\n\t\treturn { status: 400, body: { errors: [{ message: 'Missing form id' }] } }\n\t}\n\tconst form = await findFormAtLocale({\n\t\tpayload,\n\t\tid: formId,\n\t\tlocale,\n\t\treq,\n\t\toverrideAccess: true,\n\t}).catch(missingFormOnReadError)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\n\t// No-runner safety net: when a closed poll's `mostVoted`/`source` outcome was never auto-resolved\n\t// (no wired job runner fired the close task), a results read heals it. Idempotent and gate-neutral,\n\t// it runs on the already-loaded form via overrideAccess and writes only through the outcome hook, so\n\t// it cannot relax the anonymous authorization below. A failure degrades silently to the normal path.\n\tif (shouldAutoResolvePoll(form as PollFormLike)) {\n\t\tawait resolvePollOutcome({ payload, formId, req, pollVotesEnabled }).catch(() => undefined)\n\t}\n\n\tlet fields: string[] | undefined\n\tlet resolvedOptions: Record<string, { value: string; label: string }[]> | undefined\n\tif (isAuthed) {\n\t\tfields = field ? [field] : undefined\n\t\t// Label a poll's results field for admins: resolve its effective options (a source, the\n\t\t// field type's own resolver, or authored options) and inject them so a sourced/resolved poll\n\t\t// shows labels instead of raw stored values, and so an all-fields read still surfaces a\n\t\t// resolver-backed field that carries no authored options. Best-effort: a resolver/source\n\t\t// failure degrades to raw values rather than blocking the trusted read (the anonymous path\n\t\t// below fails closed instead). Only run when the read would actually surface the results field.\n\t\tconst poll = pollConfigOf(form.poll)\n\t\tconst resultsField =\n\t\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (form.pollEnabled === true && resultsField && (!field || field === resultsField)) {\n\t\t\tconst options: PollOption[] = await resolveEffectivePollOptions({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tform,\n\t\t\t}).catch(() => [])\n\t\t\tif (options.length > 0) {\n\t\t\t\tresolvedOptions = { [resultsField]: options }\n\t\t\t}\n\t\t\t// Only the explicit single-field poll read switches to the tally store; an all-fields\n\t\t\t// (or multi-field) read keeps the scan, which is the only source for non-poll fields.\n\t\t\tif (pollVotesEnabled === true && field === resultsField) {\n\t\t\t\tconst instances = Array.isArray(form.fields) ? (form.fields as FormFieldInstance[]) : []\n\t\t\t\tconst instance = instances.find((entry) => entry.name === resultsField)\n\t\t\t\tconst aggregation = await aggregateFromVotes({\n\t\t\t\t\tpayload,\n\t\t\t\t\tformId,\n\t\t\t\t\tfield: resultsField,\n\t\t\t\t\tmeta: tallyMetaOf(instance, resultsField),\n\t\t\t\t\toptions: resolvedOptions?.[resultsField] ?? [],\n\t\t\t\t\treq,\n\t\t\t\t})\n\t\t\t\treturn { status: 200, body: { results: [aggregation] } }\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst poll = pollConfigOf(form.poll)\n\t\tif (form.pollEnabled !== true || !poll) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (poll.resultsVisibility === 'afterClose' && !isPollClosed(poll)) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (access) {\n\t\t\t// No req means the seam cannot be evaluated; fail closed rather than skip a configured gate.\n\t\t\t// The concrete generated Form doc has no index signature; the seam's Record<string, unknown>\n\t\t\t// is the ergonomic host-facing contract, so widen the doc to it here.\n\t\t\tconst allowed = req\n\t\t\t\t? await access({ req, form: form as unknown as FormResultsAccessArgs['form'] })\n\t\t\t\t: false\n\t\t\tif (!allowed) {\n\t\t\t\treturn forbidden\n\t\t\t}\n\t\t}\n\t\tconst publicField =\n\t\t\ttypeof poll.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (!publicField) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (field && field !== publicField) {\n\t\t\treturn forbidden\n\t\t}\n\t\tconst instances = Array.isArray(form.fields) ? (form.fields as FormFieldInstance[]) : []\n\t\tconst instance = instances.find((entry) => entry.name === publicField)\n\t\tif (!instance) {\n\t\t\treturn forbidden\n\t\t}\n\t\tconst hasSource = typeof poll.optionSource === 'string' && poll.optionSource.length > 0\n\t\tconst authored = fieldHasOptions(instance)\n\t\t// Options that don't come from the author's own literal `options` list (a source or a\n\t\t// field-typed resolver) require the results field to be a poll-eligible type, so a legacy or\n\t\t// db-written doc pointing `resultsField` at a free-text field can never dump raw answers as\n\t\t// leftover buckets. A static authored poll is a choice field already, so it keeps serving.\n\t\tif ((hasSource || !authored) && eligibleTypes && !eligibleTypes.includes(instance.blockType)) {\n\t\t\treturn forbidden\n\t\t}\n\t\tlet options: PollOption[]\n\t\ttry {\n\t\t\toptions = await resolveEffectivePollOptions({ payload, req, form })\n\t\t} catch {\n\t\t\treturn unavailable\n\t\t}\n\t\tif (options.length === 0) {\n\t\t\treturn forbidden\n\t\t}\n\t\tif (pollVotesEnabled === true) {\n\t\t\tconst aggregation = await aggregateFromVotes({\n\t\t\t\tpayload,\n\t\t\t\tformId,\n\t\t\t\tfield: publicField,\n\t\t\t\tmeta: tallyMetaOf(instance, publicField),\n\t\t\t\toptions,\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn { status: 200, body: { results: [aggregation] } }\n\t\t}\n\t\tresolvedOptions = { [publicField]: options }\n\t\tfields = [publicField]\n\t}\n\n\tconst results = await aggregateFormResponses({ payload, formId, fields, req, resolvedOptions })\n\treturn { status: 200, body: { results } }\n}\n\n/**\n * Authorize and resolve a poll/survey results request. Authed callers may aggregate any field (or all\n * enumerable fields) and bypass the `access` seam; for a poll-enabled form they also get the results\n * field's effective options injected so sourced/resolver-backed polls render labels (best-effort, a\n * resolve failure degrades to raw values rather than blocking the trusted read). Anonymous callers are\n * allowed only when the form's poll is enabled, the poll's `resultsVisibility` permits it (`afterVote`:\n * any time; `afterClose`: only once `closesAt` has passed), and the optional host `access` seam\n * approves; and then only for the configured `poll.resultsField`, and only if that field is enumerable\n * so a misconfigured `resultsField` pointing at a free-text or PII field can never be dumped publicly. A\n * static poll is enumerable through its authored options; a poll whose options come from an\n * `optionSource` or the field type's own `resolveOptions` resolves them here (registry via\n * `config.custom`, per-request cache), gated by `eligibleTypes` and enumerable only when resolution\n * yields any, with the resolved options driving bucket order and labels. Resolution failure fails\n * closed (503) on the anonymous path. Returns only aggregate counts, never raw submissions.\n */\nexport const resolveFormResultsRequest = async (\n\targs: ResolveResultsRequestArgs\n): Promise<ResolveResultsRequestResult> => {\n\t// The visitor's `?locale=` (sent by `<Poll>`'s `submissionLocale`), clamped like a submission's so\n\t// option labels come back in the language the poll was rendered in. A localized `req` carries the\n\t// clamped value while resolving, so an option source reading `req.locale` agrees with the form, and\n\t// gets its own back afterwards: a host may hand in its own request.\n\tconst { payload, req } = args\n\tconst { localization } = payload.config\n\tconst locale = resolveSubmissionLocale(req?.locale, localization)\n\tif (!req || !localization) {\n\t\treturn resolveAtLocale(args, locale)\n\t}\n\tconst previousLocale = req.locale\n\treq.locale = locale as TypedLocale\n\ttry {\n\t\treturn await resolveAtLocale(args, locale)\n\t} finally {\n\t\treq.locale = previousLocale\n\t}\n}\n"],"mappings":";;;;;;;;;AAyDA,MAAM,YAAyC;CAC9C,QAAQ;CACR,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;AAC5C;AAKA,MAAM,cAA2C;CAChD,QAAQ;CACR,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,2BAA2B,CAAC,EAAE;AAC3D;;AAGA,MAAM,eACL,UACA,WAC4C;CAC5C,OAAO,OAAO,UAAU,UAAU,YAAY,SAAS,MAAM,SAAS,IAAI,SAAS,QAAQ;CAC3F,WAAW,UAAU;AACtB;AAEA,MAAM,kBAAkB,OACvB,MACA,WAC0C;CAC1C,MAAM,EAAE,SAAS,QAAQ,OAAO,UAAU,KAAK,QAAQ,eAAe,qBAAqB;CAC3F,IAAI,UAAU,MACb,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,kBAAkB,CAAC,EAAE;CAAE;CAE1E,MAAM,OAAO,MAAM,iBAAiB;EACnC;EACA,IAAI;EACJ;EACA;EACA,gBAAgB;CACjB,CAAC,EAAE,MAAM,sBAAsB;CAC/B,IAAI,CAAC,MACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAOpE,IAAI,sBAAsB,IAAoB,GAC7C,MAAM,mBAAmB;EAAE;EAAS;EAAQ;EAAK;CAAiB,CAAC,EAAE,YAAY,KAAA,CAAS;CAG3F,IAAI;CACJ,IAAI;CACJ,IAAI,UAAU;EACb,SAAS,QAAQ,CAAC,KAAK,IAAI,KAAA;EAO3B,MAAM,OAAO,aAAa,KAAK,IAAI;EACnC,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SA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AC,cAAc,SAAS,SAAS,SAAS,GAC1F,OAAO;EAER,IAAI;EACJ,IAAI;GACH,UAAU,MAAM,4BAA4B;IAAE;IAAS;IAAK;GAAK,CAAC;EACnE,QAAQ;GACP,OAAO;EACR;EACA,IAAI,QAAQ,WAAW,GACtB,OAAO;EAER,IAAI,qBAAqB,MASxB,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,SAAS,CAAC,MARd,mBAAmB;IAC5C;IACA;IACA,OAAO;IACP,MAAM,YAAY,UAAU,WAAW;IACvC;IACA;GACD,CAAC,CACkD,EAAE;EAAE;EAExD,kBAAkB,GAAG,cAAc,QAAQ;EAC3C,SAAS,CAAC,WAAW;CACtB;CAGA,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,SAAA,MADR,uBAAuB;GAAE;GAAS;GAAQ;GAAQ;GAAK;EAAgB,CAAC,EACxD;CAAE;AACzC;;;;;;;;;;;;;;;;AAiBA,MAAa,4BAA4B,OACxC,SAC0C;CAK1C,MAAM,EAAE,SAAS,QAAQ;CACzB,MAAM,EAAE,iBAAiB,QAAQ;CACjC,MAAM,SAAS,wBAAwB,KAAK,QAAQ,YAAY;CAChE,IAAI,CAAC,OAAO,CAAC,cACZ,OAAO,gBAAgB,MAAM,MAAM;CAEpC,MAAM,iBAAiB,IAAI;CAC3B,IAAI,SAAS;CACb,IAAI;EACH,OAAO,MAAM,gBAAgB,MAAM,MAAM;CAC1C,UAAU;EACT,IAAI,SAAS;CACd;AACD"}
@@ -7,6 +7,7 @@ type EndpointOptionsSelectProps = {
7
7
  /** The field path within the document (Payload-injected, not the endpoint path). */path?: string;
8
8
  field?: {
9
9
  label?: unknown;
10
+ localized?: boolean;
10
11
  admin?: {
11
12
  description?: unknown;
12
13
  width?: string;
@@ -87,6 +87,7 @@ const EndpointOptionsSelect = (props) => {
87
87
  children: [
88
88
  /* @__PURE__ */ jsx(FieldLabel, {
89
89
  label,
90
+ localized: props.field?.localized,
90
91
  path
91
92
  }),
92
93
  /* @__PURE__ */ jsx(ReactSelect, {
@@ -1 +1 @@
1
- {"version":3,"file":"EndpointOptionsSelect.js","names":["useTranslation"],"sources":["../../src/client/EndpointOptionsSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tuseConfig,\n\tuseDocumentInfo,\n\tuseField,\n} from '@payloadcms/ui'\nimport { type CSSProperties, useEffect, useState } from 'react'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport {\n\tbuildEndpointOptionsUrl,\n\ttype EndpointOption,\n\ttype EndpointOptionsScope,\n\tparseEndpointOptions,\n} from './endpointOptions'\nimport { toStaticLabel } from './toStaticLabel'\n\n/** Standard text-field client props plus this component's `clientProps`. */\nexport type EndpointOptionsSelectProps = {\n\t/** The field path within the document (Payload-injected, not the endpoint path). */\n\tpath?: string\n\tfield?: { label?: unknown; admin?: { description?: unknown; width?: string } }\n\tlabel?: unknown\n\t/**\n\t * Endpoint subpath under the current document's collection API route; `'poll-options'` fetches\n\t * `GET {routes.api}/{collectionSlug}/{id}/poll-options`. The endpoint must return\n\t * `{ options: { label, value }[] }`.\n\t */\n\tendpoint: string\n\t/**\n\t * What the options depend on; see {@link EndpointOptionsScope}. Default `'document'`. Pass\n\t * `'request'` for an endpoint registered at the id-less path so options load while the document\n\t * is still being created.\n\t */\n\tscope?: EndpointOptionsScope\n\t/**\n\t * Field description as a translation key, resolved client-side. Payload drops `admin.description`\n\t * functions from client fields, so a translated description must travel as a key; a static\n\t * `admin.description` string still renders when this is unset.\n\t */\n\tdescriptionKey?: TranslationKey\n\t/** Mirrors ReactSelect's `isClearable`; defaults to true. */\n\tisClearable?: boolean\n\t/**\n\t * Render a multi-value select bound to a `string[]`, for a `hasMany` field (e.g. a poll outcome\n\t * with tied winners). Default false: a single-value select bound to a `string`.\n\t */\n\tisMulti?: boolean\n}\n\ntype FetchState =\n\t| { status: 'error' | 'idle' | 'loading'; options?: never }\n\t| { status: 'loaded'; options: EndpointOption[] }\n\n/**\n * A select whose options load from a plugin endpoint, for stored values whose valid choices only\n * the server knows (e.g. a poll's source-resolved options). The pattern: pass `endpoint` via\n * `clientProps`, the component reads the document id from `useDocumentInfo` and the API route\n * from `useConfig`, fetches once with the admin cookie, and renders translated loading/error\n * states. The stored value stays selectable even when it is missing from the fetched options (or\n * the fetch failed), so opening an old document never silently drops data. Document scope (the\n * default) skips the fetch until the document is saved, since the server cannot resolve options\n * for it yet; request scope fetches immediately, create mode included, and ignores the id\n * entirely so the first save never re-fetches.\n */\nexport const EndpointOptionsSelect = (props: EndpointOptionsSelectProps) => {\n\tconst isMulti = props.isMulti === true\n\tconst { path, setValue, value } = useField<string | string[]>({ path: props.path })\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst { t } = useTranslation()\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\tconst { id, collectionSlug } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst apiRoute = config.routes.api\n\tconst scope = props.scope ?? 'document'\n\t// Request scope never puts the id in the URL; deriving undefined here keeps the effect from\n\t// re-fetching when the first save assigns one.\n\tconst docId = scope === 'request' ? undefined : id\n\tconst [state, setState] = useState<FetchState>({ status: 'idle' })\n\n\tuseEffect(() => {\n\t\tif (!collectionSlug || (scope === 'document' && docId == null)) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\tconst url = buildEndpointOptionsUrl({\n\t\t\tapiRoute,\n\t\t\tcollectionSlug,\n\t\t\tid: docId,\n\t\t\tscope,\n\t\t\tendpoint: props.endpoint,\n\t\t})\n\t\tsetState({ status: 'loading' })\n\t\tfetch(url, {\n\t\t\tcredentials: 'include',\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`Options request failed with ${response.status}`)\n\t\t\t\t}\n\t\t\t\tsetState({ status: 'loaded', options: parseEndpointOptions(await response.json()) })\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\tsetState({ status: 'error' })\n\t\t\t\t}\n\t\t\t})\n\t\treturn () => controller.abort()\n\t}, [apiRoute, collectionSlug, docId, scope, props.endpoint])\n\n\t// A missing fetched option (or a failed fetch) must never silently drop a stored value, so every\n\t// selected value the options don't cover is kept selectable by its own label.\n\tconst selectedValues: string[] = isMulti\n\t\t? Array.isArray(value)\n\t\t\t? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t\t: []\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\tconst options: ReactSelectOption[] = state.status === 'loaded' ? state.options : []\n\tconst missing = selectedValues\n\t\t.filter((selected) => !options.some((option) => option.value === selected))\n\t\t.map((selected) => ({ label: selected, value: selected }))\n\tconst allOptions = missing.length > 0 ? [...options, ...missing] : options\n\tconst selectedOptions = selectedValues\n\t\t.map((selected) => allOptions.find((option) => option.value === selected))\n\t\t.filter((option): option is ReactSelectOption => option !== undefined)\n\n\tconst handleChange = (selected: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tif (isMulti) {\n\t\t\tconst chosen = Array.isArray(selected) ? selected : selected ? [selected] : []\n\t\t\tsetValue(chosen.map((option) => option.value as string))\n\t\t\treturn\n\t\t}\n\t\tconst chosen = Array.isArray(selected) ? selected[0] : selected\n\t\tsetValue(chosen ? (chosen.value as string) : '')\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div className=\"field-type\" style={{ marginBlockEnd: '1rem', ...fieldStyle }}>\n\t\t\t<FieldLabel label={label} path={path} />\n\t\t\t<ReactSelect\n\t\t\t\toptions={allOptions}\n\t\t\t\tvalue={isMulti ? selectedOptions : (selectedOptions[0] ?? undefined)}\n\t\t\t\tisMulti={isMulti}\n\t\t\t\tisClearable={props.isClearable !== false}\n\t\t\t\tisLoading={state.status === 'loading'}\n\t\t\t\tplaceholder={state.status === 'loading' ? t(keys.endpointOptionsLoading) : undefined}\n\t\t\t\tshowError={state.status === 'error'}\n\t\t\t\tonChange={handleChange}\n\t\t\t/>\n\t\t\t<FieldDescription\n\t\t\t\tdescription={state.status === 'error' ? t(keys.endpointOptionsError) : description}\n\t\t\t\tpath={path}\n\t\t\t/>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsEA,MAAa,yBAAyB,UAAsC;CAC3E,MAAM,UAAU,MAAM,YAAY;CAClC,MAAM,EAAE,MAAM,UAAU,UAAU,SAA4B,EAAE,MAAM,MAAM,KAAK,CAAC;CAClF,MAAM,QAAQ,cAAc,MAAM,OAAO,SAAS,MAAM,KAAK;CAC7D,MAAM,EAAE,MAAMA,iBAAe;CAC7B,MAAM,cAAc,MAAM,iBACvB,EAAE,MAAM,cAAc,IACtB,cAAc,MAAM,OAAO,OAAO,WAAW;CAChD,MAAM,EAAE,IAAI,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,WAAW,OAAO,OAAO;CAC/B,MAAM,QAAQ,MAAM,SAAS;CAG7B,MAAM,QAAQ,UAAU,YAAY,KAAA,IAAY;CAChD,MAAM,CAAC,OAAO,YAAY,SAAqB,EAAE,QAAQ,OAAO,CAAC;CAEjE,gBAAgB;EACf,IAAI,CAAC,kBAAmB,UAAU,cAAc,SAAS,MACxD;EAED,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,MAAM,wBAAwB;GACnC;GACA;GACA,IAAI;GACJ;GACA,UAAU,MAAM;EACjB,CAAC;EACD,SAAS,EAAE,QAAQ,UAAU,CAAC;EAC9B,MAAM,KAAK;GACV,aAAa;GACb,SAAS,EAAE,QAAQ,mBAAmB;GACtC,QAAQ,W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MA,OACC,qBAAC,OAAD;EAAK,WAAU;EAAa,OAAO;GAAE,gBAAgB;GAAQ,GAL3C,MAAM,OAAO,OAAO,QACnC,EAAE,iBAAiB,MAAM,MAAM,MAAM,MAAM,IAC5C,KAAA;EAGyE;YAA3E;GACC,oBAAC,YAAD;IAAmB;IAAa;GAAO,CAAA;GACvC,oBAAC,aAAD;IACC,SAAS;IACT,OAAO,UAAU,kBAAmB,gBAAgB,MAAM,KAAA;IACjD;IACT,aAAa,MAAM,gBAAgB;IACnC,WAAW,MAAM,WAAW;IAC5B,aAAa,MAAM,WAAW,YAAY,EAAE,KAAK,sBAAsB,IAAI,KAAA;IAC3E,WAAW,MAAM,WAAW;IAC5B,UAAU;GACV,CAAA;GACD,oBAAC,kBAAD;IACC,aAAa,MAAM,WAAW,UAAU,EAAE,KAAK,oBAAoB,IAAI;IACjE;GACN,CAAA;EACG;;AAEP"}
1
+ {"version":3,"file":"EndpointOptionsSelect.js","names":["useTranslation"],"sources":["../../src/client/EndpointOptionsSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tuseConfig,\n\tuseDocumentInfo,\n\tuseField,\n} from '@payloadcms/ui'\nimport { type CSSProperties, useEffect, useState } from 'react'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport {\n\tbuildEndpointOptionsUrl,\n\ttype EndpointOption,\n\ttype EndpointOptionsScope,\n\tparseEndpointOptions,\n} from './endpointOptions'\nimport { toStaticLabel } from './toStaticLabel'\n\n/** Standard text-field client props plus this component's `clientProps`. */\nexport type EndpointOptionsSelectProps = {\n\t/** The field path within the document (Payload-injected, not the endpoint path). */\n\tpath?: string\n\tfield?: {\n\t\tlabel?: unknown\n\t\tlocalized?: boolean\n\t\tadmin?: { description?: unknown; width?: string }\n\t}\n\tlabel?: unknown\n\t/**\n\t * Endpoint subpath under the current document's collection API route; `'poll-options'` fetches\n\t * `GET {routes.api}/{collectionSlug}/{id}/poll-options`. The endpoint must return\n\t * `{ options: { label, value }[] }`.\n\t */\n\tendpoint: string\n\t/**\n\t * What the options depend on; see {@link EndpointOptionsScope}. Default `'document'`. Pass\n\t * `'request'` for an endpoint registered at the id-less path so options load while the document\n\t * is still being created.\n\t */\n\tscope?: EndpointOptionsScope\n\t/**\n\t * Field description as a translation key, resolved client-side. Payload drops `admin.description`\n\t * functions from client fields, so a translated description must travel as a key; a static\n\t * `admin.description` string still renders when this is unset.\n\t */\n\tdescriptionKey?: TranslationKey\n\t/** Mirrors ReactSelect's `isClearable`; defaults to true. */\n\tisClearable?: boolean\n\t/**\n\t * Render a multi-value select bound to a `string[]`, for a `hasMany` field (e.g. a poll outcome\n\t * with tied winners). Default false: a single-value select bound to a `string`.\n\t */\n\tisMulti?: boolean\n}\n\ntype FetchState =\n\t| { status: 'error' | 'idle' | 'loading'; options?: never }\n\t| { status: 'loaded'; options: EndpointOption[] }\n\n/**\n * A select whose options load from a plugin endpoint, for stored values whose valid choices only\n * the server knows (e.g. a poll's source-resolved options). The pattern: pass `endpoint` via\n * `clientProps`, the component reads the document id from `useDocumentInfo` and the API route\n * from `useConfig`, fetches once with the admin cookie, and renders translated loading/error\n * states. The stored value stays selectable even when it is missing from the fetched options (or\n * the fetch failed), so opening an old document never silently drops data. Document scope (the\n * default) skips the fetch until the document is saved, since the server cannot resolve options\n * for it yet; request scope fetches immediately, create mode included, and ignores the id\n * entirely so the first save never re-fetches.\n */\nexport const EndpointOptionsSelect = (props: EndpointOptionsSelectProps) => {\n\tconst isMulti = props.isMulti === true\n\tconst { path, setValue, value } = useField<string | string[]>({ path: props.path })\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst { t } = useTranslation()\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\tconst { id, collectionSlug } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst apiRoute = config.routes.api\n\tconst scope = props.scope ?? 'document'\n\t// Request scope never puts the id in the URL; deriving undefined here keeps the effect from\n\t// re-fetching when the first save assigns one.\n\tconst docId = scope === 'request' ? undefined : id\n\tconst [state, setState] = useState<FetchState>({ status: 'idle' })\n\n\tuseEffect(() => {\n\t\tif (!collectionSlug || (scope === 'document' && docId == null)) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\tconst url = buildEndpointOptionsUrl({\n\t\t\tapiRoute,\n\t\t\tcollectionSlug,\n\t\t\tid: docId,\n\t\t\tscope,\n\t\t\tendpoint: props.endpoint,\n\t\t})\n\t\tsetState({ status: 'loading' })\n\t\tfetch(url, {\n\t\t\tcredentials: 'include',\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`Options request failed with ${response.status}`)\n\t\t\t\t}\n\t\t\t\tsetState({ status: 'loaded', options: parseEndpointOptions(await response.json()) })\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\tsetState({ status: 'error' })\n\t\t\t\t}\n\t\t\t})\n\t\treturn () => controller.abort()\n\t}, [apiRoute, collectionSlug, docId, scope, props.endpoint])\n\n\t// A missing fetched option (or a failed fetch) must never silently drop a stored value, so every\n\t// selected value the options don't cover is kept selectable by its own label.\n\tconst selectedValues: string[] = isMulti\n\t\t? Array.isArray(value)\n\t\t\t? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t\t: []\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\tconst options: ReactSelectOption[] = state.status === 'loaded' ? state.options : []\n\tconst missing = selectedValues\n\t\t.filter((selected) => !options.some((option) => option.value === selected))\n\t\t.map((selected) => ({ label: selected, value: selected }))\n\tconst allOptions = missing.length > 0 ? [...options, ...missing] : options\n\tconst selectedOptions = selectedValues\n\t\t.map((selected) => allOptions.find((option) => option.value === selected))\n\t\t.filter((option): option is ReactSelectOption => option !== undefined)\n\n\tconst handleChange = (selected: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tif (isMulti) {\n\t\t\tconst chosen = Array.isArray(selected) ? selected : selected ? [selected] : []\n\t\t\tsetValue(chosen.map((option) => option.value as string))\n\t\t\treturn\n\t\t}\n\t\tconst chosen = Array.isArray(selected) ? selected[0] : selected\n\t\tsetValue(chosen ? (chosen.value as string) : '')\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div className=\"field-type\" style={{ marginBlockEnd: '1rem', ...fieldStyle }}>\n\t\t\t<FieldLabel label={label} localized={props.field?.localized} path={path} />\n\t\t\t<ReactSelect\n\t\t\t\toptions={allOptions}\n\t\t\t\tvalue={isMulti ? selectedOptions : (selectedOptions[0] ?? undefined)}\n\t\t\t\tisMulti={isMulti}\n\t\t\t\tisClearable={props.isClearable !== false}\n\t\t\t\tisLoading={state.status === 'loading'}\n\t\t\t\tplaceholder={state.status === 'loading' ? t(keys.endpointOptionsLoading) : undefined}\n\t\t\t\tshowError={state.status === 'error'}\n\t\t\t\tonChange={handleChange}\n\t\t\t/>\n\t\t\t<FieldDescription\n\t\t\t\tdescription={state.status === 'error' ? t(keys.endpointOptionsError) : description}\n\t\t\t\tpath={path}\n\t\t\t/>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0EA,MAAa,yBAAyB,UAAsC;CAC3E,MAAM,UAAU,MAAM,YAAY;CAClC,MAAM,EAAE,MAAM,UAAU,UAAU,SAA4B,EAAE,MAAM,MAAM,KAAK,CAAC;CAClF,MAAM,QAAQ,cAAc,MAAM,OAAO,SAAS,MAAM,KAAK;CAC7D,MAAM,EAAE,MAAMA,iBAAe;CAC7B,MAAM,cAAc,MAAM,iBACvB,EAAE,MAAM,cAAc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;
9
+ localized?: boolean;
9
10
  admin?: {
10
11
  description?: unknown;
11
12
  width?: string;
@@ -51,6 +51,7 @@ const FieldNameSelect = (props) => {
51
51
  children: [
52
52
  /* @__PURE__ */ jsx(FieldLabel, {
53
53
  label,
54
+ localized: props.field?.localized,
54
55
  path
55
56
  }),
56
57
  /* @__PURE__ */ jsx(ReactSelect, {
@@ -1 +1 @@
1
- {"version":3,"file":"FieldNameSelect.js","names":["useTranslation"],"sources":["../../src/client/FieldNameSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tuseField,\n\tuseFormFields,\n} from '@payloadcms/ui'\nimport { reduceFieldsToValues } from 'payload/shared'\nimport { type CSSProperties, useMemo } from 'react'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport type { TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport type { FieldRow } from './synthesizeClientField'\nimport { toStaticLabel } from './toStaticLabel'\n\n/** Props: standard JSON/text field client props plus the `types` allow-list we pass via clientProps. */\nexport type FieldNameSelectProps = {\n\tpath?: string\n\tfield?: { label?: unknown; admin?: { description?: unknown; width?: string } }\n\tlabel?: unknown\n\t/**\n\t * Sibling `fields` blocks whose `blockType` is in this list populate the select's options. Omit to\n\t * offer every named field regardless of type (a general field-target picker).\n\t */\n\ttypes?: string[]\n\t/**\n\t * Field description as a translation key, resolved client-side. Payload drops `admin.description`\n\t * functions from client fields, so a translated description must travel as a key; a static\n\t * `admin.description` string still renders when this is unset.\n\t */\n\tdescriptionKey?: TranslationKey\n}\n\nconst optionsFromData = (data: Record<string, unknown>, types?: string[]): ReactSelectOption[] => {\n\tconst rows = Array.isArray(data.fields) ? (data.fields as unknown[]) : []\n\tconst labels = new Map<string, string>()\n\tfor (const row of rows) {\n\t\tif (!row || typeof row !== 'object') {\n\t\t\tcontinue\n\t\t}\n\t\tconst { name, label } = row as FieldRow\n\t\tif (typeof name === 'string' && typeof label === 'string' && label.length > 0) {\n\t\t\tlabels.set(name.trim(), label)\n\t\t}\n\t}\n\tconst names = types ? fieldNamesOfType(data.fields, types) : fieldNames(data.fields)\n\treturn names.map((name) => ({\n\t\tlabel: labels.get(name) ?? name,\n\t\tvalue: name,\n\t}))\n}\n\n/**\n * The `Field` mounted on a text config field (e.g. an action's `toField`) that should be authored\n * by picking from the form's own fields rather than free-typing a name. Options come from the\n * sibling `fields` blocks array, filtered to `types` when given (every named field otherwise); the\n * stored value is kept selectable even if it no longer matches any field, so switching to this\n * component never silently drops data.\n */\nexport const FieldNameSelect = (props: FieldNameSelectProps) => {\n\tconst { path, setValue, value } = useField<string>({ path: props.path })\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst { t } = useTranslation()\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\n\tconst optionsJson = useFormFields(([fields]) =>\n\t\tJSON.stringify(optionsFromData(reduceFieldsToValues(fields, true), props.types))\n\t)\n\tconst options = useMemo(() => JSON.parse(optionsJson) as ReactSelectOption[], [optionsJson])\n\n\tconst allOptions =\n\t\tvalue && !options.some((option) => option.value === value)\n\t\t\t? [...options, { label: value, value }]\n\t\t\t: options\n\n\tconst handleChange = (selected: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tconst chosen = Array.isArray(selected) ? selected[0] : selected\n\t\tsetValue(chosen ? (chosen.value as string) : '')\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div className=\"field-type\" style={{ marginBlockEnd: '1rem', ...fieldStyle }}>\n\t\t\t<FieldLabel label={label} path={path} />\n\t\t\t<ReactSelect\n\t\t\t\toptions={allOptions}\n\t\t\t\tvalue={allOptions.find((option) => option.value === value) ?? undefined}\n\t\t\t\tisClearable\n\t\t\t\tonChange={handleChange}\n\t\t\t/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,IAAI,SAAS,KAAK;EACvD,SAAS,SAAU,OAAO,QAAmB,EAAE;CAChD;CAMA,OACC,qBAAC,OAAD;EAAK,WAAU;EAAa,OAAO;GAAE,gBAAgB;GAAQ,GAL3C,MAAM,OAAO,OAAO,QACnC,EAAE,iBAAiB,MAAM,MAAM,MAAM,MAAM,IAC5C,KAAA;EAGyE;YAA3E;GACC,oBAAC,YAAD;IAAmB;IAAa;GAAO,CAAA;GACvC,oBAAC,aAAD;IACC,SAAS;IACT,OAAO,WAAW,MAAM,WAAW,OAAO,UAAU,KAAK,KAAK,KAAA;IAC9D,aAAA;IACA,UAAU;GACV,CAAA;GACD,oBAAC,kBAAD;IAA+B;IAAmB;GAAO,CAAA;EACrD;;AAEP"}
1
+ {"version":3,"file":"FieldNameSelect.js","names":["useTranslation"],"sources":["../../src/client/FieldNameSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tuseField,\n\tuseFormFields,\n} from '@payloadcms/ui'\nimport { reduceFieldsToValues } from 'payload/shared'\nimport { type CSSProperties, useMemo } from 'react'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport type { TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport type { FieldRow } from './synthesizeClientField'\nimport { toStaticLabel } from './toStaticLabel'\n\n/** Props: standard JSON/text field client props plus the `types` allow-list we pass via clientProps. */\nexport type FieldNameSelectProps = {\n\tpath?: string\n\tfield?: {\n\t\tlabel?: unknown\n\t\tlocalized?: boolean\n\t\tadmin?: { description?: unknown; width?: string }\n\t}\n\tlabel?: unknown\n\t/**\n\t * Sibling `fields` blocks whose `blockType` is in this list populate the select's options. Omit to\n\t * offer every named field regardless of type (a general field-target picker).\n\t */\n\ttypes?: string[]\n\t/**\n\t * Field description as a translation key, resolved client-side. Payload drops `admin.description`\n\t * functions from client fields, so a translated description must travel as a key; a static\n\t * `admin.description` string still renders when this is unset.\n\t */\n\tdescriptionKey?: TranslationKey\n}\n\nconst optionsFromData = (data: Record<string, unknown>, types?: string[]): ReactSelectOption[] => {\n\tconst rows = Array.isArray(data.fields) ? (data.fields as unknown[]) : []\n\tconst labels = new Map<string, string>()\n\tfor (const row of rows) {\n\t\tif (!row || typeof row !== 'object') {\n\t\t\tcontinue\n\t\t}\n\t\tconst { name, label } = row as FieldRow\n\t\tif (typeof name === 'string' && typeof label === 'string' && label.length > 0) {\n\t\t\tlabels.set(name.trim(), label)\n\t\t}\n\t}\n\tconst names = types ? fieldNamesOfType(data.fields, types) : fieldNames(data.fields)\n\treturn names.map((name) => ({\n\t\tlabel: labels.get(name) ?? name,\n\t\tvalue: name,\n\t}))\n}\n\n/**\n * The `Field` mounted on a text config field (e.g. an action's `toField`) that should be authored\n * by picking from the form's own fields rather than free-typing a name. Options come from the\n * sibling `fields` blocks array, filtered to `types` when given (every named field otherwise); the\n * stored value is kept selectable even if it no longer matches any field, so switching to this\n * component never silently drops data.\n */\nexport const FieldNameSelect = (props: FieldNameSelectProps) => {\n\tconst { path, setValue, value } = useField<string>({ path: props.path })\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst { t } = useTranslation()\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\n\tconst optionsJson = useFormFields(([fields]) =>\n\t\tJSON.stringify(optionsFromData(reduceFieldsToValues(fields, true), props.types))\n\t)\n\tconst options = useMemo(() => JSON.parse(optionsJson) as ReactSelectOption[], [optionsJson])\n\n\tconst allOptions =\n\t\tvalue && !options.some((option) => option.value === value)\n\t\t\t? [...options, { label: value, value }]\n\t\t\t: options\n\n\tconst handleChange = (selected: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tconst chosen = Array.isArray(selected) ? selected[0] : selected\n\t\tsetValue(chosen ? (chosen.value as string) : '')\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div className=\"field-type\" style={{ marginBlockEnd: '1rem', ...fieldStyle }}>\n\t\t\t<FieldLabel label={label} localized={props.field?.localized} path={path} />\n\t\t\t<ReactSelect\n\t\t\t\toptions={allOptions}\n\t\t\t\tvalue={allOptions.find((option) => option.value === value) ?? undefined}\n\t\t\t\tisClearable\n\t\t\t\tonChange={handleChange}\n\t\t\t/>\n\t\t\t<FieldDescription description={description} path={path} />\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;AAwCA,MAAM,mBAAmB,MAA+B,UAA0C;CACjG,MAAM,OAAO,MAAM,QAAQ,KAAK,MAAM,IAAK,KAAK,SAAuB,CAAC;CACxE,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,OAAO,MAAM;EACvB,IAAI,CAAC,OAAO,OAAO,QAAQ,UAC1B;EAED,MAAM,EAAE,MAAM,UAAU;EACxB,IAAI,OAAO,SAAS,YAAY,OAAO,UAAU,YAAY,MAAM,SAAS,GAC3E,OAAO,IAAI,KAAK,KAAK,GAAG,KAAK;CAE/B;CAEA,QADc,QAAQ,iBAAiB,KAAK,QAAQ,KAAK,IAAI,WAAW,KAAK,MAAM,GACtE,KAAK,UAAU;EAC3B,OAAO,OAAO,IAAI,IAAI,KAAK;EAC3B,OAAO;CACR,EAAE;AACH;;;;;;;;AASA,MAAa,mBAAmB,UAAgC;CAC/D,MAAM,EAAE,MAAM,UAAU,UAAU,SAAiB,EAAE,MAAM,MAAM,KAAK,CAAC;CACvE,MAAM,QAAQ,cAAc,MAAM,OAAO,SAAS,MAAM,KAAK;CAC7D,MAAM,EAAE,MAAMA,iBAAe;CAC7B,MAAM,cAAc,MAAM,iBACvB,EAAE,MAAM,cAAc,IACtB,cAAc,MAAM,OAAO,OAAO,WAAW;CAEhD,MAAM,cAAc,eAAe,CAAC,YACnC,KAAK,UAAU,gBAAgB,qBAAqB,QAAQ,IAAI,GAAG,MAAM,KAAK,CAAC,CAChF;CACA,MAAM,UAAU,cAAc,KAAK,MAAM,WAAW,GAA0B,CAAC,WAAW,CAAC;CAE3F,MAAM,aACL,SAAS,CAAC,QAAQ,MAAM,WAAW,OAAO,UAAU,KAAK,IACtD,CAAC,GAAG,SAAS;EAAE,OAAO;EAAO;CAAM,CAAC,IACpC;CAEJ,MAAM,gBAAgB,aAA6D;EAClF,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK;EACvD,SAAS,SAAU,OAAO,QAAmB,EAAE;CAChD;CAMA,OACC,qBAAC,OAAD;EAAK,WAAU;EAAa,OAAO;GAAE,gBAAgB;GAAQ,GAL3C,MAAM,OAAO,OAAO,QACnC,EAAE,iBAAiB,MAAM,MAAM,MAAM,MAAM,IAC5C,KAAA;EAGyE;YAA3E;GACC,oBAAC,YAAD;IAAmB;IAAO,WAAW,MAAM,OAAO;IAAiB;GAAO,CAAA;GAC1E,oBAAC,aAAD;IACC,SAAS;IACT,OAAO,WAAW,MAAM,WAAW,OAAO,UAAU,KAAK,KAAK,KAAA;IAC9D,aAAA;IACA,UAAU;GACV,CAAA;GACD,oBAAC,kBAAD;IAA+B;IAAmB;GAAO,CAAA;EACrD;;AAEP"}
@@ -6,6 +6,7 @@ type RecipientsSelectProps = {
6
6
  path?: string;
7
7
  field?: {
8
8
  label?: unknown;
9
+ localized?: boolean;
9
10
  required?: boolean;
10
11
  admin?: {
11
12
  description?: unknown;
@@ -150,6 +150,7 @@ const RecipientsSelect = (props) => {
150
150
  CustomComponent: Label,
151
151
  Fallback: /* @__PURE__ */ jsx(FieldLabel, {
152
152
  label,
153
+ localized: props.field?.localized,
153
154
  path,
154
155
  required: props.field?.required
155
156
  })
@@ -1 +1 @@
1
- {"version":3,"file":"RecipientsSelect.js","names":["useTranslation"],"sources":["../../src/client/RecipientsSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldError,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tRenderCustomComponent,\n\tuseConfig,\n\tuseDocumentInfo,\n\tuseField,\n\tuseFormFields,\n} from '@payloadcms/ui'\nimport { reduceFieldsToValues } from 'payload/shared'\nimport { type CSSProperties, useEffect, useMemo, useState } from 'react'\nimport { isPlausibleEmail } from '../actions/emailRecipients'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport {\n\tbuildEndpointOptionsUrl,\n\ttype EndpointOption,\n\ttype EndpointOptionsScope,\n\tparseEndpointOptions,\n} from './endpointOptions'\nimport type { FieldRow } from './synthesizeClientField'\nimport { toStaticLabel } from './toStaticLabel'\n\nexport type RecipientsSelectProps = {\n\tpath?: string\n\tfield?: { label?: unknown; required?: boolean; admin?: { description?: unknown; width?: string } }\n\tlabel?: unknown\n\treadOnly?: boolean\n\t/** Endpoint subpath supplying preset address options (e.g. `'departments'`); omit for none. */\n\tendpoint?: string\n\t/** What the endpoint's options depend on; see {@link EndpointOptionsScope}. Default `'document'`. */\n\tscope?: EndpointOptionsScope\n\t/** Allow free-typed emails (default true). */\n\tallowCustom?: boolean\n\t/** Offer the form's own fields as recipient tokens (default true). */\n\tfieldTokens?: boolean\n\t/** Field types eligible as tokens (default `['email']`). */\n\ttokenFieldTypes?: string[]\n\t/** Registered recipient sources, offered as their own option group (labels resolved for the admin locale). */\n\tsources?: { value: string; label: string | Record<string, string> }[]\n\tdescriptionKey?: TranslationKey\n}\n\n/** A source label is a plain string or a per-locale record; resolve it for the admin UI language. */\nconst resolveSourceLabel = (label: string | Record<string, string>, language: string): string =>\n\ttypeof label === 'string' ? label : (label[language] ?? label.en ?? Object.values(label)[0] ?? '')\n\ntype FetchState =\n\t| { status: 'error' | 'idle' | 'loading' }\n\t| { status: 'loaded'; options: EndpointOption[] }\n\nconst tokenOptionsFromData = (\n\tdata: Record<string, unknown>,\n\ttypes?: string[]\n): ReactSelectOption[] => {\n\tconst rows = Array.isArray(data.fields) ? (data.fields as unknown[]) : []\n\tconst labels = new Map<string, string>()\n\tfor (const row of rows) {\n\t\tif (!row || typeof row !== 'object') {\n\t\t\tcontinue\n\t\t}\n\t\tconst { name, label } = row as FieldRow\n\t\tif (typeof name === 'string' && typeof label === 'string' && label.length > 0) {\n\t\t\tlabels.set(name.trim(), label)\n\t\t}\n\t}\n\tconst names =\n\t\ttypes && types.length > 0 ? fieldNamesOfType(data.fields, types) : fieldNames(data.fields)\n\treturn names.map((name) => ({ label: labels.get(name) ?? name, value: `{{${name}}}` }))\n}\n\n/**\n * A creatable, multi-value recipient field: pick a department (preset options from `endpoint`), pick a\n * form-field token (`{{field}}`, offered when `fieldTokens`), or type any email and press Enter\n * (`allowCustom`). Renders as native Payload badges (drag-reorderable), stores a `string[]`, honors\n * `admin.width` and the standard field props. Unknown or legacy stored values stay selectable.\n */\nexport const RecipientsSelect = (props: RecipientsSelectProps) => {\n\tconst allowCustom = props.allowCustom !== false\n\tconst fieldTokens = props.fieldTokens !== false\n\tconst {\n\t\tcustomComponents: { Description, Error: ErrorComponent, Label } = {},\n\t\tdisabled,\n\t\tpath,\n\t\tsetValue,\n\t\tshowError,\n\t\tvalue,\n\t} = useField<string[] | string>({ path: props.path })\n\tconst { t, i18n } = useTranslation()\n\tconst sourceOptions: ReactSelectOption[] = useMemo(\n\t\t() =>\n\t\t\t(props.sources ?? []).map((source) => ({\n\t\t\t\tvalue: source.value,\n\t\t\t\tlabel: resolveSourceLabel(source.label, i18n.language),\n\t\t\t})),\n\t\t[props.sources, i18n.language]\n\t)\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\tconst { id, collectionSlug } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst apiRoute = config.routes.api\n\tconst readOnly = props.readOnly === true || disabled === true\n\tconst [state, setState] = useState<FetchState>({ status: 'idle' })\n\n\tconst scope = props.scope ?? 'document'\n\t// Request scope never puts the id in the URL; deriving undefined here keeps the effect from\n\t// re-fetching when the first save assigns one.\n\tconst docId = scope === 'request' ? undefined : id\n\n\tuseEffect(() => {\n\t\tif (!props.endpoint || !collectionSlug || (scope === 'document' && docId == null)) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\tconst url = buildEndpointOptionsUrl({\n\t\t\tapiRoute,\n\t\t\tcollectionSlug,\n\t\t\tid: docId,\n\t\t\tscope,\n\t\t\tendpoint: props.endpoint,\n\t\t})\n\t\tsetState({ status: 'loading' })\n\t\tfetch(url, {\n\t\t\tcredentials: 'include',\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`Options request failed with ${response.status}`)\n\t\t\t\t}\n\t\t\t\tsetState({ status: 'loaded', options: parseEndpointOptions(await response.json()) })\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\tsetState({ status: 'error' })\n\t\t\t\t}\n\t\t\t})\n\t\treturn () => controller.abort()\n\t}, [apiRoute, collectionSlug, docId, scope, props.endpoint])\n\n\tconst presetOptions: ReactSelectOption[] = state.status === 'loaded' ? state.options : []\n\n\tconst tokenJson = useFormFields(([fields]) =>\n\t\tfieldTokens\n\t\t\t? JSON.stringify(\n\t\t\t\t\ttokenOptionsFromData(reduceFieldsToValues(fields, true), props.tokenFieldTypes)\n\t\t\t\t)\n\t\t\t: '[]'\n\t)\n\tconst tokenOptions = useMemo(() => JSON.parse(tokenJson) as ReactSelectOption[], [tokenJson])\n\n\tconst stored: string[] = Array.isArray(value)\n\t\t? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\n\tconst byValue = useMemo(() => {\n\t\tconst map = new Map<string, ReactSelectOption>()\n\t\tfor (const option of [...presetOptions, ...tokenOptions, ...sourceOptions]) {\n\t\t\tmap.set(option.value as string, option)\n\t\t}\n\t\treturn map\n\t}, [presetOptions, tokenOptions, sourceOptions])\n\n\tconst selected = stored.map((entry) => byValue.get(entry) ?? { label: entry, value: entry })\n\n\tconst groupedOptions = useMemo(() => {\n\t\tconst groups: { label: string; options: ReactSelectOption[] }[] = []\n\t\tif (presetOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupDepartments), options: presetOptions })\n\t\t}\n\t\tif (tokenOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupFields), options: tokenOptions })\n\t\t}\n\t\tif (sourceOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupSources), options: sourceOptions })\n\t\t}\n\t\treturn groups\n\t}, [presetOptions, tokenOptions, sourceOptions, t])\n\n\tconst handleChange = (selection: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tif (readOnly) {\n\t\t\treturn\n\t\t}\n\t\tconst chosen = Array.isArray(selection) ? selection : selection ? [selection] : []\n\t\tconst entries = chosen\n\t\t\t.map((option) => String(option.value).trim())\n\t\t\t.filter((entry) => entry.length > 0 && (isPlausibleEmail(entry) || byValue.has(entry)))\n\t\tconst deduped = new Map<string, string>()\n\t\tfor (const entry of entries) {\n\t\t\tconst key = entry.toLowerCase()\n\t\t\tif (!deduped.has(key)) {\n\t\t\t\tdeduped.set(key, entry)\n\t\t\t}\n\t\t}\n\t\tsetValue(Array.from(deduped.values()))\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div\n\t\t\tclassName={['field-type', showError && 'error', readOnly && 'read-only']\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' ')}\n\t\t\tid={path ? `field-${path.replace(/\\./g, '__')}` : undefined}\n\t\t\tstyle={{ marginBlockEnd: '1rem', ...fieldStyle }}\n\t\t>\n\t\t\t<RenderCustomComponent\n\t\t\t\tCustomComponent={Label}\n\t\t\t\tFallback={<FieldLabel label={label} path={path} required={props.field?.required} />}\n\t\t\t/>\n\t\t\t<div className=\"field-type__wrap\">\n\t\t\t\t<RenderCustomComponent\n\t\t\t\t\tCustomComponent={ErrorComponent}\n\t\t\t\t\tFallback={<FieldError path={path} showError={showError} />}\n\t\t\t\t/>\n\t\t\t\t<ReactSelect\n\t\t\t\t\toptions={groupedOptions}\n\t\t\t\t\tvalue={selected}\n\t\t\t\t\tisMulti\n\t\t\t\t\tisSortable\n\t\t\t\t\tisCreatable={allowCustom}\n\t\t\t\t\tisClearable={!readOnly}\n\t\t\t\t\tdisabled={readOnly}\n\t\t\t\t\tisLoading={state.status === 'loading'}\n\t\t\t\t\tshowError={showError}\n\t\t\t\t\tplaceholder={state.status === 'loading' ? t(keys.endpointOptionsLoading) : undefined}\n\t\t\t\t\tonChange={handleChange}\n\t\t\t\t\tfilterOption={(option, rawInput) => {\n\t\t\t\t\t\tif (!option) {\n\t\t\t\t\t\t\treturn allowCustom && isPlausibleEmail(rawInput)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst query = rawInput.toLowerCase()\n\t\t\t\t\t\treturn `${option.label} ${option.value}`.toLowerCase().includes(query)\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t\t<RenderCustomComponent\n\t\t\t\tCustomComponent={Description}\n\t\t\t\tFallback={\n\t\t\t\t\t<FieldDescription\n\t\t\t\t\t\tdescription={state.status === 'error' ? t(keys.endpointOptionsError) : description}\n\t\t\t\t\t\tpath={path}\n\t\t\t\t\t/>\n\t\t\t\t}\n\t\t\t/>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;AAkDA,MAAM,sBAAsB,OAAwC,aACnE,OAAO,UAAU,WAAW,QAAS,MAAM,aAAa,MAAM,MAAM,OAAO,OAAO,KAAK,EAAE,MAAM;AAMhG,MAAM,wBACL,MACA,U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CACtC;CAEA,MAAM,aAAa,MAAM,OAAO,OAAO,QACnC,EAAE,iBAAiB,MAAM,MAAM,MAAM,MAAM,IAC5C,KAAA;CAEH,OACC,qBAAC,OAAD;EACC,WAAW;GAAC;GAAc,aAAa;GAAS,YAAY;EAAW,EACrE,OAAO,OAAO,EACd,KAAK,GAAG;EACV,IAAI,OAAO,SAAS,KAAK,QAAQ,OAAO,IAAI,MAAM,KAAA;EAClD,OAAO;GAAE,gBAAgB;GAAQ,GAAG;EAAW;YALhD;GAOC,oBAAC,uBAAD;IACC,iBAAiB;IACjB,UAAU,oBAAC,YAAD;KAAmB;KAAa;KAAM,UAAU,MAAM,OAAO;IAAW,CAAA;GAClF,CAAA;GACD,qBAAC,OAAD;IAAK,WAAU;cAAf,CACC,oBAAC,uBAAD;KACC,iBAAiB;KACjB,UAAU,oBAAC,YAAD;MAAkB;MAAiB;KAAY,CAAA;IACzD,CAAA,GACD,oBAAC,aAAD;KACC,SAAS;KACT,OAAO;KACP,SAAA;KACA,YAAA;KACA,aAAa;KACb,aAAa,CAAC;KACd,UAAU;KACV,WAAW,MAAM,WAAW;KACjB;KACX,aAAa,MAAM,WAAW,YAAY,EAAE,KAAK,sBAAsB,IAAI,KAAA;KAC3E,UAAU;KACV,eAAe,QAAQ,aAAa;MACnC,IAAI,CAAC,QACJ,OAAO,eAAe,iBAAiB,QAAQ;MAEhD,MAAM,QAAQ,SAAS,YAAY;MACnC,OAAO,GAAG,OAAO,MAAM,GAAG,OAAO,QAAQ,YAAY,EAAE,SAAS,KAAK;KACtE;IACA,CAAA,CACG;;GACL,oBAAC,uBAAD;IACC,iBAAiB;IACjB,UACC,oBAAC,kBAAD;KACC,aAAa,MAAM,WAAW,UAAU,EAAE,KAAK,oBAAoB,IAAI;KACjE;IACN,CAAA;GAEF,CAAA;EACG;;AAEP"}
1
+ {"version":3,"file":"RecipientsSelect.js","names":["useTranslation"],"sources":["../../src/client/RecipientsSelect.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tFieldDescription,\n\tFieldError,\n\tFieldLabel,\n\tReactSelect,\n\ttype ReactSelectOption,\n\tRenderCustomComponent,\n\tuseConfig,\n\tuseDocumentInfo,\n\tuseField,\n\tuseFormFields,\n} from '@payloadcms/ui'\nimport { reduceFieldsToValues } from 'payload/shared'\nimport { type CSSProperties, useEffect, useMemo, useState } from 'react'\nimport { isPlausibleEmail } from '../actions/emailRecipients'\nimport { fieldNames, fieldNamesOfType } from '../fields/fieldNamesOfType'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport {\n\tbuildEndpointOptionsUrl,\n\ttype EndpointOption,\n\ttype EndpointOptionsScope,\n\tparseEndpointOptions,\n} from './endpointOptions'\nimport type { FieldRow } from './synthesizeClientField'\nimport { toStaticLabel } from './toStaticLabel'\n\nexport type RecipientsSelectProps = {\n\tpath?: string\n\tfield?: {\n\t\tlabel?: unknown\n\t\tlocalized?: boolean\n\t\trequired?: boolean\n\t\tadmin?: { description?: unknown; width?: string }\n\t}\n\tlabel?: unknown\n\treadOnly?: boolean\n\t/** Endpoint subpath supplying preset address options (e.g. `'departments'`); omit for none. */\n\tendpoint?: string\n\t/** What the endpoint's options depend on; see {@link EndpointOptionsScope}. Default `'document'`. */\n\tscope?: EndpointOptionsScope\n\t/** Allow free-typed emails (default true). */\n\tallowCustom?: boolean\n\t/** Offer the form's own fields as recipient tokens (default true). */\n\tfieldTokens?: boolean\n\t/** Field types eligible as tokens (default `['email']`). */\n\ttokenFieldTypes?: string[]\n\t/** Registered recipient sources, offered as their own option group (labels resolved for the admin locale). */\n\tsources?: { value: string; label: string | Record<string, string> }[]\n\tdescriptionKey?: TranslationKey\n}\n\n/** A source label is a plain string or a per-locale record; resolve it for the admin UI language. */\nconst resolveSourceLabel = (label: string | Record<string, string>, language: string): string =>\n\ttypeof label === 'string' ? label : (label[language] ?? label.en ?? Object.values(label)[0] ?? '')\n\ntype FetchState =\n\t| { status: 'error' | 'idle' | 'loading' }\n\t| { status: 'loaded'; options: EndpointOption[] }\n\nconst tokenOptionsFromData = (\n\tdata: Record<string, unknown>,\n\ttypes?: string[]\n): ReactSelectOption[] => {\n\tconst rows = Array.isArray(data.fields) ? (data.fields as unknown[]) : []\n\tconst labels = new Map<string, string>()\n\tfor (const row of rows) {\n\t\tif (!row || typeof row !== 'object') {\n\t\t\tcontinue\n\t\t}\n\t\tconst { name, label } = row as FieldRow\n\t\tif (typeof name === 'string' && typeof label === 'string' && label.length > 0) {\n\t\t\tlabels.set(name.trim(), label)\n\t\t}\n\t}\n\tconst names =\n\t\ttypes && types.length > 0 ? fieldNamesOfType(data.fields, types) : fieldNames(data.fields)\n\treturn names.map((name) => ({ label: labels.get(name) ?? name, value: `{{${name}}}` }))\n}\n\n/**\n * A creatable, multi-value recipient field: pick a department (preset options from `endpoint`), pick a\n * form-field token (`{{field}}`, offered when `fieldTokens`), or type any email and press Enter\n * (`allowCustom`). Renders as native Payload badges (drag-reorderable), stores a `string[]`, honors\n * `admin.width` and the standard field props. Unknown or legacy stored values stay selectable.\n */\nexport const RecipientsSelect = (props: RecipientsSelectProps) => {\n\tconst allowCustom = props.allowCustom !== false\n\tconst fieldTokens = props.fieldTokens !== false\n\tconst {\n\t\tcustomComponents: { Description, Error: ErrorComponent, Label } = {},\n\t\tdisabled,\n\t\tpath,\n\t\tsetValue,\n\t\tshowError,\n\t\tvalue,\n\t} = useField<string[] | string>({ path: props.path })\n\tconst { t, i18n } = useTranslation()\n\tconst sourceOptions: ReactSelectOption[] = useMemo(\n\t\t() =>\n\t\t\t(props.sources ?? []).map((source) => ({\n\t\t\t\tvalue: source.value,\n\t\t\t\tlabel: resolveSourceLabel(source.label, i18n.language),\n\t\t\t})),\n\t\t[props.sources, i18n.language]\n\t)\n\tconst label = toStaticLabel(props.field?.label ?? props.label)\n\tconst description = props.descriptionKey\n\t\t? t(props.descriptionKey)\n\t\t: toStaticLabel(props.field?.admin?.description)\n\tconst { id, collectionSlug } = useDocumentInfo()\n\tconst { config } = useConfig()\n\tconst apiRoute = config.routes.api\n\tconst readOnly = props.readOnly === true || disabled === true\n\tconst [state, setState] = useState<FetchState>({ status: 'idle' })\n\n\tconst scope = props.scope ?? 'document'\n\t// Request scope never puts the id in the URL; deriving undefined here keeps the effect from\n\t// re-fetching when the first save assigns one.\n\tconst docId = scope === 'request' ? undefined : id\n\n\tuseEffect(() => {\n\t\tif (!props.endpoint || !collectionSlug || (scope === 'document' && docId == null)) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\tconst url = buildEndpointOptionsUrl({\n\t\t\tapiRoute,\n\t\t\tcollectionSlug,\n\t\t\tid: docId,\n\t\t\tscope,\n\t\t\tendpoint: props.endpoint,\n\t\t})\n\t\tsetState({ status: 'loading' })\n\t\tfetch(url, {\n\t\t\tcredentials: 'include',\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`Options request failed with ${response.status}`)\n\t\t\t\t}\n\t\t\t\tsetState({ status: 'loaded', options: parseEndpointOptions(await response.json()) })\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\tsetState({ status: 'error' })\n\t\t\t\t}\n\t\t\t})\n\t\treturn () => controller.abort()\n\t}, [apiRoute, collectionSlug, docId, scope, props.endpoint])\n\n\tconst presetOptions: ReactSelectOption[] = state.status === 'loaded' ? state.options : []\n\n\tconst tokenJson = useFormFields(([fields]) =>\n\t\tfieldTokens\n\t\t\t? JSON.stringify(\n\t\t\t\t\ttokenOptionsFromData(reduceFieldsToValues(fields, true), props.tokenFieldTypes)\n\t\t\t\t)\n\t\t\t: '[]'\n\t)\n\tconst tokenOptions = useMemo(() => JSON.parse(tokenJson) as ReactSelectOption[], [tokenJson])\n\n\tconst stored: string[] = Array.isArray(value)\n\t\t? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t: typeof value === 'string' && value.length > 0\n\t\t\t? [value]\n\t\t\t: []\n\n\tconst byValue = useMemo(() => {\n\t\tconst map = new Map<string, ReactSelectOption>()\n\t\tfor (const option of [...presetOptions, ...tokenOptions, ...sourceOptions]) {\n\t\t\tmap.set(option.value as string, option)\n\t\t}\n\t\treturn map\n\t}, [presetOptions, tokenOptions, sourceOptions])\n\n\tconst selected = stored.map((entry) => byValue.get(entry) ?? { label: entry, value: entry })\n\n\tconst groupedOptions = useMemo(() => {\n\t\tconst groups: { label: string; options: ReactSelectOption[] }[] = []\n\t\tif (presetOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupDepartments), options: presetOptions })\n\t\t}\n\t\tif (tokenOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupFields), options: tokenOptions })\n\t\t}\n\t\tif (sourceOptions.length > 0) {\n\t\t\tgroups.push({ label: t(keys.recipientsGroupSources), options: sourceOptions })\n\t\t}\n\t\treturn groups\n\t}, [presetOptions, tokenOptions, sourceOptions, t])\n\n\tconst handleChange = (selection: ReactSelectOption | ReactSelectOption[] | null) => {\n\t\tif (readOnly) {\n\t\t\treturn\n\t\t}\n\t\tconst chosen = Array.isArray(selection) ? selection : selection ? [selection] : []\n\t\tconst entries = chosen\n\t\t\t.map((option) => String(option.value).trim())\n\t\t\t.filter((entry) => entry.length > 0 && (isPlausibleEmail(entry) || byValue.has(entry)))\n\t\tconst deduped = new Map<string, string>()\n\t\tfor (const entry of entries) {\n\t\t\tconst key = entry.toLowerCase()\n\t\t\tif (!deduped.has(key)) {\n\t\t\t\tdeduped.set(key, entry)\n\t\t\t}\n\t\t}\n\t\tsetValue(Array.from(deduped.values()))\n\t}\n\n\tconst fieldStyle = props.field?.admin?.width\n\t\t? ({ '--field-width': props.field.admin.width } as CSSProperties)\n\t\t: undefined\n\n\treturn (\n\t\t<div\n\t\t\tclassName={['field-type', showError && 'error', readOnly && 'read-only']\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' ')}\n\t\t\tid={path ? `field-${path.replace(/\\./g, '__')}` : undefined}\n\t\t\tstyle={{ marginBlockEnd: '1rem', ...fieldStyle }}\n\t\t>\n\t\t\t<RenderCustomComponent\n\t\t\t\tCustomComponent={Label}\n\t\t\t\tFallback={\n\t\t\t\t\t<FieldLabel\n\t\t\t\t\t\tlabel={label}\n\t\t\t\t\t\tlocalized={props.field?.localized}\n\t\t\t\t\t\tpath={path}\n\t\t\t\t\t\trequired={props.field?.required}\n\t\t\t\t\t/>\n\t\t\t\t}\n\t\t\t/>\n\t\t\t<div className=\"field-type__wrap\">\n\t\t\t\t<RenderCustomComponent\n\t\t\t\t\tCustomComponent={ErrorComponent}\n\t\t\t\t\tFallback={<FieldError path={path} showError={showError} />}\n\t\t\t\t/>\n\t\t\t\t<ReactSelect\n\t\t\t\t\toptions={groupedOptions}\n\t\t\t\t\tvalue={selected}\n\t\t\t\t\tisMulti\n\t\t\t\t\tisSortable\n\t\t\t\t\tisCreatable={allowCustom}\n\t\t\t\t\tisClearable={!readOnly}\n\t\t\t\t\tdisabled={readOnly}\n\t\t\t\t\tisLoading={state.status === 'loading'}\n\t\t\t\t\tshowError={showError}\n\t\t\t\t\tplaceholder={state.status === 'loading' ? t(keys.endpointOptionsLoading) : undefined}\n\t\t\t\t\tonChange={handleChange}\n\t\t\t\t\tfilterOption={(option, rawInput) => {\n\t\t\t\t\t\tif (!option) {\n\t\t\t\t\t\t\treturn allowCustom && isPlausibleEmail(rawInput)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst query = rawInput.toLowerCase()\n\t\t\t\t\t\treturn `${option.label} ${option.value}`.toLowerCase().includes(query)\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t\t<RenderCustomComponent\n\t\t\t\tCustomComponent={Description}\n\t\t\t\tFallback={\n\t\t\t\t\t<FieldDescription\n\t\t\t\t\t\tdescription={state.status === 'error' ? t(keys.endpointOptionsError) : description}\n\t\t\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,CACG;;GACL,oBAAC,uBAAD;IACC,iBAAiB;IACjB,UACC,oBAAC,kBAAD;KACC,aAAa,MAAM,WAAW,UAAU,EAAE,KAAK,oBAAoB,IAAI;KACjE;IACN,CAAA;GAEF,CAAA;EACG;;AAEP"}
@@ -1,10 +1,9 @@
1
1
  import { keys } from "../translations/keys.js";
2
2
  import { labelForKey } from "../translations/server.js";
3
- import { dispatchActions } from "../actions/dispatch.js";
4
- import { resolveEventSink } from "../events/resolveEventSink.js";
5
3
  import { pollConfigOf } from "../form/pollState.js";
6
4
  import { isLoggedIn } from "../plugin/access.js";
7
- import { FORMS_SLUG } from "./forms.js";
5
+ import { dispatchActions } from "../actions/dispatch.js";
6
+ import { resolveEventSink } from "../events/resolveEventSink.js";
8
7
  import { formIdOf } from "../submissions/formIdOf.js";
9
8
  import { makeVoteTallyHook } from "../poll/votes/voteTallyHook.js";
10
9
  import { voteChangeTargetOf } from "../submissions/voteChange.js";
@@ -13,6 +12,7 @@ import { buildSpamGuard } from "../spam/spamGuard.js";
13
12
  import { validateSubmission } from "../submissions/validateSubmission.js";
14
13
  import { verifyContext } from "../submissions/verifyContext.js";
15
14
  import { buildVoteSubmitEndpoint } from "../submissions/voteChangeEndpoint.js";
15
+ import { FORMS_SLUG } from "./forms.js";
16
16
  //#region src/collections/formSubmissions.ts
17
17
  const FORM_SUBMISSIONS_SLUG = "form-submissions";
18
18
  /**
@@ -4,8 +4,6 @@ import { asTranslate, labelForKey, resolveDefinitionLabel } from "../translation
4
4
  import { localizedIf } from "../fields/localizedIf.js";
5
5
  import { validateUrl } from "../validation/validateUrl.js";
6
6
  import { normalizeCalc } from "../calc/normalizeCalc.js";
7
- import { pollConfigOf } from "../form/pollState.js";
8
- import { isLoggedIn } from "../plugin/access.js";
9
7
  import { buildActionBlocks } from "../actions/buildActionBlocks.js";
10
8
  import { calcUsesSources, resolveCalcContext } from "../calc/resolveCalcContext.js";
11
9
  import { buildConditionTypeMap } from "../conditions/conditionType.js";
@@ -14,6 +12,8 @@ import { resolveConsentStatements } from "../consent/resolveConsentStatements.js
14
12
  import { buildFieldBlocks } from "../fields/buildFieldBlocks.js";
15
13
  import { normalizeFlow } from "../flow/normalizeFlow.js";
16
14
  import { END_OF_FORM } from "../flow/types.js";
15
+ import { pollConfigOf } from "../form/pollState.js";
16
+ import { isLoggedIn } from "../plugin/access.js";
17
17
  import { buildPollOptionSourceFields } from "../poll/buildPollOptionSourceFields.js";
18
18
  import { resolvePollTypes } from "../poll/pollTypeRegistry.js";
19
19
  import { enqueuePollClose } from "../poll/closeJob.js";
@@ -1,7 +1,7 @@
1
+ import { FormContextReference, signFormContext, verifyFormContext } from "../context/formContext.js";
1
2
  import { resolveConsentStatements } from "../consent/resolveConsentStatements.js";
2
3
  import { toFormDocument } from "../form/toFormDocument.js";
3
4
  import { VotedSubmission, resolveVotedSubmission } from "../submissions/resolveVotedSubmission.js";
4
- import { FormContextReference, signFormContext, verifyFormContext } from "../context/formContext.js";
5
5
  import { isPollClosed } from "../form/pollState.js";
6
6
  import { resolveEffectivePollOptions } from "../poll/effectivePollOptions.js";
7
7
  import { resolvePollOptions } from "../poll/resolvePollOptions.js";
@@ -1,10 +1,10 @@
1
- import { isPollClosed } from "../form/pollState.js";
2
1
  import { resolveConsentStatements } from "../consent/resolveConsentStatements.js";
2
+ import { isPollClosed } from "../form/pollState.js";
3
+ import { signFormContext, verifyFormContext } from "../context/formContext.js";
4
+ import { hasVotedCookie, votedCookieName } from "../submissions/votedCookie.js";
3
5
  import { resolvePollOptions } from "../poll/resolvePollOptions.js";
4
6
  import { resolveEffectivePollOptions } from "../poll/effectivePollOptions.js";
5
7
  import { resolvePollOutcome } from "../poll/resolvePollOutcome.js";
6
- import { signFormContext, verifyFormContext } from "../context/formContext.js";
7
- import { hasVotedCookie, votedCookieName } from "../submissions/votedCookie.js";
8
8
  import { toFormDocument } from "../form/toFormDocument.js";
9
9
  import { resolveVotedSubmission } from "../submissions/resolveVotedSubmission.js";
10
10
  import { SubmissionAnswers } from "../submissions/SubmissionAnswers.js";
@@ -0,0 +1,30 @@
1
+ import { SubmissionForm } from "../actions/submissionContext.js";
2
+ import { Payload, PayloadRequest } from "payload";
3
+
4
+ //#region src/form/findFormAtLocale.d.ts
5
+ /**
6
+ * What a `fallbackLocale` resolver returns: a locale code, an ordered list of codes, `false` for no
7
+ * fallback, or `undefined` to keep the default.
8
+ */
9
+ type FormFallbackLocaleResult = string | string[] | false | undefined;
10
+ type FormFallbackLocaleArgs = {
11
+ /**
12
+ * The form as first read at `locale` with the config's own fallback, at depth 0: a non-localized
13
+ * owner relationship (a multi-tenant host's `form.tenant`) is already on it, so no read of your own
14
+ * is needed. Decide from non-localized fields: a localized one may be empty at `locale`.
15
+ */
16
+ form: SubmissionForm; /** The locale the form is being read at (the submission's, clamped). */
17
+ locale: string;
18
+ payload: Payload;
19
+ req?: PayloadRequest;
20
+ };
21
+ /**
22
+ * Host seam choosing the fallback locale per form (plugin option `fallbackLocale`), for hosts where
23
+ * the right fallback depends on the form's owner rather than on the config, e.g. a tenant whose own
24
+ * default locale is not the config-wide one. Runs before the plugin acts on a form server-side
25
+ * (validating a submission, running its actions, serving poll results).
26
+ */
27
+ type FormFallbackLocale = (args: FormFallbackLocaleArgs) => Promise<FormFallbackLocaleResult> | FormFallbackLocaleResult;
28
+ //#endregion
29
+ export { FormFallbackLocale, FormFallbackLocaleArgs, FormFallbackLocaleResult };
30
+ //# sourceMappingURL=findFormAtLocale.d.ts.map
@@ -0,0 +1,88 @@
1
+ import { customStateOf, stashCustomState } from "../plugin/customState.js";
2
+ import { FORMS_SLUG } from "../collections/forms.js";
3
+ import { sanitizeFallbackLocale } from "payload";
4
+ //#region src/form/findFormAtLocale.ts
5
+ const stashFallbackLocale = (custom, fallbackLocale) => stashCustomState(custom, { fallbackLocale });
6
+ /**
7
+ * A host `fallbackLocale` resolver threw. Kept distinct so callers that read a failed form load as a
8
+ * deleted form (and skip quietly) let this one through instead: a transient failure in host I/O must
9
+ * fail the action run (and retry it on the queued path), never drop it.
10
+ */
11
+ var FallbackLocaleError = class extends Error {
12
+ constructor(cause) {
13
+ super(`@10x-media/form-builder: fallbackLocale resolver failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
14
+ this.name = "FallbackLocaleError";
15
+ }
16
+ };
17
+ /**
18
+ * `.catch` handler for callers that treat a form that cannot be read as missing: `null` for a read
19
+ * failure, rethrowing a `FallbackLocaleError`.
20
+ */
21
+ const missingFormOnReadError = (error) => {
22
+ if (error instanceof FallbackLocaleError) throw error;
23
+ return null;
24
+ };
25
+ /**
26
+ * Loads a form (depth 0) at `locale` for server work done on a visitor's behalf: validating a
27
+ * submission, running its actions, serving poll results. The read falls back exactly like any other
28
+ * Payload read, so with `localization.fallback: false` content the author never filled in at
29
+ * `locale` stays empty, matching what the host's own page renders.
30
+ *
31
+ * With the plugin's `fallbackLocale` resolver set, it gets the form as read and may choose another
32
+ * fallback (the way a host forces one); the form is read again only when that differs from the one
33
+ * already applied.
34
+ *
35
+ * Payload's local API writes `locale` and `fallbackLocale` onto the `req` it is handed. Both are
36
+ * restored afterwards, so a host (or job runner) request passed in comes back unchanged. The restore
37
+ * assumes one operation per `req` at a time: concurrent reads sharing a `req` (a `Promise.all` of
38
+ * creates at different locales) can interleave it, so give each its own request.
39
+ */
40
+ const findFormAtLocale = async ({ payload, id, locale, req, overrideAccess }) => {
41
+ const { localization } = payload.config;
42
+ const read = (fallbackLocale) => payload.findByID({
43
+ collection: FORMS_SLUG,
44
+ id,
45
+ depth: 0,
46
+ locale,
47
+ ...fallbackLocale === void 0 ? {} : { fallbackLocale },
48
+ ...overrideAccess === void 0 ? {} : { overrideAccess },
49
+ req
50
+ });
51
+ const previous = req ? {
52
+ locale: req.locale,
53
+ fallbackLocale: req.fallbackLocale
54
+ } : void 0;
55
+ try {
56
+ if (!localization) return await read(void 0);
57
+ const form = await read(void 0);
58
+ const resolver = customStateOf(payload).fallbackLocale;
59
+ if (!resolver) return form;
60
+ let chosen;
61
+ try {
62
+ chosen = await resolver({
63
+ form,
64
+ locale,
65
+ payload,
66
+ req
67
+ });
68
+ } catch (error) {
69
+ throw new FallbackLocaleError(error);
70
+ }
71
+ const applied = sanitizeFallbackLocale({
72
+ fallbackLocale: void 0,
73
+ locale,
74
+ localization
75
+ });
76
+ if (chosen === void 0 || chosen === locale || chosen === applied) return form;
77
+ return await read(chosen);
78
+ } finally {
79
+ if (req && previous) {
80
+ req.locale = previous.locale;
81
+ req.fallbackLocale = previous.fallbackLocale;
82
+ }
83
+ }
84
+ };
85
+ //#endregion
86
+ export { findFormAtLocale, missingFormOnReadError, stashFallbackLocale };
87
+
88
+ //# sourceMappingURL=findFormAtLocale.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"findFormAtLocale.js","names":[],"sources":["../../src/form/findFormAtLocale.ts"],"sourcesContent":["import {\n\ttype Payload,\n\ttype PayloadRequest,\n\tsanitizeFallbackLocale,\n\ttype TypedFallbackLocale,\n\ttype TypedLocale,\n} from 'payload'\nimport type { SubmissionForm } from '../actions/submissionContext'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { customStateOf, stashCustomState } from '../plugin/customState'\n\n/**\n * What a `fallbackLocale` resolver returns: a locale code, an ordered list of codes, `false` for no\n * fallback, or `undefined` to keep the default.\n */\nexport type FormFallbackLocaleResult = string | string[] | false | undefined\n\nexport type FormFallbackLocaleArgs = {\n\t/**\n\t * The form as first read at `locale` with the config's own fallback, at depth 0: a non-localized\n\t * owner relationship (a multi-tenant host's `form.tenant`) is already on it, so no read of your own\n\t * is needed. Decide from non-localized fields: a localized one may be empty at `locale`.\n\t */\n\tform: SubmissionForm\n\t/** The locale the form is being read at (the submission's, clamped). */\n\tlocale: string\n\tpayload: Payload\n\treq?: PayloadRequest\n}\n\n/**\n * Host seam choosing the fallback locale per form (plugin option `fallbackLocale`), for hosts where\n * the right fallback depends on the form's owner rather than on the config, e.g. a tenant whose own\n * default locale is not the config-wide one. Runs before the plugin acts on a form server-side\n * (validating a submission, running its actions, serving poll results).\n */\nexport type FormFallbackLocale = (\n\targs: FormFallbackLocaleArgs\n) => Promise<FormFallbackLocaleResult> | FormFallbackLocaleResult\n\ntype FallbackState = { fallbackLocale?: FormFallbackLocale }\n\nexport const stashFallbackLocale = (\n\tcustom: Record<string, unknown> | undefined,\n\tfallbackLocale: FormFallbackLocale\n): Record<string, unknown> => stashCustomState<FallbackState>(custom, { fallbackLocale })\n\nexport type FindFormAtLocaleArgs = {\n\tpayload: Payload\n\tid: number | string\n\t/** A clamped locale (see `resolveSubmissionLocale`), never raw visitor input. */\n\tlocale: string\n\treq?: PayloadRequest\n\toverrideAccess?: boolean\n}\n\n/**\n * A host `fallbackLocale` resolver threw. Kept distinct so callers that read a failed form load as a\n * deleted form (and skip quietly) let this one through instead: a transient failure in host I/O must\n * fail the action run (and retry it on the queued path), never drop it.\n */\nexport class FallbackLocaleError extends Error {\n\tconstructor(cause: unknown) {\n\t\tsuper(\n\t\t\t`@10x-media/form-builder: fallbackLocale resolver failed: ${\n\t\t\t\tcause instanceof Error ? cause.message : String(cause)\n\t\t\t}`,\n\t\t\t{ cause }\n\t\t)\n\t\tthis.name = 'FallbackLocaleError'\n\t}\n}\n\n/**\n * `.catch` handler for callers that treat a form that cannot be read as missing: `null` for a read\n * failure, rethrowing a `FallbackLocaleError`.\n */\nexport const missingFormOnReadError = (error: unknown): null => {\n\tif (error instanceof FallbackLocaleError) {\n\t\tthrow error\n\t}\n\treturn null\n}\n\n/**\n * Loads a form (depth 0) at `locale` for server work done on a visitor's behalf: validating a\n * submission, running its actions, serving poll results. The read falls back exactly like any other\n * Payload read, so with `localization.fallback: false` content the author never filled in at\n * `locale` stays empty, matching what the host's own page renders.\n *\n * With the plugin's `fallbackLocale` resolver set, it gets the form as read and may choose another\n * fallback (the way a host forces one); the form is read again only when that differs from the one\n * already applied.\n *\n * Payload's local API writes `locale` and `fallbackLocale` onto the `req` it is handed. Both are\n * restored afterwards, so a host (or job runner) request passed in comes back unchanged. The restore\n * assumes one operation per `req` at a time: concurrent reads sharing a `req` (a `Promise.all` of\n * creates at different locales) can interleave it, so give each its own request.\n */\nexport const findFormAtLocale = async ({\n\tpayload,\n\tid,\n\tlocale,\n\treq,\n\toverrideAccess,\n}: FindFormAtLocaleArgs) => {\n\tconst { localization } = payload.config\n\tconst read = (fallbackLocale: string | string[] | false | undefined) =>\n\t\tpayload.findByID({\n\t\t\tcollection: FORMS_SLUG,\n\t\t\tid,\n\t\t\tdepth: 0,\n\t\t\t// Cast: a clamped locale is one of the host's own codes, but its concrete `TypedLocale` union\n\t\t\t// is unknowable from the plugin.\n\t\t\tlocale: locale as TypedLocale,\n\t\t\t...(fallbackLocale === undefined ? {} : { fallbackLocale: fallbackLocale as TypedLocale }),\n\t\t\t...(overrideAccess === undefined ? {} : { overrideAccess }),\n\t\t\treq,\n\t\t})\n\tconst previous = req ? { locale: req.locale, fallbackLocale: req.fallbackLocale } : undefined\n\ttry {\n\t\tif (!localization) {\n\t\t\treturn await read(undefined)\n\t\t}\n\t\tconst form = await read(undefined)\n\t\tconst resolver = customStateOf<FallbackState>(payload).fallbackLocale\n\t\tif (!resolver) {\n\t\t\treturn form\n\t\t}\n\t\tlet chosen: FormFallbackLocaleResult\n\t\ttry {\n\t\t\tchosen = await resolver({\n\t\t\t\t// Double cast: a host's generated Form interface has no index signature.\n\t\t\t\tform: form as unknown as SubmissionForm,\n\t\t\t\tlocale,\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthrow new FallbackLocaleError(error)\n\t\t}\n\t\t// Falling back to the read's own locale, or to the fallback Payload already applied (resolved by\n\t\t// Payload's own sanitizer, so the two cannot drift), changes nothing.\n\t\tconst applied = sanitizeFallbackLocale({\n\t\t\tfallbackLocale: undefined as unknown as TypedFallbackLocale,\n\t\t\tlocale,\n\t\t\tlocalization,\n\t\t})\n\t\tif (chosen === undefined || chosen === locale || chosen === applied) {\n\t\t\treturn form\n\t\t}\n\t\treturn await read(chosen)\n\t} finally {\n\t\tif (req && previous) {\n\t\t\treq.locale = previous.locale\n\t\t\treq.fallbackLocale = previous.fallbackLocale\n\t\t}\n\t}\n}\n"],"mappings":";;;;AA0CA,MAAa,uBACZ,QACA,mBAC6B,iBAAgC,QAAQ,EAAE,eAAe,CAAC;;;;;;AAgBxF,IAAa,sBAAb,cAAyC,MAAM;CAC9C,YAAY,OAAgB;EAC3B,MACC,4DACC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAEtD,EAAE,MAAM,CACT;EACA,KAAK,OAAO;CACb;AACD;;;;;AAMA,MAAa,0BAA0B,UAAyB;CAC/D,IAAI,iBAAiB,qBACpB,MAAM;CAEP,OAAO;AACR;;;;;;;;;;;;;;;;AAiBA,MAAa,mBAAmB,OAAO,EACtC,SACA,IACA,QACA,KACA,qBAC2B;CAC3B,MAAM,EAAE,iBAAiB,QAAQ;CACjC,MAAM,QAAQ,mBACb,QAAQ,SAAS;EAChB,YAAY;EACZ;EACA,OAAO;EAGC;EACR,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAkB,eAA8B;EACxF,GAAI,mBAAmB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe;EACzD;CACD,CAAC;CACF,MAAM,WAAW,MAAM;EAAE,QAAQ,IAAI;EAAQ,gBAAgB,IAAI;CAAe,IAAI,KAAA;CACpF,IAAI;EACH,IAAI,CAAC,cACJ,OAAO,MAAM,KAAK,KAAA,CAAS;EAE5B,MAAM,OAAO,MAAM,KAAK,KAAA,CAAS;EACjC,MAAM,WAAW,cAA6B,OAAO,EAAE;EACvD,IAAI,CAAC,UACJ,OAAO;EAER,IAAI;EACJ,IAAI;GACH,SAAS,MAAM,SAAS;IAEjB;IACN;IACA;IACA;GACD,CAAC;EACF,SAAS,OAAO;GACf,MAAM,IAAI,oBAAoB,KAAK;EACpC;EAGA,MAAM,UAAU,uBAAuB;GACtC,gBAAgB,KAAA;GAChB;GACA;EACD,CAAC;EACD,IAAI,WAAW,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