@extantape/payload-plugin-wizards 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.
4
4
 
5
- **Status:** 0.1.0, not on npm yet. The server tests run on Payload 3.92 with an in-memory MongoDB, and the component tests in jsdom (32 tests: 14 server, 18 component). No site uses it yet, and nothing has run in a real browser.
5
+ **Status:** early (0.x). 475 tests pass: 29 server tests on Payload 3.92 with an in-memory MongoDB, 13 on SQLite for blank text, 402 for the scope option, mostly run on MongoDB and SQLite, and 31 component tests in jsdom. It hasn't been tested on a real site, and nothing has run in a real browser.
6
6
 
7
7
  ## What it does
8
8
 
@@ -12,20 +12,22 @@ Wizards for Payload: gated step-by-step flows, one question per screen with Yes
12
12
  - **choice:** options, any of which can stop the flow.
13
13
 
14
14
  Each step also has its question, a text version, an optional video with required captions, a stop message, and active or not.
15
- - Every gate and choice needs a stop message, which says what to do when the answer is No. A choice's options each need their own value.
15
+ - Every step needs a question, and every gate and choice a stop message, which says what to do when the answer is No. Text that is only spaces doesn't count. A choice's options each need their own value and a label.
16
16
  - A video has to be a video file, and its captions a WebVTT file.
17
17
  - Each step's content hash covers what a person confirms (question, text, kind, options, stop message, video and captions) in the language they read it. It's worked out each time a step is read, so it can't go stale.
18
18
  - Editors (`access.edit`, required) change steps. The public reads active ones only.
19
19
  - **Flows are registered in code:** a list of slots, either your own code steps (finding a kit with the camera, choosing an animal) or a group of content steps. Other plugins register flows at `config.custom.wizardFlows` with no import, and a flow registered twice, or one that uses a group of steps twice, stops the site at start-up.
20
- - **`flowSteps(payload, { flow, locale })`** gives the flow's slots, with active steps in order, for the page.
20
+ - **`flowSteps(payload, { flow, locale, req })`** gives the flow's slots, with active steps in order, for the page. A step whose question, stop message or an option label is blank in that language is left out and named in `blank`. With `localization.fallback: false`, an untranslated step is blank. Show an error instead of the flow when `blank` or `empty` has anything in it.
21
21
  - **`<Wizard>`** (`./client`) shows one step per screen:
22
22
  - focus on the question, "Step N of M", and Back;
23
23
  - No shows the stop message and stays, and withdraws an earlier Yes on that step;
24
24
  - video with captions, never autoplaying, and the text version always shown;
25
25
  - your code steps rendered with `next` and `back`;
26
+ - a step with a blank question, stop message or option label shows an alert in place of the step, with no way to answer it;
26
27
  - state in memory only.
27
- - **The answers are checked on the server, not trusted.** Call `answersFor(payload, { flow, answers })` before acting. It refuses:
28
+ - **The answers are checked on the server, not trusted.** Call `answersFor(payload, { flow, answers, req })` before acting. It refuses:
28
29
  - a No, or a stopping choice;
30
+ - a step whose question, stop message or an option label is blank in the language asked for (`blankStep`), so nobody is recorded agreeing to text they weren't shown;
29
31
  - a missing, extra or repeated step;
30
32
  - a group of steps with no active step, so a safety group that was never seeded, is misspelled or was switched off never waves the flow through;
31
33
  - any step whose wording changed since the screen loaded;
@@ -33,6 +35,34 @@ Wizards for Payload: gated step-by-step flows, one question per screen with Yes
33
35
 
34
36
  Pass the `locale` the person read. It returns the record to keep with your action: the language, each step's hash and question as the person read them, the answers, and the time. The hash identifies the full wording; the plugin keeps no copy of older wording, so keep versions on `guided-steps` if you need to show a past version in full. A client can't skip a gate by posting straight to your action.
35
37
 
