@klnap/payload-typeid 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ ### Patch Changes
6
+
7
+ - ed6b68c: Fix PostgreSQL guard installation: objects are qualified with the adapter schemaName (a same-named table in public is no longer modified), DDL runs only for missing or differing objects so a runtime role without owner rights can start, and the database guards are checked against an explicit schema test suite.
8
+
9
+ ## 0.3.2
10
+
11
+ ### Patch Changes
12
+
13
+ - da89ab8: Revise the README: lead with a realistic quick example, state precedence and Globals behavior precisely, separate database guarantees, and document startup requirements and existing-database migration.
14
+
3
15
  ## 0.3.1
4
16
 
5
17
  ### Patch Changes
package/README.md CHANGED
@@ -1,207 +1,224 @@
1
1
  # @klnap/payload-typeid
2
2
 
3
- Readable, type-prefixed document IDs for Payload CMS. An ID is a prefix plus a UUIDv7 in a compact suffix:
3
+ Readable, type-prefixed document IDs for Payload CMS.
4
4
 
5
5
  ```text
6
6
  article_01m8d47saaepfr8kaw7mqdxs1h
7
+ author_01m8d47sabf8ca5x5s9smzr0qz
8
+ category_01m8d47sabeyjvrxppjadz5h5w
7
9
  ```
8
10
 
9
- It is the document's one native Payload ID. The package adds no second identifier and no runtime dependencies.
11
+ ## Quick example
10
12
 
