@klnap/payload-typeid 0.2.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - fde3889: On PostgreSQL, install database guards for managed tables: generate a TypeID for raw SQL inserts without an ID, reject IDs with the wrong prefix or shape, and reject changes to an existing ID. Guards run on every Payload start and do not apply to other adapters.
8
+ - ee07f97: Manage every collection by default. Registering `typeId()` gives each collection a TypeID prefix derived from its slug using Payload's singularization. Set `custom.typeId` to a string to override, or to `false` to opt out. Central `typeId({ collections })` entries apply when a collection omits `custom.typeId`.
9
+
10
+ Breaking: this replaces the explicit opt-in from 0.2.0. Registering the plugin changes the ID type of every collection that does not opt out. Migrate existing data or set `custom.typeId: false` on those collections before upgrading.
11
+
3
12
  ## 0.2.0
4
13
 
5
14
  ### Minor Changes
package/README.md CHANGED
@@ -10,14 +10,18 @@ It is the document's one native Payload ID. The package adds no second identifie
10
10
 
11
11
  ## What changes
12
12
 
13
- Registering the plugin changes nothing by itself. Each collection opts in with `custom.typeId`.
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
14
 
15
- | Collection | Without opt-in | With `custom.typeId: "article"` |
16
- | ---------------------------- | ------------------- | ------------------------------------ |
17
- | `articles` | Payload's native ID | `article_01m8d47saaepfr8kaw7mqdxs1h` |
18
- | `users` (no `custom.typeId`) | Payload's native ID | Payload's native ID |
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 |
19
21
 
20
- New documents in opted-in collections receive a TypeID on create and on duplicate. Existing documents keep their IDs until you migrate them; see [Enabling on existing data](#enabling-on-existing-data).
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).
21
25
 
22
26
  ## Installation
23
27
 
@@ -37,7 +41,6 @@ import { typeId } from "@klnap/payload-typeid";
37
41
 
38
42
  const Articles: CollectionConfig = {
39
43
  slug: "articles",
40
- custom: { typeId: "article" },
41
44
  fields: [],
42
45
  };
43
46
 
@@ -52,7 +55,7 @@ export default buildConfig({
52
55
  });
53
56
  ```
54
57
 
55
- Register `typeId()` after plugins that add collections, so it sees the final collection list.
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.
56
59
 
57
60
  ## How it works
58
61
 
@@ -66,14 +69,20 @@ The plugin runs last (`order` is the maximum), so its `id` field and hooks apply
66
69
 
67
70
  ## Configuration
68
71
 
72
+ Each collection's prefix is resolved in this order. The first value that is set wins:
73
+
74
+ 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.
77
+
69
78
  ### On the collection: `custom.typeId`
70
79
 
71
- | Value | Effect |
72
- | ----------- | ------------------------------------------------------------------------------------------------------------ |
73
- | `"article"` | Manage the collection with exactly this prefix. |
74
- | `true` | Derive the prefix from the slug with Payload's singularization. See [Prefix derivation](#prefix-derivation). |
75
- | `false` | Keep the native ID strategy, even if the central option names this collection. |
76
- | omitted | Use the central option if it names this collection; otherwise the collection is unmanaged. |
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. |
77
86
 
78
87
  ### Centrally: `typeId({ collections })`
79
88
 
@@ -81,37 +90,29 @@ The plugin runs last (`order` is the maximum), so its `id` field and hooks apply
81
90
  typeId({
82
91
  collections: {
83
92
  articles: "article",
84
- authors: true,
93
+ authors: "writer",
85
94
  users: false,
86
95
  },
87
96
  });
88
97
  ```
89
98
 
90
- The keys are collection slugs that must exist in `config.collections`. An unknown slug throws during setup.
91
-
92
- ### Precedence
93
-
94
- For each collection, the plugin resolves the setting in this order and stops at the first value that is set:
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.
95
100
 
96
- 1. `custom.typeId` on the collection (`true`, a string, or `false`).
97
- 2. The central `collections` entry for its slug (`true`, a string, or `false`).
98
- 3. Otherwise the collection is unmanaged.
101
+ ### Examples
99
102
 
