@klnap/payload-typeid 0.1.0 → 0.2.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 +25 -0
- package/README.md +191 -132
- package/dist/index.d.ts +1 -1
- package/dist/index.js +67 -44
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0407e99: Make TypeID management explicit opt-in. `typeId()` no longer changes every collection; a collection is managed only when `custom.typeId` or `typeId({ collections })` enables it.
|
|
8
|
+
|
|
9
|
+
Breaking changes:
|
|
10
|
+
- Rename the model-level key from `custom.typeid` to `custom.typeId`. The obsolete key now throws a configuration error.
|
|
11
|
+
- Accept `true`, a prefix string, `false`, or omission. `true` derives a singular prefix from the collection slug (`articles` to `article`, `article-authors` to `article_author`). A string uses the exact prefix. `false` or omission leaves the native ID strategy unchanged.
|
|
12
|
+
- Model-level settings override central settings, including `true` and `false`.
|
|
13
|
+
- Reject `true` and prefix strings on Globals. Globals accept `false` or omission only.
|
|
14
|
+
- Reject slugs whose derived prefix is ambiguous, such as `APIKeys` or `users-2fa`, and recommend an explicit prefix.
|
|
15
|
+
|
|
16
|
+
Existing collections that relied on the previous default are no longer managed. Enabling TypeIDs on a collection with existing records changes its ID and relationship column types; migrate data before enabling it.
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 4648121: Shorten the README to the essentials: installation, quick start, configuration, utilities, limits, and compatibility.
|
|
21
|
+
|
|
22
|
+
## 0.1.1
|
|
23
|
+
|
|
24
|
+
### Patch Changes
|
|
25
|
+
|
|
26
|
+
- 338805d: Support model-level `custom.typeid` prefixes and exclusions, with precedence over central options. Expand the Payload 3.x peer range to include Payload 3.1.1 and later.
|
|
27
|
+
|
|
3
28
|
All notable changes to this package are recorded here. Changesets generates release entries.
|
package/README.md
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
# @klnap/payload-typeid
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Readable, type-prefixed document IDs for Payload CMS. An ID is a prefix plus a UUIDv7 in a compact suffix:
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
article_01m8d47saaepfr8kaw7mqdxs1h
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It is the document's one native Payload ID. The package adds no second identifier and no runtime dependencies.
|
|
10
|
+
|
|
11
|
+
## What changes
|
|
12
|
+
|
|
13
|
+
Registering the plugin changes nothing by itself. Each collection opts in with `custom.typeId`.
|
|
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 |
|
|
19
|
+
|
|
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).
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
bun add @klnap/payload-typeid
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install @klnap/payload-typeid
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
4
33
|
|
|
5
34
|
```ts
|
|
6
35
|
import { buildConfig, type CollectionConfig } from "payload";
|
|
@@ -8,64 +37,141 @@ import { typeId } from "@klnap/payload-typeid";
|
|
|
8
37
|
|
|
9
38
|
const Articles: CollectionConfig = {
|
|
10
39
|
slug: "articles",
|
|
11
|
-
custom: {
|
|
40
|
+
custom: { typeId: "article" },
|
|
12
41
|
fields: [],
|
|
13
42
|
};
|
|
14
43
|
|
|
15
|
-
const
|
|
16
|
-
slug: "
|
|
17
|
-
custom: { typeid: "author" },
|
|
18
|
-
fields: [],
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
const Categories: CollectionConfig = {
|
|
22
|
-
slug: "categories",
|
|
23
|
-
custom: { typeid: "category" },
|
|
44
|
+
const Users: CollectionConfig = {
|
|
45
|
+
slug: "users",
|
|
24
46
|
fields: [],
|
|
25
47
|
};
|
|
26
48
|
|
|
27
49
|
export default buildConfig({
|
|
28
|
-
collections: [Articles,
|
|
50
|
+
collections: [Articles, Users],
|
|
29
51
|
plugins: [typeId()],
|
|
30
52
|
});
|
|
31
53
|
```
|
|
32
54
|
|
|
33
|
-
|
|
55
|
+
Register `typeId()` after plugins that add collections, so it sees the final collection list.
|
|
34
56
|
|
|
35
|
-
|
|
36
|
-
article_01m8d47saaepfr8kaw7mqdxs1h
|
|
37
|
-
author_01m8d47sabf8ca5x5s9smzr0qz
|
|
38
|
-
category_01m8d47sabeyjvrxppjadz5h5w
|
|
39
|
-
```
|
|
57
|
+
## How it works
|
|
40
58
|
|
|
41
|
-
|
|
59
|
+
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:
|
|
42
60
|
|
|
43
|
-
|
|
61
|
+
- prepends an `id` text field whose `defaultValue` generates a TypeID with the collection's prefix;
|
|
62
|
+
- adds a `beforeChange` hook that keeps the generated ID on create, keeps the stored ID on update, and generates a fresh ID on duplicate;
|
|
63
|
+
- adds a `beforeOperation` guard that rejects `customID` and `data.id` on create and `data.id` on update, because the plugin owns the ID.
|
|
44
64
|
|
|
45
|
-
|
|
65
|
+
The plugin runs last (`order` is the maximum), so its `id` field and hooks apply after other plugins.
|
|
46
66
|
|
|
47
|
-
|
|
48
|
-
- Choose semantic prefixes on each collection or centrally in plugin options.
|
|
49
|
-
- Exclude collections while preserving their configured ID strategy.
|
|
50
|
-
- Generate new UUIDv7 IDs on document creation and duplication.
|
|
51
|
-
- Generate, validate, parse, and convert TypeIDs with the exported utilities.
|
|
52
|
-
- Add no third-party runtime dependencies.
|
|
67
|
+
## Configuration
|
|
53
68
|
|
|
54
|
-
|
|
69
|
+
### On the collection: `custom.typeId`
|
|
55
70
|
|
|
56
|
-
|
|
57
|
-
|
|
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. |
|
|
77
|
+
|
|
78
|
+
### Centrally: `typeId({ collections })`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
typeId({
|
|
82
|
+
collections: {
|
|
83
|
+
articles: "article",
|
|
84
|
+
authors: true,
|
|
85
|
+
users: false,
|
|
86
|
+
},
|
|
87
|
+
});
|
|
58
88
|
```
|
|
59
89
|
|
|
60
|
-
|
|
61
|
-
|
|
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:
|
|
95
|
+
|
|
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.
|
|
99
|
+
|
|
100
|
+
Examples:
|
|
101
|
+
|
|
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
|
+
|
|
112
|
+
### Globals
|
|
113
|
+
|
|
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
|
+
|
|
116
|
+
### Obsolete key
|
|
117
|
+
|
|
118
|
+
`custom.typeid` (lowercase `d`) throws on collections and Globals. Rename it to `custom.typeId`.
|
|
119
|
+
|
|
120
|
+
## Prefix derivation
|
|
121
|
+
|
|
122
|
+
`custom.typeId: true` derives the prefix from the slug with the same singularization Payload uses for admin labels (`formatLabels` from `payload`):
|
|
123
|
+
|
|
124
|
+
1. Replace `_` with `-` in the slug, so underscores and hyphens both separate words.
|
|
125
|
+
2. Pass the result through `formatLabels`, which singularizes the last word.
|
|
126
|
+
3. Join the words with `_` and lowercase the result.
|
|
127
|
+
|
|
128
|
+
Regular plural nouns derive cleanly:
|
|
129
|
+
|
|
130
|
+
| Slug | Derived prefix |
|
|
131
|
+
| ----------------- | ---------------- |
|
|
132
|
+
| `articles` | `article` |
|
|
133
|
+
| `article-authors` | `article_author` |
|
|
134
|
+
| `ArticleAuthors` | `article_author` |
|
|
135
|
+
| `audit-logs` | `audit_log` |
|
|
136
|
+
|
|
137
|
+
Irregular or uncountable names do not. Payload's English rules produce prefixes that are correct grammar but unexpected in IDs:
|
|
138
|
+
|
|
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"`. |
|
|
144
|
+
|
|
145
|
+
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
|
+
|
|
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:
|
|
148
|
+
|
|
149
|
+
| Slug | Result |
|
|
150
|
+
| ----------- | ----------------------------------------------- |
|
|
151
|
+
| `APIKeys` | Rejected. The label splits into single letters. |
|
|
152
|
+
| `users-2fa` | Rejected. The label contains a digit. |
|
|
153
|
+
|
|
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" } });
|
|
62
166
|
```
|
|
63
167
|
|
|
64
|
-
|
|
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.
|
|
65
169
|
|
|
66
|
-
|
|
170
|
+
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.
|
|
67
171
|
|
|
68
|
-
|
|
172
|
+
## Using IDs
|
|
173
|
+
|
|
174
|
+
Create and read documents as usual. Do not pass `id` or `customID`:
|
|
69
175
|
|
|
70
176
|
```ts
|
|
71
177
|
const article = await payload.create({
|
|
@@ -73,42 +179,41 @@ const article = await payload.create({
|
|
|
73
179
|
data: { title: "Getting started with Payload CMS" },
|
|
74
180
|
});
|
|
75
181
|
|
|
76
|
-
|
|
77
|
-
collection: "articles",
|
|
78
|
-
id: article.id,
|
|
79
|
-
});
|
|
182
|
+
await payload.findByID({ collection: "articles", id: article.id });
|
|
80
183
|
```
|
|
81
184
|
|
|
82
|
-
|
|
185
|
+
Passing `customID` or `data.id` on create throws. Passing `data.id` on update throws, because the ID does not change.
|
|
186
|
+
|
|
187
|
+
Relationships use the native ID. Set `relationTo` as usual and pass the related document's `id`.
|
|
83
188
|
|
|
84
|
-
|
|
189
|
+
### Duplicating documents
|
|
190
|
+
|
|
191
|
+
`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.
|
|
85
192
|
|
|
86
193
|
```ts
|
|
87
|
-
{
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
relationTo: "categories",
|
|
91
|
-
}
|
|
194
|
+
const copy = await payload.duplicate({ collection: "articles", id: article.id });
|
|
195
|
+
copy.id !== article.id; // true
|
|
196
|
+
copy.id.startsWith("article_"); // true
|
|
92
197
|
```
|
|
93
198
|
|
|
94
|
-
|
|
199
|
+
### Errors
|
|
95
200
|
|
|
96
|
-
|
|
97
|
-
const category = await payload.create({
|
|
98
|
-
collection: "categories",
|
|
99
|
-
data: { title: "Development" },
|
|
100
|
-
});
|
|
201
|
+
Setup and write errors come from the plugin. Each message names the fix:
|
|
101
202
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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`. |
|
|
110
215
|
|
|
111
|
-
|
|
216
|
+
## Utilities
|
|
112
217
|
|
|
113
218
|
```ts
|
|
114
219
|
import {
|
|
@@ -121,91 +226,45 @@ import {
|
|
|
121
226
|
} from "@klnap/payload-typeid";
|
|
122
227
|
|
|
123
228
|
const id: TypeID<"article"> = generateTypeId("article");
|
|
124
|
-
isTypeId(id); // true
|
|
125
229
|
isTypeId(id, "article"); // true
|
|
126
230
|
isTypeId(id, "category"); // false
|
|
127
231
|
|
|
128
232
|
const uuid = "0188bac7-4afa-78aa-bc3b-bd1eef28d881";
|
|
129
|
-
|
|
130
|
-
parseTypeId(converted).uuid === uuid; // true
|
|
131
|
-
toUUID(converted) === uuid; // true
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
| Export | Description |
|
|
135
|
-
| ---------------------------------- | --------------------------------------------------- |
|
|
136
|
-
| `typeId(options?)` | Creates the Payload plugin. |
|
|
137
|
-
| `generateTypeId(prefix)` | Generates a UUIDv7 TypeID. |
|
|
138
|
-
| `isTypeId(value, expectedPrefix?)` | Validates a TypeID and optionally its prefix. |
|
|
139
|
-
| `parseTypeId(value)` | Returns the prefix and canonical UUID. |
|
|
140
|
-
| `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID. |
|
|
141
|
-
| `toUUID(value)` | Converts a TypeID to its canonical UUID. |
|
|
142
|
-
| `TypeID<Prefix>` | Compile-time string type constrained by its prefix. |
|
|
143
|
-
| `TypeIdOptions` | Options accepted by `typeId()`. |
|
|
144
|
-
|
|
145
|
-
Codec utilities accept empty prefixes and UUIDs of any version. Invalid inputs make `parseTypeId`, `fromUUID`, and `toUUID` throw `TypeError`; `isTypeId` returns `false`. `TypeID<Prefix>` is a compile-time aid, not runtime validation. Payload-generated document types expose `id: string`.
|
|
146
|
-
|
|
147
|
-
## Configuration
|
|
148
|
-
|
|
149
|
-
Set a semantic prefix or exclude a collection in its own Payload config:
|
|
150
|
-
|
|
151
|
-
```ts
|
|
152
|
-
import type { CollectionConfig } from "payload";
|
|
153
|
-
|
|
154
|
-
export const Articles: CollectionConfig = {
|
|
155
|
-
slug: "articles",
|
|
156
|
-
custom: { typeid: "article" },
|
|
157
|
-
fields: [],
|
|
158
|
-
};
|
|
159
|
-
|
|
160
|
-
export const Users: CollectionConfig = {
|
|
161
|
-
slug: "users",
|
|
162
|
-
custom: { typeid: false },
|
|
163
|
-
fields: [],
|
|
164
|
-
};
|
|
233
|
+
toUUID(fromUUID("article", uuid)) === uuid; // true
|
|
165
234
|
```
|
|
166
235
|
|
|
167
|
-
|
|
236
|
+
| Export | Description |
|
|
237
|
+
| ---------------------------------- | --------------------------------------------- |
|
|
238
|
+
| `typeId(options?)` | Creates the Payload plugin. |
|
|
239
|
+
| `generateTypeId(prefix)` | Generates a TypeID with a new UUIDv7. |
|
|
240
|
+
| `isTypeId(value, expectedPrefix?)` | Validates a TypeID and optionally its prefix. |
|
|
241
|
+
| `parseTypeId(value)` | Returns the prefix and canonical UUID. |
|
|
242
|
+
| `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID. |
|
|
243
|
+
| `toUUID(value)` | Converts a TypeID to its canonical UUID. |
|
|
244
|
+
| `TypeID<Prefix>` | Compile-time type. Not runtime validation. |
|
|
245
|
+
| `TypeIdOptions` | Options accepted by `typeId()`. |
|
|
168
246
|
|
|
169
|
-
|
|
247
|
+
`parseTypeId`, `fromUUID`, and `toUUID` throw `TypeError` on invalid input. `isTypeId` returns `false`.
|
|
170
248
|
|
|
171
|
-
|
|
172
|
-
typeId({
|
|
173
|
-
collections: {
|
|
174
|
-
articles: "article",
|
|
175
|
-
authors: "author",
|
|
176
|
-
users: false,
|
|
177
|
-
},
|
|
178
|
-
});
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
Precedence is **model configuration > central configuration > defaults**. Model settings override central prefixes and exclusions. Unspecified collections use the central setting when present; otherwise, the plugin derives a prefix from the unchanged collection slug.
|
|
182
|
-
|
|
183
|
-
Automatic prefixes lowercase the slug, replace hyphens with underscores, and separate camel-case and acronym boundaries. They do not singularize: `articles` becomes `articles`, and `article-categories` becomes `article_categories`. Singular prefixes such as `article` are explicit conventions, not a TypeID requirement.
|
|
249
|
+
## Enabling on existing data
|
|
184
250
|
|
|
185
|
-
|
|
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.
|
|
186
252
|
|
|
187
|
-
|
|
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.
|
|
188
257
|
|
|
189
|
-
|
|
258
|
+
Direct database writes bypass Payload hooks, so they also bypass the ID rules.
|
|
190
259
|
|
|
191
260
|
## Compatibility
|
|
192
261
|
|
|
193
|
-
| Area
|
|
194
|
-
|
|
|
195
|
-
| Payload CMS
|
|
196
|
-
| Database
|
|
197
|
-
| Node.js
|
|
198
|
-
| Module format
|
|
199
|
-
|
|
200
|
-
Use the latest stable Payload 3.x for security fixes. The peer range describes compatibility, not a recommendation to run older releases.
|
|
201
|
-
|
|
202
|
-
## Documentation
|
|
203
|
-
|
|
204
|
-
- [Payload plugins](https://payloadcms.com/docs/plugins/overview)
|
|
205
|
-
- [Payload custom ID fields](https://payloadcms.com/docs/fields/default-fields#custom-id-fields)
|
|
206
|
-
- [Payload Globals](https://payloadcms.com/docs/configuration/globals)
|
|
207
|
-
- [TypeID specification](https://github.com/jetify-com/typeid/blob/main/spec/README.md)
|
|
208
|
-
- [UUIDv7 in RFC 9562](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.7)
|
|
262
|
+
| Area | Support |
|
|
263
|
+
| ------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
264
|
+
| 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. |
|
|
265
|
+
| Database | PostgreSQL 16, with the default serial strategy and `idType: "uuid"`. Other adapters are unverified. |
|
|
266
|
+
| 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`. |
|
|
267
|
+
| Module format | ESM only. |
|
|
209
268
|
|
|
210
269
|
## License
|
|
211
270
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type Plugin } from "payload";
|
|
2
2
|
export type TypeID<Prefix extends string = string> = string extends Prefix ? string : Prefix extends "" ? string : `${Prefix}_${string}`;
|
|
3
3
|
export interface TypeIdOptions {
|
|
4
|
-
collections?: Record<string,
|
|
4
|
+
collections?: Record<string, boolean | string>;
|
|
5
5
|
}
|
|
6
6
|
interface ParsedTypeID<Prefix extends string = string> {
|
|
7
7
|
prefix: Prefix;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Buffer } from "node:buffer";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
-
import { flattenAllFields, } from "payload";
|
|
3
|
+
import { flattenAllFields, formatLabels, } from "payload";
|
|
4
4
|
const prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;
|
|
5
5
|
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
6
|
const typeIdAlphabet = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
@@ -91,12 +91,18 @@ export function generateTypeId(prefix) {
|
|
|
91
91
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
92
92
|
return fromUUID(prefix, uuidFromBytes(bytes));
|
|
93
93
|
}
|
|
94
|
-
function
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
94
|
+
function deriveCollectionPrefix(slug) {
|
|
95
|
+
// Hyphens and underscores are word separators; Payload's formatLabels splits only on hyphens and whitespace.
|
|
96
|
+
const singular = formatLabels(slug.replaceAll("_", "-")).singular;
|
|
97
|
+
const words = singular.split(" ");
|
|
98
|
+
// Acronyms such as "APIKeys" split into single letters, so they cannot be derived reliably.
|
|
99
|
+
const derivable = singular !== "" &&
|
|
100
|
+
words.every((word) => /^[A-Za-z]+$/.test(word)) &&
|
|
101
|
+
!(words.length > 1 && words.some((word) => word.length === 1));
|
|
102
|
+
if (!derivable) {
|
|
103
|
+
throw new TypeError(`Collection "${slug}" cannot derive a TypeID prefix from its slug. Set custom.typeId or collections["${slug}"] to an explicit prefix string.`);
|
|
104
|
+
}
|
|
105
|
+
return words.join("_").toLowerCase();
|
|
100
106
|
}
|
|
101
107
|
function hasCustomID(fields) {
|
|
102
108
|
return flattenAllFields({ fields }).some((field) => "name" in field && field.name === "id");
|
|
@@ -153,6 +159,28 @@ function withIDOwnership(collection, prefix) {
|
|
|
153
159
|
},
|
|
154
160
|
};
|
|
155
161
|
}
|
|
162
|
+
function readSetting(value, owner) {
|
|
163
|
+
if (value === undefined || typeof value === "boolean" || typeof value === "string") {
|
|
164
|
+
return value;
|
|
165
|
+
}
|
|
166
|
+
throw new TypeError(`Invalid TypeID configuration for ${owner}: custom.typeId must be true, false, a prefix string, or undefined.`);
|
|
167
|
+
}
|
|
168
|
+
function assertCurrentKey(custom, owner) {
|
|
169
|
+
if (custom && Object.hasOwn(custom, "typeid")) {
|
|
170
|
+
throw new TypeError(`${owner} uses the obsolete custom.typeid key; rename it to custom.typeId.`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function validateCollectionPrefix(slug, prefix) {
|
|
174
|
+
if (prefix === "") {
|
|
175
|
+
throw new TypeError(`Collection "${slug}" resolved to an empty TypeID prefix; provide a non-empty prefix string.`);
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
validatePrefix(prefix);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
throw new TypeError(`Invalid TypeID prefix for collection "${slug}": ${error instanceof Error ? error.message : String(error)} Provide a valid prefix string.`, { cause: error });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
156
184
|
export function typeId(options = {}) {
|
|
157
185
|
const plugin = (config) => {
|
|
158
186
|
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
@@ -167,63 +195,58 @@ export function typeId(options = {}) {
|
|
|
167
195
|
const overrides = options.collections;
|
|
168
196
|
if (overrides !== undefined &&
|
|
169
197
|
(typeof overrides !== "object" || overrides === null || Array.isArray(overrides))) {
|
|
170
|
-
throw new TypeError("TypeID collections must be a record of collection slugs to
|
|
198
|
+
throw new TypeError("TypeID collections must be a record of collection slugs to true, false, or prefix strings.");
|
|
171
199
|
}
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const prefixes = new Map();
|
|
176
|
-
for (const global of config.globals ?? []) {
|
|
177
|
-
const typeIdOption = global.custom?.typeid;
|
|
178
|
-
if (typeIdOption !== undefined && typeIdOption !== false) {
|
|
179
|
-
throw new TypeError(`Global "${global.slug}" cannot use a TypeID prefix because Payload Globals do not expose configurable document IDs.`);
|
|
200
|
+
for (const [slug, setting] of Object.entries(overrides ?? {})) {
|
|
201
|
+
if (typeof setting !== "boolean" && typeof setting !== "string") {
|
|
202
|
+
throw new TypeError(`TypeID collections["${slug}"] must be true, false, or a prefix string.`);
|
|
180
203
|
}
|
|
181
204
|
}
|
|
182
|
-
|
|
205
|
+
const collections = config.collections ?? [];
|
|
206
|
+
const collectionSlugs = new Set(collections.map(({ slug }) => slug));
|
|
207
|
+
for (const slug of Object.keys(overrides ?? {})) {
|
|
183
208
|
if (!collectionSlugs.has(slug)) {
|
|
184
|
-
throw new TypeError(`TypeID
|
|
209
|
+
throw new TypeError(`TypeID collections references unknown collection "${slug}".`);
|
|
185
210
|
}
|
|
186
|
-
|
|
187
|
-
|
|
211
|
+
}
|
|
212
|
+
for (const global of config.globals ?? []) {
|
|
213
|
+
assertCurrentKey(global.custom, `Global "${global.slug}"`);
|
|
214
|
+
const setting = readSetting(global.custom?.typeId, `Global "${global.slug}"`);
|
|
215
|
+
if (setting !== undefined && setting !== false) {
|
|
216
|
+
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.`);
|
|
188
217
|
}
|
|
189
218
|
}
|
|
219
|
+
// Resolve opt-in first so shadowed central settings never reach prefix validation.
|
|
220
|
+
const managed = [];
|
|
190
221
|
for (const collection of collections) {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
195
|
-
const centralTypeId = overrides && Object.hasOwn(overrides, collection.slug)
|
|
222
|
+
assertCurrentKey(collection.custom, `Collection "${collection.slug}"`);
|
|
223
|
+
const modelSetting = readSetting(collection.custom?.typeId, `collection "${collection.slug}"`);
|
|
224
|
+
const centralSetting = overrides && Object.hasOwn(overrides, collection.slug)
|
|
196
225
|
? overrides[collection.slug]
|
|
197
226
|
: undefined;
|
|
198
|
-
const
|
|
199
|
-
if (
|
|
227
|
+
const setting = modelSetting ?? centralSetting;
|
|
228
|
+
if (setting === undefined || setting === false)
|
|
200
229
|
continue;
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
if (!prefix) {
|
|
209
|
-
throw new TypeError(`Collection "${collection.slug}" resolved to an empty TypeID prefix; provide an override.`);
|
|
210
|
-
}
|
|
230
|
+
managed.push({ collection, setting });
|
|
231
|
+
}
|
|
232
|
+
const prefixes = new Map();
|
|
233
|
+
const replacements = new Map();
|
|
234
|
+
for (const { collection, setting } of managed) {
|
|
235
|
+
const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;
|
|
236
|
+
validateCollectionPrefix(collection.slug, prefix);
|
|
211
237
|
const existing = prefixes.get(prefix);
|
|
212
238
|
if (existing) {
|
|
213
|
-
throw new TypeError(`Collections "${existing}" and "${collection.slug}" resolve to duplicate TypeID prefix "${prefix}".
|
|
239
|
+
throw new TypeError(`Collections "${existing}" and "${collection.slug}" resolve to duplicate TypeID prefix "${prefix}". Set an explicit prefix on one of them with custom.typeId or collections.`);
|
|
214
240
|
}
|
|
215
241
|
prefixes.set(prefix, collection.slug);
|
|
216
|
-
resolved.set(collection.slug, prefix);
|
|
217
242
|
if (hasCustomID(collection.fields)) {
|
|
218
|
-
throw new TypeError(`Collection "${collection.slug}" already has a collection-level field named "id". Set
|
|
243
|
+
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.`);
|
|
219
244
|
}
|
|
245
|
+
replacements.set(collection.slug, withIDOwnership(collection, prefix));
|
|
220
246
|
}
|
|
221
247
|
return {
|
|
222
248
|
...config,
|
|
223
|
-
collections: collections.map((collection) =>
|
|
224
|
-
const prefix = resolved.get(collection.slug);
|
|
225
|
-
return prefix ? withIDOwnership(collection, prefix) : collection;
|
|
226
|
-
}),
|
|
249
|
+
collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),
|
|
227
250
|
};
|
|
228
251
|
};
|
|
229
252
|
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,GAEjB,MAA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"node:buffer\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n type CollectionConfig,\n type Config,\n type Field,\n flattenAllFields,\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, string | false>;\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 normalizePrefix(slug: string): string {\n return slug\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replaceAll(\"-\", \"_\")\n .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\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 prefixes or false.\",\n );\n }\n\n const collections = config.collections ?? [];\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n const resolved = new Map<string, string>();\n const prefixes = new Map<string, string>();\n for (const global of config.globals ?? []) {\n const typeIdOption = global.custom?.typeid;\n if (typeIdOption !== undefined && typeIdOption !== false) {\n throw new TypeError(\n `Global \"${global.slug}\" cannot use a TypeID prefix because Payload Globals do not expose configurable document IDs.`,\n );\n }\n }\n for (const [slug, prefix] of Object.entries(overrides ?? {})) {\n if (!collectionSlugs.has(slug)) {\n throw new TypeError(`TypeID override references unknown collection \"${slug}\".`);\n }\n if (prefix !== false && typeof prefix !== \"string\") {\n throw new TypeError(`TypeID override for \"${slug}\" must be a prefix string or false.`);\n }\n }\n\n for (const collection of collections) {\n const modelTypeId = collection.custom?.typeid;\n if (modelTypeId !== undefined && modelTypeId !== false && typeof modelTypeId !== \"string\") {\n throw new TypeError(\n `Invalid TypeID configuration for collection \"${collection.slug}\": custom.typeid must be a prefix string, false, or undefined.`,\n );\n }\n const centralTypeId =\n overrides && Object.hasOwn(overrides, collection.slug)\n ? overrides[collection.slug]\n : undefined;\n const effectiveTypeId = modelTypeId !== undefined ? modelTypeId : centralTypeId;\n if (effectiveTypeId === false) continue;\n const prefix =\n typeof effectiveTypeId === \"string\" ? effectiveTypeId : normalizePrefix(collection.slug);\n try {\n validatePrefix(prefix);\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID prefix for collection \"${collection.slug}\": ${error instanceof Error ? error.message : String(error)} Provide a valid collections[\"${collection.slug}\"] override or disable this collection.`,\n { cause: error },\n );\n }\n if (!prefix) {\n throw new TypeError(\n `Collection \"${collection.slug}\" resolved to an empty TypeID prefix; provide an override.`,\n );\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}\". Provide distinct overrides or disable one collection.`,\n );\n }\n prefixes.set(prefix, collection.slug);\n resolved.set(collection.slug, prefix);\n if (hasCustomID(collection.fields)) {\n throw new TypeError(\n `Collection \"${collection.slug}\" already has a collection-level field named \"id\". Set collections[\"${collection.slug}\"] = false or rename that field before enabling TypeID.`,\n );\n }\n }\n\n return {\n ...config,\n collections: collections.map((collection) => {\n const prefix = resolved.get(collection.slug);\n return prefix ? withIDOwnership(collection, prefix) : collection;\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,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,a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O,CAAC;YACpF,wBAAwB,CAAC,UAAU,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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@klnap/payload-typeid",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Type-prefixed UUIDv7 primary keys for Payload CMS.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"prepublishOnly": "node -e \"if (require('./package.json').private) throw new Error('This package is private and cannot be published')\"",
|
|
57
57
|
"changeset": "changeset",
|
|
58
58
|
"changeset:version": "changeset version",
|
|
59
|
-
"changeset:version-check": "bun run changeset:version && bun run check"
|
|
59
|
+
"changeset:version-check": "bun run changeset:version && bunx biome format --write CHANGELOG.md && bun run check"
|
|
60
60
|
},
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"payload": "^3.1.1"
|