@quitecustard/payload 0.2.2 → 0.3.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
@@ -1,175 +1,182 @@
1
- # @quitecustard/payload
2
-
3
- Helpers generic over any Payload v3 project. One module per file — no barrels:
4
-
5
- ```ts
6
- import { relId } from '@quitecustard/payload/documents/resolve-ref'
7
- import { transactionDb } from '@quitecustard/payload/db/transaction-db'
8
- ```
9
-
10
- ## Install
11
-
12
- ```
13
- pnpm add @quitecustard/payload
14
- ```
15
-
16
- Every module is a subpath export, so TypeScript needs `moduleResolution` set to `bundler`,
17
- `node16` or `nodenext` — the legacy `node` resolution can't see subpath exports at all.
18
-
19
- Peer dependencies: `payload` (required), `@payloadcms/drizzle` + `drizzle-orm` and `next` (optional —
20
- only some modules touch them). Payload's module augmentation means a consumer's generated types
21
- flow through the `CollectionSlug`-generic helpers automatically.
22
-
23
- ## Contents
24
-
25
- Every module is one subpath: `@quitecustard/payload/<folder>/<module>`. There are no barrels, so
26
- the list below doubles as the import paths. Each export carries JSDoc, which is what your editor
27
- shows on hover — this page is the map, not the reference.
28
-
29
- ### `documents/` — reading what Payload hands back
30
-
31
- - `resolve-ref` — `relId` / `relDoc` / `relDocs` / `relIds` / `relName` / `resolveMedia`: relation
32
- narrowing without casts, tolerant of populate depth and of numeric or uuid ids
33
- - `locale-record` — flattens a `locale: 'all'` read into `Partial<Record<Locale, string>>`
34
- - `published-where` — the published clause, stated once so a bypassing read and the access rule
35
- cannot drift apart
36
- - `collection-versions` — `draftVersions(maxPerDoc?)`: the autosave + schedulePublish shape
37
- - `lexical-plain-text` — `lexicalPlainText` / `lexicalNodeText`: a rich text value as plain text,
38
- one block per line, for search indexes and excerpts
39
-
40
- ### `access/`
41
-
42
- - `anyone` — `anyone` / `anyoneFieldLevel` / `nobody`
43
- - `role-gate` — `hasRole` / `roleGate` / `roleGateFieldLevel`: the mechanism for reading a role off
44
- a caller. Which roles exist, and what each one may do, stays in the consuming project.
45
- - `self-access` — `isSameUser` / `isSelfFieldLevel` / `selfOrAdminFieldLevel`, across Payload's
46
- three field-access argument shapes; takes a `getUserId` resolver for a project with more than one
47
- auth collection
48
-
49
- ### `fields/` — field and admin-config factories
50
-
51
- Every field rendered by a custom component takes that component's import path as a **required**
52
- parameter — pass your own. Each is a factory, never a shared constant: `buildConfig` sanitises field
53
- objects in place, so two collections must not receive one.
54
-
55
- - `link-field` — polymorphic link (internal reference, custom URL, optional static route, dropdown,
56
- phone, email); each type appears only if its collection or component was supplied
57
- - `hero-field` — the image/video/poster banner group, parameterised on the two upload collections
58
- - `owner-field` — a relationship auto-stamped to the creating user, refused on update by field-level
59
- access rather than by `admin.readOnly`, which Payload never consults on a write
60
- - `seo-tab` — over `@payloadcms/plugin-seo`'s field factories
61
- - `social-url` — `normaliseSocialUrl` (bare host → `https://…`) plus `validateSocialUrl`
62
- - `colour-picker-field`, `colour-options-field`, `phone-field`, `height-field`, `size-field`,
63
- `spacing-select-field`, `layout-fields`, `media-content-fields`
64
-
65
- ### `db/` — raw SQL, transactions and bulk operations
66
-
67
- Postgres only, and the only folder needing the `@payloadcms/drizzle` + `drizzle-orm` peers.
68
-
69
- - `transaction-db` — the drizzle handle bound to an open transaction, so raw SQL commits with the
70
- local-API writes around it instead of running on a separate connection
71
- - `sessions` — `appendUserSession`: a race-safe INSERT onto an auth collection's session array
72
- - `sync-lock` — `createSyncLock({slug, table, staleMs})`: single-flight locking for a long job, as a
73
- conditional UPDATE rather than a read-then-write
74
- - `orphan-cleanup` — `findDeletableIds`, with guard rails that refuse rather than return everything
75
- - `delete-many-with-versions` — bulk delete that also purges the version snapshots the FK leaves behind
76
- - `sql-result` — `resultRows` / `rowCount` across driver response shapes
77
- - `external-ref` — provenance fields plus the partial-unique index that lets an importer upsert on
78
- `(source, id)` instead of duplicating docs on every run, and per-parent slug uniqueness for
79
- nested trees
80
-
81
- ### `errors/`
82
-
83
- - `field-errors` — the one reader for Payload's per-field error messages
84
- - `is-duplicate-error` — detects a unique-constraint violation in both shapes Payload surfaces it in
85
- - `public-error` — a message safe to show a user, or a fallback for anything that could leak internals
86
-
87
- ### `operations/` — write-path and job helpers
88
-
89
- - `publish-transition` — autosave-vs-unpublish disambiguation, cheap and exact variants
90
- - `suppress-context` — ref-counted `req.context` flags, safe under a bulk operation's shared context
91
- - `after-response` — defer non-critical work past the response, falling back to inline outside a request
92
- - `run-queued-jobs` — drains the Payload job queue, which nothing else does
93
- - `unique-slug`, `unique-username` — collision-free values, each candidate checked exactly
94
- - `accent-colour-hook` — `accentColourHook({field, source, extract})`: an afterChange hook that
95
- keeps a colour field in step with the document's picture, deferred past the response. The decode
96
- is the caller's `extract`.
97
-
98
- `src/internal/` holds implementation detail and is not importable: `"./internal/*": null` sits ahead
99
- of the wildcard in `exports`.
100
-
101
- ## Import provenance — `external-ref`
102
-
103
- For a collection whose docs can arrive from an external platform as well as being typed by hand: a
104
- product catalogue synced from Stripe or Shopify, a post archive migrated from WordPress or an RSS
105
- feed, an events listing pulled from a ticketing API, a tournament tree imported from a bracket
106
- service.
107
-
108
- The doc records which platform it came from and that platform's own id, so the importer upserts on
109
- the pair — a second run corrects the docs it already created instead of creating a duplicate of
110
- each. Hand-made docs set neither field, and no import touches them.
111
-
112
- ```ts
113
- import {
114
- externalRefFields,
115
- externalRefIndex,
116
- slugPerParentIndex,
117
- } from '@quitecustard/payload/db/external-ref'
118
-
119
- export const lessons: CollectionConfig = {
120
- slug: 'lessons',
121
- fields: [
122
- // …your fields
123
- ...externalRefFields([{ label: 'Stripe', value: 'stripe' }]),
124
- ],
125
- }
126
-
127
- export const lessonsImportIndex = externalRefIndex({ table: 'lessons', prefix: 'lessons' })
128
- export const lessonsSlugIndex = slugPerParentIndex({
129
- table: 'lessons',
130
- parent: 'module',
131
- prefix: 'lessons',
132
- })
133
- ```
134
-
135
- ```ts
136
- // payload.config.ts
137
- db: postgresAdapter({ afterSchemaInit: [lessonsImportIndex, lessonsSlugIndex] })
138
- ```
139
-
140
- Two hooks, because they answer to different needs and a collection rarely wants both:
141
-
142
- - `externalRefIndex` — unique `(externalSource, externalRef)`, partial to imported rows. This is
143
- what makes the upsert safe under concurrency: without it, two overlapping import runs both find no
144
- doc for a source id and both create one. Only for a collection carrying `externalRefFields`, since
145
- it indexes those columns.
146
- - `slugPerParentIndex` — unique `(parent, slug)`. Nothing to do with imports: it's for a tree whose
147
- slugs legitimately repeat across parents — `getting-started` under every docs section, `lesson-1`
148
- under every module — and whose lookups always AND on the parent.
149
-
150
- Payload's `afterSchemaInit` hooks compose, each wrapping the previous config builder rather than
151
- replacing it, so registering both on one table is safe.
152
-
153
- ## Contracts to know
154
-
155
- - `sync-lock` — `createSyncLock()` expects a global with `isRunning`, `startedBy` and `startedAt`
156
- fields, defaulting to slug `sync-lock` on table `sync_lock`; pass `{ slug, table, staleMs }` for
157
- anything else.
158
- - `orphan-cleanup` — `findDeletableIds` reflects foreign keys from `pg_constraint`, so the caller
159
- names the tables that count as the row's own data via `ignore`. Non-`public` schemas pass
160
- `{ schema }`.
161
- - `sessions` — `appendUserSession` defaults `table` to `users_sessions`, Payload's own naming for a
162
- `users` collection; pass `table` for any other auth collection. It is a raw INSERT rather than a
163
- `payload.update` on purpose — the module header has the FOR UPDATE / FOR KEY SHARE deadlock
164
- reason.
165
- - Everything under `db/` needs **a Postgres adapter built on `@payloadcms/drizzle`** —
166
- `@payloadcms/db-postgres` and `@payloadcms/db-vercel-postgres` both qualify, since they differ
167
- only in the connection driver. They talk to the shared drizzle layer, never to an adapter
168
- directly. What they can't run on is SQLite or Mongo: the raw SQL uses `pg_constraint`,
169
- `timestamptz` and data-modifying CTEs. No module outside `db/` imports drizzle at all, so the
170
- other five folders work on any adapter.
171
- - `fields/seo-tab` assumes `@payloadcms/plugin-seo`, and `operations/after-response` assumes `next`,
172
- as does `operations/accent-colour-hook`, which defers through it. Those are the only modules
173
- touching either peer.
174
-
175
- MIT licensed. Source: [custard-kit](https://github.com/QuiteCustard/custard-kit).
1
+ # @quitecustard/payload
2
+
3
+ Helpers generic over any Payload v3 project. One module per file — no barrels:
4
+
5
+ ```ts
6
+ import { relId } from '@quitecustard/payload/documents/resolve-ref'
7
+ import { transactionDb } from '@quitecustard/payload/db/transaction-db'
8
+ ```
9
+
10
+ ## Install
11
+
12
+ ```
13
+ pnpm add @quitecustard/payload
14
+ ```
15
+
16
+ Every module is a subpath export, so TypeScript needs `moduleResolution` set to `bundler`,
17
+ `node16` or `nodenext` — the legacy `node` resolution can't see subpath exports at all.
18
+
19
+ Peer dependencies: `payload` (required), `@payloadcms/drizzle` + `drizzle-orm` and `next` (optional —
20
+ only some modules touch them). Payload's module augmentation means a consumer's generated types
21
+ flow through the `CollectionSlug`-generic helpers automatically.
22
+
23
+ ## Contents
24
+
25
+ Every module is one subpath: `@quitecustard/payload/<folder>/<module>`. There are no barrels, so
26
+ the list below doubles as the import paths. Each export carries JSDoc, which is what your editor
27
+ shows on hover — this page is the map, not the reference.
28
+
29
+ ### `documents/` — reading what Payload hands back
30
+
31
+ - `resolve-ref` — `relId` / `relDoc` / `relDocs` / `firstRelDoc` / `relIds` / `relName` /
32
+ `resolveMedia`: relation narrowing without casts, tolerant of populate depth. Ids are typed as
33
+ Payload's `DefaultDocumentIDType`, so they are `number` or `string` to match your generated types
34
+ - `locale-record` — flattens a `locale: 'all'` read into `Partial<Record<Locale, string>>`
35
+ - `published-where` — the published clause, stated once so a bypassing read and the access rule
36
+ cannot drift apart
37
+ - `collection-versions` — `draftVersions(maxPerDoc?)`: the autosave + schedulePublish shape
38
+ - `lexical-plain-text` — `lexicalPlainText` / `lexicalNodeText`: a rich text value as plain text,
39
+ one block per line, for search indexes and excerpts
40
+
41
+ ### `access/`
42
+
43
+ - `anyone` — `anyone` / `anyoneFieldLevel` / `nobody`
44
+ - `role-gate` — `hasRole` / `roleGate` / `roleGateFieldLevel`: the mechanism for reading a role off
45
+ a caller. Which roles exist, and what each one may do, stays in the consuming project.
46
+ - `self-access` — `isSameUser` / `isSelfFieldLevel` / `selfOrAdminFieldLevel`, across Payload's
47
+ three field-access argument shapes; takes a `getUserId` resolver for a project with more than one
48
+ auth collection
49
+
50
+ ### `fields/` — field and admin-config factories
51
+
52
+ Every field rendered by a custom component takes that component's import path as a **required**
53
+ parameter — pass your own. Each is a factory, never a shared constant: `buildConfig` sanitises field
54
+ objects in place, so two collections must not receive one.
55
+
56
+ - `link-field` — polymorphic link (internal reference, custom URL, optional static route, dropdown,
57
+ in-page anchor, phone, email); each type appears only if its collection or component was supplied
58
+ - `hero-field` — the image/video/poster banner group, parameterised on the two upload collections
59
+ - `owner-field` — a relationship auto-stamped to the creating user, refused on update by field-level
60
+ access rather than by `admin.readOnly`, which Payload never consults on a write
61
+ - `seo-tab` — over `@payloadcms/plugin-seo`'s field factories
62
+ - `link-url` — `validateLinkField`: the link protocol allowlist in the one-argument shape a
63
+ field's `validate` takes
64
+ - `social-url` — `normaliseSocialUrl` (bare host → `https://…`) plus `validateSocialUrl`
65
+ - `colour-picker-field`, `colour-options-field`, `phone-field`, `height-field`, `size-field`,
66
+ `spacing-select-field`, `layout-fields`, `media-content-fields`
67
+
68
+ ### `db/` — raw SQL, transactions and bulk operations
69
+
70
+ Postgres only, and the only folder needing the `@payloadcms/drizzle` + `drizzle-orm` peers.
71
+
72
+ - `transaction-db` — the drizzle handle bound to an open transaction, so raw SQL commits with the
73
+ local-API writes around it instead of running on a separate connection
74
+ - `sessions` — `appendUserSession`: a race-safe INSERT onto an auth collection's session array
75
+ - `sync-lock` — `createSyncLock({slug, table, staleMs})`: single-flight locking for a long job, as a
76
+ conditional UPDATE rather than a read-then-write
77
+ - `orphan-cleanup` — `findDeletableIds`, with guard rails that refuse rather than return everything,
78
+ and `fkTablesReferencing`, the foreign-key reflection it is built on
79
+ - `delete-many-with-versions` — bulk delete that also purges the version snapshots the FK leaves behind
80
+ - `sql-result` — `resultRows` / `rowCount` across driver response shapes
81
+ - `external-ref` — provenance fields plus the partial-unique index that lets an importer upsert on
82
+ `(source, id)` instead of duplicating docs on every run, and per-parent slug uniqueness for
83
+ nested trees
84
+
85
+ ### `errors/`
86
+
87
+ - `field-errors` — the one reader for Payload's per-field error messages
88
+ - `is-duplicate-error` — detects a unique-constraint violation in both shapes Payload surfaces it in
89
+ - `public-error` — a message safe to show a user, or a fallback for anything that could leak internals
90
+
91
+ ### `operations/` — write-path and job helpers
92
+
93
+ - `publish-transition` — autosave-vs-unpublish disambiguation, cheap and exact variants. The exact
94
+ one reads the published row and never trusts the request's query flags
95
+ - `suppress-context` — ref-counted `req.context` flags, safe under a bulk operation's shared context
96
+ - `after-response` — defer non-critical work past the response, falling back to inline outside a request
97
+ - `run-queued-jobs` — drains the Payload job queue, which nothing else does
98
+ - `unique-slug`, `unique-username` — collision-free values, each candidate checked exactly.
99
+ `resolveUniqueUsername` takes an `isTaken` hook for a name that is unavailable for a reason the
100
+ collection cannot see
101
+ - `accent-colour-hook` — `accentColourHook({field, source, extract})`: an afterChange hook that
102
+ keeps a colour field in step with the document's picture, deferred past the response. The decode
103
+ is the caller's `extract`.
104
+
105
+ `src/internal/` holds implementation detail and is not importable: `"./internal/*": null` sits ahead
106
+ of the wildcard in `exports`.
107
+
108
+ ## Import provenance — `external-ref`
109
+
110
+ For a collection whose docs can arrive from an external platform as well as being typed by hand: a
111
+ product catalogue synced from Stripe or Shopify, a post archive migrated from WordPress or an RSS
112
+ feed, an events listing pulled from a ticketing API, a tournament tree imported from a bracket
113
+ service.
114
+
115
+ The doc records which platform it came from and that platform's own id, so the importer upserts on
116
+ the pair — a second run corrects the docs it already created instead of creating a duplicate of
117
+ each. Hand-made docs set neither field, and no import touches them.
118
+
119
+ ```ts
120
+ import {
121
+ externalRefFields,
122
+ externalRefIndex,
123
+ slugPerParentIndex,
124
+ } from '@quitecustard/payload/db/external-ref'
125
+
126
+ export const lessons: CollectionConfig = {
127
+ slug: 'lessons',
128
+ fields: [
129
+ // …your fields
130
+ ...externalRefFields([{ label: 'Stripe', value: 'stripe' }]),
131
+ ],
132
+ }
133
+
134
+ export const lessonsImportIndex = externalRefIndex({ table: 'lessons', prefix: 'lessons' })
135
+ export const lessonsSlugIndex = slugPerParentIndex({
136
+ table: 'lessons',
137
+ parent: 'module',
138
+ prefix: 'lessons',
139
+ })
140
+ ```
141
+
142
+ ```ts
143
+ // payload.config.ts
144
+ db: postgresAdapter({ afterSchemaInit: [lessonsImportIndex, lessonsSlugIndex] })
145
+ ```
146
+
147
+ Two hooks, because they answer to different needs and a collection rarely wants both:
148
+
149
+ - `externalRefIndex` — unique `(externalSource, externalRef)`, partial to imported rows. This is
150
+ what makes the upsert safe under concurrency: without it, two overlapping import runs both find no
151
+ doc for a source id and both create one. Only for a collection carrying `externalRefFields`, since
152
+ it indexes those columns.
153
+ - `slugPerParentIndex` — unique `(parent, slug)`. Nothing to do with imports: it's for a tree whose
154
+ slugs legitimately repeat across parents — `getting-started` under every docs section, `lesson-1`
155
+ under every module — and whose lookups always AND on the parent.
156
+
157
+ Payload's `afterSchemaInit` hooks compose, each wrapping the previous config builder rather than
158
+ replacing it, so registering both on one table is safe.
159
+
160
+ ## Contracts to know
161
+
162
+ - `sync-lock` — `createSyncLock()` expects a global with `isRunning`, `startedBy` and `startedAt`
163
+ fields, defaulting to slug `sync-lock` on table `sync_lock`; pass `{ slug, table, staleMs }` for
164
+ anything else.
165
+ - `orphan-cleanup` — `findDeletableIds` reflects foreign keys from `pg_constraint`, so the caller
166
+ names the tables that count as the row's own data via `ignore`. Non-`public` schemas pass
167
+ `{ schema }`.
168
+ - `sessions` — `appendUserSession` defaults `table` to `users_sessions`, Payload's own naming for a
169
+ `users` collection; pass `table` for any other auth collection. It is a raw INSERT rather than a
170
+ `payload.update` on purpose — the module header has the FOR UPDATE / FOR KEY SHARE deadlock
171
+ reason.
172
+ - Everything under `db/` needs **a Postgres adapter built on `@payloadcms/drizzle`** —
173
+ `@payloadcms/db-postgres` and `@payloadcms/db-vercel-postgres` both qualify, since they differ
174
+ only in the connection driver. They talk to the shared drizzle layer, never to an adapter
175
+ directly. What they can't run on is SQLite or Mongo: the raw SQL uses `pg_constraint`,
176
+ `timestamptz` and data-modifying CTEs. No module outside `db/` imports drizzle at all, so the
177
+ other five folders work on any adapter.
178
+ - `fields/seo-tab` assumes `@payloadcms/plugin-seo`, and `operations/after-response` assumes `next`,
179
+ as does `operations/accent-colour-hook`, which defers through it. Those are the only modules
180
+ touching either peer.
181
+
182
+ MIT licensed. Source: [custard-kit](https://github.com/QuiteCustard/custard-kit).
@@ -1,4 +1,4 @@
1
- import type { Field } from 'payload';
1
+ import type { Field, FieldAccess } from 'payload';
2
2
  import type { PostgresSchemaHook } from '@payloadcms/drizzle/postgres';
3
3
  /**
4
4
  * Marks a doc as imported from an external platform - a product synced from Stripe, a post migrated
@@ -15,11 +15,21 @@ import type { PostgresSchemaHook } from '@payloadcms/drizzle/postgres';
15
15
  * Pair them with `externalRefIndex`, which is what makes the upsert safe under concurrency. Writing
16
16
  * the fields is the importer's job: attaching a source id to a doc that was made by hand is a
17
17
  * repair, and belongs in a script rather than the admin form.
18
+ *
19
+ * `access` is field-level access for both fields. Set `update` wherever the collection lets a
20
+ * non-staff owner edit the doc: re-pointing provenance would hand them a synced doc, or break the
21
+ * importer's upsert key.
18
22
  */
19
23
  export declare const externalRefFields: (sources: {
20
24
  label: string;
21
25
  value: string;
22
- }[]) => Field[];
26
+ }[], { access }?: {
27
+ access?: {
28
+ create?: FieldAccess;
29
+ read?: FieldAccess;
30
+ update?: FieldAccess;
31
+ };
32
+ }) => Field[];
23
33
  type AfterSchemaInitHook = PostgresSchemaHook;
