@quitecustard/payload 0.2.1 → 0.3.0

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,169 +1,180 @@
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
-
38
- ### `access/`
39
-
40
- - `anyone` — `anyone` / `anyoneFieldLevel` / `nobody`
41
- - `role-gate` — `hasRole` / `roleGate` / `roleGateFieldLevel`: the mechanism for reading a role off
42
- a caller. Which roles exist, and what each one may do, stays in the consuming project.
43
- - `self-access` — `isSameUser` / `isSelfFieldLevel` / `selfOrAdminFieldLevel`, across Payload's
44
- three field-access argument shapes; takes a `getUserId` resolver for a project with more than one
45
- auth collection
46
-
47
- ### `fields/` — field and admin-config factories
48
-
49
- Every field rendered by a custom component takes that component's import path as a **required**
50
- parameter — pass your own. Each is a factory, never a shared constant: `buildConfig` sanitises field
51
- objects in place, so two collections must not receive one.
52
-
53
- - `link-field` — polymorphic link (internal reference, custom URL, optional static route, dropdown,
54
- phone, email); each type appears only if its collection or component was supplied
55
- - `hero-field` — the image/video/poster banner group, parameterised on the two upload collections
56
- - `owner-field` — a relationship auto-stamped to the creating user, refused on update by field-level
57
- access rather than by `admin.readOnly`, which Payload never consults on a write
58
- - `seo-tab` — over `@payloadcms/plugin-seo`'s field factories
59
- - `social-url` — `normaliseSocialUrl` (bare host → `https://…`) plus `validateSocialUrl`
60
- - `colour-picker-field`, `colour-options-field`, `phone-field`, `height-field`, `size-field`,
61
- `spacing-select-field`, `layout-fields`, `media-content-fields`
62
-
63
- ### `db/` — raw SQL, transactions and bulk operations
64
-
65
- Postgres only, and the only folder needing the `@payloadcms/drizzle` + `drizzle-orm` peers.
66
-
67
- - `transaction-db` — the drizzle handle bound to an open transaction, so raw SQL commits with the
68
- local-API writes around it instead of running on a separate connection
69
- - `sessions` — `appendUserSession`: a race-safe INSERT onto an auth collection's session array
70
- - `sync-lock` — `createSyncLock({slug, table, staleMs})`: single-flight locking for a long job, as a
71
- conditional UPDATE rather than a read-then-write
72
- - `orphan-cleanup` — `findDeletableIds`, with guard rails that refuse rather than return everything
73
- - `delete-many-with-versions` — bulk delete that also purges the version snapshots the FK leaves behind
74
- - `sql-result` — `resultRows` / `rowCount` across driver response shapes
75
- - `external-ref` — provenance fields plus the partial-unique index that lets an importer upsert on
76
- `(source, id)` instead of duplicating docs on every run, and per-parent slug uniqueness for
77
- nested trees
78
-
79
- ### `errors/`
80
-
81
- - `field-errors` — the one reader for Payload's per-field error messages
82
- - `is-duplicate-error` — detects a unique-constraint violation in both shapes Payload surfaces it in
83
- - `public-error` — a message safe to show a user, or a fallback for anything that could leak internals
84
-
85
- ### `operations/` — write-path and job helpers
86
-
87
- - `publish-transition` — autosave-vs-unpublish disambiguation, cheap and exact variants
88
- - `suppress-context` — ref-counted `req.context` flags, safe under a bulk operation's shared context
89
- - `after-response` — defer non-critical work past the response, falling back to inline outside a request
90
- - `run-queued-jobs` — drains the Payload job queue, which nothing else does
91
- - `unique-slug`, `unique-username` — collision-free values, each candidate checked exactly
92
-
93
- `src/internal/` holds implementation detail and is not importable: `"./internal/*": null` sits ahead
94
- of the wildcard in `exports`.
95
-
96
- ## Import provenance — `external-ref`
97
-
98
- For a collection whose docs can arrive from an external platform as well as being typed by hand: a
99
- product catalogue synced from Stripe or Shopify, a post archive migrated from WordPress or an RSS
100
- feed, an events listing pulled from a ticketing API, a tournament tree imported from a bracket
101
- service.
102
-
103
- The doc records which platform it came from and that platform's own id, so the importer upserts on
104
- the pair — a second run corrects the docs it already created instead of creating a duplicate of
105
- each. Hand-made docs set neither field, and no import touches them.
106
-
107
- ```ts
108
- import {
109
- externalRefFields,
110
- externalRefIndex,
111
- slugPerParentIndex,
112
- } from '@quitecustard/payload/db/external-ref'
113
-
114
- export const lessons: CollectionConfig = {
115
- slug: 'lessons',
116
- fields: [
117
- // …your fields
118
- ...externalRefFields([{ label: 'Stripe', value: 'stripe' }]),
119
- ],
120
- }
121
-
122
- export const lessonsImportIndex = externalRefIndex({ table: 'lessons', prefix: 'lessons' })
123
- export const lessonsSlugIndex = slugPerParentIndex({
124
- table: 'lessons',
125
- parent: 'module',
126
- prefix: 'lessons',
127
- })
128
- ```
129
-
130
- ```ts
131
- // payload.config.ts
132
- db: postgresAdapter({ afterSchemaInit: [lessonsImportIndex, lessonsSlugIndex] })
133
- ```
134
-
135
- Two hooks, because they answer to different needs and a collection rarely wants both:
136
-
137
- - `externalRefIndex` — unique `(externalSource, externalRef)`, partial to imported rows. This is
138
- what makes the upsert safe under concurrency: without it, two overlapping import runs both find no
139
- doc for a source id and both create one. Only for a collection carrying `externalRefFields`, since
140
- it indexes those columns.
141
- - `slugPerParentIndex` — unique `(parent, slug)`. Nothing to do with imports: it's for a tree whose
142
- slugs legitimately repeat across parents — `getting-started` under every docs section, `lesson-1`
143
- under every module — and whose lookups always AND on the parent.
144
-
145
- Payload's `afterSchemaInit` hooks compose, each wrapping the previous config builder rather than
146
- replacing it, so registering both on one table is safe.
147
-
148
- ## Contracts to know
149
-
150
- - `sync-lock` — `createSyncLock()` expects a global with `isRunning`, `startedBy` and `startedAt`
151
- fields, defaulting to slug `sync-lock` on table `sync_lock`; pass `{ slug, table, staleMs }` for
152
- anything else.
153
- - `orphan-cleanup` — `findDeletableIds` reflects foreign keys from `pg_constraint`, so the caller
154
- names the tables that count as the row's own data via `ignore`. Non-`public` schemas pass
155
- `{ schema }`.
156
- - `sessions` — `appendUserSession` defaults `table` to `users_sessions`, Payload's own naming for a
157
- `users` collection; pass `table` for any other auth collection. It is a raw INSERT rather than a
158
- `payload.update` on purpose — the module header has the FOR UPDATE / FOR KEY SHARE deadlock
159
- reason.
160
- - Everything under `db/` needs **a Postgres adapter built on `@payloadcms/drizzle`** —
161
- `@payloadcms/db-postgres` and `@payloadcms/db-vercel-postgres` both qualify, since they differ
162
- only in the connection driver. They talk to the shared drizzle layer, never to an adapter
163
- directly. What they can't run on is SQLite or Mongo: the raw SQL uses `pg_constraint`,
164
- `timestamptz` and data-modifying CTEs. No module outside `db/` imports drizzle at all, so the
165
- other five folders work on any adapter.
166
- - `fields/seo-tab` assumes `@payloadcms/plugin-seo`, and `operations/after-response` assumes `next`.
167
- Those two are the only modules touching either peer.
168
-
169
- 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
+ - `social-url` — `normaliseSocialUrl` (bare host → `https://…`) plus `validateSocialUrl`
63
+ - `colour-picker-field`, `colour-options-field`, `phone-field`, `height-field`, `size-field`,
64
+ `spacing-select-field`, `layout-fields`, `media-content-fields`
65
+
66
+ ### `db/` — raw SQL, transactions and bulk operations
67
+
68
+ Postgres only, and the only folder needing the `@payloadcms/drizzle` + `drizzle-orm` peers.
69
+
70
+ - `transaction-db` — the drizzle handle bound to an open transaction, so raw SQL commits with the
71
+ local-API writes around it instead of running on a separate connection
72
+ - `sessions` — `appendUserSession`: a race-safe INSERT onto an auth collection's session array
73
+ - `sync-lock` — `createSyncLock({slug, table, staleMs})`: single-flight locking for a long job, as a
74
+ conditional UPDATE rather than a read-then-write
75
+ - `orphan-cleanup` — `findDeletableIds`, with guard rails that refuse rather than return everything,
76
+ and `fkTablesReferencing`, the foreign-key reflection it is built on
77
+ - `delete-many-with-versions` — bulk delete that also purges the version snapshots the FK leaves behind
78
+ - `sql-result` — `resultRows` / `rowCount` across driver response shapes
79
+ - `external-ref` — provenance fields plus the partial-unique index that lets an importer upsert on
80
+ `(source, id)` instead of duplicating docs on every run, and per-parent slug uniqueness for
81
+ nested trees
82
+
83
+ ### `errors/`
84
+
85
+ - `field-errors` — the one reader for Payload's per-field error messages
86
+ - `is-duplicate-error` — detects a unique-constraint violation in both shapes Payload surfaces it in
87
+ - `public-error` — a message safe to show a user, or a fallback for anything that could leak internals
88
+
89
+ ### `operations/` — write-path and job helpers
90
+
91
+ - `publish-transition` — autosave-vs-unpublish disambiguation, cheap and exact variants. The exact
92
+ one reads the published row and never trusts the request's query flags
93
+ - `suppress-context` — ref-counted `req.context` flags, safe under a bulk operation's shared context
94
+ - `after-response` — defer non-critical work past the response, falling back to inline outside a request
95
+ - `run-queued-jobs` — drains the Payload job queue, which nothing else does
96
+ - `unique-slug`, `unique-username` — collision-free values, each candidate checked exactly.
97
+ `resolveUniqueUsername` takes an `isTaken` hook for a name that is unavailable for a reason the
98
+ collection cannot see
99
+ - `accent-colour-hook` — `accentColourHook({field, source, extract})`: an afterChange hook that
100
+ keeps a colour field in step with the document's picture, deferred past the response. The decode
101
+ is the caller's `extract`.
102
+
103
+ `src/internal/` holds implementation detail and is not importable: `"./internal/*": null` sits ahead
104
+ of the wildcard in `exports`.
105
+
106
+ ## Import provenance — `external-ref`
107
+
108
+ For a collection whose docs can arrive from an external platform as well as being typed by hand: a
109
+ product catalogue synced from Stripe or Shopify, a post archive migrated from WordPress or an RSS
110
+ feed, an events listing pulled from a ticketing API, a tournament tree imported from a bracket
111
+ service.
112
+
113
+ The doc records which platform it came from and that platform's own id, so the importer upserts on
114
+ the pair — a second run corrects the docs it already created instead of creating a duplicate of
115
+ each. Hand-made docs set neither field, and no import touches them.
116
+
117
+ ```ts
118
+ import {
119
+ externalRefFields,
120
+ externalRefIndex,
121
+ slugPerParentIndex,
122
+ } from '@quitecustard/payload/db/external-ref'
123
+
124
+ export const lessons: CollectionConfig = {
125
+ slug: 'lessons',
126
+ fields: [
127
+ // …your fields
128
+ ...externalRefFields([{ label: 'Stripe', value: 'stripe' }]),
129
+ ],
130
+ }
131
+
132
+ export const lessonsImportIndex = externalRefIndex({ table: 'lessons', prefix: 'lessons' })
133
+ export const lessonsSlugIndex = slugPerParentIndex({
134
+ table: 'lessons',
135
+ parent: 'module',
136
+ prefix: 'lessons',
137
+ })
138
+ ```
139
+
140
+ ```ts
141
+ // payload.config.ts
142
+ db: postgresAdapter({ afterSchemaInit: [lessonsImportIndex, lessonsSlugIndex] })
143
+ ```
144
+
145
+ Two hooks, because they answer to different needs and a collection rarely wants both:
146
+
147
+ - `externalRefIndex` — unique `(externalSource, externalRef)`, partial to imported rows. This is
148
+ what makes the upsert safe under concurrency: without it, two overlapping import runs both find no
149
+ doc for a source id and both create one. Only for a collection carrying `externalRefFields`, since
150
+ it indexes those columns.
151
+ - `slugPerParentIndex` — unique `(parent, slug)`. Nothing to do with imports: it's for a tree whose
152
+ slugs legitimately repeat across parents — `getting-started` under every docs section, `lesson-1`
153
+ under every module — and whose lookups always AND on the parent.
154
+
155
+ Payload's `afterSchemaInit` hooks compose, each wrapping the previous config builder rather than
156
+ replacing it, so registering both on one table is safe.
157
+
158
+ ## Contracts to know
159
+
160
+ - `sync-lock` — `createSyncLock()` expects a global with `isRunning`, `startedBy` and `startedAt`
161
+ fields, defaulting to slug `sync-lock` on table `sync_lock`; pass `{ slug, table, staleMs }` for
162
+ anything else.
163
+ - `orphan-cleanup` — `findDeletableIds` reflects foreign keys from `pg_constraint`, so the caller
164
+ names the tables that count as the row's own data via `ignore`. Non-`public` schemas pass
165
+ `{ schema }`.
166
+ - `sessions` — `appendUserSession` defaults `table` to `users_sessions`, Payload's own naming for a
167
+ `users` collection; pass `table` for any other auth collection. It is a raw INSERT rather than a
168
+ `payload.update` on purpose — the module header has the FOR UPDATE / FOR KEY SHARE deadlock
169
+ reason.
170
+ - Everything under `db/` needs **a Postgres adapter built on `@payloadcms/drizzle`** —
171
+ `@payloadcms/db-postgres` and `@payloadcms/db-vercel-postgres` both qualify, since they differ
172
+ only in the connection driver. They talk to the shared drizzle layer, never to an adapter
173
+ directly. What they can't run on is SQLite or Mongo: the raw SQL uses `pg_constraint`,
174
+ `timestamptz` and data-modifying CTEs. No module outside `db/` imports drizzle at all, so the
175
+ other five folders work on any adapter.
176
+ - `fields/seo-tab` assumes `@payloadcms/plugin-seo`, and `operations/after-response` assumes `next`,
177
+ as does `operations/accent-colour-hook`, which defers through it. Those are the only modules
178
+ touching either peer.
179
+
180
+ 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
  };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The plain text of one serialised Lexical node and everything beneath it.