11
- ## What changes
12
-
13
- Registering `typeId()` manages **every collection** with a TypeID prefix derived from its slug. You do not need to configure each collection. Opt out or override where needed.
14
-
15
- | Collection | Without `typeId()` | With `typeId()` |
16
- | -------------------------------------- | ------------------- | ------------------------------------ |
17
- | `articles` | Payload's native ID | `article_01m8d47saaepfr8kaw7mqdxs1h` |
18
- | `users` | Payload's native ID | `user_…` |
19
- | `articles` with `custom.typeId: "art"` | Payload's native ID | `art_…` |
20
- | `users` with `custom.typeId: false` | Payload's native ID | Payload's native ID |
21
-
22
- Globals are not affected: they keep Payload's ID strategy.
23
-
24
- **Upgrading an existing project is a data migration.** Every managed collection changes its ID type and its relationship columns. Existing documents keep their IDs until you migrate them. Before you register `typeId()` on a project with data, either migrate that data or set `custom.typeId: false` on each collection you do not want to change. See [Enabling on existing data](#enabling-on-existing-data).
25
-
26
- ## Installation
27
-
28
- ```bash
29
- bun add @klnap/payload-typeid
30
- ```
31
-
32
- ```bash
33
- npm install @klnap/payload-typeid
34
- ```
35
-
36
- ## Quick start
13
+ Register the plugin. Each collection gets a prefix from its slug, with no per-collection configuration:
37
14
 
38
15
  ```ts
16
+ // payload.config.ts
39
17
  import { buildConfig, type CollectionConfig } from "payload";
40
18
  import { typeId } from "@klnap/payload-typeid";
41
19
 
42
- const Articles: CollectionConfig = {
43
- slug: "articles",
44
- fields: [],
20
+ const Categories: CollectionConfig = {
21
+ slug: "categories",
22
+ fields: [{ name: "title", type: "text", required: true }],
45
23
  };
46
24
 
47
- const Users: CollectionConfig = {
48
- slug: "users",
49
- fields: [],
25
+ const Authors: CollectionConfig = {
26
+ slug: "authors",
27
+ fields: [{ name: "name", type: "text", required: true }],
28
+ };
29
+
30
+ const Articles: CollectionConfig = {
31
+ slug: "articles",
32
+ fields: [
33
+ { name: "title", type: "text", required: true },
34
+ { name: "category", type: "relationship", relationTo: "categories", required: true },
35
+ { name: "author", type: "relationship", relationTo: "authors", required: true },
36
+ ],
50
37
  };
51
38
 
52
39
  export default buildConfig({
53
- collections: [Articles, Users],
40
+ // database, secret, editor, and the rest of your configuration
41
+ collections: [Categories, Authors, Articles],
54
42
  plugins: [typeId()],
55
43
  });
56
44
  ```
57
45
 
58
- `articles` gets `article_…` IDs and `users` gets `user_…` IDs, with no per-collection configuration. Register `typeId()` after plugins that add collections, so it sees the final collection list.
46
+ Use the normal Payload API. Relationships take the related document's `id`:
47
+
48
+ ```ts
49
+ const category = await payload.create({ collection: "categories", data: { title: "Guides" } });
50
+ const author = await payload.create({ collection: "authors", data: { name: "Ada" } });
51
+
52
+ const article = await payload.create({
53
+ collection: "articles",
54
+ data: { title: "Getting started", category: category.id, author: author.id },
55
+ });
56
+
57
+ article.id; // for example "article_01m8d47saaepfr8kaw7mqdxs1h"
58
+ ```
59
+
60
+ The ID is the document's only identifier. There is no second public ID field and no lookup table.
59
61
 
60
- ## How it works
62
+ ## Why?
61
63
 
62
- The plugin uses Payload's native custom ID mechanism, a top-level field named `id`. It does not change the database adapter. For each managed collection, it:
64
+ Payload's default IDs do not show what kind of record an ID refers to in logs, URLs, or API responses. Projects sometimes add a second, readable identifier for that purpose, which duplicates the key and needs translation. This package keeps one identifier: the readable prefix is part of the native Payload ID.
63
65
 
64
- - prepends an `id` text field whose `defaultValue` generates a TypeID with the collection's prefix;
65
- - adds a `beforeChange` hook that keeps the generated ID on create, keeps the stored ID on update, and generates a fresh ID on duplicate;
66
- - adds a `beforeOperation` guard that rejects `customID` and `data.id` on create and `data.id` on update, because the plugin owns the ID.
66
+ ## Features
67
67
 
68
- The plugin runs last (`order` is the maximum), so its `id` field and hooks apply after other plugins.
68
+ - **Native IDs.** Managed collections use Payload's text ID field. Existing APIs and relationships work unchanged.
69
+ - **Automatic prefixes.** Each collection's prefix comes from its slug, singularized with Payload's own `formatLabels`.
70
+ - **Overrides.** Set a prefix per collection, opt a collection out, or configure all of them in one place.
71
+ - **ID ownership.** IDs are generated on create and duplicate. Callers cannot supply or change them through Payload operations.
72
+ - **PostgreSQL guards.** Triggers and a `CHECK` constraint apply the same rules to raw SQL writes.
73
+ - **Utilities.** Generate, validate, parse, and convert TypeIDs. No runtime dependencies.
74
+
75
+ ## Installation
76
+
77
+ ```bash
78
+ bun add @klnap/payload-typeid
79
+ ```
80
+
81
+ ```bash
82
+ npm install @klnap/payload-typeid
83
+ ```
69
84
 
70
85
  ## Configuration
71
86
 
72
- Each collection's prefix is resolved in this order. The first value that is set wins:
87
+ ### Prefixes
88
+
89
+ Each collection's prefix is resolved in this order. The first defined value wins:
73
90
 
74
91
  1. `custom.typeId` on the collection.
75
- 2. The central `typeId({ collections })` entry for its slug.
76
- 3. The default: a prefix derived from the slug.
92
+ 2. The central `collections` option passed to `typeId()`.
93
+ 3. The automatic prefix from the slug.
77
94
 
78
- ### On the collection: `custom.typeId`
95
+ `custom.typeId` accepts:
79
96
 
80
- | Value | Effect |
81
- | ------- | ----------------------------------------------------------------------------- |
82
- | `"art"` | Use exactly this prefix. Use it when the derived prefix is not what you want. |
83
- | `true` | Derive the prefix from the slug. Same as omitting the value. |
84
- | `false` | Opt out: keep Payload's native ID strategy for this collection. |
85
- | omitted | Use the central entry, or derive the prefix from the slug. |
97
+ | Value | Effect |
98
+ | ------- | -------------------------------------------------------------------------- |
99
+ | `"art"` | Use this exact prefix. |
100
+ | `true` | Use the automatic prefix, even when the central option sets another value. |
101
+ | `false` | Opt out: keep Payload's native ID strategy. |
102
+ | omitted | Use the central option, or the automatic prefix. |
86
103
 
87
- ### Centrally: `typeId({ collections })`
104
+ Configure a whole project in one place with the same values:
88
105
 
89
106
  ```ts
90
107
  typeId({
91
108
  collections: {
92
109
  articles: "article",
93
- authors: "writer",
94
- users: false,
110
+ authors: "author",
111
+ categories: false,
95
112
  },
96
113
  });
97
114
  ```
98
115
 
99
- Keys are collection slugs that must exist in `config.collections`. An unknown slug throws during setup. A central value applies only when the collection's `custom.typeId` is omitted.
116
+ Precedence for each combination of collection-level and central values:
100
117
 
101
- ### Examples
118
+ | `custom.typeId` | Central value | Result |
119
+ | --------------- | ------------- | ------------------- |
120
+ | omitted | omitted | Automatic prefix |
121
+ | `true` | omitted | Automatic prefix |
122
+ | `true` | `"article"` | Automatic prefix |
123
+ | `true` | `false` | Automatic prefix |
124
+ | `"art"` | `"article"` | `art` |
125
+ | `"art"` | `false` | `art` |
126
+ | omitted | `"article"` | `article` |
127
+ | omitted | `false` | Native ID (opt-out) |
128
+ | `false` | `"article"` | Native ID (opt-out) |
129
+ | `false` | `true` | Native ID (opt-out) |
102
130
 
103
- | Collection `custom.typeId` | Central entry | Result |
104
- | -------------------------- | ------------- | -------------------------------- |
105
- | `"art"` | `"article"` | `art_…` |
106
- | omitted | `"article"` | `article_…` |
107
- | `false` | `"article"` | Native ID (opt-out) |
108
- | omitted | `false` | Native ID (opt-out) |
109
- | omitted | omitted | Derived prefix, e.g. `article_…` |
131
+ Central keys must be collection slugs in `config.collections`. An unknown key throws during setup.
110
132
 
111
- A collection-level value always wins. `false` at either level opts the collection out.
133
+ ### Automatic prefixes
112
134
 
113
- ### Globals
135
+ Automatic prefixes use the slug, with the last word singularized by Payload's `formatLabels`:
114
136
 
115
- Globals keep Payload's ID strategy. They accept only `false` or omission. `true` or a prefix string on a Global throws during setup, because Payload does not expose configurable Global document IDs.
137
+ | Collection slug | Prefix |
138
+ | ----------------- | ---------------- |
139
+ | `articles` | `article` |
140
+ | `authors` | `author` |
141
+ | `categories` | `category` |
142
+ | `article-authors` | `article_author` |
116
143
 
117
- ### Obsolete key
144
+ Automatic prefixes are convenient but follow Payload's English rules. Set an explicit prefix when a name is irregular, when it is domain-specific, or when the prefix is a stable part of your API. An explicit prefix must be 1–63 lowercase ASCII letters or underscores, starting and ending with a letter.
118
145
 
119
- `custom.typeid` (lowercase `d`) throws on collections and Globals. Rename it to `custom.typeId`.
146
+ The plugin rejects a slug whose label cannot be split into words reliably (for example `APIKeys` or `users-2fa`). Those collections need an explicit prefix or `false`.
120
147
 
121
- ## Prefix derivation
148
+ Two managed collections that resolve to the same prefix are rejected during setup. Changing a prefix does not change existing IDs; see [Existing databases](#existing-databases).
122
149
 
123
- When no explicit prefix applies, the prefix comes from the slug with Payload's own singularization, `formatLabels` from `payload`, the same function Payload uses for admin labels:
150
+ ### Globals
124
151
 
125
- 1. Replace `_` with `-` in the slug, so underscores and hyphens both separate words.
126
- 2. Pass the result through `formatLabels`, which singularizes the last word.
127
- 3. Join the words with `_` and lowercase the result.
152
+ TypeIDs apply to collections only. Globals are accessed by slug and keep Payload's native behavior, so no configuration is needed. Setting `custom.typeId` to `false` on a Global is allowed. Setting it to `true` or to a prefix string throws during setup.
128
153
 
129
- Regular plural nouns derive cleanly:
154
+ ### Obsolete key
130
155
 
131
- | Slug | Derived prefix |
132
- | ----------------- | ---------------- |
133
- | `articles` | `article` |
134
- | `article-authors` | `article_author` |
135
- | `ArticleAuthors` | `article_author` |
136
- | `audit-logs` | `audit_log` |
137
- | `users` | `user` |
156
+ Use `custom.typeId`. The obsolete `custom.typeid` spelling is rejected on collections and Globals.
138
157
 
139
- Irregular or uncountable names derive to correct English that may read oddly in an ID. Payload's English rules decide the result:
158
+ ## ID ownership
140
159
 
141
- | Slug | Derived prefix | Recommendation |
142
- | -------- | -------------- | ---------------------------------------------------------- |
143
- | `people` | `person` | Acceptable. Set `"person"` if you prefer an explicit name. |
144
- | `data` | `datum` | Set an explicit prefix such as `"dataset"`. |
145
- | `dice` | `die` | Set an explicit prefix such as `"roll"`. |
160
+ For managed collections, the plugin owns the ID:
146
161
 
147
- Derivation depends on Payload's English rules. A future Payload release could change a derived prefix, and new IDs would follow the new rule. Set explicit prefixes for any collection whose IDs you store, log, or expose.
162
+ - **Create** generates a TypeID. Passing `id`, `data.id`, or `customID` throws.
163
+ - **Update** cannot change the ID. Passing `data.id` throws.
164
+ - **Duplicate** creates a new TypeID with the same prefix. The original keeps its ID.
148
165
 
149
- The plugin rejects a slug whose label contains characters other than letters, or whose multi-word label contains a single letter, because those cannot be split reliably. Because derivation is the default, such a slug fails setup for the whole project until you set a prefix or `false` on it:
166
+ These rules apply to Payload operations. Raw SQL writes are covered by the database guards below.
150
167
 
151
- | Slug | Result |
152
- | ----------- | ----------------------------------------------- |
153
- | `APIKeys` | Rejected. The label splits into single letters. |
154
- | `users-2fa` | Rejected. The label contains a digit. |
168
+ ```ts
169
+ const copy = await payload.duplicate({ collection: "articles", id: article.id });
170
+ copy.id !== article.id; // true
171
+ ```
155
172
 
156
- ## Prefix rules
173
+ Payload's `idType` setting for the database adapter does not need to change.
157
174
 
158
- Explicit prefixes must be 1–63 lowercase ASCII letters or underscores, starting and ending with a letter. Two managed collections that resolve to the same prefix throw during setup, so give one of them an explicit prefix.
175
+ ## Database guards (PostgreSQL)
159
176
 
160
- A managed collection cannot define its own top-level field named `id`. Either set `custom.typeId: false` on it or rename that field before enabling TypeIDs.
177
+ For each managed table, the plugin installs database-level rules when Payload starts. They apply to any write to that table, including raw SQL:
161
178
 
162
- ## Using IDs
179
+ | Guarantee | Provided by |
180
+ | ---------------------- | --------------------------------------------------------------- |
181
+ | ID generation | A trigger that creates an ID when an `INSERT` has none. |
182
+ | Format validation | A `CHECK` constraint on the prefix and the 26-character suffix. |
183
+ | Immutability | A trigger that rejects an `UPDATE` changing `id`. |
184
+ | Primary-key uniqueness | Payload's `PRIMARY KEY (id)`. |
185
+ | Referential integrity | Foreign keys from relationship and version tables to `id`. |
163
186
 
164
- Create and read documents as usual. Do not pass `id` or `customID`:
187
+ Notes:
165
188
 
166
- ```ts
167
- const article = await payload.create({
168
- collection: "articles",
169
- data: { title: "Getting started with Payload CMS" },
170
- });
189
+ - A generated ID is a UUIDv7 in TypeID form. The generator follows RFC 9562 and matches `generateTypeId`.
190
+ - The `CHECK` validates the prefix and the suffix's characters and length. It does not verify the UUID version or variant bits.
191
+ - A correctly formatted ID supplied in a raw `INSERT` is accepted. Payload operations reject supplied IDs; the database does not.
192
+ - The guards cover managed tables only, not other tables in the database.
193
+ - Versions and relationship tables are protected through their foreign keys to the managed `id` columns, not through their own triggers.
171
194
 
172
- await payload.findByID({ collection: "articles", id: article.id });
173
- ```
195
+ ### Startup requirements
174
196
 
175
- Passing `customID` or `data.id` on create throws. Passing `data.id` on update throws, because the ID does not change.
197
+ Guard installation runs when Payload starts. It compares each function, constraint, and trigger with its expected definition and runs DDL only for objects that are missing or different. A database that is already up to date needs no DDL, so a runtime role without table-owner rights can still start.
176
198
 
177
- Relationships use the native ID. Set `relationTo` as usual and pass the related document's `id`.
199
+ - Each managed table must already exist in the schema Payload uses (see below). The plugin reports a missing table.
200
+ - The first installation, or a plugin upgrade that changes a function body, needs a role that owns the affected functions and tables.
201
+ - Existing rows must satisfy the `CHECK`. If they do not, startup fails and no guard is installed. Migrate those rows first.
202
+ - Guards are created in the schema set by `schemaName` in the Payload database adapter. Without `schemaName`, objects are unqualified and resolve through `search_path`, as Payload's tables do.
203
+ - The functions use `gen_random_uuid()`, built into PostgreSQL 13 and later.
178
204
 
179
- ### Duplicating documents
205
+ The schema tests (non-default schema with a same-named table in `public`, a restricted runtime role starting on up-to-date guards, and opt-out after activation) run against the development Payload version. They are not part of the Payload 3.1.1 CI job. Manual checks on 3.1.1 confirmed that guards land in the configured schema, but the same test sequence does not complete reliably there in one process.
180
206
 
181
- `payload.duplicate()` gives the copy a **new** TypeID with the same prefix. The original keeps its ID. The repository's PostgreSQL integration test checks this on every supported Payload version.
207
+ ### What the guards cannot stop
182
208
 
183
- ```ts
184
- const copy = await payload.duplicate({ collection: "articles", id: article.id });
185
- copy.id !== article.id; // true
186
- copy.id.startsWith("article_"); // true
187
- ```
209
+ A superuser can disable triggers or constraints. `DROP`, `TRUNCATE`, and restoring an older backup bypass all rules. Keep those privileges with migrations and operators.
210
+
211
+ ## Existing databases
188
212
 
189
- ### Errors
213
+ Enabling TypeIDs on a populated database is a migration, not a configuration change:
190
214
 
191
- Setup and write errors come from the plugin. Each message names the fix:
215
+ - Existing IDs and relationship values are not converted.
216
+ - The ID column type of managed tables and of the references to them changes.
217
+ - Startup fails if existing rows do not match the `CHECK`.
192
218
 
193
- | Message (starts with) | Cause and fix |
194
- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
195
- | `... uses the obsolete custom.typeid key` | Rename `custom.typeid` to `custom.typeId`. |
196
- | `Invalid TypeID configuration ... custom.typeId must be true, false, a prefix string` | The value has another type. Use one of the accepted values. |
197
- | `Collection "x" cannot derive a TypeID prefix from its slug` | The slug is ambiguous. Set `custom.typeId` to an explicit string, or `false`. |
198
- | `Collections "a" and "b" resolve to duplicate TypeID prefix` | Two collections share a prefix. Set an explicit prefix on one of them. |
199
- | `Global "x" cannot use custom.typeId` | Globals accept only `false` or omission. |
200
- | `TypeID collections references unknown collection` | A central key is not a collection slug in `config.collections`. |
201
- | `Collection "x" already has a collection-level field named "id"` | Rename that field, or set `custom.typeId: false` on the collection. |
202
- | `Collection "x" owns its IDs; omit customID and data.id when creating` | Remove `customID` and `data.id` from the create call. |
203
- | `Collection "x" IDs are immutable; omit data.id when updating` | Remove `data.id` from the update call. |
204
- | `Register typeId() only once` | Keep a single `typeId()` entry in `plugins`. |
219
+ To keep a collection on its native IDs, set `custom.typeId: false` before the first start with the plugin.
220
+
221
+ After the plugin has activated on a database, setting `custom.typeId: false` does not restore column types, convert IDs, rewrite references, or remove guards. The collection keeps generating TypeIDs. Opting out is only a clean change before the first activation.
205
222
 
206
223
  ## Utilities
207
224
 
@@ -216,61 +233,46 @@ import {
216
233
  } from "@klnap/payload-typeid";
217
234
 
218
235
  const id: TypeID<"article"> = generateTypeId("article");
236
+
237
+ isTypeId(id); // true
219
238
  isTypeId(id, "article"); // true
220
- isTypeId(id, "category"); // false
239
+ isTypeId(id, "author"); // false
221
240
 
222
- const uuid = "0188bac7-4afa-78aa-bc3b-bd1eef28d881";
223
- toUUID(fromUUID("article", uuid)) === uuid; // true
241
+ const uuid = parseTypeId(id).uuid; // canonical UUID string
242
+ fromUUID("article", uuid) === id; // true
243
+ toUUID(id) === uuid; // true
224
244
  ```
225
245
 
226
- | Export | Description |
227
- | ---------------------------------- | --------------------------------------------- |
228
- | `typeId(options?)` | Creates the Payload plugin. |
229
- | `generateTypeId(prefix)` | Generates a TypeID with a new UUIDv7. |
230
- | `isTypeId(value, expectedPrefix?)` | Validates a TypeID and optionally its prefix. |
231
- | `parseTypeId(value)` | Returns the prefix and canonical UUID. |
232
- | `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID. |
233
- | `toUUID(value)` | Converts a TypeID to its canonical UUID. |
234
- | `TypeID<Prefix>` | Compile-time type. Not runtime validation. |
235
- | `TypeIdOptions` | Options accepted by `typeId()`. |
246
+ | Export | Description |
247
+ | ---------------------------------- | ---------------------------------------------------------------------------- |
248
+ | `generateTypeId(prefix)` | Returns a TypeID with a new UUIDv7. |
249
+ | `isTypeId(value, expectedPrefix?)` | Runtime check that `value` is a valid TypeID, optionally with that prefix. |
250
+ | `parseTypeId(value)` | Returns `{ prefix, uuid }`. Throws `TypeError` on invalid input. |
251
+ | `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID. Accepts UUIDs of any version. |
252
+ | `toUUID(value)` | Returns the canonical UUID of a TypeID. Throws `TypeError` on invalid input. |
253
+ | `TypeID<Prefix>` | Compile-time string type. It does not validate values at runtime. |
254
+ | `TypeIdOptions` | The options type for `typeId()`. |
236
255
 
237
- `parseTypeId`, `fromUUID`, and `toUUID` throw `TypeError` on invalid input. `isTypeId` returns `false`.
256
+ `TypeID<Prefix>` documents intent in your types. Use `isTypeId` to check untrusted input. Generated Payload document types do not know which prefix a collection uses.
238
257
 
239
- ## Enabling on existing data
240
-
241
- Registering `typeId()` on a project with data changes the ID column type of every managed collection and of every relationship that points to it. Existing IDs and relationship values are not migrated automatically.
242
-
243
- Choose one before you deploy:
244
-
245
- 1. **Migrate.** Back up the database. Write a migration that assigns a TypeID to each existing document and rewrites relationship values to match. Deploy it together with the plugin.
246
- 2. **Opt out.** Set `custom.typeId: false` on each existing collection you do not want to change. Only new collections get TypeIDs.
247
-
248
- The database guards below run on writes that bypass Payload hooks. Existing data that does not match them blocks startup until it is migrated.
249
-
250
- ## Database guards (PostgreSQL)
251
-
252
- Payload hooks do not run for raw SQL, so the plugin installs the ID rules in the database as well. For each managed table, on every Payload start:
258
+ ## Compatibility
253
259
 
254
- - **Generation:** an `INSERT` without `id` receives a TypeID with the table's prefix. The SQL encoder matches `generateTypeId`, and the test suite checks that the two agree.
255
- - **Validation:** a `CHECK` constraint rejects any `id` that is not `prefix_` followed by 26 Base32 characters, with the first character in `0`–`7`. A wrong prefix is rejected too.
256
- - **Immutability:** a trigger rejects any `UPDATE` that changes `id`. Other columns can still be updated.
260
+ | Area | Support |
261
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
262
+ | Payload | Peer range `^3.1.1`. PostgreSQL integration tests run on `3.1.1`, `3.68.4`, `3.71.0`, and the development version (currently `3.94.2`). Other 3.x versions are not tested. Payload 4 is unverified. |
263
+ | Database | PostgreSQL integration tests run on PostgreSQL 16, with the default serial ID strategy and `idType: "uuid"`. Guards are PostgreSQL-only; other adapters log a warning and keep application-level rules. |
264
+ | Node.js | `>=22.14.0`. Payload's own engine requirements also apply. |
265
+ | Module format | ESM only. |
257
266
 
258
- The guards are idempotent and survive a repeated `push`; the test suite runs twice against the same database to check this. Limits:
267
+ ## Security
259
268
 
260
- - **PostgreSQL only.** Other adapters log a warning at startup and keep only application-level rules.
261
- - **Existing data.** The `CHECK` applies to all rows. If a managed table already holds IDs that do not match, startup fails and no guard is installed. Migrate those rows first (see [Enabling on existing data](#enabling-on-existing-data)).
262
- - **Relations and versions.** Relationship join tables and versions tables are not guarded by triggers. Their references to managed documents are foreign keys to the guarded `id` columns, so a row cannot point at a TypeID that no managed document has. The integration suite checks this for both.
263
- - **What the database cannot stop.** A superuser can disable triggers or constraints, and `DROP`, `TRUNCATE`, or restoring an old backup bypass every rule. Restrict those privileges to migrations. Other adapters are unguarded (see above).
264
- - **Fields.** The guards check only `id`. Other constraints and field rules are not changed.
269
+ TypeIDs identify documents. They do not authenticate users or authorize access. Use Payload's access control and your application's authorization for every operation. The UUIDv7 part includes a timestamp, and the prefix reveals the record type, so do not treat IDs as secrets.
265
270
 
266
- ## Compatibility
271
+ ## Documentation
267
272
 
268
- | Area | Support |
269
- | ------------- | ----------------------------------------------------------------------------------------------------------------------------- |
270
- | Payload CMS | Peer range `^3.1.1`. PostgreSQL integration tests pass on `3.1.1`, `3.68.4`, `3.71.0`, and `3.94.2`. Payload 4 is unverified. |
271
- | Database | PostgreSQL 16, with the default serial strategy and `idType: "uuid"`. Other adapters are unverified. |
272
- | Node.js | `>=22.14.0`. Payload's own engine range applies too; Payload `3.94.2` requires `^22.23.5 \|\| ^24.22.3 \|\| >=26.13.1`. |
273
- | Module format | ESM only. |
273
+ - [Payload custom ID fields](https://payloadcms.com/docs/fields/default-fields#custom-id-fields)
274
+ - [RFC 9562, UUIDv7](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.7)
275
+ - [TypeID format specification](https://github.com/jetify-com/typeid/blob/main/spec/README.md), which this package's encoding follows
274
276
 
275
277
  ## License
276
278
 
package/dist/index.js CHANGED
@@ -3,10 +3,27 @@ import { randomBytes } from "node:crypto";
3
3
  import { flattenAllFields, formatLabels, } from "payload";
4
4
  const identifierPattern = /^[a-z_][a-z0-9_]*$/;
5
5
  const prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;
6
+ // Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.
7
+ function tableNameForSlug(slug) {
8
+ return slug
9
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
10
+ .replace(/([a-z\d])([A-Z])/g, "$1_$2")
11
+ .replace(/[-\s]+/g, "_")
12
+ .toLowerCase();
13
+ }
14
+ // Objects are qualified with the adapter's schema; without one they stay unqualified, like Payload's tables.
15
+ function qualifier(schema) {
16
+ return (name) => (schema ? `"${schema}"."${name}"` : `"${name}"`);
17
+ }
6
18
  // Mirrors encodeUuid/decodeSuffix: a 128-bit value as 26 Base32 characters, most significant first.
7
- const encodeFunction = `
8
- CREATE OR REPLACE FUNCTION payload_typeid_encode(hex text) RETURNS text
9
- LANGUAGE plpgsql IMMUTABLE AS $$
19
+ function functionSpecs(q) {
20
+ const specs = [
21
+ {
22
+ name: "payload_typeid_encode",
23
+ args: "hex text",
24
+ returns: "text",
25
+ attributes: "LANGUAGE plpgsql IMMUTABLE",
26
+ body: `
10
27
  DECLARE
11
28
  value numeric := 0;
12
29
  remainder integer;
@@ -22,11 +39,15 @@ BEGIN
22
39
  value := (value - remainder) / 32;
23
40
  END LOOP;
24
41
  RETURN result;
25
- END $$;`;
26
- // UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.
27
- const uuidV7Function = `
28
- CREATE OR REPLACE FUNCTION payload_typeid_uuid_v7_hex() RETURNS text
29
- LANGUAGE plpgsql VOLATILE AS $$
42
+ END `,
43
+ },
44
+ // UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.
45
+ {
46
+ name: "payload_typeid_uuid_v7_hex",
47
+ args: "",
48
+ returns: "text",
49
+ attributes: "LANGUAGE plpgsql VOLATILE",
50
+ body: `
30
51
  DECLARE
31
52
  millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
32
53
  random_hex text := replace(gen_random_uuid()::text, '-', '');
@@ -35,11 +56,15 @@ BEGIN
35
56
  || '7' || substr(random_hex, 14, 3)
36
57
  || to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)
37
58
  || substr(random_hex, 18, 15);
38
- END $$;`;
39
- // Generates an ID when none is supplied, and rejects any change to an existing ID.
40
- const guardFunction = `
41
- CREATE OR REPLACE FUNCTION payload_typeid_guard() RETURNS trigger
42
- LANGUAGE plpgsql AS $$
59
+ END `,
60
+ },
61
+ // Generates an ID when none is supplied, and rejects any change to an existing ID.
62
+ {
63
+ name: "payload_typeid_guard",
64
+ args: "",
65
+ returns: "trigger",
66
+ attributes: "LANGUAGE plpgsql",
67
+ body: `
43
68
  BEGIN
44
69
  IF TG_OP = 'UPDATE' THEN
45
70
  IF NEW.id IS DISTINCT FROM OLD.id THEN
@@ -49,57 +74,76 @@ BEGIN
49
74
  RETURN NEW;
50
75
  END IF;
51
76
  IF NEW.id IS NULL THEN
52
- NEW.id := TG_ARGV[0] || '_' || payload_typeid_encode(payload_typeid_uuid_v7_hex());
77
+ NEW.id := TG_ARGV[0] || '_' || ${q("payload_typeid_encode")}(${q("payload_typeid_uuid_v7_hex")}());
53
78
  END IF;
54
79
  RETURN NEW;
55
- END $$;`;
56
- // Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.
57
- function tableNameForSlug(slug) {
58
- return slug
59
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
60
- .replace(/([a-z\d])([A-Z])/g, "$1_$2")
61
- .replace(/[-\s]+/g, "_")
62
- .toLowerCase();
80
+ END `,
81
+ },
82
+ ];
83
+ return specs.map((spec) => ({
84
+ // to_regprocedure takes argument types only, not parameter names.
85
+ signature: `${q(spec.name)}(${spec.args.replace(/^\w+ /, "")})`,
86
+ body: spec.body,
87
+ create: `CREATE OR REPLACE FUNCTION ${q(spec.name)}(${spec.args}) RETURNS ${spec.returns} ${spec.attributes} AS $$${spec.body}$$;`,
88
+ }));
63
89
  }
64
- /** SQL that installs the ID functions, a per-table CHECK constraint, and a per-table trigger. */
65
- function typeIdDatabaseSql(guards) {
66
- const statements = [encodeFunction, uuidV7Function, guardFunction];
67
- for (const { table, prefix } of guards) {
68
- if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {
69
- throw new TypeError(`Refusing to guard unsafe table or prefix "${table}" / "${prefix}".`);
70
- }
71
- const constraint = `payload_typeid_${table}_id_check`;
72
- const trigger = `payload_typeid_${table}_guard`;
73
- statements.push(`ALTER TABLE "${table}" DROP CONSTRAINT IF EXISTS "${constraint}";`, `ALTER TABLE "${table}" ADD CONSTRAINT "${constraint}" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`, `DROP TRIGGER IF EXISTS "${trigger}" ON "${table}";`, `CREATE TRIGGER "${trigger}" BEFORE INSERT OR UPDATE ON "${table}" FOR EACH ROW EXECUTE FUNCTION payload_typeid_guard('${prefix}');`);
74
- }
75
- return statements.join("\n");
90
+ async function catalogValue(pool, sql, values) {
91
+ const { rows } = await pool.query(sql, values);
92
+ return rows[0]?.value;
76
93
  }
77
94
  /**
78
95
  * Installs the database guards on the Postgres adapter. Other adapters get a warning instead:
79
96
  * the guards are SQL and cannot be applied to them.
80
97
  */
81
98
  async function installTypeIdDatabaseGuards(payload, guards) {
82
- if (guards.length === 0)
83
- return;
84
99
  if (payload.db.name !== "postgres") {
85
100
  payload.logger.warn(`payload-typeid: database guards are only installed on PostgreSQL; the "${payload.db.name}" adapter keeps application-level rules only.`);
86
101
  return;
87
102
  }
88
- const pool = payload.db.pool;
103
+ const db = payload.db;
104
+ const schema = db.schemaName;
105
+ if (schema !== undefined && !identifierPattern.test(schema)) {
106
+ throw new TypeError(`payload-typeid: unsupported PostgreSQL schema name "${schema}".`);
107
+ }
108
+ const q = qualifier(schema);
109
+ const pool = db.pool;
89
110
  const tables = guards.map(({ slug, prefix }) => {
90
111
  const defaultName = tableNameForSlug(slug);
91
- const tableNameMap = payload.db
92
- .tableNameMap;
93
- const table = tableNameMap?.get(defaultName) ?? defaultName;
94
- return { slug, prefix, table };
112
+ return { slug, prefix, table: db.tableNameMap?.get(defaultName) ?? defaultName };
95
113
  });
96
- for (const { slug, table } of tables) {
97
- const { rows } = await pool.query("SELECT to_regclass($1) AS relation", [`"${table}"`]);
98
- if (!rows[0]?.relation) {
114
+ for (const { slug, prefix, table } of tables) {
115
+ if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {
116
+ throw new TypeError(`payload-typeid: refusing to guard unsafe table "${table}" or prefix "${prefix}".`);
117
+ }
118
+ const relation = await catalogValue(pool, "SELECT to_regclass($1)::text AS value", [q(table)]);
119
+ if (!relation) {
99
120
  throw new TypeError(`payload-typeid: no table "${table}" for collection "${slug}". Set the collection's dbName or rename it before enabling TypeIDs.`);
100
121
  }
101
122
  }
102
- await pool.query(typeIdDatabaseSql(tables.map(({ table, prefix }) => ({ table, prefix }))));
123
+ // Only missing or differing objects are changed, so an up-to-date database needs no DDL and
124
+ // a role without table-owner rights can still start.
125
+ const statements = [];
126
+ for (const spec of functionSpecs(q)) {
127
+ const current = await catalogValue(pool, "SELECT prosrc AS value FROM pg_proc WHERE oid = to_regprocedure($1)", [spec.signature]);
128
+ if (current !== spec.body)
129
+ statements.push(spec.create);
130
+ }
131
+ for (const { prefix, table } of tables) {
132
+ const constraint = `payload_typeid_${table}_id_check`;
133
+ const trigger = `payload_typeid_${table}_guard`;
134
+ const constraintDef = await catalogValue(pool, "SELECT pg_get_constraintdef(c.oid) AS value FROM pg_constraint c WHERE c.conrelid = to_regclass($1) AND c.conname = $2", [q(table), constraint]);
135
+ if (!constraintDef?.includes(`'^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$'`)) {
136
+ statements.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS "${constraint}";`, `ALTER TABLE ${q(table)} ADD CONSTRAINT "${constraint}" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`);
137
+ }
138
+ const triggerDef = await catalogValue(pool, "SELECT pg_get_triggerdef(t.oid) AS value FROM pg_trigger t WHERE t.tgrelid = to_regclass($1) AND t.tgname = $2 AND NOT t.tgisinternal", [q(table), trigger]);
139
+ if (!triggerDef?.includes(`payload_typeid_guard('${prefix}')`)) {
140
+ statements.push(`DROP TRIGGER IF EXISTS "${trigger}" ON ${q(table)};`, `CREATE TRIGGER "${trigger}" BEFORE INSERT OR UPDATE ON ${q(table)} FOR EACH ROW EXECUTE FUNCTION ${q("payload_typeid_guard")}('${prefix}');`);
141
+ }
142
+ }
143
+ if (statements.length > 0) {
144
+ // A multi-statement query runs as one transaction: a failure leaves the previous guards in place.
145
+ await pool.query(statements.join("\n"));
146
+ }
103
147
  }
104
148
  const prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;
105
149
  const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;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AAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;YACvE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QACjD,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,OAAO;YACL,GAAG,MAAM;YACT,WAAW,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC;YAC7F,qGAAqG;YACrG,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;gBACxB,MAAM,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;gBACxB,MAAM,2BAA2B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YACrD,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,gBAAgB,CAAC;IACvC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n type CollectionConfig,\n type Config,\n type Field,\n flattenAllFields,\n type Payload,\n formatLabels,\n type Plugin,\n} from \"payload\";\n\ninterface TypeIdTableGuard {\n slug: string;\n prefix: string;\n}\n\nconst identifierPattern = /^[a-z_][a-z0-9_]*$/;\nconst prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;\n\n// Mirrors encodeUuid/decodeSuffix: a 128-bit value as 26 Base32 characters, most significant first.\nconst encodeFunction = `\nCREATE OR REPLACE FUNCTION payload_typeid_encode(hex text) RETURNS text\nLANGUAGE plpgsql IMMUTABLE AS $$\nDECLARE\n value numeric := 0;\n remainder integer;\n result text := '';\n alphabet text := '0123456789abcdefghjkmnpqrstvwxyz';\nBEGIN\n FOR i IN 1..32 LOOP\n value := value * 16 + ('x' || substr(hex, i, 1))::bit(4)::int;\n END LOOP;\n FOR i IN 1..26 LOOP\n remainder := (value % 32)::integer;\n result := substr(alphabet, remainder + 1, 1) || result;\n value := (value - remainder) / 32;\n END LOOP;\n RETURN result;\nEND $$;`;\n\n// UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.\nconst uuidV7Function = `\nCREATE OR REPLACE FUNCTION payload_typeid_uuid_v7_hex() RETURNS text\nLANGUAGE plpgsql VOLATILE AS $$\nDECLARE\n millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;\n random_hex text := replace(gen_random_uuid()::text, '-', '');\nBEGIN\n RETURN lpad(to_hex(millis), 12, '0')\n || '7' || substr(random_hex, 14, 3)\n || to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)\n || substr(random_hex, 18, 15);\nEND $$;`;\n\n// Generates an ID when none is supplied, and rejects any change to an existing ID.\nconst guardFunction = `\nCREATE OR REPLACE FUNCTION payload_typeid_guard() RETURNS trigger\nLANGUAGE plpgsql AS $$\nBEGIN\n IF TG_OP = 'UPDATE' THEN\n IF NEW.id IS DISTINCT FROM OLD.id THEN\n RAISE EXCEPTION 'TypeID document IDs are immutable (table %)', TG_TABLE_NAME\n USING ERRCODE = 'check_violation';\n END IF;\n RETURN NEW;\n END IF;\n IF NEW.id IS NULL THEN\n NEW.id := TG_ARGV[0] || '_' || payload_typeid_encode(payload_typeid_uuid_v7_hex());\n END IF;\n RETURN NEW;\nEND $$;`;\n\n// Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.\nfunction tableNameForSlug(slug: string): string {\n return slug\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z\\d])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n/** SQL that installs the ID functions, a per-table CHECK constraint, and a per-table trigger. */\nfunction typeIdDatabaseSql(guards: ReadonlyArray<{ table: string; prefix: string }>): string {\n const statements = [encodeFunction, uuidV7Function, guardFunction];\n for (const { table, prefix } of guards) {\n if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {\n throw new TypeError(`Refusing to guard unsafe table or prefix \"${table}\" / \"${prefix}\".`);\n }\n const constraint = `payload_typeid_${table}_id_check`;\n const trigger = `payload_typeid_${table}_guard`;\n statements.push(\n `ALTER TABLE \"${table}\" DROP CONSTRAINT IF EXISTS \"${constraint}\";`,\n `ALTER TABLE \"${table}\" ADD CONSTRAINT \"${constraint}\" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`,\n `DROP TRIGGER IF EXISTS \"${trigger}\" ON \"${table}\";`,\n `CREATE TRIGGER \"${trigger}\" BEFORE INSERT OR UPDATE ON \"${table}\" FOR EACH ROW EXECUTE FUNCTION payload_typeid_guard('${prefix}');`,\n );\n }\n return statements.join(\"\\n\");\n}\n\ntype PostgresPool = { query(text: string, values?: unknown[]): Promise<{ rows: unknown[] }> };\n\n/**\n * Installs the database guards on the Postgres adapter. Other adapters get a warning instead:\n * the guards are SQL and cannot be applied to them.\n */\nasync function installTypeIdDatabaseGuards(\n payload: Payload,\n guards: ReadonlyArray<TypeIdTableGuard>,\n): Promise<void> {\n if (guards.length === 0) return;\n if (payload.db.name !== \"postgres\") {\n payload.logger.warn(\n `payload-typeid: database guards are only installed on PostgreSQL; the \"${payload.db.name}\" adapter keeps application-level rules only.`,\n );\n return;\n }\n\n const pool = (payload.db as unknown as { pool: PostgresPool }).pool;\n const tables = guards.map(({ slug, prefix }) => {\n const defaultName = tableNameForSlug(slug);\n const tableNameMap = (payload.db as unknown as { tableNameMap?: Map<string, string> })\n .tableNameMap;\n const table = tableNameMap?.get(defaultName) ?? defaultName;\n return { slug, prefix, table };\n });\n\n for (const { slug, table } of tables) {\n const { rows } = await pool.query(\"SELECT to_regclass($1) AS relation\", [`\"${table}\"`]);\n if (!(rows[0] as { relation: unknown } | undefined)?.relation) {\n throw new TypeError(\n `payload-typeid: no table \"${table}\" for collection \"${slug}\". Set the collection's dbName or rename it before enabling TypeIDs.`,\n );\n }\n }\n\n await pool.query(typeIdDatabaseSql(tables.map(({ table, prefix }) => ({ table, prefix }))));\n}\n\nexport type TypeID<Prefix extends string = string> = string extends Prefix\n ? string\n : Prefix extends \"\"\n ? string\n : `${Prefix}_${string}`;\n\nexport interface TypeIdOptions {\n collections?: Record<string, boolean | string>;\n}\n\ninterface ParsedTypeID<Prefix extends string = string> {\n prefix: Prefix;\n uuid: string;\n}\n\nconst prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;\nconst uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst typeIdAlphabet = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst maxUuid = (1n << 128n) - 1n;\n\nfunction validatePrefix(prefix: string): void {\n if (!prefixPattern.test(prefix)) {\n throw new TypeError(\n `Invalid TypeID prefix \"${prefix}\". Prefixes must be empty or 1–63 lowercase ASCII letters and underscores, starting and ending with a letter.`,\n );\n }\n}\n\nfunction uuidFromBytes(bytes: Uint8Array): string {\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUuid(uuid: string): string {\n let value = BigInt(`0x${uuid.replaceAll(\"-\", \"\")}`);\n let suffix = \"\";\n for (let index = 0; index < 26; index += 1) {\n suffix = typeIdAlphabet[Number(value & 31n)] + suffix;\n value >>= 5n;\n }\n return suffix;\n}\n\nfunction decodeSuffix(suffix: string): string {\n let value = 0n;\n for (const character of suffix) {\n const digit = typeIdAlphabet.indexOf(character);\n if (digit === -1)\n throw new TypeError(\"Suffix contains a character outside the TypeID alphabet.\");\n value = (value << 5n) | BigInt(digit);\n }\n if (value > maxUuid) throw new TypeError(\"Suffix exceeds the 128-bit UUID range.\");\n return value.toString(16).padStart(32, \"0\");\n}\n\nexport function fromUUID<const Prefix extends string>(\n prefix: Prefix,\n uuid: string,\n): TypeID<Prefix> {\n validatePrefix(prefix);\n if (!uuidPattern.test(uuid)) {\n throw new TypeError(`Invalid UUID \"${uuid}\". Expected a canonical 36-character UUID.`);\n }\n return `${prefix ? `${prefix}_` : \"\"}${encodeUuid(uuid)}` as TypeID<Prefix>;\n}\n\nexport function parseTypeId<const Prefix extends string = string>(\n value: string,\n): ParsedTypeID<Prefix> {\n if (typeof value !== \"string\") throw new TypeError(\"TypeID must be a string.\");\n const separator = value.lastIndexOf(\"_\");\n const prefix = separator === -1 ? \"\" : value.slice(0, separator);\n const suffix = separator === -1 ? value : value.slice(separator + 1);\n try {\n validatePrefix(prefix);\n if (separator !== -1 && prefix === \"\") {\n throw new TypeError(\"An empty prefix must not include a separator.\");\n }\n if (suffix.length !== 26) throw new TypeError(\"Suffix must contain exactly 26 characters.\");\n const hex = decodeSuffix(suffix);\n return {\n prefix: prefix as Prefix,\n uuid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n };\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID \"${value}\": ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function toUUID(value: string): string {\n return parseTypeId(value).uuid;\n}\n\nexport function isTypeId<Prefix extends string = string>(\n value: unknown,\n expectedPrefix?: Prefix,\n): value is TypeID<Prefix> {\n if (typeof value !== \"string\") return false;\n try {\n const parsed = parseTypeId(value);\n return expectedPrefix === undefined || parsed.prefix === expectedPrefix;\n } catch {\n return false;\n }\n}\n\nexport function generateTypeId<const Prefix extends string>(prefix: Prefix): TypeID<Prefix> {\n validatePrefix(prefix);\n const bytes = randomBytes(16);\n let timestamp = BigInt(Date.now());\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = Number(timestamp & 0xffn);\n timestamp >>= 8n;\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n return fromUUID(prefix, uuidFromBytes(bytes));\n}\n\nfunction deriveCollectionPrefix(slug: string): string {\n // Hyphens and underscores are word separators; Payload's formatLabels splits only on hyphens and whitespace.\n const singular = formatLabels(slug.replaceAll(\"_\", \"-\")).singular;\n const words = singular.split(\" \");\n // Acronyms such as \"APIKeys\" split into single letters, so they cannot be derived reliably.\n const derivable =\n singular !== \"\" &&\n words.every((word) => /^[A-Za-z]+$/.test(word)) &&\n !(words.length > 1 && words.some((word) => word.length === 1));\n if (!derivable) {\n throw new TypeError(\n `Collection \"${slug}\" cannot derive a TypeID prefix from its slug. Set custom.typeId or collections[\"${slug}\"] to an explicit prefix string.`,\n );\n }\n return words.join(\"_\").toLowerCase();\n}\n\nfunction hasCustomID(fields: Field[]): boolean {\n return flattenAllFields({ fields }).some((field) => \"name\" in field && field.name === \"id\");\n}\n\nfunction createIDField(prefix: string): Field {\n return {\n name: \"id\",\n type: \"text\",\n required: true,\n admin: { hidden: true, readOnly: true },\n access: {\n create: () => true,\n update: () => false,\n },\n defaultValue: () => generateTypeId(prefix),\n hooks: {\n beforeChange: [\n ({ operation, originalDoc, value }) => {\n if (operation === \"create\") return value || generateTypeId(prefix);\n return originalDoc?.id ?? value;\n },\n ],\n beforeDuplicate: [() => generateTypeId(prefix)],\n },\n };\n}\n\nfunction withIDOwnership(collection: CollectionConfig, prefix: string): CollectionConfig {\n const beforeOperation = collection.hooks?.beforeOperation ?? [];\n return {\n ...collection,\n // Payload stops custom ID discovery when it reaches structural fields.\n fields: [createIDField(prefix), ...collection.fields],\n hooks: {\n ...collection.hooks,\n beforeOperation: [\n ...beforeOperation,\n ({ operation, args }) => {\n if (operation === \"create\") {\n const createArgs = args as { customID?: unknown; data?: Record<string, unknown> };\n if (createArgs.customID !== undefined || createArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" owns its IDs; omit customID and data.id when creating documents.`,\n );\n }\n }\n if (operation === \"update\") {\n const updateArgs = args as { data?: Record<string, unknown> };\n if (updateArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" IDs are immutable; omit data.id when updating documents.`,\n );\n }\n }\n return args;\n },\n ],\n },\n };\n}\n\nfunction readSetting(value: unknown, owner: string): boolean | string | undefined {\n if (value === undefined || typeof value === \"boolean\" || typeof value === \"string\") {\n return value;\n }\n throw new TypeError(\n `Invalid TypeID configuration for ${owner}: custom.typeId must be true, false, a prefix string, or undefined.`,\n );\n}\n\nfunction assertCurrentKey(custom: Record<string, unknown> | undefined, owner: string): void {\n if (custom && Object.hasOwn(custom, \"typeid\")) {\n throw new TypeError(\n `${owner} uses the obsolete custom.typeid key; rename it to custom.typeId.`,\n );\n }\n}\n\nfunction validateCollectionPrefix(slug: string, prefix: string): void {\n if (prefix === \"\") {\n throw new TypeError(\n `Collection \"${slug}\" resolved to an empty TypeID prefix; provide a non-empty prefix string.`,\n );\n }\n try {\n validatePrefix(prefix);\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID prefix for collection \"${slug}\": ${error instanceof Error ? error.message : String(error)} Provide a valid prefix string.`,\n { cause: error },\n );\n }\n}\n\nexport function typeId(options: TypeIdOptions = {}): Plugin {\n const plugin: Plugin = (config: Config) => {\n if (typeof options !== \"object\" || options === null || Array.isArray(options)) {\n throw new TypeError(\"TypeID options must be an object.\");\n }\n if (Object.keys(options).some((key) => key !== \"collections\")) {\n throw new TypeError('TypeID options only support \"collections\".');\n }\n if ((config.plugins?.filter(({ slug }) => slug === \"payload-typeid\").length ?? 0) > 1) {\n throw new TypeError(\"Register typeId() only once in the Payload plugins array.\");\n }\n\n const overrides = options.collections;\n if (\n overrides !== undefined &&\n (typeof overrides !== \"object\" || overrides === null || Array.isArray(overrides))\n ) {\n throw new TypeError(\n \"TypeID collections must be a record of collection slugs to true, false, or prefix strings.\",\n );\n }\n for (const [slug, setting] of Object.entries(overrides ?? {})) {\n if (typeof setting !== \"boolean\" && typeof setting !== \"string\") {\n throw new TypeError(\n `TypeID collections[\"${slug}\"] must be true, false, or a prefix string.`,\n );\n }\n }\n\n const collections = config.collections ?? [];\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n for (const slug of Object.keys(overrides ?? {})) {\n if (!collectionSlugs.has(slug)) {\n throw new TypeError(`TypeID collections references unknown collection \"${slug}\".`);\n }\n }\n\n for (const global of config.globals ?? []) {\n assertCurrentKey(global.custom, `Global \"${global.slug}\"`);\n const setting = readSetting(global.custom?.typeId, `Global \"${global.slug}\"`);\n if (setting !== undefined && setting !== false) {\n throw new TypeError(\n `Global \"${global.slug}\" cannot use custom.typeId ${JSON.stringify(setting)} because Payload Globals do not expose configurable document IDs. Use false or omit custom.typeId.`,\n );\n }\n }\n\n // Resolve opt-out first so shadowed central settings never reach prefix validation.\n // Precedence: model custom.typeId > central collections entry > default (derived prefix).\n const managed: Array<{ collection: CollectionConfig; setting: true | string }> = [];\n for (const collection of collections) {\n assertCurrentKey(collection.custom, `Collection \"${collection.slug}\"`);\n const modelSetting = readSetting(\n collection.custom?.typeId,\n `collection \"${collection.slug}\"`,\n );\n const centralSetting =\n overrides && Object.hasOwn(overrides, collection.slug)\n ? overrides[collection.slug]\n : undefined;\n const setting = modelSetting ?? centralSetting ?? true;\n if (setting === false) continue;\n managed.push({ collection, setting });\n }\n\n const prefixes = new Map<string, string>();\n const replacements = new Map<string, CollectionConfig>();\n const guards: TypeIdTableGuard[] = [];\n for (const { collection, setting } of managed) {\n const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;\n validateCollectionPrefix(collection.slug, prefix);\n\n const existing = prefixes.get(prefix);\n if (existing) {\n throw new TypeError(\n `Collections \"${existing}\" and \"${collection.slug}\" resolve to duplicate TypeID prefix \"${prefix}\". Set an explicit prefix on one of them with custom.typeId or collections.`,\n );\n }\n prefixes.set(prefix, collection.slug);\n\n if (hasCustomID(collection.fields)) {\n throw new TypeError(\n `Collection \"${collection.slug}\" already has a collection-level field named \"id\". Set custom.typeId = false or rename that field before enabling TypeID.`,\n );\n }\n replacements.set(collection.slug, withIDOwnership(collection, prefix));\n guards.push({ slug: collection.slug, prefix });\n }\n\n const onInit = config.onInit;\n return {\n ...config,\n collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),\n // Database guards run after Payload has created its tables, so the CHECK and triggers apply to them.\n onInit: async (payload) => {\n await onInit?.(payload);\n await installTypeIdDatabaseGuards(payload, guards);\n },\n };\n };\n\n plugin.slug = \"payload-typeid\";\n plugin.order = Number.MAX_SAFE_INTEGER;\n return plugin;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAIL,gBAAgB,EAEhB,YAAY,GAEb,MAAM,SAAS,CAAC;AAOjB,MAAM,iBAAiB,GAAG,oBAAoB,CAAC;AAC/C,MAAM,iBAAiB,GAAG,6BAA6B,CAAC;AAExD,iGAAiG;AACjG,SAAS,gBAAgB,CAAC,IAAY;IACpC,OAAO,IAAI;SACR,OAAO,CAAC,uBAAuB,EAAE,OAAO,CAAC;SACzC,OAAO,CAAC,mBAAmB,EAAE,OAAO,CAAC;SACrC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,WAAW,EAAE,CAAC;AACnB,CAAC;AAED,6GAA6G;AAC7G,SAAS,SAAS,CAAC,MAA0B;IAC3C,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;AACpE,CAAC;AAED,oGAAoG;AACpG,SAAS,aAAa,CAAC,CAA2B;IAChD,MAAM,KAAK,GAAG;QACZ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,CAAC;YACJ,CAAC;YACD,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YAEtC,IAAI,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnC,MAAM,IAAI,SAAS,CACjB,eAAe,UAAU,CAAC,IAAI,2HAA2H,CAC1J,CAAC;YACJ,CAAC;YACD,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;YACvE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QACjD,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QAC7B,OAAO;YACL,GAAG,MAAM;YACT,WAAW,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC;YAC7F,qGAAqG;YACrG,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;gBACxB,MAAM,MAAM,EAAE,CAAC,OAAO,CAAC,CAAC;gBACxB,MAAM,2BAA2B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YACrD,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,gBAAgB,CAAC;IACvC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n type CollectionConfig,\n type Config,\n type Field,\n flattenAllFields,\n type Payload,\n formatLabels,\n type Plugin,\n} from \"payload\";\n\ninterface TypeIdTableGuard {\n slug: string;\n prefix: string;\n}\n\nconst identifierPattern = /^[a-z_][a-z0-9_]*$/;\nconst prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;\n\n// Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.\nfunction tableNameForSlug(slug: string): string {\n return slug\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z\\d])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n// Objects are qualified with the adapter's schema; without one they stay unqualified, like Payload's tables.\nfunction qualifier(schema: string | undefined): (name: string) => string {\n return (name) => (schema ? `\"${schema}\".\"${name}\"` : `\"${name}\"`);\n}\n\n// Mirrors encodeUuid/decodeSuffix: a 128-bit value as 26 Base32 characters, most significant first.\nfunction functionSpecs(q: (name: string) => string) {\n const specs = [\n {\n name: \"payload_typeid_encode\",\n args: \"hex text\",\n returns: \"text\",\n attributes: \"LANGUAGE plpgsql IMMUTABLE\",\n body: `\nDECLARE\n value numeric := 0;\n remainder integer;\n result text := '';\n alphabet text := '0123456789abcdefghjkmnpqrstvwxyz';\nBEGIN\n FOR i IN 1..32 LOOP\n value := value * 16 + ('x' || substr(hex, i, 1))::bit(4)::int;\n END LOOP;\n FOR i IN 1..26 LOOP\n remainder := (value % 32)::integer;\n result := substr(alphabet, remainder + 1, 1) || result;\n value := (value - remainder) / 32;\n END LOOP;\n RETURN result;\nEND `,\n },\n // UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.\n {\n name: \"payload_typeid_uuid_v7_hex\",\n args: \"\",\n returns: \"text\",\n attributes: \"LANGUAGE plpgsql VOLATILE\",\n body: `\nDECLARE\n millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;\n random_hex text := replace(gen_random_uuid()::text, '-', '');\nBEGIN\n RETURN lpad(to_hex(millis), 12, '0')\n || '7' || substr(random_hex, 14, 3)\n || to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)\n || substr(random_hex, 18, 15);\nEND `,\n },\n // Generates an ID when none is supplied, and rejects any change to an existing ID.\n {\n name: \"payload_typeid_guard\",\n args: \"\",\n returns: \"trigger\",\n attributes: \"LANGUAGE plpgsql\",\n body: `\nBEGIN\n IF TG_OP = 'UPDATE' THEN\n IF NEW.id IS DISTINCT FROM OLD.id THEN\n RAISE EXCEPTION 'TypeID document IDs are immutable (table %)', TG_TABLE_NAME\n USING ERRCODE = 'check_violation';\n END IF;\n RETURN NEW;\n END IF;\n IF NEW.id IS NULL THEN\n NEW.id := TG_ARGV[0] || '_' || ${q(\"payload_typeid_encode\")}(${q(\"payload_typeid_uuid_v7_hex\")}());\n END IF;\n RETURN NEW;\nEND `,\n },\n ];\n return specs.map((spec) => ({\n // to_regprocedure takes argument types only, not parameter names.\n signature: `${q(spec.name)}(${spec.args.replace(/^\\w+ /, \"\")})`,\n body: spec.body,\n create: `CREATE OR REPLACE FUNCTION ${q(spec.name)}(${spec.args}) RETURNS ${spec.returns} ${spec.attributes} AS $$${spec.body}$$;`,\n }));\n}\n\ntype PostgresPool = {\n query(text: string, values?: unknown[]): Promise<{ rows: Array<Record<string, unknown>> }>;\n};\n\nasync function catalogValue(pool: PostgresPool, sql: string, values: unknown[]) {\n const { rows } = await pool.query(sql, values);\n return rows[0]?.value as string | null | undefined;\n}\n\n/**\n * Installs the database guards on the Postgres adapter. Other adapters get a warning instead:\n * the guards are SQL and cannot be applied to them.\n */\nasync function installTypeIdDatabaseGuards(\n payload: Payload,\n guards: ReadonlyArray<TypeIdTableGuard>,\n): Promise<void> {\n if (payload.db.name !== \"postgres\") {\n payload.logger.warn(\n `payload-typeid: database guards are only installed on PostgreSQL; the \"${payload.db.name}\" adapter keeps application-level rules only.`,\n );\n return;\n }\n\n const db = payload.db as unknown as {\n pool: PostgresPool;\n schemaName?: string;\n tableNameMap?: Map<string, string>;\n };\n const schema = db.schemaName;\n if (schema !== undefined && !identifierPattern.test(schema)) {\n throw new TypeError(`payload-typeid: unsupported PostgreSQL schema name \"${schema}\".`);\n }\n const q = qualifier(schema);\n const pool = db.pool;\n\n const tables = guards.map(({ slug, prefix }) => {\n const defaultName = tableNameForSlug(slug);\n return { slug, prefix, table: db.tableNameMap?.get(defaultName) ?? defaultName };\n });\n for (const { slug, prefix, table } of tables) {\n if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {\n throw new TypeError(\n `payload-typeid: refusing to guard unsafe table \"${table}\" or prefix \"${prefix}\".`,\n );\n }\n const relation = await catalogValue(pool, \"SELECT to_regclass($1)::text AS value\", [q(table)]);\n if (!relation) {\n throw new TypeError(\n `payload-typeid: no table \"${table}\" for collection \"${slug}\". Set the collection's dbName or rename it before enabling TypeIDs.`,\n );\n }\n }\n\n // Only missing or differing objects are changed, so an up-to-date database needs no DDL and\n // a role without table-owner rights can still start.\n const statements: string[] = [];\n for (const spec of functionSpecs(q)) {\n const current = await catalogValue(\n pool,\n \"SELECT prosrc AS value FROM pg_proc WHERE oid = to_regprocedure($1)\",\n [spec.signature],\n );\n if (current !== spec.body) statements.push(spec.create);\n }\n\n for (const { prefix, table } of tables) {\n const constraint = `payload_typeid_${table}_id_check`;\n const trigger = `payload_typeid_${table}_guard`;\n const constraintDef = await catalogValue(\n pool,\n \"SELECT pg_get_constraintdef(c.oid) AS value FROM pg_constraint c WHERE c.conrelid = to_regclass($1) AND c.conname = $2\",\n [q(table), constraint],\n );\n if (!constraintDef?.includes(`'^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$'`)) {\n statements.push(\n `ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS \"${constraint}\";`,\n `ALTER TABLE ${q(table)} ADD CONSTRAINT \"${constraint}\" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`,\n );\n }\n const triggerDef = await catalogValue(\n pool,\n \"SELECT pg_get_triggerdef(t.oid) AS value FROM pg_trigger t WHERE t.tgrelid = to_regclass($1) AND t.tgname = $2 AND NOT t.tgisinternal\",\n [q(table), trigger],\n );\n if (!triggerDef?.includes(`payload_typeid_guard('${prefix}')`)) {\n statements.push(\n `DROP TRIGGER IF EXISTS \"${trigger}\" ON ${q(table)};`,\n `CREATE TRIGGER \"${trigger}\" BEFORE INSERT OR UPDATE ON ${q(table)} FOR EACH ROW EXECUTE FUNCTION ${q(\"payload_typeid_guard\")}('${prefix}');`,\n );\n }\n }\n\n if (statements.length > 0) {\n // A multi-statement query runs as one transaction: a failure leaves the previous guards in place.\n await pool.query(statements.join(\"\\n\"));\n }\n}\n\nexport type TypeID<Prefix extends string = string> = string extends Prefix\n ? string\n : Prefix extends \"\"\n ? string\n : `${Prefix}_${string}`;\n\nexport interface TypeIdOptions {\n collections?: Record<string, boolean | string>;\n}\n\ninterface ParsedTypeID<Prefix extends string = string> {\n prefix: Prefix;\n uuid: string;\n}\n\nconst prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;\nconst uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst typeIdAlphabet = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst maxUuid = (1n << 128n) - 1n;\n\nfunction validatePrefix(prefix: string): void {\n if (!prefixPattern.test(prefix)) {\n throw new TypeError(\n `Invalid TypeID prefix \"${prefix}\". Prefixes must be empty or 1–63 lowercase ASCII letters and underscores, starting and ending with a letter.`,\n );\n }\n}\n\nfunction uuidFromBytes(bytes: Uint8Array): string {\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUuid(uuid: string): string {\n let value = BigInt(`0x${uuid.replaceAll(\"-\", \"\")}`);\n let suffix = \"\";\n for (let index = 0; index < 26; index += 1) {\n suffix = typeIdAlphabet[Number(value & 31n)] + suffix;\n value >>= 5n;\n }\n return suffix;\n}\n\nfunction decodeSuffix(suffix: string): string {\n let value = 0n;\n for (const character of suffix) {\n const digit = typeIdAlphabet.indexOf(character);\n if (digit === -1)\n throw new TypeError(\"Suffix contains a character outside the TypeID alphabet.\");\n value = (value << 5n) | BigInt(digit);\n }\n if (value > maxUuid) throw new TypeError(\"Suffix exceeds the 128-bit UUID range.\");\n return value.toString(16).padStart(32, \"0\");\n}\n\nexport function fromUUID<const Prefix extends string>(\n prefix: Prefix,\n uuid: string,\n): TypeID<Prefix> {\n validatePrefix(prefix);\n if (!uuidPattern.test(uuid)) {\n throw new TypeError(`Invalid UUID \"${uuid}\". Expected a canonical 36-character UUID.`);\n }\n return `${prefix ? `${prefix}_` : \"\"}${encodeUuid(uuid)}` as TypeID<Prefix>;\n}\n\nexport function parseTypeId<const Prefix extends string = string>(\n value: string,\n): ParsedTypeID<Prefix> {\n if (typeof value !== \"string\") throw new TypeError(\"TypeID must be a string.\");\n const separator = value.lastIndexOf(\"_\");\n const prefix = separator === -1 ? \"\" : value.slice(0, separator);\n const suffix = separator === -1 ? value : value.slice(separator + 1);\n try {\n validatePrefix(prefix);\n if (separator !== -1 && prefix === \"\") {\n throw new TypeError(\"An empty prefix must not include a separator.\");\n }\n if (suffix.length !== 26) throw new TypeError(\"Suffix must contain exactly 26 characters.\");\n const hex = decodeSuffix(suffix);\n return {\n prefix: prefix as Prefix,\n uuid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n };\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID \"${value}\": ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function toUUID(value: string): string {\n return parseTypeId(value).uuid;\n}\n\nexport function isTypeId<Prefix extends string = string>(\n value: unknown,\n expectedPrefix?: Prefix,\n): value is TypeID<Prefix> {\n if (typeof value !== \"string\") return false;\n try {\n const parsed = parseTypeId(value);\n return expectedPrefix === undefined || parsed.prefix === expectedPrefix;\n } catch {\n return false;\n }\n}\n\nexport function generateTypeId<const Prefix extends string>(prefix: Prefix): TypeID<Prefix> {\n validatePrefix(prefix);\n const bytes = randomBytes(16);\n let timestamp = BigInt(Date.now());\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = Number(timestamp & 0xffn);\n timestamp >>= 8n;\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n return fromUUID(prefix, uuidFromBytes(bytes));\n}\n\nfunction deriveCollectionPrefix(slug: string): string {\n // Hyphens and underscores are word separators; Payload's formatLabels splits only on hyphens and whitespace.\n const singular = formatLabels(slug.replaceAll(\"_\", \"-\")).singular;\n const words = singular.split(\" \");\n // Acronyms such as \"APIKeys\" split into single letters, so they cannot be derived reliably.\n const derivable =\n singular !== \"\" &&\n words.every((word) => /^[A-Za-z]+$/.test(word)) &&\n !(words.length > 1 && words.some((word) => word.length === 1));\n if (!derivable) {\n throw new TypeError(\n `Collection \"${slug}\" cannot derive a TypeID prefix from its slug. Set custom.typeId or collections[\"${slug}\"] to an explicit prefix string.`,\n );\n }\n return words.join(\"_\").toLowerCase();\n}\n\nfunction hasCustomID(fields: Field[]): boolean {\n return flattenAllFields({ fields }).some((field) => \"name\" in field && field.name === \"id\");\n}\n\nfunction createIDField(prefix: string): Field {\n return {\n name: \"id\",\n type: \"text\",\n required: true,\n admin: { hidden: true, readOnly: true },\n access: {\n create: () => true,\n update: () => false,\n },\n defaultValue: () => generateTypeId(prefix),\n hooks: {\n beforeChange: [\n ({ operation, originalDoc, value }) => {\n if (operation === \"create\") return value || generateTypeId(prefix);\n return originalDoc?.id ?? value;\n },\n ],\n beforeDuplicate: [() => generateTypeId(prefix)],\n },\n };\n}\n\nfunction withIDOwnership(collection: CollectionConfig, prefix: string): CollectionConfig {\n const beforeOperation = collection.hooks?.beforeOperation ?? [];\n return {\n ...collection,\n // Payload stops custom ID discovery when it reaches structural fields.\n fields: [createIDField(prefix), ...collection.fields],\n hooks: {\n ...collection.hooks,\n beforeOperation: [\n ...beforeOperation,\n ({ operation, args }) => {\n if (operation === \"create\") {\n const createArgs = args as { customID?: unknown; data?: Record<string, unknown> };\n if (createArgs.customID !== undefined || createArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" owns its IDs; omit customID and data.id when creating documents.`,\n );\n }\n }\n if (operation === \"update\") {\n const updateArgs = args as { data?: Record<string, unknown> };\n if (updateArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" IDs are immutable; omit data.id when updating documents.`,\n );\n }\n }\n return args;\n },\n ],\n },\n };\n}\n\nfunction readSetting(value: unknown, owner: string): boolean | string | undefined {\n if (value === undefined || typeof value === \"boolean\" || typeof value === \"string\") {\n return value;\n }\n throw new TypeError(\n `Invalid TypeID configuration for ${owner}: custom.typeId must be true, false, a prefix string, or undefined.`,\n );\n}\n\nfunction assertCurrentKey(custom: Record<string, unknown> | undefined, owner: string): void {\n if (custom && Object.hasOwn(custom, \"typeid\")) {\n throw new TypeError(\n `${owner} uses the obsolete custom.typeid key; rename it to custom.typeId.`,\n );\n }\n}\n\nfunction validateCollectionPrefix(slug: string, prefix: string): void {\n if (prefix === \"\") {\n throw new TypeError(\n `Collection \"${slug}\" resolved to an empty TypeID prefix; provide a non-empty prefix string.`,\n );\n }\n try {\n validatePrefix(prefix);\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID prefix for collection \"${slug}\": ${error instanceof Error ? error.message : String(error)} Provide a valid prefix string.`,\n { cause: error },\n );\n }\n}\n\nexport function typeId(options: TypeIdOptions = {}): Plugin {\n const plugin: Plugin = (config: Config) => {\n if (typeof options !== \"object\" || options === null || Array.isArray(options)) {\n throw new TypeError(\"TypeID options must be an object.\");\n }\n if (Object.keys(options).some((key) => key !== \"collections\")) {\n throw new TypeError('TypeID options only support \"collections\".');\n }\n if ((config.plugins?.filter(({ slug }) => slug === \"payload-typeid\").length ?? 0) > 1) {\n throw new TypeError(\"Register typeId() only once in the Payload plugins array.\");\n }\n\n const overrides = options.collections;\n if (\n overrides !== undefined &&\n (typeof overrides !== \"object\" || overrides === null || Array.isArray(overrides))\n ) {\n throw new TypeError(\n \"TypeID collections must be a record of collection slugs to true, false, or prefix strings.\",\n );\n }\n for (const [slug, setting] of Object.entries(overrides ?? {})) {\n if (typeof setting !== \"boolean\" && typeof setting !== \"string\") {\n throw new TypeError(\n `TypeID collections[\"${slug}\"] must be true, false, or a prefix string.`,\n );\n }\n }\n\n const collections = config.collections ?? [];\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n for (const slug of Object.keys(overrides ?? {})) {\n if (!collectionSlugs.has(slug)) {\n throw new TypeError(`TypeID collections references unknown collection \"${slug}\".`);\n }\n }\n\n for (const global of config.globals ?? []) {\n assertCurrentKey(global.custom, `Global \"${global.slug}\"`);\n const setting = readSetting(global.custom?.typeId, `Global \"${global.slug}\"`);\n if (setting !== undefined && setting !== false) {\n throw new TypeError(\n `Global \"${global.slug}\" cannot use custom.typeId ${JSON.stringify(setting)} because Payload Globals do not expose configurable document IDs. Use false or omit custom.typeId.`,\n );\n }\n }\n\n // Resolve opt-out first so shadowed central settings never reach prefix validation.\n // Precedence: model custom.typeId > central collections entry > default (derived prefix).\n const managed: Array<{ collection: CollectionConfig; setting: true | string }> = [];\n for (const collection of collections) {\n assertCurrentKey(collection.custom, `Collection \"${collection.slug}\"`);\n const modelSetting = readSetting(\n collection.custom?.typeId,\n `collection \"${collection.slug}\"`,\n );\n const centralSetting =\n overrides && Object.hasOwn(overrides, collection.slug)\n ? overrides[collection.slug]\n : undefined;\n const setting = modelSetting ?? centralSetting ?? true;\n if (setting === false) continue;\n managed.push({ collection, setting });\n }\n\n const prefixes = new Map<string, string>();\n const replacements = new Map<string, CollectionConfig>();\n const guards: TypeIdTableGuard[] = [];\n for (const { collection, setting } of managed) {\n const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;\n validateCollectionPrefix(collection.slug, prefix);\n\n const existing = prefixes.get(prefix);\n if (existing) {\n throw new TypeError(\n `Collections \"${existing}\" and \"${collection.slug}\" resolve to duplicate TypeID prefix \"${prefix}\". Set an explicit prefix on one of them with custom.typeId or collections.`,\n );\n }\n prefixes.set(prefix, collection.slug);\n\n if (hasCustomID(collection.fields)) {\n throw new TypeError(\n `Collection \"${collection.slug}\" already has a collection-level field named \"id\". Set custom.typeId = false or rename that field before enabling TypeID.`,\n );\n }\n replacements.set(collection.slug, withIDOwnership(collection, prefix));\n guards.push({ slug: collection.slug, prefix });\n }\n\n const onInit = config.onInit;\n return {\n ...config,\n collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),\n // Database guards run after Payload has created its tables, so the CHECK and triggers apply to them.\n onInit: async (payload) => {\n await onInit?.(payload);\n await installTypeIdDatabaseGuards(payload, guards);\n },\n };\n };\n\n plugin.slug = \"payload-typeid\";\n plugin.order = Number.MAX_SAFE_INTEGER;\n return plugin;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/payload-typeid",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Type-prefixed UUIDv7 primary keys for Payload CMS.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -50,7 +50,7 @@
50
50
  "format:write": "biome format --write .",
51
51
  "typecheck": "tsc --noEmit -p tsconfig.json",
52
52
  "test": "bun test",
53
- "test:postgres": "PAYLOAD_DB_PUSH=true PAYLOAD_FORCE_DRIZZLE_PUSH=true bun test --timeout 30000 ./tests/postgres.integration.ts",
53
+ "test:postgres": "PAYLOAD_DB_PUSH=true PAYLOAD_FORCE_DRIZZLE_PUSH=true bun test --timeout 30000 ./tests/postgres.integration.ts ./tests/postgres.schema.integration.ts",
54
54
  "verify:package": "publint --strict && attw --profile esm-only --pack .",
55
55
  "check": "bun run format && bun run lint && bun run typecheck && bun run build && bun test && bun run verify:package",
56
56
  "prepublishOnly": "node -e \"if (require('./package.json').private) throw new Error('This package is private and cannot be published')\"",