38
+ ## Scope: one site's steps for one site
39
+
40
+ For a platform that runs several sites from one database. Unset, nothing changes: every caller sees every step, as in 0.1.0.
41
+
42
+ ```ts
43
+ wizardsPlugin({
44
+ flows,
45
+ access: { edit },
46
+ scope: {
47
+ where: ({ req }) => {
48
+ if (!req.user?.site) throw new Error('No site') // refuses plainly
49
+ return { site: { equals: req.user.site } }
50
+ },
51
+ indexWith: ['site'],
52
+ },
53
+ })
54
+ ```
55
+
56
+ - **`where`** runs on every call with the request. If it throws, the call is refused. A scope may use only `equals` and `in`. `equals` takes one non-empty string or number. `in` takes a non-empty list of them. The plugin refuses everything else at every depth, so a filter can't match everything by accident or mean one thing in memory and another in a database: any other operator (`not_equals`, `not_in`, `exists`, `like`, `contains` and the comparisons), an empty string, `null` or `undefined`, a list with an empty or null entry, an empty `and` or `or`, an empty `{}`, and anything that isn't a plain object. `and` and `or` can nest. Build `or` lists so that a user with no sites throws instead of producing `{ or: [] }`. If a user's site can be an object (a populated relationship), return its id. A host that wants every site leaves `scope` unset.
57
+ - **Reads:** the scope is ANDed with what the access rules already allow, so the REST API, GraphQL, count and the Local API with `overrideAccess: false` only see the caller's steps. `flowSteps` and `answersFor` take `req` and apply the scope themselves. With a scope set and no `req` they refuse (`answersFor` answers `noScope`) and never fall back to all sites.
58
+ - **Writes:** update and delete access are limited to the caller's steps. A create or update is checked at the database adapter, on the step exactly as it will be stored, after every field hook and every collection hook, including any your own plugins add. One that would leave the scope, including a move to another site, is refused with a 403 and nothing is written. That works the same with or without database transactions. The stored value of every field in the scope has to be a string or a number, so a missing, null, list or object value is refused. An update or a delete also reads the steps it would touch and refuses unless every one of them is inside the scope, so a call can't take another site's step into its own site or delete it. That covers `overrideAccess: true` calls and direct `db.updateOne`, `db.deleteOne` and `db.deleteMany` calls, and a `where` that matches steps on two sites is refused whole. A call with no `req` is refused. While a scope is set, `updateMany` and `upsert` on the adapter for the steps are refused, and so is `updateOne` with `upsert` set. A delete through the collection is also checked in `beforeDelete`. The stored-step check reads first and writes after, and the write is handed the scope in its `where`, so a step that moves to another site in between is not touched (the call then does nothing, or touches only the steps still in scope). The read uses the call's locale. A seeding script has to pass a `req` the hook accepts.
59
+ - **Plugin order:** the check wraps `db`, so set `db` in the config before this plugin and list `wizardsPlugin` last among the plugins that touch `db`. A plugin listed before it that wraps `create`, `updateOne` or `deleteOne` (or `deleteMany`) runs after the check, so its changes to those calls are not checked. At start-up the plugin looks at the adapter the site actually runs. If `find`, `create`, `updateOne`, `deleteOne`, `deleteMany`, `updateMany` or `upsert` is not the one this plugin wrapped (a later plugin put the original `db` back, or wrapped it again), the site refuses to start and the error says so.
60
+ - **`indexWith`** adds your field names to the unique index on flow + key. Sites that share step keys need it, because without it the index is flow + key alone, so a second site can't reuse a key. Even then a duplicate key is answered with a 400 "must be unique" without `indexWith`, including for a key that only another site uses, so the answer tells a caller that the key exists elsewhere. Set `indexWith` if that matters to you. You add the field yourself, in a plugin or config that runs after Wizards (`{ name: 'site', type: 'text', required: true, index: true }`, for example); naming a field that doesn't exist stops the site at start-up. If `scope` is set without `indexWith`, a warning is logged at start-up.
61
+ - **Videos and captions:** the file-type check when a step is saved, and the files `flowSteps` returns, are looked up as the caller (`overrideAccess: false`), so a site can't attach or show another site's files. Give your media collection its own site-based read access. A file the caller can't read shows as no video.
62
+ - **Per-site checks:** the group-with-no-active-step refusal runs inside the caller's scope. A site that never seeded its safety group is refused even when another site has one. The start-up checks (a flow registered twice, a group used twice) stay across the whole config.
63
+ - **Versions and drafts:** with a scope set, the steps collection can't have `versions` or `drafts` (autosave included). They write through adapter calls the scope check doesn't cover, and their reads aren't scoped. If a later plugin or your config turns them on, the site refuses to start. With no scope, nothing changes.
64
+ - **Limits:** Tested on MongoDB (replica set and standalone) and SQLite (with and without transactions).
65
+
36
66
  ## On its own, and with others
37
67
 
38
68
  **On its own:** Wizards needs only Payload, an `access.edit` rule, and an upload collection if your steps have videos (`media`, or `false` for none). Your site registers its flows in `flows` and renders its own code steps.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Text a person must read is there: a string that still has a letter, number, punctuation mark or symbol once the
3
+ * characters that draw nothing are removed. Spaces, control characters and lone combining marks don't count.
4
+ * Anything else counts as blank, including a missing value and an object (such as every language at once).
5
+ */
6
+ export declare const hasText: (v: unknown) => v is string;
7
+ /**
8
+ * Whether a step, as read in one language, lacks text a person is asked to agree to or be stopped by: the question
9
+ * (the title of an information step), the stop message of a gate or choice, or the label of any option of a choice.
10
+ * Such a step is never shown, answered or recorded.
11
+ */
12
+ export declare const isBlankStep: (s: {
13
+ kind?: unknown;
14
+ question?: unknown;
15
+ stopMessage?: unknown;
16
+ options?: unknown;
17
+ }) => boolean;
package/dist/blank.js ADDED
@@ -0,0 +1,18 @@
1
+ /** Characters that draw nothing: Unicode's default-ignorable code points, plus the braille blank (U+2800). */
2
+ const invisible = /[\p{Default_Ignorable_Code_Point}\u2800]/gu;
3
+ /** What counts as something to read: a letter, number, punctuation mark or symbol (emoji included). */
4
+ const readable = /[\p{L}\p{N}\p{P}\p{S}]/u;
5
+ /**
6
+ * Text a person must read is there: a string that still has a letter, number, punctuation mark or symbol once the
7
+ * characters that draw nothing are removed. Spaces, control characters and lone combining marks don't count.
8
+ * Anything else counts as blank, including a missing value and an object (such as every language at once).
9
+ */
10
+ export const hasText = (v) => typeof v === 'string' && readable.test(v.replace(invisible, ''));
11
+ /**
12
+ * Whether a step, as read in one language, lacks text a person is asked to agree to or be stopped by: the question
13
+ * (the title of an information step), the stop message of a gate or choice, or the label of any option of a choice.
14
+ * Such a step is never shown, answered or recorded.
15
+ */
16
+ export const isBlankStep = (s) => !hasText(s.question) ||
17
+ (s.kind !== 'info' && !hasText(s.stopMessage)) ||
18
+ (s.kind === 'choice' && !(Array.isArray(s.options) && s.options.every((o) => Boolean(o) && typeof o === 'object' && hasText(o.label))));
@@ -29,6 +29,8 @@ export type WizardLabels = {
29
29
  missingCode: (code: string) => string;
30
30
  /** Shown when onFinish throws or rejects. The buttons come back so the person can try again. */
31
31
  finishFailed: string;
32
+ /** Shown instead of a step whose question, stop message or an option label is blank. There is no way to answer it. */
33
+ blankStep: string;
32
34
  /** Visible marker on the option or button chosen earlier, so the choice isn't shown by color alone. */
33
35
  chosen: string;
34
36
  };
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useCallback, useEffect, useId, useRef, useState } from 'react';
4
+ import { isBlankStep } from '../blank.js';
4
5
  export const defaultLabels = {
5
6
  yes: 'Yes',
6
7
  no: 'No',
@@ -9,6 +10,7 @@ export const defaultLabels = {
9
10
  stepOf: (n, m) => `Step ${n} of ${m}`,
10
11
  missingCode: (code) => `This step ("${code}") can't be shown. Please contact the site.`,
11
12
  finishFailed: "That didn't go through. Please try again.",
13
+ blankStep: "This step can't be shown in your language yet, so it can't be answered. Please contact the site.",
12
14
  chosen: '(chosen)',
13
15
  };
14
16
  const buttonStyle = { minHeight: 44, minWidth: 44, padding: '0.5rem 1rem' };
@@ -74,6 +76,8 @@ export function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, })
74
76
  setIndex(index - 1);