100
- Examples:
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_…` |
101
110
 
102
- | Collection `custom.typeId` | Central entry | Result |
103
- | -------------------------- | ------------- | ---------------- |
104
- | `"art"` | `"article"` | Prefix `art` |
105
- | `false` | `"article"` | Unmanaged |
106
- | omitted | `"article"` | Prefix `article` |
107
- | omitted | `true` | Derived prefix |
108
- | omitted | omitted | Unmanaged |
109
-
110
- A collection-level value always wins over the central one. `false` at either level keeps the collection unmanaged.
111
+ A collection-level value always wins. `false` at either level opts the collection out.
111
112
 
112
113
  ### Globals
113
114
 
114
- Globals accept only `false` or omission. Payload does not expose configurable Global document IDs, so `true` or a prefix string on a Global throws during setup.
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.
115
116
 
116
117
  ### Obsolete key
117
118
 
@@ -119,7 +120,7 @@ Globals accept only `false` or omission. Payload does not expose configurable Gl
119
120
 
120
121
  ## Prefix derivation
121
122
 
122
- `custom.typeId: true` derives the prefix from the slug with the same singularization Payload uses for admin labels (`formatLabels` from `payload`):
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:
123
124
 
124
125
  1. Replace `_` with `-` in the slug, so underscores and hyphens both separate words.
125
126
  2. Pass the result through `formatLabels`, which singularizes the last word.
@@ -133,39 +134,28 @@ Regular plural nouns derive cleanly:
133
134
  | `article-authors` | `article_author` |
134
135
  | `ArticleAuthors` | `article_author` |
135
136
  | `audit-logs` | `audit_log` |
137
+ | `users` | `user` |
136
138
 
137
- Irregular or uncountable names do not. Payload's English rules produce prefixes that are correct grammar but unexpected in IDs:
139
+ Irregular or uncountable names derive to correct English that may read oddly in an ID. Payload's English rules decide the result:
138
140
 
139
- | Slug | Derived prefix | Recommendation |
140
- | -------- | -------------- | ------------------------------------------------------------ |
141
- | `people` | `person` | Acceptable, but set `"person"` if you prefer explicit names. |
142
- | `data` | `datum` | Set an explicit prefix such as `"dataset"`. |
143
- | `dice` | `die` | Set an explicit prefix such as `"roll"`. |
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"`. |
144
146
 
145
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.
146
148
 
147
- 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:
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:
148
150
 
149
151
  | Slug | Result |
150
152
  | ----------- | ----------------------------------------------- |
151
153
  | `APIKeys` | Rejected. The label splits into single letters. |
152
154
  | `users-2fa` | Rejected. The label contains a digit. |
153
155
 
154
- For irregular or domain-specific names, set the prefix explicitly instead of relying on derivation.
155
-
156
- ## Overriding the prefix
157
-
158
- Set a string to skip derivation:
159
-
160
- ```ts
161
- // Model level: wins over any central entry.
162
- custom: { typeId: "art" },
163
-
164
- // Central:
165
- typeId({ collections: { articles: "art" } });
166
- ```
156
+ ## Prefix rules
167
157
 
168
- 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.
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.
169
159
 
170
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.
171
161
 
@@ -200,18 +190,18 @@ copy.id.startsWith("article_"); // true
200
190
 
201
191
  Setup and write errors come from the plugin. Each message names the fix:
202
192
 