3
+ *
4
+ * Blocks come out one per line, a table row as its cells joined by `" | "`, a list item with a
5
+ * leading `"- "`, and a line break as `"\n"`. Formatting, link targets and block or upload nodes
6
+ * (which carry no `children`) contribute nothing. Reads the node structurally, so it takes whatever
7
+ * a rich text field hands back and returns `''` for anything that is not a node.
8
+ */
9
+ export declare const lexicalNodeText: (node: unknown) => string;
10
+ /**
11
+ * The plain text of a rich text field's value (the editor state, `{ root }`), for search indexes,
12
+ * excerpts and anywhere else markup cannot go. An empty or missing value reads as `''`.
13
+ *
14
+ * ```ts
15
+ * lexicalPlainText(post.content) // "First paragraph\n- a list item\nName | Value"
16
+ * ```
17
+ *
18
+ * See `lexicalNodeText` for how each node type is written out.
19
+ */
20
+ export declare const lexicalPlainText: (value: unknown) => string;
@@ -0,0 +1,44 @@
1
+ import { isRecord } from '@quitecustard/core/utils/is-record';
2
+ const childrenOf = (node) => Array.isArray(node.children) ? node.children : [];
3
+ // Containers whose children are blocks of their own. Every other node (paragraph, heading, link,
4
+ // table cell) holds inline content and reads as one run.
5
+ const blockContainers = new Set(['root', 'list', 'table']);
6
+ const joinFilled = (parts, separator) => parts
7
+ .map((part) => part.trim())
8
+ .filter(Boolean)
9
+ .join(separator);
10
+ /**
11
+ * The plain text of one serialised Lexical node and everything beneath it.
12
+ *
13
+ * Blocks come out one per line, a table row as its cells joined by `" | "`, a list item with a
14
+ * leading `"- "`, and a line break as `"\n"`. Formatting, link targets and block or upload nodes
15
+ * (which carry no `children`) contribute nothing. Reads the node structurally, so it takes whatever
16
+ * a rich text field hands back and returns `''` for anything that is not a node.
17
+ */
18
+ export const lexicalNodeText = (node) => {
19
+ if (!isRecord(node))
20
+ return '';
21
+ if (node.type === 'linebreak')
22
+ return '\n';
23
+ if (typeof node.text === 'string')
24
+ return node.text;
25
+ const parts = childrenOf(node).map(lexicalNodeText);
26
+ if (node.type === 'tablerow')
27
+ return joinFilled(parts, ' | ');
28
+ if (node.type === 'listitem')
29
+ return `- ${parts.join('').trim()}`;
30
+ if (typeof node.type === 'string' && blockContainers.has(node.type))
31
+ return joinFilled(parts, '\n');
32
+ return parts.join('');
33
+ };
34
+ /**
35
+ * The plain text of a rich text field's value (the editor state, `{ root }`), for search indexes,
36
+ * excerpts and anywhere else markup cannot go. An empty or missing value reads as `''`.
37
+ *
38
+ * ```ts
39
+ * lexicalPlainText(post.content) // "First paragraph\n- a list item\nName | Value"
40
+ * ```
41
+ *
42
+ * See `lexicalNodeText` for how each node type is written out.
43
+ */
44
+ export const lexicalPlainText = (value) => isRecord(value) ? lexicalNodeText(value.root) : '';
@@ -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, 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,12 @@ 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;
25
31
  /** Style select options (e.g. primary/secondary/outline). Omit to skip the style field. */
26
32
  styleOptions?: SelectOption[];
27
33
  /** 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, 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,18 @@ 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
+ condition: (_, siblingData) => siblingData?.type === 'anchor',
110
+ components: { Field: anchorComponent },
111
+ },
112
+ });
113
+ }
100
114
  const linkResult = {
101
115
  name: 'link',
102
116
  type: 'group',
@@ -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.1",
3
+ "version": "0.3.0",
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",