@10x-media/form-builder 0.1.0-beta.10 → 0.1.0-beta.12
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.
- package/CHANGELOG.md +25 -0
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +3 -1
- package/dist/actions/builtin/emailAction.js +43 -12
- package/dist/actions/builtin/emailAction.js.map +1 -1
- package/dist/actions/builtin/emailTeam.js +11 -5
- package/dist/actions/builtin/emailTeam.js.map +1 -1
- package/dist/actions/defineAction.d.ts +3 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.js +1 -1
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/emailRecipients.js +34 -7
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +34 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/task.js +20 -0
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +32 -3
- package/dist/aggregation/resolveResultsRequest.js.map +1 -1
- package/dist/calc/computeCalcFields.d.ts +5 -3
- package/dist/calc/computeCalcFields.js +4 -3
- package/dist/calc/computeCalcFields.js.map +1 -1
- package/dist/calc/evaluate.d.ts +26 -3
- package/dist/calc/evaluate.js +33 -11
- package/dist/calc/evaluate.js.map +1 -1
- package/dist/calc/formatCalc.d.ts +11 -0
- package/dist/calc/formatCalc.js +35 -0
- package/dist/calc/formatCalc.js.map +1 -0
- package/dist/calc/formatCalcValue.d.ts +17 -0
- package/dist/calc/formatCalcValue.js +17 -0
- package/dist/calc/formatCalcValue.js.map +1 -0
- package/dist/calc/normalizeCalc.d.ts +17 -3
- package/dist/calc/normalizeCalc.js +39 -17
- package/dist/calc/normalizeCalc.js.map +1 -1
- package/dist/calc/registry.d.ts +43 -0
- package/dist/calc/registry.js +27 -0
- package/dist/calc/registry.js.map +1 -0
- package/dist/calc/resolveCalcContext.d.ts +36 -0
- package/dist/calc/resolveCalcContext.js +87 -0
- package/dist/calc/resolveCalcContext.js.map +1 -0
- package/dist/calc/types.d.ts +18 -3
- package/dist/calc/types.js +2 -1
- package/dist/calc/types.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +890 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/RecipientsSelect.d.ts +5 -1
- package/dist/client/RecipientsSelect.js +22 -3
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +282 -0
- package/dist/collections/formSubmissions.js +34 -16
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +59 -27
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +4 -2
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +31 -0
- package/dist/collections/settingsFields.js +45 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/context/formContext.d.ts +30 -0
- package/dist/context/formContext.js +54 -0
- package/dist/context/formContext.js.map +1 -0
- package/dist/exports/client.d.ts +2 -1
- package/dist/exports/client.js +2 -1
- package/dist/exports/react.d.ts +7 -3
- package/dist/exports/react.js +6 -2
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/rsc.js +3 -2
- package/dist/exports/types.d.ts +1 -1
- package/dist/fields/buildFieldBlocks.js +2 -1
- package/dist/fields/buildFieldBlocks.js.map +1 -1
- package/dist/fields/builtin/calculation.d.ts +17 -0
- package/dist/fields/builtin/calculation.js +170 -115
- package/dist/fields/builtin/calculation.js.map +1 -1
- package/dist/fields/builtin/checkbox.js +15 -0
- package/dist/fields/builtin/checkbox.js.map +1 -1
- package/dist/fields/builtin/email.js +7 -0
- package/dist/fields/builtin/email.js.map +1 -1
- package/dist/fields/builtin/index.d.ts +6 -2
- package/dist/fields/builtin/index.js +9 -4
- package/dist/fields/builtin/index.js.map +1 -1
- package/dist/fields/builtin/select.js +20 -1
- package/dist/fields/builtin/select.js.map +1 -1
- package/dist/fields/builtin/text.js +7 -0
- package/dist/fields/builtin/text.js.map +1 -1
- package/dist/fields/instanceOptions.js +1 -1
- package/dist/fields/instanceOptions.js.map +1 -1
- package/dist/fields/sharedConfig.js +15 -11
- package/dist/fields/sharedConfig.js.map +1 -1
- package/dist/fields/types.d.ts +8 -2
- package/dist/form/toFormDocument.d.ts +7 -0
- package/dist/form/toFormDocument.js +2 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +7 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.js +40 -9
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +42 -0
- package/dist/plugin/registerCollections.js +29 -19
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +6 -4
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +2 -1
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +17 -3
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +53 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +72 -0
- package/dist/poll/votes/bumpPollVote.js.map +1 -0
- package/dist/poll/votes/recountPollVotes.d.ts +20 -0
- package/dist/poll/votes/recountPollVotes.js +63 -0
- package/dist/poll/votes/recountPollVotes.js.map +1 -0
- package/dist/poll/votes/voteTallyHook.js +58 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +19 -0
- package/dist/poll/votes/votesCollection.js +89 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +15 -1
- package/dist/react/Form.js +24 -3
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +8 -1
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/primitives/Checkbox.d.ts +4 -2
- package/dist/react/primitives/Checkbox.js +3 -2
- package/dist/react/primitives/Checkbox.js.map +1 -1
- package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
- package/dist/react/primitives/ChoiceGroup.js +33 -0
- package/dist/react/primitives/ChoiceGroup.js.map +1 -0
- package/dist/react/primitives/FieldShell.d.ts +11 -1
- package/dist/react/primitives/FieldShell.js +43 -33
- package/dist/react/primitives/FieldShell.js.map +1 -1
- package/dist/react/primitives/Input.d.ts +3 -1
- package/dist/react/primitives/Input.js +2 -1
- package/dist/react/primitives/Input.js.map +1 -1
- package/dist/react/renderers/calculation.js +6 -1
- package/dist/react/renderers/calculation.js.map +1 -1
- package/dist/react/renderers/checkbox.js +2 -1
- package/dist/react/renderers/checkbox.js.map +1 -1
- package/dist/react/renderers/email.js +3 -1
- package/dist/react/renderers/email.js.map +1 -1
- package/dist/react/renderers/select.js +20 -2
- package/dist/react/renderers/select.js.map +1 -1
- package/dist/react/renderers/text.js +3 -1
- package/dist/react/renderers/text.js.map +1 -1
- package/dist/react/useCalcValues.d.ts +10 -0
- package/dist/react/useCalcValues.js +13 -0
- package/dist/react/useCalcValues.js.map +1 -0
- package/dist/recall/resolver.js +1 -1
- package/dist/recall/resolver.js.map +1 -1
- package/dist/spam/constants.js +7 -1
- package/dist/spam/constants.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/runSubmission.js +3 -3
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/validateSubmission.js +26 -2
- package/dist/submissions/validateSubmission.js.map +1 -1
- package/dist/submissions/verifyContext.js +35 -0
- package/dist/submissions/verifyContext.js.map +1 -0
- package/dist/translations/de.js +62 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +62 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/keys.d.ts +60 -1
- package/dist/translations/keys.js +60 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/validation/builtin/index.js +2 -0
- package/dist/validation/builtin/index.js.map +1 -1
- package/dist/validation/builtin/integer.js +15 -0
- package/dist/validation/builtin/integer.js.map +1 -0
- package/package.json +11 -5
- package/styles/form-builder.css +84 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bumpPollVote.js","names":[],"sources":["../../../src/poll/votes/bumpPollVote.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { POLL_VOTES_SLUG, VOTE_SHARDS } from './votesCollection'\n\nconst PG_TABLE_KEY = 'form_poll_votes'\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n\tsessions?: Record<number | string, unknown>\n}\ntype PgInsert = {\n\tinsert: (t: unknown) => {\n\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t}\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: PgInsert\n\tsessions?: Record<number | string, { db: PgInsert }>\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\n/**\n * Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment\n * statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique\n * compound index makes concurrent bumps for the same key safe without read-modify-write races.\n * The shard column is internal: transactional Mongo bumps pick a random shard in\n * [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);\n * Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.\n *\n * When `transactionID` names an open Payload transaction, the write joins it: a bump failure\n * thrown from the submission hook rolls back the submission create (no undercount), and an\n * aborted create rolls back the joined bump (no overcount). Residual risk on transactional\n * Mongo: two concurrent bumps that land on the same shard still abort one transaction\n * (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,\n * so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.\n * Mongo with transactions disabled) the write lands on the root handle immediately; a later\n * recount from stored submissions is the healer for any drift that window allows.\n */\n// biome-ignore lint/complexity/useMaxParams: write primitive signature (payload, key, by, transactionID)\nexport async function bumpPollVote(\n\tpayload: Payload,\n\tkey: { form: string; field: string; value: string },\n\tby: number,\n\ttransactionID?: number | string\n): Promise<void> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[POLL_VOTES_SLUG]\n\t\tif (!model) throw new Error(`form-builder: mongoose collection \"${POLL_VOTES_SLUG}\" not found`)\n\t\tconst session = transactionID !== undefined ? db.sessions?.[transactionID] : undefined\n\t\tconst shard = session ? Math.floor(Math.random() * VOTE_SHARDS) : 0\n\t\tconst shardedKey = { ...key, shard }\n\t\tconst update = { $inc: { count: by }, $setOnInsert: shardedKey }\n\t\tconst options = session ? { upsert: true, session } : { upsert: true }\n\t\ttry {\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t} catch (error) {\n\t\t\t// Concurrent first inserts for a new key can race the upsert into E11000; outside a\n\t\t\t// transaction the row now exists, so one retry takes the $inc branch. Inside a\n\t\t\t// transaction the error propagates and Payload's rollback/retry semantics apply.\n\t\t\tconst duplicate = (error as { code?: unknown } | null)?.code === 11000\n\t\t\tif (session || !duplicate) throw error\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t}\n\t\treturn\n\t}\n\tconst { sql } = await import('@payloadcms/db-postgres')\n\tconst db = payload.db as unknown as PgDb\n\tconst tableName = db.tableNameMap.get(PG_TABLE_KEY)\n\tif (!tableName) throw new Error(`form-builder: drizzle table \"${PG_TABLE_KEY}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`form-builder: drizzle table object for \"${tableName}\" not found`)\n\tconst txn = transactionID !== undefined ? db.sessions?.[transactionID]?.db : undefined\n\tawait (txn ?? db.drizzle)\n\t\t.insert(table)\n\t\t.values({ ...key, shard: 0, count: by })\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: [table.form, table.field, table.value, table.shard],\n\t\t\tset: { count: sql`${table.count} + ${by}` },\n\t\t})\n}\n"],"mappings":";;AAGA,MAAM,eAAe;;;;;;;;;;;;;;;;;;AA2CrB,eAAsB,aACrB,SACA,KACA,IACA,eACgB;CAChB,IAAI,QAAQ,GAAG,SAAS,YAAY;EACnC,MAAM,KAAK,QAAQ;EACnB,MAAM,QAAQ,GAAG,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,sCAAsC,gBAAgB,YAAY;EAC9F,MAAM,UAAU,kBAAkB,KAAA,IAAY,GAAG,WAAW,iBAAiB,KAAA;EAC7E,MAAM,QAAQ,UAAU,KAAK,MAAM,KAAK,OAAO,IAAA,CAAe,IAAI;EAClE,MAAM,aAAa;GAAE,GAAG;GAAK;EAAM;EACnC,MAAM,SAAS;GAAE,MAAM,EAAE,OAAO,GAAG;GAAG,cAAc;EAAW;EAC/D,MAAM,UAAU,UAAU;GAAE,QAAQ;GAAM;EAAQ,IAAI,EAAE,QAAQ,KAAK;EACrE,IAAI;GACH,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D,SAAS,OAAO;GAIf,MAAM,YAAa,OAAqC,SAAS;GACjE,IAAI,WAAW,CAAC,WAAW,MAAM;GACjC,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,OAAO;CAC7B,MAAM,KAAK,QAAQ;CACnB,MAAM,YAAY,GAAG,aAAa,IAAI,YAAY;CAClD,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,gCAAgC,aAAa,YAAY;CACzF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,2CAA2C,UAAU,YAAY;CAE7F,QADY,kBAAkB,KAAA,IAAY,GAAG,WAAW,gBAAgB,KAAK,KAAA,MAC/D,GAAG,SACf,OAAO,KAAK,EACZ,OAAO;EAAE,GAAG;EAAK,OAAO;EAAG,OAAO;CAAG,CAAC,EACtC,mBAAmB;EACnB,QAAQ;GAAC,MAAM;GAAM,MAAM;GAAO,MAAM;GAAO,MAAM;EAAK;EAC1D,KAAK,EAAE,OAAO,GAAG,GAAG,MAAM,MAAM,KAAK,KAAK;CAC3C,CAAC;AACH"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Payload, PayloadRequest } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/poll/votes/recountPollVotes.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
|
|
6
|
+
* changes, or backfill after enabling a poll late). Scans first and refuses a truncated
|
|
7
|
+
* aggregation, then deletes the form's tally rows for the results field and replays the scan
|
|
8
|
+
* into fresh rows, so the store is never left holding a knowingly partial count. Writes join
|
|
9
|
+
* the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
|
|
10
|
+
* its submissions are pruned, so the tally store is the only record of its votes and a rebuild
|
|
11
|
+
* would wipe them.
|
|
12
|
+
*/
|
|
13
|
+
declare const recountPollVotes: (args: {
|
|
14
|
+
payload: Payload;
|
|
15
|
+
formId: number | string;
|
|
16
|
+
req?: PayloadRequest;
|
|
17
|
+
}) => Promise<void>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { recountPollVotes };
|
|
20
|
+
//# sourceMappingURL=recountPollVotes.d.ts.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { pollConfigOf } from "../../form/pollState.js";
|
|
2
|
+
import { aggregateFieldResponses } from "../../aggregation/aggregateResponses.js";
|
|
3
|
+
import { POLL_VOTES_SLUG } from "./votesCollection.js";
|
|
4
|
+
import { FORMS_SLUG } from "../../collections/forms.js";
|
|
5
|
+
import { bumpPollVote } from "./bumpPollVote.js";
|
|
6
|
+
import { transactionIDOf } from "./voteTallyHook.js";
|
|
7
|
+
//#region src/poll/votes/recountPollVotes.ts
|
|
8
|
+
const RECOUNT_MAX_SUBMISSIONS = 1e5;
|
|
9
|
+
/**
|
|
10
|
+
* Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
|
|
11
|
+
* changes, or backfill after enabling a poll late). Scans first and refuses a truncated
|
|
12
|
+
* aggregation, then deletes the form's tally rows for the results field and replays the scan
|
|
13
|
+
* into fresh rows, so the store is never left holding a knowingly partial count. Writes join
|
|
14
|
+
* the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
|
|
15
|
+
* its submissions are pruned, so the tally store is the only record of its votes and a rebuild
|
|
16
|
+
* would wipe them.
|
|
17
|
+
*/
|
|
18
|
+
const recountPollVotes = async (args) => {
|
|
19
|
+
const { payload, formId, req } = args;
|
|
20
|
+
const form = await payload.findByID({
|
|
21
|
+
collection: FORMS_SLUG,
|
|
22
|
+
id: formId,
|
|
23
|
+
depth: 0,
|
|
24
|
+
overrideAccess: true,
|
|
25
|
+
req
|
|
26
|
+
}).catch(() => null);
|
|
27
|
+
const poll = form ? pollConfigOf(form.poll) : void 0;
|
|
28
|
+
const resultsField = typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
|
|
29
|
+
if (!resultsField) return;
|
|
30
|
+
if (form?.persistSubmissions === false) throw new Error(`form-builder: recountPollVotes cannot rebuild form "${String(formId)}": it does not persist submissions, so the tally store is the only record of its votes.`);
|
|
31
|
+
const aggregation = await aggregateFieldResponses({
|
|
32
|
+
payload,
|
|
33
|
+
formId,
|
|
34
|
+
field: resultsField,
|
|
35
|
+
req,
|
|
36
|
+
maxSubmissions: RECOUNT_MAX_SUBMISSIONS
|
|
37
|
+
});
|
|
38
|
+
if (aggregation?.truncated) throw new Error(`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`);
|
|
39
|
+
await payload.delete({
|
|
40
|
+
collection: POLL_VOTES_SLUG,
|
|
41
|
+
where: { and: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }] },
|
|
42
|
+
overrideAccess: true,
|
|
43
|
+
req
|
|
44
|
+
});
|
|
45
|
+
if (!aggregation) return;
|
|
46
|
+
const transactionID = transactionIDOf(req?.transactionID);
|
|
47
|
+
const base = {
|
|
48
|
+
form: String(formId),
|
|
49
|
+
field: resultsField
|
|
50
|
+
};
|
|
51
|
+
for (const bucket of aggregation.buckets) if (bucket.count > 0) await bumpPollVote(payload, {
|
|
52
|
+
...base,
|
|
53
|
+
value: bucket.value
|
|
54
|
+
}, bucket.count, transactionID);
|
|
55
|
+
if (aggregation.total > 0) await bumpPollVote(payload, {
|
|
56
|
+
...base,
|
|
57
|
+
value: ""
|
|
58
|
+
}, aggregation.total, transactionID);
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { recountPollVotes };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=recountPollVotes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recountPollVotes.js","names":[],"sources":["../../../src/poll/votes/recountPollVotes.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { aggregateFieldResponses } from '../../aggregation/aggregateResponses'\nimport { FORMS_SLUG } from '../../collections/forms'\nimport { pollConfigOf } from '../../form/pollState'\nimport { bumpPollVote } from './bumpPollVote'\nimport { POLL_VOTES_SLUG, RESPONDENTS_VALUE } from './votesCollection'\nimport { transactionIDOf } from './voteTallyHook'\n\nconst RECOUNT_MAX_SUBMISSIONS = 100_000\n\n/**\n * Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB\n * changes, or backfill after enabling a poll late). Scans first and refuses a truncated\n * aggregation, then deletes the form's tally rows for the results field and replays the scan\n * into fresh rows, so the store is never left holding a knowingly partial count. Writes join\n * the request's transaction when one is open. Refuses a form with `persistSubmissions` off:\n * its submissions are pruned, so the tally store is the only record of its votes and a rebuild\n * would wipe them.\n */\nexport const recountPollVotes = async (args: {\n\tpayload: Payload\n\tformId: number | string\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, formId, req } = args\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tconst poll = form ? pollConfigOf(form.poll) : undefined\n\tconst resultsField =\n\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t? poll.resultsField\n\t\t\t: undefined\n\tif (!resultsField) {\n\t\treturn\n\t}\n\tif (form?.persistSubmissions === false) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recountPollVotes cannot rebuild form \"${String(formId)}\": it does not persist submissions, so the tally store is the only record of its votes.`\n\t\t)\n\t}\n\tconst aggregation = await aggregateFieldResponses({\n\t\tpayload,\n\t\tformId,\n\t\tfield: resultsField,\n\t\treq,\n\t\tmaxSubmissions: RECOUNT_MAX_SUBMISSIONS,\n\t})\n\tif (aggregation?.truncated) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`\n\t\t)\n\t}\n\tawait payload.delete({\n\t\tcollection: POLL_VOTES_SLUG,\n\t\twhere: {\n\t\t\tand: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }],\n\t\t},\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\tif (!aggregation) {\n\t\treturn\n\t}\n\tconst transactionID = transactionIDOf(req?.transactionID)\n\tconst base = { form: String(formId), field: resultsField }\n\tfor (const bucket of aggregation.buckets) {\n\t\tif (bucket.count > 0) {\n\t\t\tawait bumpPollVote(payload, { ...base, value: bucket.value }, bucket.count, transactionID)\n\t\t}\n\t}\n\tif (aggregation.total > 0) {\n\t\tawait bumpPollVote(\n\t\t\tpayload,\n\t\t\t{ ...base, value: RESPONDENTS_VALUE },\n\t\t\taggregation.total,\n\t\t\ttransactionID\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;AAQA,MAAM,0BAA0B;;;;;;;;;;AAWhC,MAAa,mBAAmB,OAAO,SAIlB;CACpB,MAAM,EAAE,SAAS,QAAQ,QAAQ;CACjC,MAAM,OAAO,MAAM,QACjB,SAAS;EAAE,YAAY;EAAY,IAAI;EAAQ,OAAO;EAAG,gBAAgB;EAAM;CAAI,CAAC,EACpF,YAAY,IAAI;CAClB,MAAM,OAAO,OAAO,aAAa,KAAK,IAAI,IAAI,KAAA;CAC9C,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SAAS,IAClE,KAAK,eACL,KAAA;CACJ,IAAI,CAAC,cACJ;CAED,IAAI,MAAM,uBAAuB,OAChC,MAAM,IAAI,MACT,uDAAuD,OAAO,MAAM,EAAE,wFACvE;CAED,MAAM,cAAc,MAAM,wBAAwB;EACjD;EACA;EACA,OAAO;EACP;EACA,gBAAgB;CACjB,CAAC;CACD,IAAI,aAAa,WAChB,MAAM,IAAI,MACT,kCAAkC,OAAO,MAAM,EAAE,sBAAsB,wBAAwB,2EAChG;CAED,MAAM,QAAQ,OAAO;EACpB,YAAY;EACZ,OAAO,EACN,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,aAAa,EAAE,CAAC,EAChF;EACA,gBAAgB;EAChB;CACD,CAAC;CACD,IAAI,CAAC,aACJ;CAED,MAAM,gBAAgB,gBAAgB,KAAK,aAAa;CACxD,MAAM,OAAO;EAAE,MAAM,OAAO,MAAM;EAAG,OAAO;CAAa;CACzD,KAAK,MAAM,UAAU,YAAY,SAChC,IAAI,OAAO,QAAQ,GAClB,MAAM,aAAa,SAAS;EAAE,GAAG;EAAM,OAAO,OAAO;CAAM,GAAG,OAAO,OAAO,aAAa;CAG3F,IAAI,YAAY,QAAQ,GACvB,MAAM,aACL,SACA;EAAE,GAAG;EAAM,OAAA;CAAyB,GACpC,YAAY,OACZ,aACD;AAEF"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { pollConfigOf } from "../../form/pollState.js";
|
|
2
|
+
import "./votesCollection.js";
|
|
3
|
+
import { FORMS_SLUG } from "../../collections/forms.js";
|
|
4
|
+
import { formIdOf } from "../../submissions/formIdOf.js";
|
|
5
|
+
import { bumpPollVote } from "./bumpPollVote.js";
|
|
6
|
+
//#region src/poll/votes/voteTallyHook.ts
|
|
7
|
+
const isComplete = (doc) => doc.status == null || doc.status === "complete";
|
|
8
|
+
const answerValues = (values, field) => {
|
|
9
|
+
if (!Array.isArray(values)) return [];
|
|
10
|
+
const entry = values.find((row) => row.field === field);
|
|
11
|
+
if (entry == null) return [];
|
|
12
|
+
return (Array.isArray(entry.value) ? entry.value : [entry.value]).filter((value) => value != null && value !== "").map((value) => String(value));
|
|
13
|
+
};
|
|
14
|
+
/** Narrow a request's loosely typed `transactionID` to the value `bumpPollVote` accepts. */
|
|
15
|
+
const transactionIDOf = (transactionID) => typeof transactionID === "number" || typeof transactionID === "string" ? transactionID : void 0;
|
|
16
|
+
/**
|
|
17
|
+
* Append-only vote counting: a submission entering `complete` bumps one tally per answer value
|
|
18
|
+
* for the poll results field, plus the shared respondents row. Votes are permanent by design:
|
|
19
|
+
* no decrement on delete, edit, or prune, which is what lets a pruned submission's vote
|
|
20
|
+
* survive. Bump failures propagate so the enclosing transaction rolls the submission back
|
|
21
|
+
* rather than silently undercounting; registered before the swallow-all dispatch hook.
|
|
22
|
+
*/
|
|
23
|
+
const makeVoteTallyHook = () => async ({ doc, previousDoc, operation, req }) => {
|
|
24
|
+
if (operation !== "create" && operation !== "update") return doc;
|
|
25
|
+
if (!(operation === "create" && isComplete(doc) || operation === "update" && isComplete(doc) && !isComplete(previousDoc ?? {}))) return doc;
|
|
26
|
+
const formId = formIdOf(doc.form);
|
|
27
|
+
if (formId == null) return doc;
|
|
28
|
+
const form = await req.payload.findByID({
|
|
29
|
+
collection: FORMS_SLUG,
|
|
30
|
+
id: formId,
|
|
31
|
+
depth: 0,
|
|
32
|
+
overrideAccess: true,
|
|
33
|
+
req
|
|
34
|
+
}).catch(() => null);
|
|
35
|
+
const poll = form?.pollEnabled === true ? pollConfigOf(form.poll) : void 0;
|
|
36
|
+
const resultsField = typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
|
|
37
|
+
if (!resultsField) return doc;
|
|
38
|
+
const votes = answerValues(doc.values, resultsField);
|
|
39
|
+
if (votes.length === 0) return doc;
|
|
40
|
+
const transactionID = transactionIDOf(req.transactionID);
|
|
41
|
+
const base = {
|
|
42
|
+
form: String(formId),
|
|
43
|
+
field: resultsField
|
|
44
|
+
};
|
|
45
|
+
for (const value of votes) await bumpPollVote(req.payload, {
|
|
46
|
+
...base,
|
|
47
|
+
value
|
|
48
|
+
}, 1, transactionID);
|
|
49
|
+
await bumpPollVote(req.payload, {
|
|
50
|
+
...base,
|
|
51
|
+
value: ""
|
|
52
|
+
}, 1, transactionID);
|
|
53
|
+
return doc;
|
|
54
|
+
};
|
|
55
|
+
//#endregion
|
|
56
|
+
export { makeVoteTallyHook, transactionIDOf };
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=voteTallyHook.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"voteTallyHook.js","names":[],"sources":["../../../src/poll/votes/voteTallyHook.ts"],"sourcesContent":["import type { CollectionAfterChangeHook } from 'payload'\nimport { FORMS_SLUG } from '../../collections/forms'\nimport { pollConfigOf } from '../../form/pollState'\nimport { formIdOf } from '../../submissions/formIdOf'\nimport type { SubmissionValue } from '../../submissions/types'\nimport { bumpPollVote } from './bumpPollVote'\nimport { RESPONDENTS_VALUE } from './votesCollection'\n\nconst isComplete = (doc: { status?: unknown }): boolean =>\n\tdoc.status == null || doc.status === 'complete'\n\nconst answerValues = (values: unknown, field: string): string[] => {\n\tif (!Array.isArray(values)) return []\n\tconst entry = (values as SubmissionValue[]).find((row) => row.field === field)\n\tif (entry == null) return []\n\tconst raw = Array.isArray(entry.value) ? entry.value : [entry.value]\n\treturn raw.filter((value) => value != null && value !== '').map((value) => String(value))\n}\n\n/** Narrow a request's loosely typed `transactionID` to the value `bumpPollVote` accepts. */\nexport const transactionIDOf = (transactionID: unknown): number | string | undefined =>\n\ttypeof transactionID === 'number' || typeof transactionID === 'string' ? transactionID : undefined\n\n/**\n * Append-only vote counting: a submission entering `complete` bumps one tally per answer value\n * for the poll results field, plus the shared respondents row. Votes are permanent by design:\n * no decrement on delete, edit, or prune, which is what lets a pruned submission's vote\n * survive. Bump failures propagate so the enclosing transaction rolls the submission back\n * rather than silently undercounting; registered before the swallow-all dispatch hook.\n */\nexport const makeVoteTallyHook =\n\t(): CollectionAfterChangeHook =>\n\tasync ({ doc, previousDoc, operation, req }) => {\n\t\tif (operation !== 'create' && operation !== 'update') return doc\n\t\tconst entering =\n\t\t\t(operation === 'create' && isComplete(doc)) ||\n\t\t\t(operation === 'update' && isComplete(doc) && !isComplete(previousDoc ?? {}))\n\t\tif (!entering) return doc\n\t\tconst formId = formIdOf(doc.form)\n\t\tif (formId == null) return doc\n\t\tconst form = await req.payload\n\t\t\t.findByID({ collection: FORMS_SLUG, id: formId, depth: 0, overrideAccess: true, req })\n\t\t\t.catch(() => null)\n\t\tconst poll = form?.pollEnabled === true ? pollConfigOf(form.poll) : undefined\n\t\tconst resultsField =\n\t\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t? poll.resultsField\n\t\t\t\t: undefined\n\t\tif (!resultsField) return doc\n\t\tconst votes = answerValues(doc.values, resultsField)\n\t\tif (votes.length === 0) return doc\n\t\tconst transactionID = transactionIDOf(req.transactionID)\n\t\tconst base = { form: String(formId), field: resultsField }\n\t\tfor (const value of votes) {\n\t\t\tawait bumpPollVote(req.payload, { ...base, value }, 1, transactionID)\n\t\t}\n\t\tawait bumpPollVote(req.payload, { ...base, value: RESPONDENTS_VALUE }, 1, transactionID)\n\t\treturn doc\n\t}\n"],"mappings":";;;;;;AAQA,MAAM,cAAc,QACnB,IAAI,UAAU,QAAQ,IAAI,WAAW;AAEtC,MAAM,gBAAgB,QAAiB,UAA4B;CAClE,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC;CACpC,MAAM,QAAS,OAA6B,MAAM,QAAQ,IAAI,UAAU,KAAK;CAC7E,IAAI,SAAS,MAAM,OAAO,CAAC;CAE3B,QADY,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,GACxD,QAAQ,UAAU,SAAS,QAAQ,UAAU,EAAE,EAAE,KAAK,UAAU,OAAO,KAAK,CAAC;AACzF;;AAGA,MAAa,mBAAmB,kBAC/B,OAAO,kBAAkB,YAAY,OAAO,kBAAkB,WAAW,gBAAgB,KAAA;;;;;;;;AAS1F,MAAa,0BAEZ,OAAO,EAAE,KAAK,aAAa,WAAW,UAAU;CAC/C,IAAI,cAAc,YAAY,cAAc,UAAU,OAAO;CAI7D,IAAI,EAFF,cAAc,YAAY,WAAW,GAAG,KACxC,cAAc,YAAY,WAAW,GAAG,KAAK,CAAC,WAAW,eAAe,CAAC,CAAC,IAC7D,OAAO;CACtB,MAAM,SAAS,SAAS,IAAI,IAAI;CAChC,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,OAAO,MAAM,IAAI,QACrB,SAAS;EAAE,YAAY;EAAY,IAAI;EAAQ,OAAO;EAAG,gBAAgB;EAAM;CAAI,CAAC,EACpF,YAAY,IAAI;CAClB,MAAM,OAAO,MAAM,gBAAgB,OAAO,aAAa,KAAK,IAAI,IAAI,KAAA;CACpE,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SAAS,IAClE,KAAK,eACL,KAAA;CACJ,IAAI,CAAC,cAAc,OAAO;CAC1B,MAAM,QAAQ,aAAa,IAAI,QAAQ,YAAY;CACnD,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,gBAAgB,gBAAgB,IAAI,aAAa;CACvD,MAAM,OAAO;EAAE,MAAM,OAAO,MAAM;EAAG,OAAO;CAAa;CACzD,KAAK,MAAM,SAAS,OACnB,MAAM,aAAa,IAAI,SAAS;EAAE,GAAG;EAAM;CAAM,GAAG,GAAG,aAAa;CAErE,MAAM,aAAa,IAAI,SAAS;EAAE,GAAG;EAAM,OAAA;CAAyB,GAAG,GAAG,aAAa;CACvF,OAAO;AACR"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { CollectionConfig } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/poll/votes/votesCollection.d.ts
|
|
4
|
+
declare const POLL_VOTES_SLUG = "form-poll-votes";
|
|
5
|
+
/** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */
|
|
6
|
+
declare const RESPONDENTS_VALUE = "";
|
|
7
|
+
/**
|
|
8
|
+
* Shard count for hot tally counters. Mongo aborts one of two transactions that write the same
|
|
9
|
+
* document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the
|
|
10
|
+
* same (form, field, value) would deterministically fail one submission. Spreading each
|
|
11
|
+
* transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards
|
|
12
|
+
* with high probability, so transactions stop contending. Postgres row locks serialize
|
|
13
|
+
* ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so
|
|
14
|
+
* both always use shard 0. Reads sum counts across shards.
|
|
15
|
+
*/
|
|
16
|
+
declare const VOTE_SHARDS = 8;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { POLL_VOTES_SLUG, RESPONDENTS_VALUE, VOTE_SHARDS };
|
|
19
|
+
//# sourceMappingURL=votesCollection.d.ts.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { keys } from "../../translations/keys.js";
|
|
2
|
+
import { labelForKey } from "../../translations/server.js";
|
|
3
|
+
import { isLoggedIn } from "../../plugin/access.js";
|
|
4
|
+
//#region src/poll/votes/votesCollection.ts
|
|
5
|
+
const POLL_VOTES_SLUG = "form-poll-votes";
|
|
6
|
+
/** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */
|
|
7
|
+
const RESPONDENTS_VALUE = "";
|
|
8
|
+
/**
|
|
9
|
+
* Shard count for hot tally counters. Mongo aborts one of two transactions that write the same
|
|
10
|
+
* document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the
|
|
11
|
+
* same (form, field, value) would deterministically fail one submission. Spreading each
|
|
12
|
+
* transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards
|
|
13
|
+
* with high probability, so transactions stop contending. Postgres row locks serialize
|
|
14
|
+
* ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so
|
|
15
|
+
* both always use shard 0. Reads sum counts across shards.
|
|
16
|
+
*/
|
|
17
|
+
const VOTE_SHARDS = 8;
|
|
18
|
+
/**
|
|
19
|
+
* Append-only aggregate tallies: up to VOTE_SHARDS rows per (form, field, value) with running
|
|
20
|
+
* counts that readers sum, plus respondents rows per (form, field) under RESPONDENTS_VALUE.
|
|
21
|
+
* Rows carry no per-voter data and are written via atomic upsert-increments (see bumpPollVote),
|
|
22
|
+
* made concurrency-safe by the unique compound index. Ids are stored as strings for cross-DB
|
|
23
|
+
* parity.
|
|
24
|
+
*
|
|
25
|
+
* `indexes` is intentionally not part of the override surface: the unique compound index is
|
|
26
|
+
* load-bearing for the atomic upsert-increment, so it is fixed rather than spread with the rest.
|
|
27
|
+
*/
|
|
28
|
+
const buildPollVotesCollection = (args) => {
|
|
29
|
+
const defaultFields = [
|
|
30
|
+
{
|
|
31
|
+
name: "form",
|
|
32
|
+
type: "text",
|
|
33
|
+
required: true,
|
|
34
|
+
index: true
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: "field",
|
|
38
|
+
type: "text",
|
|
39
|
+
required: true
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: "value",
|
|
43
|
+
type: "text"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
name: "shard",
|
|
47
|
+
type: "number",
|
|
48
|
+
required: true,
|
|
49
|
+
defaultValue: 0
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "count",
|
|
53
|
+
type: "number",
|
|
54
|
+
required: true,
|
|
55
|
+
defaultValue: 0
|
|
56
|
+
}
|
|
57
|
+
];
|
|
58
|
+
return {
|
|
59
|
+
...args.overrides ?? {},
|
|
60
|
+
slug: POLL_VOTES_SLUG,
|
|
61
|
+
labels: {
|
|
62
|
+
singular: labelForKey(keys.collectionPollVoteSingular),
|
|
63
|
+
plural: labelForKey(keys.collectionPollVotePlural),
|
|
64
|
+
...args.overrides?.labels ?? {}
|
|
65
|
+
},
|
|
66
|
+
admin: {
|
|
67
|
+
hidden: true,
|
|
68
|
+
...args.overrides?.admin ?? {}
|
|
69
|
+
},
|
|
70
|
+
access: {
|
|
71
|
+
read: isLoggedIn,
|
|
72
|
+
...args.overrides?.access ?? {}
|
|
73
|
+
},
|
|
74
|
+
indexes: [{
|
|
75
|
+
fields: [
|
|
76
|
+
"form",
|
|
77
|
+
"field",
|
|
78
|
+
"value",
|
|
79
|
+
"shard"
|
|
80
|
+
],
|
|
81
|
+
unique: true
|
|
82
|
+
}],
|
|
83
|
+
fields: args.overrides?.fields ? args.overrides.fields({ defaultFields }) : defaultFields
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
export { POLL_VOTES_SLUG, RESPONDENTS_VALUE, VOTE_SHARDS, buildPollVotesCollection };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=votesCollection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"votesCollection.js","names":[],"sources":["../../../src/poll/votes/votesCollection.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\nimport { isLoggedIn } from '../../plugin/access'\nimport type { CollectionOverrides } from '../../plugin/collectionOverrides'\nimport { keys } from '../../translations/keys'\nimport { labelForKey } from '../../translations/server'\n\nexport const POLL_VOTES_SLUG = 'form-poll-votes'\n\n/** Reserved tally `value` marking the per-field respondents counter (empty answers are never counted, so '' is free). */\nexport const RESPONDENTS_VALUE = ''\n\n/**\n * Shard count for hot tally counters. Mongo aborts one of two transactions that write the same\n * document (WriteConflict/TransientTransactionError), so concurrent transactional votes for the\n * same (form, field, value) would deterministically fail one submission. Spreading each\n * transactional bump across VOTE_SHARDS rows makes concurrent bumps land on different shards\n * with high probability, so transactions stop contending. Postgres row locks serialize\n * ON CONFLICT updates without aborting and non-transactional Mongo $inc is conflict-free, so\n * both always use shard 0. Reads sum counts across shards.\n */\nexport const VOTE_SHARDS = 8\n\n/**\n * Append-only aggregate tallies: up to VOTE_SHARDS rows per (form, field, value) with running\n * counts that readers sum, plus respondents rows per (form, field) under RESPONDENTS_VALUE.\n * Rows carry no per-voter data and are written via atomic upsert-increments (see bumpPollVote),\n * made concurrency-safe by the unique compound index. Ids are stored as strings for cross-DB\n * parity.\n *\n * `indexes` is intentionally not part of the override surface: the unique compound index is\n * load-bearing for the atomic upsert-increment, so it is fixed rather than spread with the rest.\n */\nexport const buildPollVotesCollection = (args: {\n\toverrides?: CollectionOverrides\n}): CollectionConfig => {\n\tconst defaultFields: CollectionConfig['fields'] = [\n\t\t{ name: 'form', type: 'text', required: true, index: true },\n\t\t{ name: 'field', type: 'text', required: true },\n\t\t{ name: 'value', type: 'text' },\n\t\t{ name: 'shard', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'count', type: 'number', required: true, defaultValue: 0 },\n\t]\n\n\treturn {\n\t\t...(args.overrides ?? {}),\n\t\tslug: POLL_VOTES_SLUG,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.collectionPollVoteSingular),\n\t\t\tplural: labelForKey(keys.collectionPollVotePlural),\n\t\t\t...(args.overrides?.labels ?? {}),\n\t\t},\n\t\tadmin: { hidden: true, ...(args.overrides?.admin ?? {}) },\n\t\taccess: { read: isLoggedIn, ...(args.overrides?.access ?? {}) },\n\t\tindexes: [{ fields: ['form', 'field', 'value', 'shard'], unique: true }],\n\t\tfields: args.overrides?.fields ? args.overrides.fields({ defaultFields }) : defaultFields,\n\t}\n}\n"],"mappings":";;;;AAMA,MAAa,kBAAkB;;AAG/B,MAAa,oBAAoB;;;;;;;;;;AAWjC,MAAa,cAAc;;;;;;;;;;;AAY3B,MAAa,4BAA4B,SAEjB;CACvB,MAAM,gBAA4C;EACjD;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAS,MAAM;GAAQ,UAAU;EAAK;EAC9C;GAAE,MAAM;GAAS,MAAM;EAAO;EAC9B;GAAE,MAAM;GAAS,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACjE;GAAE,MAAM;GAAS,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;CAClE;CAEA,OAAO;EACN,GAAI,KAAK,aAAa,CAAC;EACvB,MAAM;EACN,QAAQ;GACP,UAAU,YAAY,KAAK,0BAA0B;GACrD,QAAQ,YAAY,KAAK,wBAAwB;GACjD,GAAI,KAAK,WAAW,UAAU,CAAC;EAChC;EACA,OAAO;GAAE,QAAQ;GAAM,GAAI,KAAK,WAAW,SAAS,CAAC;EAAG;EACxD,QAAQ;GAAE,MAAM;GAAY,GAAI,KAAK,WAAW,UAAU,CAAC;EAAG;EAC9D,SAAS,CAAC;GAAE,QAAQ;IAAC;IAAQ;IAAS;IAAS;GAAO;GAAG,QAAQ;EAAK,CAAC;EACvE,QAAQ,KAAK,WAAW,SAAS,KAAK,UAAU,OAAO,EAAE,cAAc,CAAC,IAAI;CAC7E;AACD"}
|
package/dist/react/Form.d.ts
CHANGED
|
@@ -52,6 +52,12 @@ type FormProps = {
|
|
|
52
52
|
* and keep the form usable.
|
|
53
53
|
*/
|
|
54
54
|
successBehavior?: 'replace' | 'reset';
|
|
55
|
+
/**
|
|
56
|
+
* Client halves of the plugin's registered `calc.functions` (same keys), used for the live calc
|
|
57
|
+
* preview only; the server always recomputes authoritatively at submit with the registry's own
|
|
58
|
+
* functions.
|
|
59
|
+
*/
|
|
60
|
+
calcFunctions?: Record<string, (args: number[]) => number>;
|
|
55
61
|
events?: FormEventSink;
|
|
56
62
|
t?: RendererTranslate;
|
|
57
63
|
locale?: string;
|
|
@@ -74,7 +80,13 @@ type FormProps = {
|
|
|
74
80
|
honeypot?: false | {
|
|
75
81
|
name?: string;
|
|
76
82
|
}; /** A token from your captcha widget; verified server-side when a captcha provider is configured. */
|
|
77
|
-
captchaToken?: string;
|
|
83
|
+
captchaToken?: string;
|
|
84
|
+
/**
|
|
85
|
+
* A signed form-context token from `signFormContext` (server/RSC), tying this render to a document
|
|
86
|
+
* (e.g. the profile page it is on). Carried alongside the answers, verified server-side, and
|
|
87
|
+
* available to `email.recipientSources`; it is never stored as an answer.
|
|
88
|
+
*/
|
|
89
|
+
context?: string; /** Custom layout: render fields with `useField`/`useFormState` instead of the auto-rendered field loop. */
|
|
78
90
|
children?: ReactNode; /** Chrome rendered inside the form, above the fields, in default mode (e.g. `<FormSteps />`). */
|
|
79
91
|
header?: ReactNode; /** Additional CSS class names applied to the root `<form>` element (and the success node). */
|
|
80
92
|
className?: string; /** Replace the default submit button entirely. Receives the resolved label and submitting state. */
|
|
@@ -97,6 +109,7 @@ declare const Form: ({
|
|
|
97
109
|
onError,
|
|
98
110
|
converters,
|
|
99
111
|
successBehavior,
|
|
112
|
+
calcFunctions,
|
|
100
113
|
events,
|
|
101
114
|
t,
|
|
102
115
|
locale,
|
|
@@ -113,6 +126,7 @@ declare const Form: ({
|
|
|
113
126
|
initialValues,
|
|
114
127
|
honeypot,
|
|
115
128
|
captchaToken,
|
|
129
|
+
context,
|
|
116
130
|
children,
|
|
117
131
|
header,
|
|
118
132
|
className,
|
package/dist/react/Form.js
CHANGED
|
@@ -3,9 +3,9 @@ import { keys } from "../translations/keys.js";
|
|
|
3
3
|
import { interpolate } from "../recall/interpolate.js";
|
|
4
4
|
import { serializeBody } from "../actions/body/serializeBody.js";
|
|
5
5
|
import { noopEventSink } from "../events/noopSink.js";
|
|
6
|
-
import { CAPTCHA_TOKEN_KEY, HONEYPOT_VALUE_KEY } from "../spam/constants.js";
|
|
7
6
|
import { fieldKey, isNamedField } from "../fields/fieldKey.js";
|
|
8
7
|
import { calcExpressionOf, computeCalcFields } from "../calc/computeCalcFields.js";
|
|
8
|
+
import { CAPTCHA_TOKEN_KEY, CONTEXT_KEY, HONEYPOT_VALUE_KEY } from "../spam/constants.js";
|
|
9
9
|
import { evaluateCondition } from "../conditions/evaluate.js";
|
|
10
10
|
import { resolveMessage } from "../validation/message.js";
|
|
11
11
|
import { en } from "../translations/en.js";
|
|
@@ -60,7 +60,7 @@ const focusFirstIn = (root, selector) => {
|
|
|
60
60
|
/** A stored button label counts only when it is a non-empty string; anything else falls through. */
|
|
61
61
|
const storedLabel = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
62
62
|
/** The headless form controller: state, progressive client validation, conditional visibility, submission, events. */
|
|
63
|
-
const Form = ({ form, fieldTypes, rules, renderers, apiRoute, onSubmit, onSuccess, onError, converters, successBehavior = "replace", events, t, locale = "en", layout, submitLabel, nextLabel, prevLabel, closeLabel, successMessage, presentation, presentations, onClose, title, initialValues, honeypot, captchaToken, children, header, className, renderSubmit, renderNext, renderBack, submitButtonClassName, nextButtonClassName, backButtonClassName }) => {
|
|
63
|
+
const Form = ({ form, fieldTypes, rules, renderers, apiRoute, onSubmit, onSuccess, onError, converters, successBehavior = "replace", calcFunctions, events, t, locale = "en", layout, submitLabel, nextLabel, prevLabel, closeLabel, successMessage, presentation, presentations, onClose, title, initialValues, honeypot, captchaToken, context, children, header, className, renderSubmit, renderNext, renderBack, submitButtonClassName, nextButtonClassName, backButtonClassName }) => {
|
|
64
64
|
const honeypotName = honeypot === false ? null : honeypot?.name ?? "website";
|
|
65
65
|
const honeypotRef = useRef(null);
|
|
66
66
|
const registry = useMemo(() => buildFieldTypeRegistry(fieldTypes), [fieldTypes]);
|
|
@@ -92,7 +92,23 @@ const Form = ({ form, fieldTypes, rules, renderers, apiRoute, onSubmit, onSucces
|
|
|
92
92
|
...seedFieldValues(fields),
|
|
93
93
|
...initialValues ?? {}
|
|
94
94
|
}));
|
|
95
|
-
const effectiveValues = useMemo(() => computeCalcFields(form.fields, state.values
|
|
95
|
+
const effectiveValues = useMemo(() => computeCalcFields(form.fields, state.values, {
|
|
96
|
+
...form.calcResolved ?? {},
|
|
97
|
+
...calcFunctions ? { functions: calcFunctions } : {}
|
|
98
|
+
}), [
|
|
99
|
+
form.fields,
|
|
100
|
+
state.values,
|
|
101
|
+
form.calcResolved,
|
|
102
|
+
calcFunctions
|
|
103
|
+
]);
|
|
104
|
+
const calcValues = useMemo(() => {
|
|
105
|
+
const values = {};
|
|
106
|
+
for (const field of form.fields) if (calcExpressionOf(field) && isNamedField(field)) {
|
|
107
|
+
const computed = effectiveValues[field.name];
|
|
108
|
+
values[field.name] = typeof computed === "number" ? computed : 0;
|
|
109
|
+
}
|
|
110
|
+
return values;
|
|
111
|
+
}, [form.fields, effectiveValues]);
|
|
96
112
|
const recall = useMemo(() => buildRecallResolver({
|
|
97
113
|
fields: form.fields,
|
|
98
114
|
values: effectiveValues,
|
|
@@ -416,6 +432,10 @@ const Form = ({ form, fieldTypes, rules, renderers, apiRoute, onSubmit, onSucces
|
|
|
416
432
|
field: CAPTCHA_TOKEN_KEY,
|
|
417
433
|
value: captchaToken
|
|
418
434
|
});
|
|
435
|
+
if (context) values.push({
|
|
436
|
+
field: CONTEXT_KEY,
|
|
437
|
+
value: context
|
|
438
|
+
});
|
|
419
439
|
const result = onSubmit ? await onSubmit({
|
|
420
440
|
formId: form.id,
|
|
421
441
|
values
|
|
@@ -511,6 +531,7 @@ const Form = ({ form, fieldTypes, rules, renderers, apiRoute, onSubmit, onSucces
|
|
|
511
531
|
labels,
|
|
512
532
|
t: translate,
|
|
513
533
|
effectiveValues,
|
|
534
|
+
calcValues,
|
|
514
535
|
recall,
|
|
515
536
|
renderedFields: (flow ? stepVisible : visible).filter((field) => field.hidden !== true && field.calcDisplay !== false),
|
|
516
537
|
converters,
|