203
- | Message (starts with) | Cause and fix |
204
- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
205
- | `... uses the obsolete custom.typeid key` | Rename `custom.typeid` to `custom.typeId`. |
206
- | `Invalid TypeID configuration ... custom.typeId must be true, false, a prefix string` | The value has another type. Use one of the accepted values. |
207
- | `Collection "x" cannot derive a TypeID prefix from its slug` | The slug is ambiguous. Set `custom.typeId` to an explicit string. |
208
- | `Collections "a" and "b" resolve to duplicate TypeID prefix` | Two collections share a prefix. Set an explicit prefix on one of them. |
209
- | `Global "x" cannot use custom.typeId` | Globals accept only `false` or omission. |
210
- | `TypeID collections references unknown collection` | A central key is not a collection slug in `config.collections`. |
211
- | `Collection "x" already has a collection-level field named "id"` | Rename that field, or set `custom.typeId: false` on the collection. |
212
- | `Collection "x" owns its IDs; omit customID and data.id when creating` | Remove `customID` and `data.id` from the create call. |
213
- | `Collection "x" IDs are immutable; omit data.id when updating` | Remove `data.id` from the update call. |
214
- | `Register typeId() only once` | Keep a single `typeId()` entry in `plugins`. |
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`. |
215
205
 
216
206
  ## Utilities
217
207
 
@@ -248,14 +238,29 @@ toUUID(fromUUID("article", uuid)) === uuid; // true
248
238
 
249
239
  ## Enabling on existing data
250
240
 
251
- Enabling TypeIDs on a collection with records changes its ID column type and the type of every relationship that points to it. Existing IDs and relationship values are not migrated automatically.
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:
253
+
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.
252
257
 
253
- 1. Back up the database.
254
- 2. Write a migration that assigns a TypeID to each existing document and rewrites relationship values to match.
255
- 3. Deploy the migration with `custom.typeId` set.
256
- 4. Verify relationships before removing old columns.
258
+ The guards are idempotent and survive a repeated `push`; the test suite runs twice against the same database to check this. Limits:
257
259
 
258
- Direct database writes bypass Payload hooks, so they also bypass the ID rules.
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
+ - **Scope.** Versions tables (`_<table>_v`) and relationship join tables are not guarded; their IDs belong to Payload.
263
+ - **Fields.** The guards check only `id`. Other constraints and field rules are not changed.
259
264
 
260
265
  ## Compatibility
261
266
 
package/dist/index.js CHANGED
@@ -1,6 +1,106 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { randomBytes } from "node:crypto";
3
3
  import { flattenAllFields, formatLabels, } from "payload";
4
+ const identifierPattern = /^[a-z_][a-z0-9_]*$/;
5
+ const prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;
6
+ // 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 $$
10
+ DECLARE
11
+ value numeric := 0;
12
+ remainder integer;
13
+ result text := '';
14
+ alphabet text := '0123456789abcdefghjkmnpqrstvwxyz';
15
+ BEGIN
16
+ FOR i IN 1..32 LOOP
17
+ value := value * 16 + ('x' || substr(hex, i, 1))::bit(4)::int;
18
+ END LOOP;
19
+ FOR i IN 1..26 LOOP
20
+ remainder := (value % 32)::integer;
21
+ result := substr(alphabet, remainder + 1, 1) || result;
22
+ value := (value - remainder) / 32;
23
+ END LOOP;
24
+ 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 $$
30
+ DECLARE
31
+ millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
32
+ random_hex text := replace(gen_random_uuid()::text, '-', '');
33
+ BEGIN
34
+ RETURN lpad(to_hex(millis), 12, '0')
35
+ || '7' || substr(random_hex, 14, 3)
36
+ || to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)
37
+ || 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 $$
43
+ BEGIN
44
+ IF TG_OP = 'UPDATE' THEN
45
+ IF NEW.id IS DISTINCT FROM OLD.id THEN
46
+ RAISE EXCEPTION 'TypeID document IDs are immutable (table %)', TG_TABLE_NAME
47
+ USING ERRCODE = 'check_violation';
48
+ END IF;
49
+ RETURN NEW;
50
+ END IF;
51
+ IF NEW.id IS NULL THEN
52
+ NEW.id := TG_ARGV[0] || '_' || payload_typeid_encode(payload_typeid_uuid_v7_hex());
53
+ END IF;
54
+ 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();
63
+ }
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");
76
+ }
77
+ /**
78
+ * Installs the database guards on the Postgres adapter. Other adapters get a warning instead:
79
+ * the guards are SQL and cannot be applied to them.
80
+ */
81
+ async function installTypeIdDatabaseGuards(payload, guards) {
82
+ if (guards.length === 0)
83
+ return;
84
+ if (payload.db.name !== "postgres") {
85
+ payload.logger.warn(`payload-typeid: database guards are only installed on PostgreSQL; the "${payload.db.name}" adapter keeps application-level rules only.`);
86
+ return;
87
+ }
88
+ const pool = payload.db.pool;
89
+ const tables = guards.map(({ slug, prefix }) => {
90
+ const defaultName = tableNameForSlug(slug);
91
+ const tableNameMap = payload.db
92
+ .tableNameMap;
93
+ const table = tableNameMap?.get(defaultName) ?? defaultName;
94
+ return { slug, prefix, table };
95
+ });
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) {
99
+ throw new TypeError(`payload-typeid: no table "${table}" for collection "${slug}". Set the collection's dbName or rename it before enabling TypeIDs.`);
100
+ }
101
+ }
102
+ await pool.query(typeIdDatabaseSql(tables.map(({ table, prefix }) => ({ table, prefix }))));
103
+ }
4
104
  const prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;