24
34
  /**
25
35
  * One imported doc per source id: a unique index on `(externalSource, externalRef)`, partial to the
@@ -1,4 +1,5 @@
1
1
  import { sql } from 'drizzle-orm';
2
+ import { isRecord } from '@quitecustard/core/utils/is-record';
2
3
  import { uniqueIndex } from 'drizzle-orm/pg-core';
3
4
  // Import provenance: the fields an importer stamps on a doc, and the indexes its upsert leans on.
4
5
  // A plain `//` header like this one is stripped from the emitted .d.ts, so anything a consumer
@@ -18,12 +19,17 @@ import { uniqueIndex } from 'drizzle-orm/pg-core';
18
19
  * Pair them with `externalRefIndex`, which is what makes the upsert safe under concurrency. Writing
19
20
  * the fields is the importer's job: attaching a source id to a doc that was made by hand is a
20
21
  * repair, and belongs in a script rather than the admin form.
22
+ *
23
+ * `access` is field-level access for both fields. Set `update` wherever the collection lets a
24
+ * non-staff owner edit the doc: re-pointing provenance would hand them a synced doc, or break the
25
+ * importer's upsert key.
21
26
  */
22
- export const externalRefFields = (sources) => [
27
+ export const externalRefFields = (sources, { access } = {}) => [
23
28
  {
24
29
  name: 'externalSource',
25
30
  type: 'select',
26
31
  options: sources,
32
+ ...(access ? { access } : {}),
27
33
  admin: {
28
34
  position: 'sidebar',
29
35
  description: 'Source platform this doc was imported from.',
@@ -34,6 +40,7 @@ export const externalRefFields = (sources) => [
34
40
  name: 'externalRef',
35
41
  label: 'External Ref',
36
42
  type: 'text',
43
+ ...(access ? { access } : {}),
37
44
  admin: {
38
45
  position: 'sidebar',
39
46
  description: "The source platform's own id for this doc, stored verbatim.",
@@ -49,6 +56,20 @@ const extendWith = (table, extraConfig) => {
49
56
  return schema;
50
57
  };
51
58
  };
59
+ const plainIdentifier = /^[a-z_][a-z0-9_]*$/;
60
+ // The column's PHYSICAL name, read off the column rather than written out: a `dbName` on the field
61
+ // changes it, and a literal `external_source` would then name a column that isn't there.
62
+ //
63
+ // Rendered bare, not by interpolating the column object. Interpolation emits `"table"."column"`,
64
+ // and the predicate's text is stored verbatim in the migration snapshot - so the two spellings of
65
+ // one index read as a schema change, and the index is dropped and recreated. A name that needs
66
+ // quoting to be valid still gets it.
67
+ const columnName = (column) => {
68
+ const name = isRecord(column) && typeof column.name === 'string' ? column.name : '';
69
+ if (!name)
70
+ throw new Error('externalRefIndex: the table has no externalSource column');
71
+ return plainIdentifier.test(name) ? sql.raw(name) : sql.identifier(name);
72
+ };
52
73
  /**
53
74
  * One imported doc per source id: a unique index on `(externalSource, externalRef)`, partial to the
54
75
  * rows that have a source, which is what makes an importer's upsert safe under concurrency.
@@ -64,9 +85,7 @@ const extendWith = (table, extraConfig) => {
64
85
  export const externalRefIndex = ({ table, prefix, }) => extendWith(table, (t) => ({
65
86
  externalRefUnique: uniqueIndex(`${prefix}_external_ref_uq`)
66
87
  .on(t.externalSource, t.externalRef)
67
- // Interpolated rather than written out: a `dbName` on the field changes the physical column,
68
- // and a literal `external_source` here would name a column that isn't there.
69
- .where(sql `${t.externalSource} IS NOT NULL`),
88
+ .where(sql `${columnName(t.externalSource)} IS NOT NULL`),
70
89
  }));
71
90
  /**
72
91
  * Slug uniqueness scoped to a parent instead of the whole collection - for a tree whose slugs
@@ -1,5 +1,21 @@
1
1
  import type { BasePayload } from 'payload';
2
2
  import { type SQL } from 'drizzle-orm';
3
+ /** One foreign key pointing at a table: the referring table and its column. */
4
+ export type FkRef = {
5
+ tbl: string;
6
+ col: string;
7
+ };
8
+ /**
9
+ * Every foreign key that references `target`, read from `pg_constraint` at call time - what a
10
+ * purge has to clear or check before a row of `target` can go.
11
+ *
12
+ * ```ts
13
+ * const refs = await fkTablesReferencing(payload, 'media')
14
+ * ```
15
+ *
16
+ * Only the first column of a composite foreign key is reported.
17
+ */
18
+ export declare const fkTablesReferencing: (payload: BasePayload, target: string, schema?: string) => Promise<FkRef[]>;
3
19
  /** What counts as the row's own data, and where to look for the tables. */
4
20
  export type OrphanScanOptions = {
5
21
  /**
@@ -1,14 +1,24 @@
1
1
  import { sql } from 'drizzle-orm';
2
2
  import { isRecord } from '@quitecustard/core/utils/is-record';
3
3
  import { resultRows } from './sql-result.js';
4
- const fkTablesReferencing = async (payload, target, schema) => {
5
- const res = await payload.db.drizzle.execute(sql `
6
- SELECT t.relname AS tbl, a.attname AS col
7
- FROM pg_constraint con
8
- JOIN pg_class ft ON ft.oid = con.confrelid
9
- JOIN pg_class t ON t.oid = con.conrelid
10
- JOIN pg_namespace n ON n.oid = con.connamespace
11
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = con.conkey[1]
4
+ /**
5
+ * Every foreign key that references `target`, read from `pg_constraint` at call time - what a
6
+ * purge has to clear or check before a row of `target` can go.
7
+ *
8
+ * ```ts
9
+ * const refs = await fkTablesReferencing(payload, 'media')
10
+ * ```
11
+ *
12
+ * Only the first column of a composite foreign key is reported.
13
+ */
14
+ export const fkTablesReferencing = async (payload, target, schema = 'public') => {
15
+ const res = await payload.db.drizzle.execute(sql `
16
+ SELECT t.relname AS tbl, a.attname AS col
17
+ FROM pg_constraint con
18
+ JOIN pg_class ft ON ft.oid = con.confrelid
19
+ JOIN pg_class t ON t.oid = con.conrelid
20
+ JOIN pg_namespace n ON n.oid = con.connamespace
21
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = con.conkey[1]
12
22
  WHERE n.nspname = ${schema} AND con.contype = 'f' AND ft.relname = ${target}`);
13
23
  return resultRows(res).flatMap((row) => {
14
24
  if (!isRecord(row))
@@ -25,6 +25,9 @@ import type { BasePayload, PayloadRequest } from 'payload';
25
25
  *
26
26
  * Pass `req` wherever one exists: the statement then runs on the operation's own transaction
27
27
  * instead of the pooled root handle.
28
+ *
29
+ * Throws when `req` names a transaction that has no live session. Falling back to the root handle
30
+ * there would autocommit the INSERT outside the caller's transaction and whatever lock it holds.
28
31
  */
29
32
  export declare const appendUserSession: ({ payload, userId, sid, createdAt, expiresAt, req, table, }: {
30
33
  payload: BasePayload;
@@ -39,7 +42,7 @@ export declare const appendUserSession: ({ payload, userId, sid, createdAt, expi
39
42
  * uncommitted parent row (foreign key violation) and can deadlock against locks the outer
40
43
  * transaction already holds.
41
44
  */
42
- req?: PayloadRequest;
45
+ req?: Partial<PayloadRequest>;
43
46
  /** Physical table backing the auth collection's `sessions` array field. Defaults to Payload's
44
47
  * own naming for a `users` collection - `<collection>_sessions` for any other slug. */
45
48
  table?: string;
@@ -26,6 +26,9 @@ import { transactionDb } from './transaction-db.js';
26
26
  *
27
27
  * Pass `req` wherever one exists: the statement then runs on the operation's own transaction
28
28
  * instead of the pooled root handle.
29
+ *
30
+ * Throws when `req` names a transaction that has no live session. Falling back to the root handle
31
+ * there would autocommit the INSERT outside the caller's transaction and whatever lock it holds.
29
32
  */
30
33
  export const appendUserSession = async ({ payload, userId, sid, createdAt, expiresAt, req, table = 'users_sessions', }) => {
31
34
  const sessionsTable = sql.raw(`"${table}"`);
@@ -35,16 +38,18 @@ export const appendUserSession = async ({ payload, userId, sid, createdAt, expir
35
38
  // Awaited because Payload leaves `transactionID` as a promise while the transaction is still
36
39
  // being opened.
37
40
  const transactionID = await req?.transactionID;
38
- await transactionDb(payload, transactionID).execute(sql `
39
- WITH pruned AS (
40
- DELETE FROM ${sessionsTable} WHERE _parent_id = ${userId} AND expires_at <= now()
41
- )
42
- INSERT INTO ${sessionsTable} (id, _parent_id, _order, created_at, expires_at)
43
- VALUES (
44
- ${sid},
45
- ${userId},
46
- COALESCE((SELECT max(_order) FROM ${sessionsTable} WHERE _parent_id = ${userId}), 0) + 1,
47
- ${createdAt.toISOString()}::timestamptz,
48
- ${expiresAt.toISOString()}::timestamptz
41
+ if (transactionID != null && !payload.db.sessions?.[transactionID])
42
+ throw new Error('Session insertion requires an active transaction');
43
+ await transactionDb(payload, transactionID).execute(sql `
44
+ WITH pruned AS (
45
+ DELETE FROM ${sessionsTable} WHERE _parent_id = ${userId} AND expires_at <= now()
46
+ )
47
+ INSERT INTO ${sessionsTable} (id, _parent_id, _order, created_at, expires_at)
48
+ VALUES (
49
+ ${sid},
50
+ ${userId},
51
+ COALESCE((SELECT max(_order) FROM ${sessionsTable} WHERE _parent_id = ${userId}), 0) + 1,
52
+ ${createdAt.toISOString()}::timestamptz,
53
+ ${expiresAt.toISOString()}::timestamptz
49
54
  )`);
50
55
  };
@@ -1,10 +1,14 @@
1
+ import type { DefaultDocumentIDType } from 'payload';
1
2
  /**
2
3
  * A relationship field as Payload hands it over: an id at depth 0, the doc once populated, or empty.
3
4
  */
4
5
  export type Relation<T> = number | string | T | null | undefined;
5
- /** Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for
6
- * both numeric (Postgres serial) and string (UUID) primary keys. */
7
- export declare const relId: (rel: unknown) => number | string | null;
6
+ /**
7
+ * Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for both
8
+ * numeric (Postgres serial) and string (UUID) primary keys, and is typed as whichever the project's
9
+ * generated types say its ids are.
10
+ */
11
+ export declare const relId: (rel: unknown) => DefaultDocumentIDType | null;
8
12
  /** Narrow a relation to its populated doc (object), or null when it's still an unresolved id. */
9
13
  export declare const relDoc: <T extends {
10
14
  id: number | string;
@@ -13,8 +17,12 @@ export declare const relDoc: <T extends {
13
17
  export declare const relDocs: <T extends {
14
18
  id: number | string;
15
19
  }>(refs: readonly Relation<T>[] | null | undefined) => T[];
20
+ /** The first populated doc in a hasMany or join relation, or null when none is populated. */
21
+ export declare const firstRelDoc: <T extends {
22
+ id: number | string;
23
+ }>(refs: readonly Relation<T>[] | null | undefined) => T | null;
16
24
  /** A list of relationship values as plain ids, tolerant of populate depth; misses drop out. */
17
- export declare const relIds: (refs: readonly unknown[] | null | undefined) => (number | string)[];
25
+ export declare const relIds: (refs: readonly unknown[] | null | undefined) => DefaultDocumentIDType[];
18
26
  /**
19
27
  * A populated doc's display name, or null - for a bare id (depth 0), a missing relation, or a doc
20
28
  * with no name there is no name to give. `unknown` on purpose: this is THE narrowing for "name off
@@ -24,6 +32,6 @@ export declare const relIds: (refs: readonly unknown[] | null | undefined) => (n
24
32
  export declare const relName: (rel: unknown) => string | null;
25
33
  /** An upload relation as `{ id, url }`, or null when it is unpopulated or has no url yet. */
26
34
  export declare const resolveMedia: (val: unknown) => {
27
- id: number | string;
35
+ id: DefaultDocumentIDType;
28
36
  url: string;
29
37
  } | null;
@@ -1,8 +1,11 @@
1
1
  import { isRecord } from '@quitecustard/core/utils/is-record';
2
2
  /** The value at `key` on a maybe-populated ref, as unknown; undefined for ids and misses. */
3
3
  const refField = (rel, key) => (isRecord(rel) ? rel[key] : undefined);
4
- /** Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for
5
- * both numeric (Postgres serial) and string (UUID) primary keys. */
4
+ /**
5
+ * Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for both
6
+ * numeric (Postgres serial) and string (UUID) primary keys, and is typed as whichever the project's
7
+ * generated types say its ids are.
8
+ */
6
9
  export const relId = (rel) => {
7
10
  if (typeof rel === 'number' || typeof rel === 'string')
8
11
  return rel;
@@ -13,6 +16,8 @@ export const relId = (rel) => {
13
16
  export const relDoc = (rel) => isRecord(rel) ? rel : null;
14
17
  /** The populated docs of a relationship list; rows still held as ids (depth 0) drop out. */
15
18
  export const relDocs = (refs) => (refs ?? []).flatMap((ref) => relDoc(ref) ?? []);
19
+ /** The first populated doc in a hasMany or join relation, or null when none is populated. */
20
+ export const firstRelDoc = (refs) => relDocs(refs)[0] ?? null;
16
21
  /** A list of relationship values as plain ids, tolerant of populate depth; misses drop out. */
17
22
  export const relIds = (refs) => (refs ?? []).flatMap((ref) => {
18
23
  const id = relId(ref);
@@ -8,10 +8,13 @@
8
8
  * }
9
9
  * ```
10
10
  *
11
- * Payload's errors are safe to surface: a ValidationError's per-field messages are authored by the
12
- * project's own hooks for the user, and an APIError carries a message written for API consumers.
13
- * The field detail is preferred over a ValidationError's top-level message, which is only "The
14
- * following field is invalid: …". Anything else - a DB driver or network failure - can leak
15
- * internals like SQL fragments and constraint names, so it collapses to the fallback.
11
+ * Only a PUBLIC Payload error is surfaced: an `APIError` whose `isPublic` is not `false`. A
12
+ * ValidationError's per-field messages are authored by the project's own hooks for the user, and
13
+ * an APIError carries a message written for API consumers. The field detail is preferred over a
14
+ * ValidationError's top-level message, which is only "The following field is invalid: …".
15
+ *
16
+ * Anything else collapses to the fallback: a DB driver or network failure can leak internals like
17
+ * SQL fragments and constraint names, an APIError marked `isPublic: false` says so itself, and a
18
+ * plain object that merely has a `data.errors` array was not authored by anyone for a user.
16
19
  */
17
20
  export declare const publicErrorMessage: (err: unknown, fallback: string) => string;
@@ -10,17 +10,18 @@ import { fieldErrorMessages } from './field-errors.js';
10
10
  * }
11
11
  * ```
12
12
  *
13
- * Payload's errors are safe to surface: a ValidationError's per-field messages are authored by the
14
- * project's own hooks for the user, and an APIError carries a message written for API consumers.
15
- * The field detail is preferred over a ValidationError's top-level message, which is only "The
16
- * following field is invalid: …". Anything else - a DB driver or network failure - can leak
17
- * internals like SQL fragments and constraint names, so it collapses to the fallback.
13
+ * Only a PUBLIC Payload error is surfaced: an `APIError` whose `isPublic` is not `false`. A
14
+ * ValidationError's per-field messages are authored by the project's own hooks for the user, and
15
+ * an APIError carries a message written for API consumers. The field detail is preferred over a
16
+ * ValidationError's top-level message, which is only "The following field is invalid: …".
17
+ *
18
+ * Anything else collapses to the fallback: a DB driver or network failure can leak internals like
19
+ * SQL fragments and constraint names, an APIError marked `isPublic: false` says so itself, and a
20
+ * plain object that merely has a `data.errors` array was not authored by anyone for a user.
18
21
  */
19
22
  export const publicErrorMessage = (err, fallback) => {
23
+ if (!(err instanceof APIError) || err.isPublic === false)
24
+ return fallback;
20
25
  const detail = fieldErrorMessages(err);
21
- if (detail.length > 0)
22
- return detail.join(' ');
23
- if (err instanceof APIError)
24
- return err.message;
25
- return fallback;
26
+ return detail.length > 0 ? detail.join(' ') : err.message;
26
27
  };
@@ -1,6 +1,22 @@
1
1
  import type { Field, SelectField } from 'payload';
2
- /** Left/center/right text alignment select, defaulting to left. */
3
- export declare const alignmentField: () => SelectField;
2
+ /**
3
+ * Left/center/right text alignment select, defaulting to left.
4
+ *
5
+ * ```ts
6
+ * alignmentField({ options: [{ label: 'Left', value: 'left' }, { label: 'Center', value: 'center' }], defaultValue: 'center' })
7
+ * ```
8
+ *
9
+ * Narrow `options` where a layout cannot honour all three, and move `defaultValue` with it - both
10
+ * are part of the stored enum, so they are the caller's to fix rather than this factory's.
11
+ */
12
+ export declare const alignmentField: (overrides?: {
13
+ defaultValue?: string;
14
+ options?: {
15
+ label: string;
16
+ value: string;
17
+ }[];
18
+ admin?: SelectField["admin"];
19
+ }) => SelectField;
4
20
  /** A plain "stretch to full width" toggle. */
5
21
  export declare const fullWidthField: () => Field;
6
22
  /** A scroll-reveal animation toggle plus its style (fade/rise/zoom). */
@@ -2,8 +2,17 @@
2
2
  // `hooks`, `access` and `admin` onto the object it was handed, and deletes `localized` where the
3
3
  // parent forbids it. One exported object reused across collections is therefore one object every
4
4
  // collection mutates.
5
- /** Left/center/right text alignment select, defaulting to left. */
6
- export const alignmentField = () => ({
5
+ /**
6
+ * Left/center/right text alignment select, defaulting to left.
7
+ *
8
+ * ```ts
9
+ * alignmentField({ options: [{ label: 'Left', value: 'left' }, { label: 'Center', value: 'center' }], defaultValue: 'center' })
10
+ * ```
11
+ *
12
+ * Narrow `options` where a layout cannot honour all three, and move `defaultValue` with it - both
13
+ * are part of the stored enum, so they are the caller's to fix rather than this factory's.
14
+ */
15
+ export const alignmentField = (overrides = {}) => ({
7
16
  name: 'alignment',
8
17
  type: 'select',
9
18
  defaultValue: 'left',
@@ -13,6 +22,7 @@ export const alignmentField = () => ({
13
22
  { label: 'Center', value: 'center' },
14
23
  { label: 'Right', value: 'right' },
15
24
  ],
25
+ ...overrides,
16
26
  });
17
27
  /** A plain "stretch to full width" toggle. */
18
28
  export const fullWidthField = () => ({
@@ -6,14 +6,14 @@ type SelectOption = {
6
6
  };
7
7
  /**
8
8
  * A polymorphic link field: internal reference, custom URL, and optionally a static route, a
9
- * dropdown-menu reference, and phone/email - each type only appears if its collection/component is
10
- * given, so an unwanted type is simply omitted rather than toggled off.
9
+ * dropdown-menu reference, an in-page anchor, and phone/email - each type only appears if its
10
+ * collection/component is given, so an unwanted type is simply omitted rather than toggled off.
11
11
  *
12
12
  * ```ts
13
13
  * linkField({ relationTo: ['pages', 'posts'], styleOptions: [{ label: 'Primary', value: 'primary' }] })
14
14
  * ```
15
15
  */
16
- export declare const linkField: ({ relationTo, dropdown, staticOptions, phoneComponent, styleOptions, disableLabel, localizedLabel, overrides, maxDepth, }: {
16
+ export declare const linkField: ({ relationTo, dropdown, staticOptions, phoneComponent, anchorComponent, anchorDescription, styleOptions, disableLabel, localizedLabel, overrides, maxDepth, }: {
17
17
  /** Collections the "internal link" type may point to. */
18
18
  relationTo: CollectionSlug[];
19
19
  /** Collection slug for a "dropdown" link type (e.g. a menus collection). Omit to disable it. */
@@ -22,6 +22,14 @@ export declare const linkField: ({ relationTo, dropdown, staticOptions, phoneCom
22
22
  staticOptions?: Option[];
23
23
  /** Admin component path for the "phone" type (see `phoneField`). Omit to disable phone/email. */
24
24
  phoneComponent?: string;
25
+ /**
26
+ * Admin component path for an "anchor" type: a link to a named marker on the same document. The
27
+ * value is stored as text; the component is the picker that lists the markers there are. Omit to
28
+ * disable it.
29
+ */
30
+ anchorComponent?: string;
31
+ /** Help text under the anchor picker, e.g. where its markers come from. */
32
+ anchorDescription?: string;
25
33
  /** Style select options (e.g. primary/secondary/outline). Omit to skip the style field. */
26
34
  styleOptions?: SelectOption[];
27
35
  /** Whether the field also carries a "Label" text input alongside the link type. */
@@ -7,14 +7,14 @@ import { phoneField } from './phone-field.js';
7
7
  const withRowWidth = (field) => ({ ...field, admin: { ...field.admin, width: '50%' } });
8
8
  /**
9
9
  * A polymorphic link field: internal reference, custom URL, and optionally a static route, a
10
- * dropdown-menu reference, and phone/email - each type only appears if its collection/component is
11
- * given, so an unwanted type is simply omitted rather than toggled off.
10
+ * dropdown-menu reference, an in-page anchor, and phone/email - each type only appears if its
11
+ * collection/component is given, so an unwanted type is simply omitted rather than toggled off.
12
12
  *
13
13
  * ```ts
14
14
  * linkField({ relationTo: ['pages', 'posts'], styleOptions: [{ label: 'Primary', value: 'primary' }] })
15
15
  * ```
16
16
  */
17
- export const linkField = ({ relationTo, dropdown, staticOptions, phoneComponent, styleOptions, disableLabel = false, localizedLabel = false, overrides = {}, maxDepth = 1, }) => {
17
+ export const linkField = ({ relationTo, dropdown, staticOptions, phoneComponent, anchorComponent, anchorDescription, styleOptions, disableLabel = false, localizedLabel = false, overrides = {}, maxDepth = 1, }) => {
18
18
  const typeOptions = [
19
19
  { label: 'Internal link', value: 'reference' },
20
20
  { label: 'Custom URL', value: 'custom' },
@@ -23,6 +23,8 @@ export const linkField = ({ relationTo, dropdown, staticOptions, phoneComponent,
23
23
  typeOptions.push({ label: 'Static link', value: 'static' });
24
24
  if (dropdown)
25
25
  typeOptions.push({ label: 'Dropdown', value: 'dropdown' });
26
+ if (anchorComponent)
27
+ typeOptions.push({ label: 'Anchor', value: 'anchor' });
26
28
  if (phoneComponent)
27
29
  typeOptions.push({ label: 'Phone', value: 'phone' }, { label: 'Email', value: 'email' });
28
30
  const noNewTabTypes = new Set([
@@ -97,6 +99,19 @@ export const linkField = ({ relationTo, dropdown, staticOptions, phoneComponent,
97
99
  },
98
100
  });
99
101
  }
102
+ if (anchorComponent) {
103
+ linkTypes.push({
104
+ name: 'anchor',
105
+ label: 'Marker',
106
+ type: 'text',
107
+ required: true,
108
+ admin: {
109
+ ...(anchorDescription ? { description: anchorDescription } : {}),
110
+ condition: (_, siblingData) => siblingData?.type === 'anchor',
111
+ components: { Field: anchorComponent },
112
+ },
113
+ });
114
+ }
100
115
  const linkResult = {
101
116
  name: 'link',
102
117
  type: 'group',
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The link protocol allowlist as a text field's `validate`: root-relative paths, in-page anchors,
3
+ * http(s), mailto: and tel:, never javascript:/data:. Empty values pass, so pair it with
4
+ * `required` where the field must be filled.
5
+ *
6
+ * ```ts
7
+ * { name: 'website', type: 'text', validate: validateLinkField }
8
+ * ```
9
+ *
10
+ * Use this, not `validateLinkUrl` from `@quitecustard/core/url/link-protocol`, as the `validate`
11
+ * itself. Payload calls `validate(value, options)`, and `validateLinkUrl`'s second parameter is a
12
+ * protocol allowlist - the options object would land in that slot.
13
+ */
14
+ export declare const validateLinkField: (value: string | null | undefined) => true | string;
@@ -0,0 +1,15 @@
1
+ import { validateLinkUrl } from '@quitecustard/core/url/link-protocol';
2
+ /**
3
+ * The link protocol allowlist as a text field's `validate`: root-relative paths, in-page anchors,
4
+ * http(s), mailto: and tel:, never javascript:/data:. Empty values pass, so pair it with
5
+ * `required` where the field must be filled.
6
+ *
7
+ * ```ts
8
+ * { name: 'website', type: 'text', validate: validateLinkField }
9
+ * ```
10
+ *
11
+ * Use this, not `validateLinkUrl` from `@quitecustard/core/url/link-protocol`, as the `validate`
12
+ * itself. Payload calls `validate(value, options)`, and `validateLinkUrl`'s second parameter is a
13
+ * protocol allowlist - the options object would land in that slot.
14
+ */
15
+ export const validateLinkField = (value) => validateLinkUrl(value);
@@ -7,11 +7,17 @@ import { type CollectionSlug, type Field, type GroupField, type RichTextField }
7
7
  * mediaContentFields({ editor, imageCollection: 'images', videoCollection: 'videos' })
8
8
  * ```
9
9
  */
10
- export declare const mediaContentFields: ({ editor, imageCollection, videoCollection, disableMedia, }: {
10
+ export declare const mediaContentFields: ({ editor, imageCollection, videoCollection, disableMedia, localizedWysiwyg, }: {
11
11
  editor: RichTextField["editor"];
12
12
  imageCollection: CollectionSlug;
13
13
  videoCollection: CollectionSlug;
14
14
  disableMedia?: boolean;
15
+ /**
16
+ * Localise the rich-text body. Only where the fields sit OUTSIDE an already-localised parent: a
17
+ * field inside a localised blocks field rides that localisation, and Payload strips a nested
18
+ * `localized` there.
19
+ */
20
+ localizedWysiwyg?: boolean;
15
21
  }) => Field[];
16
22
  /** `mediaContentFields`, wrapped in an unlabelled group - the shape most blocks actually embed. */
17
23
  export declare const mediaContentGroupField: (options: {
@@ -19,5 +25,6 @@ export declare const mediaContentGroupField: (options: {
19
25
  imageCollection: CollectionSlug;
20
26
  videoCollection: CollectionSlug;
21
27
  disableMedia?: boolean;
28
+ localizedWysiwyg?: boolean;
22
29
  overrides?: Partial<GroupField>;
23
30
  }) => GroupField;
@@ -1,5 +1,5 @@
1
1
  import { deepMerge, } from 'payload';
2
- const buildContentFields = (editor) => [
2
+ const buildContentFields = (editor, localizedWysiwyg) => [
3
3
  {
4
4
  name: 'hasWysiwyg',
5
5
  type: 'checkbox',
@@ -20,6 +20,7 @@ const buildContentFields = (editor) => [
20
20
  type: 'richText',
21
21
  editor,
22
22
  label: false,
23
+ ...(localizedWysiwyg ? { localized: true } : {}),
23
24
  admin: {
24
25
  condition: (_, { hasWysiwyg } = {}) => hasWysiwyg,
25
26
  },
@@ -87,8 +88,8 @@ const buildMediaPickerFields = (imageCollection, videoCollection) => [
87
88
  * mediaContentFields({ editor, imageCollection: 'images', videoCollection: 'videos' })
88
89
  * ```
89
90
  */
90
- export const mediaContentFields = ({ editor, imageCollection, videoCollection, disableMedia = false, }) => [
91
- ...buildContentFields(editor),
91
+ export const mediaContentFields = ({ editor, imageCollection, videoCollection, disableMedia = false, localizedWysiwyg = false, }) => [
92
+ ...buildContentFields(editor, localizedWysiwyg),
92
93
  ...(disableMedia ? [] : buildMediaPickerFields(imageCollection, videoCollection)),
93
94
  ];
94
95
  /** `mediaContentFields`, wrapped in an unlabelled group - the shape most blocks actually embed. */
@@ -1,4 +1,4 @@
1
- import { after } from 'next/server';
1
+ import { after } from 'next/server.js';
2
2
  /**
3
3
  * Run non-critical follow-up work *after* the HTTP response has been sent, via
4
4
  * Next.js `after` (backed by Vercel's `waitUntil`, so the serverless invocation
@@ -19,6 +19,10 @@ type StatusDoc = {
19
19
  * sets either flag - it seeds `req.query` from whatever it was handed and adds only `depth` - so
20
20
  * those flags, which are all this helper tests, are absent on a Local API call and a Local API
21
21
  * draft save always reads as a real transition here.
22
+ *
23
+ * The flags are a hint, not evidence, in the other direction too: `autosave=true` without
24
+ * `draft=true` can still perform a real unpublish. Use this only where a wrong answer costs a
25
+ * redundant cache purge; {@link isDraftSaveNotUnpublish} is the exact check.
22
26
  */
23
27
  export declare const looksLikeAutosaveTick: (req: PayloadRequest, doc: StatusDoc) => boolean;
24
28
  /**
@@ -38,8 +42,11 @@ export declare const isCurrentlyPublished: (payload: BasePayload, collection: Co
38
42
  * `_versions` only and leaves the published row intact, while a real unpublish flips it. Costs one
39
43
  * indexed read, and only on the ambiguous (draft-direction) branch.
40
44
  *
41
- * Use this wherever the answer drives a STATE MUTATION or an outbound side effect. The cheap sync
42
- * check above is proportionate only where a false negative merely costs a redundant cache purge.
45
+ * The published row is the only evidence read. The request's query flags are never consulted:
46
+ * a Local API call carries none, and `autosave=true` without `draft=true` can be a real unpublish.
47
+ *
48
+ * Use this wherever the answer drives a STATE MUTATION, an outbound side effect or a public cache
49
+ * purge.
43
50
  */
44
51
  export declare const isDraftSaveNotUnpublish: (collection: CollectionSlug, doc: StatusDoc, req: PayloadRequest) => Promise<boolean>;
45
52
  export {};
@@ -16,6 +16,10 @@ const flagged = (value) => value === true || value === 'true';
16
16
  * sets either flag - it seeds `req.query` from whatever it was handed and adds only `depth` - so
17
17
  * those flags, which are all this helper tests, are absent on a Local API call and a Local API
18
18
  * draft save always reads as a real transition here.
19
+ *
20
+ * The flags are a hint, not evidence, in the other direction too: `autosave=true` without
21
+ * `draft=true` can still perform a real unpublish. Use this only where a wrong answer costs a
22
+ * redundant cache purge; {@link isDraftSaveNotUnpublish} is the exact check.
19
23
  */
20
24
  export const looksLikeAutosaveTick = (req, doc) => {
21
25
  if (doc._status === 'published')
@@ -50,15 +54,16 @@ export const isCurrentlyPublished = async (payload, collection, id) => {
50
54
  * `_versions` only and leaves the published row intact, while a real unpublish flips it. Costs one
51
55
  * indexed read, and only on the ambiguous (draft-direction) branch.
52
56
  *
53
- * Use this wherever the answer drives a STATE MUTATION or an outbound side effect. The cheap sync
54
- * check above is proportionate only where a false negative merely costs a redundant cache purge.
57
+ * The published row is the only evidence read. The request's query flags are never consulted:
58
+ * a Local API call carries none, and `autosave=true` without `draft=true` can be a real unpublish.
59
+ *
60
+ * Use this wherever the answer drives a STATE MUTATION, an outbound side effect or a public cache
61
+ * purge.
55
62
  */
56
63
  export const isDraftSaveNotUnpublish = async (collection, doc, req) => {
57
64
  // Publishing is always a genuine transition; only the draft direction is ambiguous.
58
65
  if (doc._status === 'published')
59
66
  return false;
60
- if (looksLikeAutosaveTick(req, doc))
61
- return true;
62
67
  try {
63
68
  // Threading `req` keeps this on the operation's own transaction (a req-less nested call would
64
69
  // open a second one and deadlock against it) and shows the row as this write left it.
@@ -66,6 +71,10 @@ export const isDraftSaveNotUnpublish = async (collection, doc, req) => {
66
71
  collection,
67
72
  id: doc.id,
68
73
  depth: 0,
74
+ // Explicit, because a request that arrived with `?draft=true` would otherwise read the latest
75
+ // version - the very row this check must not be answered from.
76
+ draft: false,
77
+ select: { _status: true },
69
78
  req,
70
79
  });
71
80
  return isRecord(persisted) && persisted._status === 'published';
@@ -10,6 +10,12 @@ export type UniqueUsernameOptions = {
10
10
  * concurrently in one run; each candidate this resolves is added to the set.
11
11
  */
12
12
  reserved?: Set<string>;
13
+ /**
14
+ * An extra reason a candidate is unavailable, asked alongside the collection lookup - a name
15
+ * that still redirects to its previous holder, one on a reserved-routes list. Return true to
16
+ * skip the candidate.
17
+ */
18
+ isTaken?: (candidate: string) => Promise<boolean>;
13
19
  };
14
20
  /**
15
21
  * A username derived from `base` that nobody currently holds - the base itself where it is free,
@@ -37,4 +43,4 @@ export type UniqueUsernameOptions = {
37
43
  * an emoji-only or purely punctuation name would normalise to '', and every such base would collide
38
44
  * on the same empty username.
39
45
  */
40
- export declare const resolveUniqueUsername: (base: string, payload: BasePayload, { collection, field, reserved }?: UniqueUsernameOptions) => Promise<string>;
46
+ export declare const resolveUniqueUsername: (base: string, payload: BasePayload, { collection, field, reserved, isTaken }?: UniqueUsernameOptions) => Promise<string>;
@@ -25,7 +25,7 @@ import { normaliseUsernameSlug } from '@quitecustard/core/format/normalise';
25
25
  * an emoji-only or purely punctuation name would normalise to '', and every such base would collide
26
26
  * on the same empty username.
27
27
  */
28
- export const resolveUniqueUsername = async (base, payload, { collection = 'users', field = 'username', reserved } = {}) => {
28
+ export const resolveUniqueUsername = async (base, payload, { collection = 'users', field = 'username', reserved, isTaken } = {}) => {
29
29
  const normalised = normaliseUsernameSlug(base);
30
30
  if (!normalised)
31
31
  throw new Error(`Cannot derive a username from ${JSON.stringify(base)}`);
@@ -42,11 +42,11 @@ export const resolveUniqueUsername = async (base, payload, { collection = 'users
42
42
  const candidate = claimCandidate(i);
43
43
  if (!candidate)
44
44
  continue;
45
- const { totalDocs } = await payload.count({
46
- collection,
47
- where: { [field]: { equals: candidate } },
48
- });
49
- if (totalDocs === 0)
45
+ const [{ totalDocs }, takenElsewhere] = await Promise.all([
46
+ payload.count({ collection, where: { [field]: { equals: candidate } } }),
47
+ isTaken ? isTaken(candidate) : false,
48
+ ]);
49
+ if (totalDocs === 0 && !takenElsewhere)
50
50
  return candidate;
51
51
  }
52
52
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quitecustard/payload",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "Payload v3 helpers: relation narrowing, transactions, autosave-vs-unpublish detection, sync locks, unique slugs and usernames",
5
5
  "keywords": [
6
6
  "payload",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@quitecustard/core": "^0.2.1"
41
+ "@quitecustard/core": "^0.3.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@payloadcms/drizzle": "^3.0.0",