75
77
  }, [busy, done, index]);
76
78
  const record = (step, value) => {
79
+ if (isBlankStep(step))
80
+ return;
77
81
  const nextAnswers = { ...answers, [index]: { key: step.key, hash: step.hash, value } };
78
82
  setAnswers(nextAnswers);
79
83
  advance(nextAnswers, values);
@@ -97,8 +101,10 @@ export function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, })
97
101
  const progressId = `${baseId}-progress`;
98
102
  const headingId = `${baseId}-heading`;
99
103
  const progress = labels.stepOf(index + 1, slots.length);
104
+ const blank = !isCode(slot) && isBlankStep(slot.step);
105
+ const alertText = blank ? labels.blankStep : error;
100
106
  const backButton = index > 0 ? (_jsx("button", { type: "button", style: buttonStyle, onClick: back, disabled: disabled, className: "wizard-back", children: labels.back })) : null;
101
- const liveRegions = (_jsxs(_Fragment, { children: [_jsx("div", { role: "status", "aria-live": "polite", className: "wizard-stop", children: stopMessage ? _jsx("p", { children: stopMessage }) : null }), _jsx("div", { role: "alert", className: "wizard-error", children: error ? _jsx("p", { children: error }) : null })] }));
107
+ const liveRegions = (_jsxs(_Fragment, { children: [_jsx("div", { role: "status", "aria-live": "polite", className: "wizard-stop", children: stopMessage ? _jsx("p", { children: stopMessage }) : null }), _jsx("div", { role: "alert", className: "wizard-error", children: alertText ? _jsx("p", { children: alertText }) : null })] }));
102
108
  if (isCode(slot)) {
103
109
  const render = renderCode[slot.code];
104
110
  const ctx = {
@@ -119,6 +125,8 @@ export function Wizard({ slots, renderCode, onFinish, labels: labelOverrides, })
119
125
  }
120
126
  const step = slot.step;
121
127
  const previous = answers[index]?.value;
128
+ if (blank)
129
+ return (_jsxs("section", { className: "wizard", "data-step": step.key, "aria-labelledby": progressId, children: [_jsx("p", { id: progressId, className: "wizard-progress", tabIndex: -1, ref: (el) => { focusTarget.current = el; }, children: progress }), liveRegions, _jsx("div", { className: "wizard-nav", children: backButton })] }));
122
130
  return (_jsxs("section", { className: "wizard", "data-step": step.key, "aria-labelledby": headingId, "aria-busy": busy || undefined, children: [_jsx("p", { id: progressId, className: "wizard-progress", children: progress }), _jsx("h2", { id: headingId, tabIndex: -1, "aria-describedby": progressId, ref: (el) => {
123
131
  focusTarget.current = el;
124
132
  }, children: step.question }), step.video ? (
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { wizardsPlugin } from './plugin.js';
2
2
  export { answersFor, contentHash, flowSteps, flowsOf } from './steps.js';
3
- export type { Answer, Flow, FlowRegistration, Slot, Step, WizardRecord, WizardsOptions } from './types.js';
3
+ export type { Answer, Flow, FlowRegistration, ScopeOption, Slot, Step, WizardRecord, WizardsOptions } from './types.js';
package/dist/plugin.js CHANGED
@@ -1,17 +1,25 @@
1
- import { flowsOf, stepsCollection } from './steps.js';
1
+ import { assertGuarded, flowsOf, guardDb, stepsCollection } from './steps.js';
2
2
  /** Wizards: gated step-by-step flows, steps edited in the admin, and answers checked on the server. */
3
3
  export const wizardsPlugin = (options) => (config) => {
4
- const o = { slug: options.slug ?? 'guided-steps', flows: options.flows ?? {}, edit: options?.access?.edit, media: options.media === undefined ? 'media' : options.media, adminGroup: options.adminGroup ?? 'Wizards' };
4
+ const o = { scope: options.scope, slug: options.slug ?? 'guided-steps', flows: options.flows ?? {}, edit: options?.access?.edit, media: options.media === undefined ? 'media' : options.media, adminGroup: options.adminGroup ?? 'Wizards' };
5
+ if (o.scope && typeof o.scope.where !== 'function')
6
+ throw new Error('Wizards: `scope.where` must be a function.');
7
+ if (o.scope?.indexWith && !(Array.isArray(o.scope.indexWith) && o.scope.indexWith.every((f) => typeof f === 'string' && f)))
8
+ throw new Error('Wizards: `scope.indexWith` must be a list of field names.');
5
9
  if (typeof o.edit !== 'function')
6
10
  throw new Error('Wizards: give `access.edit`, saying who may change the steps.');
7
11
  if (o.media && !(config.collections ?? []).some((c) => c.slug === o.media && c.upload))
8
12
  throw new Error(`Wizards: "${o.media}" isn't an upload collection. Set \`media\`, or false for no videos.`);
9
13
  return {
10
14
  ...config,
15
+ db: guardDb(o, config.db),
11
16
  custom: { ...config.custom, wizards: o },
12
17
  collections: [...(config.collections ?? []), stepsCollection(o)],
13
18
  onInit: async (payload) => {
14
19
  flowsOf(payload);
20
+ assertGuarded(o, payload);
21
+ if (o.scope && !o.scope.indexWith?.length)
22
+ payload.logger.warn('Wizards: scope is set without indexWith, so two sites can’t use the same step key. Add indexWith (and the field) if sites share keys.');
15
23
  await config.onInit?.(payload);
16
24
  },
17
25
  };
package/dist/steps.d.ts CHANGED
@@ -1,5 +1,27 @@
1
- import type { CollectionConfig, Payload } from 'payload';
2
- import type { Flow, Resolved, Step, WizardRecord } from './types.js';
1
+ import { APIError } from 'payload';
2
+ import type { CollectionConfig, Config, Payload } from 'payload';
3
+ import type { Flow, Req, Resolved, Step, WizardRecord } from './types.js';
4
+ /** The scope could not be worked out, or a write or read falls outside it. Carries status 403. */
5
+ export declare class ScopeError extends APIError {
6
+ constructor(message: string);
7
+ }
8
+ /**
9
+ * Puts the scope check at the one place every save passes last: the database adapter's create and update, which
10
+ * receive the step exactly as it will be stored, after every field hook and every collection hook any plugin added,
11
+ * whatever the plugins do before the adapter is called. An update or delete also reads the stored steps and refuses
12
+ * unless every one is inside the scope, so a call can't move another site's step into its own site or delete it, and
13
+ * the write itself is handed the scope in its `where` (and no `id`), so a step that changes between the read and the
14
+ * write is still not touched. A bulk update or an upsert straight on the adapter is refused while a scope is set. A
15
+ * plugin that wraps `db` and is listed before this one runs after the check on `create`, `updateOne`, `deleteOne`
16
+ * and `deleteMany`, so its changes to those calls are not checked.
17
+ */
18
+ export declare const guardDb: (o: Resolved, db: Config["db"] | undefined) => Config["db"];
19
+ /**
20
+ * Start-up check with a scope set: the adapter the site actually runs must still carry this plugin's check (a plugin
21
+ * that puts back an earlier `config.db` removes it), and the steps must have no versions or drafts, which write
22
+ * through adapter calls the check does not cover.
23
+ */
24
+ export declare const assertGuarded: (o: Resolved, payload: Payload) => void;
3
25
  /**
4
26
  * What a person confirms, in the language they read it: question, body, kind, options, the stop message, and the
5
27
  * video with its captions. Worked out each time a step is read in a locale, never stored, so it can't be stale or
@@ -19,11 +41,14 @@ export declare const stepsCollection: (o: Resolved) => CollectionConfig;
19
41
  export declare function flowsOf(payload: Payload): Record<string, Flow>;
20
42
  /**
21
43
  * The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
22
- * `empty` names any group of steps with no active step: the flow can't be passed until an editor fixes it.
44
+ * `empty` names any group of steps with no active step, and `blank` the key of any step left out because its
45
+ * question, its stop message or an option label is blank in that locale (with `fallback: false`, an untranslated
46
+ * step is blank). Either way the flow can't be passed until an editor fixes it.
23
47
  */
24
48
  export declare function flowSteps(payload: Payload, args: {
25
49
  flow: string;
26
50
  locale?: string;
51
+ req?: Req;
27
52
  }): Promise<{
28
53
  slots: ({
29
54
  code: string;
@@ -31,24 +56,28 @@ export declare function flowSteps(payload: Payload, args: {
31
56
  step: Step;
32
57
  })[];
33
58
  empty: string[];
59
+ blank: string[];
34
60
  }>;
35
61
  /**
36
62
  * Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
37
63
  * answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
38
64
  * choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
39
- * mistake never waves a flow through. A step changed since the screen loaded fails, and the person sees the new
65
+ * mistake never waves a flow through. A step whose question, stop message or option label is blank in that locale
66
+ * fails (`blankStep`), so nobody agrees to, or is recorded agreeing to, text they were never shown. A step changed since the screen loaded fails, and the person sees the new
40
67
  * wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
41
- * the person read it, with the answer and the time.
68
+ * the person read it, with the answer and the time. With a `scope` set, `req` is required and the check runs inside
69
+ * the caller's scope; without it the answer is `noScope`, never all sites.
42
70
  */
43
71
  export declare function answersFor(payload: Payload, args: {
44
72
  flow: string;
45
73
  answers: unknown;
46
74
  locale?: string;
75
+ req?: Req;
47
76
  }): Promise<{
48
77
  ok: true;
49
78
  record: WizardRecord;
50
79
  } | {
51
80
  ok: false;
52
- problem: 'unknownFlow' | 'noSteps' | 'badAnswers' | 'missing' | 'extra' | 'changed' | 'notYes';
81
+ problem: 'noScope' | 'unknownFlow' | 'noSteps' | 'blankStep' | 'badAnswers' | 'missing' | 'extra' | 'changed' | 'notYes';
53
82
  key?: string;
54
83
  }>;
package/dist/steps.js CHANGED
@@ -1,10 +1,231 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { APIError } from 'payload';
3
+ import { hasText, isBlankStep } from './blank.js';
2
4
  const configOf = (payload) => {
3
5
  const o = payload.config.custom?.wizards;
4
6
  if (!o)
5
7
  throw new Error('Wizards: the plugin is not configured on this site.');
6
8
  return o;
7
9
  };
10
+ /** The scope could not be worked out, or a write or read falls outside it. Carries status 403. */
11
+ export class ScopeError extends APIError {
12
+ constructor(message) {
13
+ super(message, 403, undefined, true);
14
+ }
15
+ }
16
+ const isObject = (v) => {
17
+ if (!v || typeof v !== 'object' || Array.isArray(v))
18
+ return false;
19
+ const proto = Object.getPrototypeOf(v);
20
+ return proto === Object.prototype || proto === null;
21
+ };
22
+ /** A value a scope may compare to: a non-empty string or a finite number. Nothing else is allowed, so nothing can match everything. */
23
+ const scalar = (v) => (typeof v === 'string' && v !== '') || (typeof v === 'number' && Number.isFinite(v));
24
+ /**
25
+ * A scope is safe to apply only if it can't match everything by accident and means the same thing in memory and in
26
+ * every database. At every depth: `and` and `or` are non-empty arrays of scopes, and a field maps to a non-empty
27
+ * object of `equals` (one non-empty string or finite number) and `in` (a non-empty list of them). Any other operator,
28
+ * an empty or null value and anything not recognized is refused. Plain objects only. A deliberate match-all is the
29
+ * host's own choice, made without the scope option.
30
+ */
31
+ const validScope = (w) => {
32
+ if (!isObject(w))
33
+ return false;
34
+ const keys = Object.keys(w);
35
+ if (!keys.length)
36
+ return false;
37
+ return keys.every((k) => {
38
+ const v = w[k];
39
+ if (k === 'and' || k === 'or')
40
+ return Array.isArray(v) && v.length > 0 && v.every(validScope);
41
+ if (!isObject(v))
42
+ return false;
43
+ const ops = Object.keys(v);
44
+ return ops.length > 0 && ops.every((op) => (op === 'equals' ? scalar(v[op]) : op === 'in' ? Array.isArray(v[op]) && v[op].length > 0 && v[op].every(scalar) : false));
45
+ });
46
+ };
47
+ const pathValue = (doc, path) => path.split('.').reduce((acc, k) => (acc && typeof acc === 'object' ? acc[k] : undefined), doc);
48
+ /**
49
+ * Whether a document (as it will be saved) matches a validated scope. A stored value that isn't a string or a number
50
+ * (an object, a list, null, nothing) matches nothing, so a write the databases would read differently is refused.
51
+ */
52
+ const matches = (doc, w) => Object.entries(w).every(([k, v]) => {
53
+ if (k === 'and')
54
+ return v.every((x) => matches(doc, x));
55
+ if (k === 'or')
56
+ return v.some((x) => matches(doc, x));
57
+ const raw = pathValue(doc, k);
58
+ if (typeof raw !== 'string' && typeof raw !== 'number')
59
+ return false;
60
+ const val = String(raw);
61
+ return Object.entries(v).every(([op, arg]) => (op === 'equals' ? val === String(arg) : op === 'in' ? arg.map(String).includes(val) : false));
62
+ });
63
+ /**
64
+ * The caller's scope: `null` when the host set none (0.1.0 behavior), otherwise its `where`. Fails closed: no
65
+ * request, a hook that throws, or anything that isn't a valid scope raises ScopeError.
66
+ */
67
+ const scopeOf = async (o, req) => {
68
+ if (!o.scope)
69
+ return null;
70
+ if (!req)
71
+ throw new ScopeError('Wizards: a scope is set, so this call needs `req`.');
72
+ let w;
73
+ try {
74
+ w = await o.scope.where({ req: req });
75
+ }
76
+ catch {
77
+ throw new ScopeError('Wizards: the scope hook threw, so the call is refused.');
78
+ }
79
+ if (!validScope(w))
80
+ throw new ScopeError('Wizards: the scope hook must return a non-empty filter that uses only `equals` and `in`, with non-empty string or number values, so the call is refused.');
81
+ return w;
82
+ };
83
+ /** An access result with the scope ANDed in. `false` stays false; a failing scope refuses. */
84
+ const withScope = async (o, req, result) => {
85
+ if (result === false)
86
+ return false;
87
+ let scope;
88
+ try {
89
+ scope = await scopeOf(o, req);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ if (!scope)
95
+ return result;
96
+ return result === true ? scope : { and: [result, scope] };
97
+ };
98
+ /** Refuses, before anything is saved, a step that would sit outside the caller's scope. */
99
+ const checkWrite = (next, scope) => {
100
+ if (!matches(next, scope))
101
+ throw new ScopeError('This step would be outside your scope.');
102
+ };
103
+ /** The adapter functions this plugin put its check in, so start-up can tell whether a later plugin took them out. */
104
+ const guarded = new WeakSet();
105
+ const checked = ['create', 'updateOne', 'deleteOne', 'deleteMany'];
106
+ const refused = ['updateMany', 'upsert'];
107
+ /** Passed straight through, but marked: the stored-step check reads with `find`, so a later plugin that wraps it would be noticed. */
108
+ const watched = ['find'];
109
+ /** Whether an object has anything in it. */
110
+ const hasKeys = (w) => Boolean(w) && Object.keys(w).length > 0;
111
+ /**
112
+ * What the adapter will act on, worked out the way the adapters do: `updateOne` uses `id` when it is truthy and the
113
+ * `where` otherwise; `deleteOne` and `deleteMany` use only the `where` and ignore an `id`.
114
+ */
115
+ const targetOf = (name, a) => (name === 'updateOne' && a.id ? { id: { equals: a.id } } : a.where);
116
+ /**
117
+ * Reads the stored steps the call would touch and refuses unless every one of them is inside the scope. It reads in
118
+ * the locale the call uses, so a `where` on a localized field means the same here as in the write, and it reads with
119
+ * `find`, which every database allows inside a transaction.
120
+ */
121
+ const checkStored = async (adapter, o, a, target, scope) => {
122
+ const locale = a.locale ?? a.req?.locale;
123
+ const howMany = async (where) => (await adapter.find.call(adapter, { collection: o.slug, where, locale, limit: 0, pagination: false, select: { id: true }, req: a.req })).docs.length;
124
+ const base = hasKeys(target) ? target : {};
125
+ const all = await howMany(base);
126
+ if (all && (await howMany(hasKeys(target) ? { and: [base, scope] } : scope)) !== all)
127
+ throw new ScopeError('This step is outside your scope.');
128
+ };
129
+ /**
130
+ * Puts the scope check at the one place every save passes last: the database adapter's create and update, which
131
+ * receive the step exactly as it will be stored, after every field hook and every collection hook any plugin added,
132
+ * whatever the plugins do before the adapter is called. An update or delete also reads the stored steps and refuses
133
+ * unless every one is inside the scope, so a call can't move another site's step into its own site or delete it, and
134
+ * the write itself is handed the scope in its `where` (and no `id`), so a step that changes between the read and the
135
+ * write is still not touched. A bulk update or an upsert straight on the adapter is refused while a scope is set. A
136
+ * plugin that wraps `db` and is listed before this one runs after the check on `create`, `updateOne`, `deleteOne`
137
+ * and `deleteMany`, so its changes to those calls are not checked.
138
+ */
139
+ export const guardDb = (o, db) => {
140
+ if (!o.scope)
141
+ return db;
142
+ if (!db || typeof db.init !== 'function')
143
+ throw new Error('Wizards: a scope needs `db` set before this plugin, so the check can sit at the database.');
144
+ return {
145
+ ...db,
146
+ init: (args) => {
147
+ const adapter = db.init(args);
148
+ for (const name of watched) {
149
+ const original = adapter[name];
150
+ if (typeof original !== 'function')
151
+ throw new Error(`Wizards: the database adapter has no ${name}, so the scope can't be enforced.`);
152
+ const wrapped = function (a) {
153
+ return original.call(this, a);
154
+ };
155
+ guarded.add(wrapped);
156
+ adapter[name] = wrapped;
157
+ }
158
+ for (const name of checked) {
159
+ const original = adapter[name];
160
+ if (typeof original !== 'function')
161
+ throw new Error(`Wizards: the database adapter has no ${name}, so the scope can't be enforced.`);
162
+ const wrapped = async function (a) {
163
+ if (a?.collection !== o.slug)
164
+ return original.call(this, a);
165
+ const scope = await scopeOf(o, a.req);
166
+ if (!scope)
167
+ return original.call(this, a);
168
+ if (name === 'create') {
169
+ checkWrite((a.data ?? {}), scope);
170
+ return original.call(this, a);
171
+ }
172
+ if (name === 'updateOne') {
173
+ // An upsert inserts when nothing matches, so the stored-step check would have nothing to read. Refused like `upsert` itself.
174
+ if (a.upsert || a.options?.upsert)
175
+ throw new ScopeError('Wizards: an upsert on the steps is refused while a scope is set.');
176
+ checkWrite((a.data ?? {}), scope);
177
+ }
178
+ const target = targetOf(name, a);
179
+ await checkStored(adapter, o, a, target, scope);
180
+ const { id: _id, ...rest } = a;
181
+ return original.call(this, { ...rest, where: hasKeys(target) ? { and: [target, scope] } : scope });
182
+ };
183
+ guarded.add(wrapped);
184
+ adapter[name] = wrapped;
185
+ }
186
+ for (const name of refused) {
187
+ const original = adapter[name];
188
+ if (typeof original !== 'function')
189
+ continue;
190
+ const wrapped = async function (a) {
191
+ if (a?.collection === o.slug)
192
+ throw new ScopeError(`Wizards: ${name} on the steps is refused while a scope is set.`);
193
+ return original.call(this, a);
194
+ };
195
+ guarded.add(wrapped);
196
+ adapter[name] = wrapped;
197
+ }
198
+ return adapter;
199
+ },
200
+ };
201
+ };
202
+ /**
203
+ * Start-up check with a scope set: the adapter the site actually runs must still carry this plugin's check (a plugin
204
+ * that puts back an earlier `config.db` removes it), and the steps must have no versions or drafts, which write
205
+ * through adapter calls the check does not cover.
206
+ */
207
+ export const assertGuarded = (o, payload) => {
208
+ if (!o.scope)
209
+ return;
210
+ const db = payload.db;
211
+ for (const name of [...watched, ...checked, ...refused]) {
212
+ const fn = db[name];
213
+ if (typeof fn === 'function' && !guarded.has(fn))
214
+ throw new Error(`Wizards: the database adapter's ${name} is not the one this plugin wrapped, so the scope isn't enforced. Another plugin replaced or re-wrapped \`db\`. Put \`wizardsPlugin\` last among the plugins that touch \`db\`.`);
215
+ }
216
+ const steps = payload.config.collections.find((c) => c.slug === o.slug);
217
+ if (steps?.versions)
218
+ throw new Error('Wizards: a scope is set, so the steps collection can\u2019t have versions or drafts. They write through adapter calls the scope check does not cover.');
219
+ };
220
+ /** Refuses, before the delete, a step outside the caller's scope. */
221
+ const beforeDelete = (o) => async ({ id, req }) => {
222
+ const scope = await scopeOf(o, req);
223
+ if (!scope)
224
+ return;
225
+ const { totalDocs } = await req.payload.count({ collection: o.slug, where: { and: [{ id: { equals: id } }, scope] }, overrideAccess: true, req });
226
+ if (!totalDocs)
227
+ throw new ScopeError('This step is outside your scope.');
228
+ };
8
229
  /** A media file as the hash sees it: its id and when it last changed, so a swapped or replaced file counts as new. */
9
230
  const fileOf = (v) => (v && typeof v === 'object' ? [String(v.id ?? ''), String(v.updatedAt ?? '')] : v ? [String(v), ''] : null);
10
231
  /**
@@ -19,6 +240,7 @@ export const contentHash = (s) => createHash('sha256')
19
240
  const idOf = (v) => (v && typeof v === 'object' ? v.id : v);
20
241
  const beforeChange = (o) => async ({ data, originalDoc, req }) => {
21
242
  const next = { ...originalDoc, ...data };
243
+ // The scope is checked later, at the database, once every hook has run.
22
244
  if (next.video && !next.captions)
23
245
  throw new Error('A step with a video needs its captions (a WebVTT file).');
24
246
  if (next.kind === 'choice' && !(Array.isArray(next.options) && next.options.length >= 2))
@@ -29,10 +251,14 @@ const beforeChange = (o) => async ({ data, originalDoc, req }) => {
29
251
  if (new Set(values).size !== values.length)
30
252
  throw new Error('Each option in a choice step needs its own value.');
31
253
  }
32
- if (next.kind !== 'info' && !String(next.stopMessage ?? '').trim())
254
+ if (!hasText(next.question))
255
+ throw new Error('A step needs a question with words in it, in each language it is saved in.');
256
+ if (next.kind === 'choice' && !next.options.every((x) => hasText(x?.label)))
257
+ throw new Error('Each option in a choice step needs a label with words in it.');
258
+ if (next.kind !== 'info' && !hasText(next.stopMessage))
33
259
  throw new Error('A gate or choice step needs a stop message: what to do when the answer is No.');
34
260
  if (o.media && (next.video || next.captions)) {
35
- const mime = async (v) => String((await req.payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: true, req }).catch(() => null))?.mimeType ?? '');
261
+ const mime = async (v) => String((await req.payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: !o.scope, req }).catch(() => null))?.mimeType ?? '');
36
262
  if (next.video && !(await mime(next.video)).startsWith('video/'))
37
263
  throw new Error('The video needs to be a video file.');
38
264
  if (next.captions && !/^text\/(vtt|plain)$/.test(await mime(next.captions)))
@@ -45,13 +271,13 @@ export const stepsCollection = (o) => ({
45
271
  labels: { singular: 'Guided step', plural: 'Guided steps' },
46
272
  admin: { group: o.adminGroup, useAsTitle: 'question', defaultColumns: ['flow', 'group', 'order', 'question', 'active'] },
47
273
  access: {
48
- read: async (args) => ((await o.edit(args)) === true ? true : { active: { equals: true } }),
49
- create: async (args) => (await o.edit(args)) === true,
50
- update: async (args) => (await o.edit(args)) === true,
51
- delete: async (args) => (await o.edit(args)) === true,
274
+ read: async (args) => withScope(o, args.req, (await o.edit(args)) === true ? true : { active: { equals: true } }),
275
+ create: async (args) => (await o.edit(args)) === true && (await withScope(o, args.req, true)) !== false,
276
+ update: async (args) => withScope(o, args.req, (await o.edit(args)) === true),
277
+ delete: async (args) => withScope(o, args.req, (await o.edit(args)) === true),
52
278
  },
53
- hooks: { beforeChange: [beforeChange(o)] },
54
- indexes: [{ fields: ['flow', 'key'], unique: true }],
279
+ hooks: { beforeChange: [beforeChange(o)], beforeDelete: [beforeDelete(o)] },
280
+ indexes: [{ fields: ['flow', 'key', ...(o.scope?.indexWith ?? [])], unique: true }],
55
281
  fields: [
56
282
  { name: 'flow', type: 'text', required: true, index: true },
57
283
  { name: 'key', type: 'text', required: true, admin: { description: 'Stable: answers name it. Don’t reuse a key for a different question.' } },
@@ -108,17 +334,31 @@ export function flowsOf(payload) {
108
334
  const urlOf = (v) => (v && typeof v === 'object' && typeof v.url === 'string' ? v.url : null);
109
335
  /**
110
336
  * The content steps of a flow, in slot order, as the client shows them, in the locale asked for. Only active steps.
111
- * `empty` names any group of steps with no active step: the flow can't be passed until an editor fixes it.
337
+ * `empty` names any group of steps with no active step, and `blank` the key of any step left out because its
338
+ * question, its stop message or an option label is blank in that locale (with `fallback: false`, an untranslated
339
+ * step is blank). Either way the flow can't be passed until an editor fixes it.
112
340
  */
113
341
  export async function flowSteps(payload, args) {
114
342
  const o = configOf(payload);
343
+ const scope = await scopeOf(o, args.req);
115
344
  const flows = flowsOf(payload);
116
345
  const flow = Object.hasOwn(flows, args.flow) ? flows[args.flow] : null;
117
346
  if (!flow)
118
347
  throw new Error(`Wizards: no flow "${args.flow}".`);
119
- const docs = (await payload.find({ collection: o.slug, where: { and: [{ flow: { equals: args.flow } }, { active: { equals: true } }] }, sort: ['order', 'key'], pagination: false, depth: 1, overrideAccess: true, ...(args.locale ? { locale: args.locale } : {}) })).docs;
348
+ const docs = (await payload.find({ collection: o.slug, where: { and: [{ flow: { equals: args.flow } }, { active: { equals: true } }, ...(scope ? [scope] : [])] }, sort: ['order', 'key'], pagination: false, depth: scope ? 0 : 1, overrideAccess: true, ...(args.locale ? { locale: args.locale } : {}) })).docs;
349
+ // With a scope, files are fetched as the caller, so another site's video and captions never reach this site's page.
350
+ if (scope) {
351
+ const asCaller = async (v) => (v ? (await payload.findByID({ collection: o.media, id: idOf(v), depth: 0, overrideAccess: false, req: args.req }).catch(() => null)) : null);
352
+ for (const d of docs) {
353
+ if (o.media) {
354
+ d.video = await asCaller(d.video);
355
+ d.captions = await asCaller(d.captions);
356
+ }
357
+ }
358
+ }
120
359
  const out = [];
121
360
  const empty = [];
361
+ const blank = [];
122
362
  for (const slot of flow.slots) {
123
363
  if ('code' in slot)
124
364
  out.push({ code: slot.code });
@@ -127,6 +367,10 @@ export async function flowSteps(payload, args) {
127
367
  if (!group.length)
128
368
  empty.push(slot.steps);
129
369
  for (const d of group) {
370
+ if (isBlankStep(d)) {
371
+ blank.push(String(d.key));
372
+ continue;
373
+ }
130
374
  const video = urlOf(d.video);
131
375
  const captions = urlOf(d.captions);
132
376
  out.push({
@@ -145,26 +389,32 @@ export async function flowSteps(payload, args) {
145
389
  }
146
390
  }
147
391
  }
148
- return { slots: out, empty };
392
+ return { slots: out, empty, blank };
149
393
  }
150
394
  /**
151
395
  * Checks a flow's answers on the server before the owner acts. Fails closed: every active content step must be
152
396
  * answered exactly once, with the wording the server has now in that locale (its hash), and every gate Yes and every
153
397
  * choice a non-stopping option. A group of steps with no active step fails (`noSteps`): a safety group emptied by
154
- * mistake never waves a flow through. A step changed since the screen loaded fails, and the person sees the new
398
+ * mistake never waves a flow through. A step whose question, stop message or option label is blank in that locale
399
+ * fails (`blankStep`), so nobody agrees to, or is recorded agreeing to, text they were never shown. A step changed since the screen loaded fails, and the person sees the new
155
400
  * wording. Returns the record to store with the action: the locale, and for each step the hash and the question as
156
- * the person read it, with the answer and the time.
401
+ * the person read it, with the answer and the time. With a `scope` set, `req` is required and the check runs inside
402
+ * the caller's scope; without it the answer is `noScope`, never all sites.
157
403
  */
158
404
  export async function answersFor(payload, args) {
159
405
  let flow;
160
406
  try {
161
- flow = await flowSteps(payload, { flow: args.flow, locale: args.locale });
407
+ flow = await flowSteps(payload, { flow: args.flow, locale: args.locale, req: args.req });
162
408
  }
163
- catch {
409
+ catch (e) {
410
+ if (e instanceof ScopeError)
411
+ return { ok: false, problem: 'noScope' };
164
412
  return { ok: false, problem: 'unknownFlow' };
165
413
  }
166
414
  if (flow.empty.length)
167
415
  return { ok: false, problem: 'noSteps', key: flow.empty[0] };
416
+ if (flow.blank.length)
417
+ return { ok: false, problem: 'blankStep', key: flow.blank[0] };
168
418
  if (!Array.isArray(args.answers) || args.answers.some((a) => !a || typeof a !== 'object' || typeof a.key !== 'string' || typeof a.hash !== 'string' || typeof a.value !== 'string'))
169
419
  return { ok: false, problem: 'badAnswers' };
170
420
  const answers = args.answers;
@@ -180,6 +430,8 @@ export async function answersFor(payload, args) {
180
430
  if (given.length !== 1)
181
431
  return { ok: false, problem: given.length ? 'extra' : 'missing', key: s.key };
182
432
  const a = given[0];
433
+ if (isBlankStep(s))
434
+ return { ok: false, problem: 'blankStep', key: s.key };
183
435
  if (a.hash !== s.hash)
184
436
  return { ok: false, problem: 'changed', key: s.key };
185
437
  if (s.kind === 'gate' && a.value !== 'yes')
@@ -191,8 +443,10 @@ export async function answersFor(payload, args) {
191
443
  if (!opt || opt.stops)
192
444
  return { ok: false, problem: 'notYes', key: s.key };
193
445
  }
446
+ if (s.kind !== 'gate' && s.kind !== 'info' && s.kind !== 'choice')
447
+ return { ok: false, problem: 'notYes', key: s.key };
194
448
  }
195
449
  const localization = payload.config.localization;
196
- const locale = args.locale ?? (localization ? localization.defaultLocale : null);
450
+ const locale = args.locale || (localization ? localization.defaultLocale : null);
197
451
  return { ok: true, record: { flow: args.flow, at: new Date().toISOString(), locale, answers: steps.map((s) => ({ key: s.key, hash: s.hash, value: byKey.get(s.key)[0].value, question: s.question })) } };
198
452
  }
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Access, Payload, PayloadRequest } from 'payload';
1
+ import type { Access, Payload, PayloadRequest, Where } from 'payload';
2
2
  export type Req = Partial<PayloadRequest>;
3
3
  /** A slot in a flow: a code step the site renders, or every active guided step in a group, in order. */
4
4
  export type Slot = {
@@ -47,7 +47,21 @@ export type WizardRecord = {
47
47
  question: string;
48
48
  })[];
49
49
  };
50
+ /**
51
+ * Limits every read and write of the steps to the caller's slice, such as one site. `where` runs for each call with
52
+ * the request and must return a non-empty plain object; anything else (a throw, `{}`, `null`, an array) refuses.
53
+ * `indexWith` adds the host's own field names (such as `site`) to the unique index on flow + key. The host adds
54
+ * those fields to the steps collection itself.
55
+ */
56
+ export type ScopeOption = {
57
+ where: (args: {
58
+ req: PayloadRequest;
59
+ }) => Where | Promise<Where>;
60
+ indexWith?: string[];
61
+ };
50
62
  export type WizardsOptions = {
63
+ /** Unset keeps every step visible to every caller, as in 0.1.0. */
64
+ scope?: ScopeOption;
51
65
  flows?: Record<string, Flow>;
52
66
  /** Who edits the steps. Required; only an answer of exactly true counts. */
53
67
  access: {
@@ -59,6 +73,7 @@ export type WizardsOptions = {
59
73
  adminGroup?: string;
60
74
  };
61
75
  export type Resolved = {
76
+ scope?: ScopeOption;
62
77
  slug: string;
63
78
  flows: Record<string, Flow>;
64
79
  edit: Access;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-wizards",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Wizards for Payload: gated step-by-step flows, one question per screen with Yes needed to go on, a video and text per step edited in the admin, and the answers checked on the server and recorded.",
5
5
  "homepage": "https://github.com/ExtantApe/payload-plugin-wizards#readme",
6
6
  "bugs": {
@@ -59,6 +59,8 @@
59
59
  },
60
60
  "devDependencies": {
61
61
  "@payloadcms/db-mongodb": "3.92.1",
62
+ "@payloadcms/db-sqlite": "3.92.1",
63
+ "@payloadcms/graphql": "3.92.1",
62
64
  "@testing-library/react": "^16.3.3",
63
65
  "@types/node": "^24.0.0",
64
66
  "@types/react": "^19.3.0",