5
105
  const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
106
  const typeIdAlphabet = "0123456789abcdefghjkmnpqrstvwxyz";
@@ -216,7 +316,8 @@ export function typeId(options = {}) {
216
316
  throw new TypeError(`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.`);
217
317
  }
218
318
  }
219
- // Resolve opt-in first so shadowed central settings never reach prefix validation.
319
+ // Resolve opt-out first so shadowed central settings never reach prefix validation.
320
+ // Precedence: model custom.typeId > central collections entry > default (derived prefix).
220
321
  const managed = [];
221
322
  for (const collection of collections) {
222
323
  assertCurrentKey(collection.custom, `Collection "${collection.slug}"`);
@@ -224,13 +325,14 @@ export function typeId(options = {}) {
224
325
  const centralSetting = overrides && Object.hasOwn(overrides, collection.slug)
225
326
  ? overrides[collection.slug]
226
327
  : undefined;
227
- const setting = modelSetting ?? centralSetting;
228
- if (setting === undefined || setting === false)
328
+ const setting = modelSetting ?? centralSetting ?? true;
329
+ if (setting === false)
229
330
  continue;
230
331
  managed.push({ collection, setting });
231
332
  }
232
333
  const prefixes = new Map();
233
334
  const replacements = new Map();
335
+ const guards = [];
234
336
  for (const { collection, setting } of managed) {
235
337
  const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;
236
338
  validateCollectionPrefix(collection.slug, prefix);
@@ -243,10 +345,17 @@ export function typeId(options = {}) {
243
345
  throw new TypeError(`Collection "${collection.slug}" already has a collection-level field named "id". Set custom.typeId = false or rename that field before enabling TypeID.`);
244
346
  }
245
347
  replacements.set(collection.slug, withIDOwnership(collection, prefix));
348
+ guards.push({ slug: collection.slug, prefix });
246
349
  }
350
+ const onInit = config.onInit;
247
351
  return {
248
352
  ...config,
249
353
  collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),
354
+ // Database guards run after Payload has created its tables, so the CHECK and triggers apply to them.
355
+ onInit: async (payload) => {
356
+ await onInit?.(payload);
357
+ await installTypeIdDatabaseGuards(payload, guards);
358
+ },
250
359
  };
251
360
  };
252
361
  plugin.slug = "payload-typeid";
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;AAC1C,OAAO,EAIL,gBAAgB,EAChB,YAAY,GAEb,MAAM,SAAS,CAAC;AAiBjB,MAAM,aAAa,GAAG,gCAAgC,CAAC;AACvD,MAAM,WAAW,GAAG,iEAAiE,CAAC;AACtF,MAAM,cAAc,GAAG,kCAAkC,CAAC;AAC1D,MAAM,OAAO,GAAG,CAAC,EAAE,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AAElC,SAAS,cAAc,CAAC,MAAc;IACpC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CACjB,0BAA0B,MAAM,+GAA+G,CAChJ,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAiB;IACtC,MAAM,GAA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,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YAElD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACtC,IAAI,QAAQ,EAAE,CAAC;gBACb,MAAM,IAAI,SAAS,CACjB,gBAAgB,QAAQ,UAAU,UAAU,CAAC,IAAI,yCAAyC,MAAM,6EAA6E,CAC9K,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;QACzE,CAAC;QAED,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;SAC9F,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 formatLabels,\n type Plugin,\n} from \"payload\";\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-in first so shadowed central settings never reach prefix validation.\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;\n if (setting === undefined || 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 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 }\n\n return {\n ...config,\n collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),\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,EA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C,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// 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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/payload-typeid",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Type-prefixed UUIDv7 primary keys for Payload CMS.",
5
5
  "type": "module",
6
6
  "private": false,