@0001-labs/idv1 0.3.5 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,297 +1,53 @@
1
1
  # IDv1
2
2
 
3
- An ID system for short, memorable IDs that are easy to keep unique.
3
+ Six-character IDs for agents: five shapes, taxonomy and namespaces, and a command that reads a codebase's `.id` file.
4
4
 
5
5
  ```sh
6
6
  npm install @0001-labs/idv1
7
7
  ```
8
8
 
9
9
  ```ts
10
- import { codeCandidate, codeKind } from '@0001-labs/idv1'
10
+ import { codeCandidate, parseCode } from '@0001-labs/idv1'
11
11
 
12
12
  const candidate = codeCandidate('item')
13
- codeKind(candidate) // 'item'
13
+ const parsed = parseCode(candidate)
14
14
  ```
15
15
 
16
- Use a unique constraint or a transaction to claim the candidate in your app.
16
+ `parseCode(unknown)` returns a discriminated `{ kind, id }` with a shape-branded TypeScript `Id`, or `null`. `codeKind` and the `isCodeOf`/shape predicates use that parser. Validation establishes syntax, not an assigned record. `AccountId`, `ListId`, `ProjectId`, `ItemId` and `EventId` are distinct types.
17
17
 
18
- ## Templates
18
+ `codeCandidate(kind)` draws with Web Crypto and returns the corresponding branded ID. All generators use mixed-case ASCII letters. Account and Project accept an optional exact two-letter prefix, preserving case: `codeCandidate('project', { letters: 'AR' })`. Candidates obey word filters; Project also excludes blocked digit pairs. A bounded draw fails after 1,000 attempts. An injected `random` must return finite numbers in `[0, 1)`. These are candidate generators, not allocators: claim a candidate in its namespace and store it next to the record's UUID. A code is a short handle for agents, not a permanent identity; when a pool runs out it resets and its codes are issued again.
19
19
 
20
- Every code is six letters and digits, and its shape alone says what it names:
20
+ `ID_SPACE` counts the five structural pools before generation filters; `TOTAL_ID_SPACE` is their sum. Event is part of the main API, without a separate expanded classifier. Scan encoding retains its checksum and payload format, accepts exactly the same six-character IDs, and all scanner paths support all five shapes. Scan results are branded IDs; use `parseCode` to read their kind.
21
21
 
22
- | Shape | Pattern | Example | For |
23
- |---|---|---|---|
24
- | Account | `LLNNNN` | `Jo4712` | a person |
25
- | Product | `LLLLNN` | `ABCD12` | a thing with a code printed on it |
26
- | List | `NNLLLL` | `12ABCD` | something that holds things |
27
- | Item | `LLNNxx` | `Ab12Cd` | one thing kept |
28
- | Project | `NLLLLL` | `1Syste` | a project, a digit and five letters |
22
+ ## The idv1 command
29
23
 
30
- `L` is a letter, `N` a digit and `x` either, and an item's last two are never both digits, or it would be an account. Every other six letters and digits are left for event codes (`advanced`). `codeCandidate(kind)` draws a code at random in a shape. An app can go further and lay a template over a shape, fixing some characters so a code also says which kind of thing in that app it is and which thing it names.
24
+ A codebase that uses IDv1 keeps one `.id` file at its root: its namespaces and taxonomies, each with its shorthand and real name, then its parts and the facts between them ([format](https://idv1.0001.dev/docs/annotate)). The `idv1` command reads it from any folder below:
31
25
 
32
- ### Building a template
33
-
34
- - **A fixed prefix per kind.** Fixed characters mark the kind: a project's digit (`1LLLLL`), a list's two digits (`02LLLL`, `03LLLL`), or a small letter that no name starts with, as `aLNNNN` for an agent.
35
- - **Letters that read as the name.** The letters come from the thing's name, then vary letter by letter until the code is free: a project called Design system 1 is `1Desig`.
36
- - **An owner's two letters lead an item.** An item starts with its owner's two letters, and the first digit can mark the kind inside that owner: `Ds10Bu` is a component of Design system 1.
37
- - **People and agents take an account's shape.** A person's two name letters and four digits, `Le0125`; an agent's `a`, its initial and four digits, `aG4008`.
38
-
39
- A fixed character spends space. A list prefix leaves 26⁴ = 456,976 codes in capitals; an item template with fixed owner letters and a fixed kind digit leaves 10 × 26 × 26 = 6,760 per owner and kind if its last pair is a capital and a small letter. Fix only what a reader needs.
40
-
41
- ### Different apps, different templates
42
-
43
- **Ezo draws.** People make millions of lists and items whose titles change, so nothing in those codes is meant to be read:
44
-
45
- | Kind | Template | How |
46
- |---|---|---|
47
- | Account | `LLNNNN` | the person's name letters, then four drawn digits |
48
- | Product | `LLLLNN` | drawn, again if the letters or digits are blocked |
49
- | List | `NNLLLL` | drawn, in capitals |
50
- | Item | `LLNNxx` | drawn |
51
-
52
- **System derives.** An inventory of a few hundred named parts wants codes a reader can place on sight, so each kind has a template and the letters come from the name:
53
-
54
- | Kind | Shape | Template | Example |
55
- |---|---|---|---|
56
- | Projects | project | `1LLLLL` | `1Desig` |
57
- | Stack | list | `02LLLL` | `02Conv` |
58
- | Platforms | list | `03LLLL` | `03Webx` |
59
- | Connections | list | `04LLLL` | `04Gmai` |
60
- | Components | item | owner's `LL`, `1N`, `LL` | `Ds10Bu` |
61
- | Tool calls | product | `tc`, the HTTP verb (`G`, `P`, `U`, `D`), `LNN` | `tcGi02` |
62
- | Engineers | account | `LLNNNN` | `Le0125` |
63
- | Agents | account | `aLNNNN` | `aG4008` |
64
- | Harnesses | product | `hLLLNN` | `hCla01` |
65
-
66
- An app with many short-lived things should draw; one naming a small catalogue can derive. Either way a code, once given, stays when the name changes.
67
-
68
- ### Junctions
69
-
70
- Codes joined by a hyphen name the place where things meet, and each part still says what it is: `1Ezoxx-tcGi02` is a tool of a project, `1Systs-Sy10Us-Sy10Fl` a path down a tree, `01Sysm-MJ99ST` an item in a list. `junction(...codes)` joins them and refuses anything that is not a code; `junctionParts(value)` reads one back with each part's kind.
71
-
72
- ### Rules every template keeps
73
-
74
- - **Six characters**, letters `A–Z a–z` and digits only.
75
- - **Its shape.** Every code a template makes passes `isCodeOf(shape, code)`, and `codeKind(code)` reads it back as that shape.
76
- - **No blocked words or digits.** Check all of a code's letters together with `blockedCodeLetters`, and a product's last two digits against `BLOCKED_CODE_DIGITS`, before taking a candidate.
77
- - **Never two shapes for one code.** A template sits inside one shape, two templates in one app never make the same code, and a code names one thing: claim it with a unique constraint.
78
-
79
- ## Numeric references in a message
80
-
81
- Two agents can describe a graph using one line per fact: subject, relation, object. In this proposed text format, all three positions use the same IDv1 dictionary. Each line has three tokens separated by single ASCII spaces. LF separates lines. A final LF is optional.
82
-
83
- Read left to right from an empty dictionary. On first use, send the literal six-character ID and give it the next number, starting at 1. On every later use, send its number in decimal with no leading zero. A six-character token is always a literal, even if all its characters are digits. A reference has one to five digits and must already have an entry. Start a new message before introducing a 100,000th distinct ID. Each message can then be decoded independently. Agents agree on what each relation means before exchanging messages.
84
-
85
- ### System architecture
86
-
87
- System’s Tags and tools directory supplies the entity IDs. The project and its MCP app both carry the short code `SYSM`. Their IDv1s distinguish them: the project is `1Systs` and the MCP app is `1Syste`. The directory gives Review the junction `1Systs-Sy11Re-Sy12Re` (System → Reach → Review) and the tool tagged `get_inventory` the junction `1Syste-tcGi04`. The seven relation IDs below are vocabulary proposed for this example.
88
-
89
- The first four facts show how a number can move from the object position to the subject position:
90
-
91
- ```text
92
- 1Systs rHasPt Sy11Re
93
- 1 2 Sy10Pr
94
- 3 2 Sy10Ad
95
- 3 2 Sy12Re
26
+ ```sh
27
+ npx idv1 architecture # namespaces, taxonomies, the parts as a tree, the facts
28
+ npx idv1 status # counts by shape and taxonomy, and whether it is healthy
29
+ npx idv1 health # every broken rule; exits 1 so it can run in a build
30
+ npx idv1 resolve co14Ch # one id, a -SH- qualified id or a junction, with its facts
96
31
  ```
97
32
 
98
- The first line assigns 1 to System, 2 to “has part” and 3 to Reach. The second adds Projects under System. The third and fourth use 3 as their subject: Reach contains Ads and Review.
33
+ It runs on Node 22.18 or later. The same functions are exported for apps: `readArchitecture`, `architectureHealth`, `resolveCode`, `taxonomyOf`, `describeArchitecture`, `describeStatus` and `runArchitectureCommand`.
99
34
 
100
- The snapshot covers the System inventory’s ownership tree, relationships into or out of System, outgoing relationships of its catalogued parts, requirements marked inapplicable, and tools in its MCP catalogue. It describes architectural relationships at the time of capture. Runtime state, permissions and tool arguments belong to other messages.
35
+ ## Upgrading from 0.3.x to Release 1
101
36
 
102
- | Example relation | Meaning |
37
+ Release 1 uses five shapes. Here `L` is an ASCII letter and `N` is a digit.
38
+
39
+ | Kind | Shape |
103
40
  | --- | --- |
104
- | `rHasPt` | Contains the object as a direct part |
105
- | `rNeeds` | Depends on the object |
106
- | `rShare` | Uses a shared implementation |
107
- | `rLocal` | Implements the object locally |
108
- | `rOppor` | Records a potential integration |
109
- | `rNoApp` | Marks a requirement as inapplicable |
110
- | `rTools` | Exposes the object as an MCP tool |
41
+ | Account | `LLNNNN` |
42
+ | List | `NNLLLL` |
43
+ | Project | `LLLLNN`, formerly also accepted as Account |
44
+ | Item | `LLNN` followed by two ASCII letters or digits, with at least one letter |
45
+ | Event | Any remaining string of exactly six ASCII letters or digits |
111
46
 
112
- <details>
113
- <summary>Full System message — 177 facts, 2,109 ASCII bytes without a trailing LF</summary>
47
+ Use the root export and `parseCode` in place of the `advanced` subpath and its classifier. The Product kind and studio-specific account reservations were removed. Keep reservations in the application, choose the intended shape for each former Product use, and review stored codes before changing how your app classifies them.
114
48
 
115
- ```text
116
- 1Systs rHasPt Sy11Re
117
- 1 2 Sy10Pr
118
- 3 2 Sy10Ad
119
- 3 2 Sy12Re
120
- 1 2 Sy10In
121
- 1 2 Sy10Sy
122
- Sy10Us 2 Sy10Fl
123
- 1 2 Sy10Ma
124
- 1 2 Sy11Ma
125
- 1 2 Sy11Si
126
- 4 2 Sy12Co
127
- 1 2 Sy10Ci
128
- 1 2 Sy10Is
129
- Sy12Se 2 Sy10Ap
130
- 17 2 Sy10Di
131
- 17 2 Sy10Ya
132
- 17 2 Sy11Co
133
- 1 2 9
134
- 17 2 Sy10Va
135
- 1 2 17
136
- 4 2 Sy11Au
137
- 1 2 Sy10Te
138
- 1 rNeeds 1Dragx
139
- 1 25 1Aaxxx
140
- 1 rShare Sy10De
141
- 1 28 10
142
- 1 rLocal 03Webx
143
- 1 30 03Iosx
144
- 1 25 Sy10Ne
145
- 1 25 1DSone
146
- 1 30 Sy10Au
147
- 1 28 8
148
- 1 28 Sy10Ta
149
- 1 25 02Vite
150
- 1 25 02Clou
151
- 1 30 03Clix
152
- 1 25 1Idvxx
153
- 1 25 02Litx
154
- 1 30 Sy10Se
155
- 10 28 40
156
- 1 30 03Mcpx
157
- 1Consc rOppor 1
158
- 1 30 03Apix
159
- 1 30 11
160
- 1 30 12
161
- 1 30 13
162
- 1 30 3
163
- 1 30 14
164
- 1 30 15
165
- 1 30 16
166
- 1 30 18
167
- 1 30 19
168
- 1 30 4
169
- 1 30 20
170
- 1 30 21
171
- 1 30 9
172
- 9 30 10
173
- 1 30 22
174
- 1 30 04Gmai
175
- 1 30 Sy11Se
176
- 1 30 Sy10Do
177
- 1 25 7
178
- 1 25 1Ezoxe
179
- 1 28 1Linkl
180
- 1 28 44
181
- 1 28 Sy10Co
182
- 7 28 10
183
- 7 30 43
184
- 1 30 5
185
- 1 30 Sy10Ag
186
- 1 30 23
187
- 1 30 03Nati
188
- 7 28 26
189
- 1 30 24
190
- 7 25 34
191
- 1 30 Sy11Ca
192
- 1 25 02Bomb
193
- 7 25 44
194
- 1 rNoApp Sy10Su
195
- 1 57 Sy10Sh
196
- 1 57 Sy10Af
197
- 1 57 Sy10Re
198
- 1 57 Sy10On
199
- 1 57 Sy10As
200
- 1 57 Sy11Su
201
- 1 57 Sy10Ca
202
- 1 57 1Priva
203
- 1 57 Sy10Si
204
- 1 57 Sy10If
205
- 1 2 1Syste
206
- 69 rTools tcUr01
207
- 69 70 tcDr01
208
- 69 70 tcUe02
209
- 69 70 tcUl02
210
- 69 70 tcUo01
211
- 69 70 tcUp08
212
- 69 70 tcUr02
213
- 69 70 tcPi02
214
- 69 70 tcPr03
215
- 69 70 tcUr03
216
- 69 70 tcDs04
217
- 69 70 tcGa06
218
- 69 70 tcGa07
219
- 69 70 tcGa08
220
- 69 70 tcGa09
221
- 69 70 tcGa10
222
- 69 70 tcGc07
223
- 69 70 tcGc08
224
- 69 70 tcGc09
225
- 69 70 tcGc10
226
- 69 70 tcGc11
227
- 69 70 tcGc12
228
- 69 70 tcGd01
229
- 69 70 tcGg01
230
- 69 70 tcGi04
231
- 69 70 tcGi05
232
- 69 70 tcGm03
233
- 69 70 tcGp14
234
- 69 70 tcGr01
235
- 69 70 tcGr02
236
- 69 70 tcGr03
237
- 69 70 tcGr04
238
- 69 70 tcGr05
239
- 69 70 tcGr06
240
- 69 70 tcGr07
241
- 69 70 tcGr08
242
- 69 70 tcGr09
243
- 69 70 tcGr10
244
- 69 70 tcGs10
245
- 69 70 tcGs11
246
- 69 70 tcGs12
247
- 69 70 tcGt03
248
- 69 70 tcGu01
249
- 69 70 tcGu02
250
- 69 70 tcGv01
251
- 69 70 tcGa11
252
- 69 70 tcGc13
253
- 69 70 tcGc14
254
- 69 70 tcGi06
255
- 69 70 tcGp15
256
- 69 70 tcGp16
257
- 69 70 tcGr11
258
- 69 70 tcGr12
259
- 69 70 tcGr13
260
- 69 70 tcGr14
261
- 69 70 tcGs13
262
- 69 70 tcGs14
263
- 69 70 tcUr04
264
- 69 70 tcUr05
265
- 69 70 tcGr15
266
- 69 70 tcPr04
267
- 69 70 tcPc04
268
- 69 70 tcPc05
269
- 69 70 tcPc06
270
- 69 70 tcPr05
271
- 69 70 tcGp17
272
- 69 70 tcGr16
273
- 69 70 tcDr02
274
- 69 70 tcPp05
275
- 69 70 tcPa05
276
- 69 70 tcPa06
277
- 69 70 tcPr06
278
- 69 70 tcPr07
279
- 69 70 tcPr08
280
- 69 70 tcPr09
281
- 69 70 tcPr10
282
- 69 70 tcPr11
283
- 69 70 tcPr12
284
- 69 70 tcPr13
285
- 69 70 tcPr14
286
- 69 70 tcPr15
287
- 69 70 tcPr16
288
- 69 70 tcGa12
289
- 69 70 tcGp18
290
- 69 70 tcGs15
291
- 69 70 tcUr06
292
- 69 70 tcUi03
293
- ```
49
+ ## Documentation
294
50
 
295
- </details>
51
+ The [IDv1 specification](https://idv1.0001.dev/docs/spec) is the authoritative reference for identifier shapes, namespaces, taxonomy, allocation and message examples. See the [documentation index](https://idv1.0001.dev/docs) for the remaining guides.
296
52
 
297
53
  [MIT license](LICENSE)
package/bin/idv1.mjs ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { register } from 'node:module'
5
+
6
+ register('data:text/javascript,' + encodeURIComponent(`export async function resolve(specifier, context, next) {
7
+ if (/^\\.\\.?\\//.test(specifier) && !/\\.[cm]?[jt]s$/.test(specifier) && context.parentURL?.includes('/src/')) return next(specifier + '.ts', context)
8
+ return next(specifier, context)
9
+ }`))
10
+ const { runArchitectureCommand } = await import('../src/architecture.ts')
11
+
12
+ const [command, ...args] = process.argv.slice(2)
13
+ let dir = resolve(process.cwd())
14
+ while (!existsSync(join(dir, '.id')) && dirname(dir) !== dir) dir = dirname(dir)
15
+ const file = join(dir, '.id')
16
+ if (!existsSync(file)) {
17
+ console.error('No .id file here or above. See https://idv1.0001.dev/docs/annotate')
18
+ process.exit(2)
19
+ }
20
+ const { code, out } = runArchitectureCommand(command, args, readFileSync(file, 'utf8'), path => existsSync(join(dir, path)))
21
+ console.log(out)
22
+ process.exit(code)
package/package.json CHANGED
@@ -1,21 +1,27 @@
1
1
  {
2
2
  "name": "@0001-labs/idv1",
3
- "version": "0.3.5",
4
- "description": "An ID system for short, memorable IDs that are easy to keep unique.",
3
+ "version": "1.0.1",
4
+ "description": "Six-character IDs for agents: five shapes, taxonomy and namespaces, and a CLI that reads a codebase's .id file.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/0001-labs/idv1.git"
9
9
  },
10
+ "bin": {
11
+ "idv1": "./bin/idv1.mjs"
12
+ },
10
13
  "files": [
14
+ "bin/",
11
15
  "src/",
12
16
  "README.md",
13
17
  "LICENSE"
14
18
  ],
15
19
  "type": "module",
16
20
  "exports": {
17
- ".": "./src/index.ts",
18
- "./advanced": "./src/advanced.ts"
21
+ ".": "./src/index.ts"
22
+ },
23
+ "engines": {
24
+ "node": ">=22.18"
19
25
  },
20
26
  "devDependencies": {
21
27
  "@types/node": "^22.13.1",
@@ -38,6 +44,7 @@
38
44
  "scripts": {
39
45
  "check": "vp exec tsc --noEmit",
40
46
  "test": "vp test run",
41
- "release": "node scripts/release.mjs"
47
+ "release": "node scripts/release.mjs",
48
+ "release:pilot": "node scripts/release-pilot.mjs"
42
49
  }
43
50
  }
@@ -0,0 +1,129 @@
1
+ import { parseCode, type CodeKind } from './shapes'
2
+ import { blockedCodeLetters, blockedProjectCode } from './words'
3
+ import { JUNCTION_SEPARATOR } from './junction'
4
+
5
+ export type Namespace = { shorthand: string; name: string }
6
+ export type Taxonomy = { shorthand: string; name: string; shape: CodeKind; pattern: string }
7
+ export type Part = { id: string; shape: CodeKind; name: string; path: string | null }
8
+ export type Architecture = { namespaces: Namespace[]; taxonomies: Taxonomy[]; parts: Part[]; facts: string[] }
9
+ export type Resolved = { id: string; shape: CodeKind | null; namespace?: Namespace; taxonomy?: Taxonomy; part?: Part; facts: string[] }
10
+
11
+ const SHAPES: CodeKind[] = ['account', 'list', 'project', 'item', 'event']
12
+ const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value : []) as T[]
13
+
14
+ export function readArchitecture(text: string): Architecture {
15
+ const value = JSON.parse(text) as Partial<Architecture>
16
+ return { namespaces: list(value.namespaces), taxonomies: list(value.taxonomies), parts: list(value.parts), facts: list(value.facts) }
17
+ }
18
+
19
+ export function taxonomyOf(architecture: Architecture, id: string): Taxonomy | undefined {
20
+ const shape = parseCode(id)?.kind
21
+ return architecture.taxonomies.find(taxonomy => {
22
+ const at = taxonomy.pattern.replace(/\s/g, '').indexOf(taxonomy.shorthand)
23
+ return taxonomy.shape === shape && at >= 0 && id.slice(at, at + 2) === taxonomy.shorthand
24
+ })
25
+ }
26
+
27
+ export function architectureHealth(architecture: Architecture, exists: (path: string) => boolean = () => true): string[] {
28
+ const problems: string[] = []
29
+ const seen = (values: string[], what: string) => values.forEach((value, index) => { if (values.indexOf(value) !== index) problems.push(`${what} ${value} is declared twice`) })
30
+ for (const { shorthand, name } of architecture.namespaces) {
31
+ if (!/^[A-Z]{2}$/.test(shorthand)) problems.push(`Namespace ${shorthand} is not two capitals`)
32
+ if (!name) problems.push(`Namespace ${shorthand} has no name`)
33
+ }
34
+ for (const { shorthand, name, shape, pattern } of architecture.taxonomies) {
35
+ if (!/^[a-z]{2}$/.test(shorthand)) problems.push(`Taxonomy ${shorthand} is not two small letters`)
36
+ if (!name) problems.push(`Taxonomy ${shorthand} has no name`)
37
+ if (!SHAPES.includes(shape)) problems.push(`Taxonomy ${shorthand} has no shape`)
38
+ const compact = String(pattern ?? '').replace(/\s/g, '')
39
+ if (compact.length !== 6 || !compact.includes(shorthand)) problems.push(`Taxonomy ${shorthand} has no six-character pattern holding ${shorthand}`)
40
+ }
41
+ seen(architecture.namespaces.map(namespace => namespace.shorthand), 'Namespace')
42
+ seen(architecture.taxonomies.map(taxonomy => taxonomy.shorthand), 'Taxonomy')
43
+ seen(architecture.parts.map(part => part.id), 'Id')
44
+ const ids = new Set(architecture.parts.map(part => part.id))
45
+ for (const part of architecture.parts) {
46
+ const shape = parseCode(part.id)?.kind
47
+ if (shape !== part.shape) problems.push(`${part.id} reads as ${shape ?? 'no shape'}, not ${part.shape}`)
48
+ else if (shape === 'project' ? blockedProjectCode(part.id) : blockedCodeLetters(part.id)) problems.push(`${part.id} uses blocked letters or digits`)
49
+ if (!part.name) problems.push(`${part.id} has no name`)
50
+ if (part.path && !exists(part.path)) problems.push(`${part.id}: ${part.path} is gone`)
51
+ }
52
+ for (const fact of architecture.facts) {
53
+ const [subject, relation, object, extra] = fact.split(' ')
54
+ if (extra !== undefined || !/^r[A-Za-z]{5}$/.test(relation ?? '')) problems.push(`Not a fact: ${fact}`)
55
+ else for (const id of [subject, object]) if (!ids.has(id)) problems.push(`Unknown id ${id} in: ${fact}`)
56
+ }
57
+ return problems
58
+ }
59
+
60
+ export function resolveCode(architecture: Architecture, value: string): Resolved[] {
61
+ const qualified = /^-([A-Z]{2})-(.+)$/.exec(value)
62
+ const ids = (qualified ? qualified[2] : value).split(JUNCTION_SEPARATOR)
63
+ return ids.map(id => {
64
+ const shape = parseCode(id)?.kind ?? null
65
+ const shorthand = qualified?.[1] ?? (shape === 'project' ? id.slice(0, 2) : undefined)
66
+ const namespace = architecture.namespaces.find(namespace => namespace.shorthand === shorthand) ?? (architecture.namespaces.length === 1 ? architecture.namespaces[0] : undefined)
67
+ const facts = architecture.facts.filter(fact => { const [subject, , object] = fact.split(' '); return subject === id || object === id })
68
+ return { id, shape, namespace, taxonomy: shape ? taxonomyOf(architecture, id) : undefined, part: architecture.parts.find(part => part.id === id), facts }
69
+ })
70
+ }
71
+
72
+ const nameOf = (architecture: Architecture, id: string) => architecture.parts.find(part => part.id === id)?.name ?? id
73
+ const readFact = (architecture: Architecture, fact: string) => { const [subject, relation, object] = fact.split(' '); return `${subject} ${relation} ${object} ${nameOf(architecture, subject)} → ${nameOf(architecture, object)}` }
74
+
75
+ export function describeResolved(architecture: Architecture, resolved: Resolved[]): string {
76
+ return resolved.map(({ id, shape, namespace, taxonomy, part, facts }) => [
77
+ `${id} ${part?.name ?? (shape ? 'not in .id' : 'not a code')}`,
78
+ ` shape ${shape ?? '—'}`,
79
+ ...(taxonomy ? [` taxonomy ${taxonomy.shorthand} · ${taxonomy.name}`] : []),
80
+ ...(namespace ? [` namespace ${namespace.shorthand} · ${namespace.name}`] : []),
81
+ ...(part?.path ? [` path ${part.path}`] : []),
82
+ ...facts.map(fact => ` fact ${readFact(architecture, fact)}`),
83
+ ].join('\n')).join('\n\n')
84
+ }
85
+
86
+ export function describeStatus(architecture: Architecture, problems: string[]): string {
87
+ const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
88
+ const shapes = SHAPES.map(shape => [shape, architecture.parts.filter(part => part.shape === shape).length] as const).filter(([, n]) => n)
89
+ return [
90
+ `${count(architecture.parts.length, 'part')} · ${count(architecture.facts.length, 'fact')} · ${count(architecture.namespaces.length, 'namespace')} · ${count(architecture.taxonomies.length, 'taxonomy', 'taxonomies')}`,
91
+ problems.length ? `${count(problems.length, 'problem')}: run idv1 health` : 'healthy',
92
+ '',
93
+ ...shapes.map(([shape, n]) => ` ${shape.padEnd(9)}${n}`),
94
+ ...architecture.taxonomies.map(taxonomy => ` ${taxonomy.shorthand.padEnd(9)}${architecture.parts.filter(part => taxonomyOf(architecture, part.id) === taxonomy).length} ${taxonomy.name}`),
95
+ ].join('\n')
96
+ }
97
+
98
+ export function describeArchitecture(architecture: Architecture): string {
99
+ const contains = architecture.facts.map(fact => fact.split(' ')).filter(([, relation]) => relation === 'rHasPt')
100
+ const children = (id: string) => contains.filter(([subject]) => subject === id).map(([, , object]) => object)
101
+ const roots = architecture.parts.filter(part => !contains.some(([, , object]) => object === part.id))
102
+ const line = (part: Part | undefined, id: string, depth: number) => `${' '.repeat(depth)}${id} ${part?.name ?? '?'}${part && taxonomyOf(architecture, id) ? ` (${taxonomyOf(architecture, id)!.name})` : ''}${part?.path ? ` ${part.path}` : ''}`
103
+ const tree = (id: string, depth: number, trail: Set<string>): string[] => trail.has(id) ? [] : [line(architecture.parts.find(part => part.id === id), id, depth), ...children(id).flatMap(child => tree(child, depth + 1, new Set([...trail, id])))]
104
+ return [
105
+ 'Namespaces',
106
+ ...architecture.namespaces.map(({ shorthand, name }) => ` ${shorthand} ${name}`),
107
+ '',
108
+ 'Taxonomies',
109
+ ...architecture.taxonomies.map(({ shorthand, name, shape, pattern }) => ` ${shorthand} ${name} ${shape} ${pattern}`),
110
+ '',
111
+ 'Parts',
112
+ ...roots.flatMap(part => tree(part.id, 1, new Set())),
113
+ '',
114
+ 'Facts',
115
+ ...architecture.facts.filter(fact => fact.split(' ')[1] !== 'rHasPt').map(fact => ` ${readFact(architecture, fact)}`),
116
+ ].join('\n')
117
+ }
118
+
119
+ export function runArchitectureCommand(command: string | undefined, args: string[], text: string, exists?: (path: string) => boolean): { code: number; out: string } {
120
+ const architecture = readArchitecture(text)
121
+ const problems = architectureHealth(architecture, exists)
122
+ switch (command) {
123
+ case 'health': return { code: problems.length ? 1 : 0, out: problems.length ? problems.join('\n') : 'healthy' }
124
+ case 'status': return { code: 0, out: describeStatus(architecture, problems) }
125
+ case 'resolve': return args.length ? { code: 0, out: args.map(value => describeResolved(architecture, resolveCode(architecture, value))).join('\n\n') } : { code: 2, out: 'idv1 resolve <id | junction | -NS-id>' }
126
+ case 'architecture': case undefined: return { code: 0, out: describeArchitecture(architecture) }
127
+ default: return { code: 2, out: 'idv1 architecture | status | health | resolve <id>' }
128
+ }
129
+ }
package/src/index.ts CHANGED
@@ -3,3 +3,4 @@ export * from './space'
3
3
  export * from './junction'
4
4
  export * from './words'
5
5
  export * from './scanCode'
6
+ export * from './architecture'
package/src/scanCode.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { isAccountCode, isListCode } from './shapes'
1
+ import { ALPHABET, isAccountCode, isListCode, parseCode, type Id } from './shapes'
2
2
  import { scanCodeChecksum, scanCodeColumns, scanCodeRows } from './scanCodeDrawing'
3
3
  export { CODE_END_RADIUS, encodeScanCode, scanCodeColumns, scanCodePath, scanCodeRows } from './scanCodeDrawing'
4
4
 
5
- const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
5
+ const alphabet = ALPHABET
6
6
  const idSpace = 62 ** 6
7
7
 
8
- export function decodeScanCode(bits: readonly boolean[]): string | null {
8
+ export function decodeScanCode(bits: readonly boolean[]): Id | null {
9
9
  if (bits.length !== 64) return null
10
10
  const bytes: number[] = []
11
11
  for (let offset = 0; offset < 64; offset += 8) {
@@ -22,12 +22,12 @@ export function decodeScanCode(bits: readonly boolean[]): string | null {
22
22
  id = alphabet[value % 62] + id
23
23
  value = Math.floor(value / 62)
24
24
  }
25
- return id
25
+ return parseCode(id)?.id ?? null
26
26
  }
27
27
 
28
28
  export const isListScanId = (id: string): boolean => isListCode(id)
29
29
  export const isUserScanId = (id: string): boolean => isAccountCode(id)
30
- export const isSupportedScanId = (id: string): boolean => isListScanId(id) || isUserScanId(id)
30
+ export const isSupportedScanId = (id: string): boolean => parseCode(id) !== null
31
31
 
32
32
  export type ScanRect = { x: number; y: number; width: number; height: number }
33
33
  export type Luminance = (x: number, y: number) => number
@@ -39,7 +39,7 @@ const insetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({
39
39
  const offsetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({ ...rect, x: rect.x + dx, y: rect.y + dy })
40
40
  const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value))
41
41
 
42
- export function sampleScanCode(width: number, height: number, luminance: Luminance, rect?: ScanRect): string | null {
42
+ export function sampleScanCode(width: number, height: number, luminance: Luminance, rect?: ScanRect): Id | null {
43
43
  if (width < 80 || height < 20) return null
44
44
  const guideWidth = rect?.width ?? width * 0.8
45
45
  const guideHeight = rect?.height ?? guideWidth / 4
@@ -102,7 +102,7 @@ export type ScanCorners = readonly [x0: number, y0: number, x1: number, y1: numb
102
102
 
103
103
  const rectCorners = (rect: ScanRect): ScanCorners => [rect.x, rect.y, rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height]
104
104
 
105
- export function sampleWrittenScanCode(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): string | null {
105
+ export function sampleWrittenScanCode(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): Id | null {
106
106
  const [x0, y0, x1, y1, x2, y2, x3, y3] = 'width' in place ? rectCorners(place) : place
107
107
  const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanCodeColumns
108
108
  if (cell < 5) return null
@@ -127,9 +127,9 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
127
127
  }
128
128
  return cells
129
129
  }
130
- const taken = (dark: readonly boolean[]): string | null => {
130
+ const taken = (dark: readonly boolean[]): Id | null => {
131
131
  const id = decodeScanCode(dark as boolean[]) ?? decodeScanCode(dark.map(bit => !bit))
132
- return id && isSupportedScanId(id) ? id : null
132
+ return id
133
133
  }
134
134
  const middles = sampled(0.6)
135
135
  for (const share of WRITTEN_SHARES) {
@@ -148,7 +148,7 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
148
148
  }, cell, taken)
149
149
  }
150
150
 
151
- function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => string | null): string | null {
151
+ function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => Id | null): Id | null {
152
152
  const n = Math.max(4, Math.min(8, Math.round(cell * 0.8)))
153
153
  const count = scanCodeColumns * scanCodeRows, each = n * n
154
154
  const light = new Float32Array(count * each)
@@ -381,9 +381,9 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
381
381
  return result
382
382
  }
383
383
 
384
- export type ScanFound = { id: string; rect: ScanRect }
384
+ export type ScanFound = { id: Id; rect: ScanRect }
385
385
 
386
- export function readScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): string | null {
386
+ export function readScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): Id | null {
387
387
  return locateScanFrame(width, height, luminance, chroma)?.id ?? null
388
388
  }
389
389
 
@@ -441,7 +441,7 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
441
441
  return null
442
442
  }
443
443
 
444
- export function readRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): string | null {
444
+ export function readRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): Id | null {
445
445
  return locateRgbaScanFrame(rgba, width, height)?.id ?? null
446
446
  }
447
447
 
@@ -466,12 +466,13 @@ export function locateRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width:
466
466
  }
467
467
 
468
468
  export class StableScan {
469
- private last: string | null = null
469
+ private last: Id | null = null
470
470
  private count = 0
471
- accept(id: string | null): string | null {
472
- if (!id) { this.last = null; this.count = 0; return null }
471
+ accept(id: string | null): Id | null {
472
+ const parsed = parseCode(id)
473
+ if (!parsed) { this.last = null; this.count = 0; return null }
473
474
  if (id === this.last) this.count++
474
- else { this.last = id; this.count = 1 }
475
- return this.count >= 3 ? id : null
475
+ else { this.last = parsed.id; this.count = 1 }
476
+ return this.count >= 3 ? parsed.id : null
476
477
  }
477
478
  }
@@ -1,4 +1,5 @@
1
- const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
1
+ import { ALPHABET, parseCode } from './shapes'
2
+ const alphabet = ALPHABET
2
3
 
3
4
  export const scanCodeColumns = 16
4
5
  export const scanCodeRows = 4
@@ -14,7 +15,7 @@ export function scanCodeChecksum(bytes: readonly number[]): number {
14
15
  }
15
16
 
16
17
  export function encodeScanCode(id: string): boolean[] | null {
17
- if (!/^[A-Za-z0-9]{6}$/.test(id)) return null
18
+ if (!parseCode(id)) return null
18
19
  let value = 0
19
20
  for (const character of id) value = value * 62 + alphabet.indexOf(character)
20
21
  const bytes = [3]
package/src/shapes.ts CHANGED
@@ -1,35 +1,59 @@
1
+ import { blockedCodeLetters, blockedProjectCode } from './words'
2
+
1
3
  export const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
2
4
  export const CAPITALS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
3
5
  export const DIGITS = '0123456789'
6
+ export const ALPHABET = DIGITS + LETTERS
7
+
8
+ export const ACCOUNT_CODE = /^[A-Za-z]{2}[0-9]{4}(?![\s\S])/
9
+ export const LIST_CODE = /^[0-9]{2}[A-Za-z]{4}(?![\s\S])/
10
+ export const PROJECT_CODE = /^[A-Za-z]{4}[0-9]{2}(?![\s\S])/
11
+ export const ITEM_CODE = /^[A-Za-z]{2}[0-9]{2}(?:[A-Za-z][A-Za-z0-9]|[0-9][A-Za-z])(?![\s\S])/
12
+ export const ANY_CODE = /^[A-Za-z0-9]{6}(?![\s\S])/
13
+ export const EVENT_CODE = new RegExp(`^(?!${[ACCOUNT_CODE, LIST_CODE, PROJECT_CODE, ITEM_CODE].map(pattern => pattern.source.slice(1)).join('|')})[A-Za-z0-9]{6}(?![\\s\\S])`)
14
+
15
+ export type CodeKind = 'account' | 'list' | 'project' | 'item' | 'event'
16
+ declare const idBrand: unique symbol
17
+ export type Id<K extends CodeKind = CodeKind> = string & { readonly [idBrand]: K }
18
+ export type AccountId = Id<'account'>
19
+ export type ListId = Id<'list'>
20
+ export type ProjectId = Id<'project'>
21
+ export type ItemId = Id<'item'>
22
+ export type EventId = Id<'event'>
23
+ export type ParsedCode = { [K in CodeKind]: { kind: K; id: Id<K> } }[CodeKind]
24
+
25
+ export const CODE_PATTERN = { account: ACCOUNT_CODE, list: LIST_CODE, project: PROJECT_CODE, item: ITEM_CODE, event: EVENT_CODE } as const
26
+
27
+ export function parseCode(value: unknown): ParsedCode | null {
28
+ if (typeof value !== 'string' || !ANY_CODE.test(value)) return null
29
+ for (const kind of ['account', 'list', 'project', 'item'] as const) {
30
+ if (CODE_PATTERN[kind].test(value)) return { kind, id: value } as ParsedCode
31
+ }
32
+ return { kind: 'event', id: value as EventId }
33
+ }
4
34
 
5
- export const NAME_CODE = /^[A-Za-z]{2}\d{4}$/
6
- export const PRODUCT_CODE = /^[A-Za-z]{4}\d{2}$/
7
- export const ACCOUNT_CODE = /^(?:[A-Za-z]{2}\d{4}|[A-Za-z]{4}\d{2})$/
8
- export const LIST_CODE = /^\d{2}[A-Za-z]{4}$/
9
- export const ITEM_CODE = /^[A-Za-z]{2}\d{2}(?:[A-Za-z][A-Za-z0-9]|\d[A-Za-z])$/
10
- export const PROJECT_CODE = /^\d[A-Za-z]{5}$/
11
-
12
- import { blockedCodeLetters, blockedProductCode } from './words'
13
-
14
- export type CodeKind = 'account' | 'product' | 'list' | 'item' | 'project'
35
+ export const codeKind = (value: unknown): CodeKind | null => parseCode(value)?.kind ?? null
36
+ export const isCodeOf = <K extends CodeKind>(kind: K, value: unknown): value is Id<K> => codeKind(value) === kind
37
+ export const isAccountCode = (value: unknown): value is AccountId => isCodeOf('account', value)
38
+ export const isListCode = (value: unknown): value is ListId => isCodeOf('list', value)
39
+ export const isProjectCode = (value: unknown): value is ProjectId => isCodeOf('project', value)
40
+ export const isItemCode = (value: unknown): value is ItemId => isCodeOf('item', value)
41
+ export const isEventCode = (value: unknown): value is EventId => isCodeOf('event', value)
15
42
 
16
- export const isAccountCode = (value: string): boolean => ACCOUNT_CODE.test(value)
17
- export const isProductCode = (value: string): boolean => PRODUCT_CODE.test(value)
18
- export const isListCode = (value: string): boolean => LIST_CODE.test(value)
19
- export const isItemCode = (value: string): boolean => ITEM_CODE.test(value)
20
- export const isProjectCode = (value: string): boolean => PROJECT_CODE.test(value)
43
+ export type Random = () => number
21
44
 
22
- export function codeKind(value: string): CodeKind | null {
23
- if (NAME_CODE.test(value)) return 'account'
24
- if (PRODUCT_CODE.test(value)) return 'product'
25
- if (LIST_CODE.test(value)) return 'list'
26
- if (ITEM_CODE.test(value)) return 'item'
27
- if (PROJECT_CODE.test(value)) return 'project'
28
- return null
45
+ export function secureRandom(): number {
46
+ const value = new Uint32Array(1)
47
+ globalThis.crypto.getRandomValues(value)
48
+ return value[0] / 2 ** 32
29
49
  }
30
50
 
31
- type Random = () => number
32
- const pick = (chars: string, random: Random) => chars[Math.floor(random() * chars.length)]
51
+ const pick = (chars: string, random: Random): string => {
52
+ const value = random()
53
+ if (!Number.isFinite(value) || value < 0 || value >= 1) throw new RangeError('Random values must be in [0, 1).')
54
+ return chars[Math.floor(value * chars.length)]
55
+ }
56
+ const draw = (chars: string, count: number, random: Random) => Array.from({ length: count }, () => pick(chars, random)).join('')
33
57
 
34
58
  const PLAIN: Record<string, string> = { ø: 'o', æ: 'a', œ: 'o', ß: 's', ð: 'd', þ: 't', ł: 'l', đ: 'd', ı: 'i' }
35
59
 
@@ -49,68 +73,33 @@ export function nameLetters(name: string, email = ''): string | null {
49
73
  return null
50
74
  }
51
75
 
52
- export function accountCodeCandidate(letters: string | null, random: Random = Math.random): string {
53
- const start = letters ?? pick(LETTERS, random) + pick(LETTERS, random)
54
- for (;;) {
55
- const code = start + String(Math.floor(random() * 10000)).padStart(4, '0')
56
- if (!isReservedAccountCode(code)) return code
57
- }
58
- }
59
-
60
- export const RESERVED_ACCOUNT_CODES = { owner: 'Jo4712', studio: 'Jo0001', onboarding: 'On0001', test: 'Te0001' } as const satisfies Record<string, string>
61
-
62
- export type ReservedRole = keyof typeof RESERVED_ACCOUNT_CODES
63
-
64
- export const FORMER_RESERVED_ACCOUNT_CODES = ['On4713'] as const
65
-
66
- let reserved: Set<string> | undefined
67
-
68
- export const isReservedAccountCode = (code: string): boolean =>
69
- (reserved ??= new Set([...Object.values(RESERVED_ACCOUNT_CODES), ...FORMER_RESERVED_ACCOUNT_CODES].map(kept => kept.toLowerCase()))).has(code.toLowerCase())
70
-
71
-
72
- export function productCodeCandidate(random: Random = Math.random): string {
73
- for (let attempt = 0; attempt < 1000; attempt++) {
74
- const code = Array.from({ length: 4 }, () => pick(LETTERS, random)).join('') + String(Math.floor(random() * 100)).padStart(2, '0')
75
- if (!blockedProductCode(code)) return code
76
+ export function codeCandidate<K extends CodeKind>(kind: K, options: { letters?: string | null; random?: Random } = {}): Id<K> {
77
+ const random = options.random ?? secureRandom
78
+ const prefix = options.letters ?? ''
79
+ if (prefix && (!['account', 'project'].includes(kind) || !/^[A-Za-z]{2}(?![\s\S])/.test(prefix))) {
80
+ throw new Error('A prefix must be exactly two ASCII letters for an Account or Project.')
76
81
  }
77
- throw new Error('No product code could be drawn.')
78
- }
79
-
80
- export function listCodeCandidate(random: Random = Math.random): string {
81
- return pick(DIGITS, random) + pick(DIGITS, random) + Array.from({ length: 4 }, () => pick(CAPITALS, random)).join('')
82
- }
83
-
84
- export function itemCodeCandidate(random: Random = Math.random): string {
85
- const start = pick(LETTERS, random) + pick(LETTERS, random) + pick(DIGITS, random) + pick(DIGITS, random)
86
- const first = pick(LETTERS + DIGITS, random)
87
- const second = pick(LETTERS + DIGITS, random)
88
- return start + (/\d/.test(first) && /\d/.test(second) ? pick(LETTERS, random) : first) + second
89
- }
90
-
91
- export function projectCodeCandidate(letters: string | null = null, random: Random = Math.random): string {
92
- const named = letters ? latinLetters(letters) : ''
93
82
  for (let attempt = 0; attempt < 1000; attempt++) {
94
- const drawn = (named + Array.from({ length: 5 }, () => pick(CAPITALS, random).toLowerCase()).join('')).slice(0, 5)
95
- const tail = attempt && named ? named.slice(0, 4) + pick(CAPITALS, random).toLowerCase() : drawn
96
- const code = pick(DIGITS, random) + tail[0].toUpperCase() + tail.slice(1)
97
- if (!blockedCodeLetters(code)) return code
83
+ let candidate: string
84
+ switch (kind) {
85
+ case 'account': candidate = (prefix || draw(LETTERS, 2, random)) + draw(DIGITS, 4, random); break
86
+ case 'list': candidate = draw(DIGITS, 2, random) + draw(LETTERS, 4, random); break
87
+ case 'project': candidate = (prefix || draw(LETTERS, 2, random)) + draw(LETTERS, 2, random) + draw(DIGITS, 2, random); break
88
+ case 'item': candidate = draw(LETTERS, 2, random) + draw(DIGITS, 2, random) + draw(ALPHABET, 2, random); break
89
+ case 'event': candidate = draw(ALPHABET, 6, random); break
90
+ default: throw new Error('Unknown IDv1 shape.')
91
+ }
92
+ const parsed = parseCode(candidate)
93
+ if (parsed?.kind === kind && !(kind === 'project' ? blockedProjectCode(candidate) : blockedCodeLetters(candidate))) return parsed.id as Id<K>
98
94
  }
99
- throw new Error('No project code could be drawn.')
95
+ throw new Error(`No ${kind} code could be drawn.`)
100
96
  }
101
97
 
102
- export const CODE_PATTERN: Record<CodeKind, RegExp> = { account: ACCOUNT_CODE, product: PRODUCT_CODE, list: LIST_CODE, item: ITEM_CODE, project: PROJECT_CODE }
103
-
104
- export const isCodeOf = (kind: CodeKind, value: string): boolean => CODE_PATTERN[kind].test(value)
105
-
106
- export function codeCandidate(kind: CodeKind, options: { letters?: string | null; random?: Random } = {}): string {
107
- const random = options.random ?? Math.random
108
- if (kind === 'account') return accountCodeCandidate(options.letters ?? null, random)
109
- if (kind === 'product') return productCodeCandidate(random)
110
- if (kind === 'list') return listCodeCandidate(random)
111
- if (kind === 'project') return projectCodeCandidate(options.letters ?? null, random)
112
- return itemCodeCandidate(random)
113
- }
98
+ export const accountCodeCandidate = (letters: string | null = null, random: Random = secureRandom): AccountId => codeCandidate('account', { letters, random })
99
+ export const listCodeCandidate = (random: Random = secureRandom): ListId => codeCandidate('list', { random })
100
+ export const projectCodeCandidate = (letters: string | null = null, random: Random = secureRandom): ProjectId => codeCandidate('project', { letters, random })
101
+ export const itemCodeCandidate = (random: Random = secureRandom): ItemId => codeCandidate('item', { random })
102
+ export const eventCodeCandidate = (random: Random = secureRandom): EventId => codeCandidate('event', { random })
114
103
 
115
104
  export function accountCodeCaseVariants(code: string): string[] {
116
105
  const [first, second] = [code[0], code[1]].map(letter => [...new Set([letter.toUpperCase(), letter.toLowerCase()])])
package/src/space.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  const LETTERS = 52
2
- const CAPITALS = 26
3
2
  const DIGITS = 10
3
+ export const TOTAL_ID_SPACE = (LETTERS + DIGITS) ** 6
4
+ const accounts = LETTERS ** 2 * DIGITS ** 4
5
+ const lists = DIGITS ** 2 * LETTERS ** 4
6
+ const projects = LETTERS ** 4 * DIGITS ** 2
7
+ const items = LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2)
4
8
 
5
- export const ID_SPACE = {
6
- accounts: LETTERS ** 2 * DIGITS ** 4,
7
- products: LETTERS ** 4 * DIGITS ** 2,
8
- lists: DIGITS ** 2 * CAPITALS ** 4,
9
- items: LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2),
10
- projects: DIGITS * LETTERS ** 5,
11
- } as const
12
-
9
+ export const ID_SPACE = { accounts, lists, projects, items, events: TOTAL_ID_SPACE - accounts - lists - projects - items } as const
13
10
  export type IdSpaceKind = keyof typeof ID_SPACE
14
11
 
15
12
  export function idUsage(kind: IdSpaceKind, used: number): { used: number; space: number; left: number; percent: number } {
16
13
  const space = ID_SPACE[kind]
14
+ if (!Number.isSafeInteger(used) || used < 0) throw new RangeError('Usage must be a nonnegative safe integer.')
17
15
  return { used, space, left: Math.max(0, space - used), percent: (used / space) * 100 }
18
16
  }
package/src/words.ts CHANGED
@@ -19,6 +19,6 @@ export function blockedCodeLetters(letters: string): boolean {
19
19
  return BLOCKED_CODE_WORDS.some(word => small.includes(word))
20
20
  }
21
21
 
22
- export function blockedProductCode(code: string): boolean {
22
+ export function blockedProjectCode(code: string): boolean {
23
23
  return blockedCodeLetters(code.slice(0, 4)) || BLOCKED_CODE_DIGITS.includes(code.slice(4))
24
24
  }
package/src/advanced.ts DELETED
@@ -1,49 +0,0 @@
1
- import { CODE_PATTERN, codeKind, type CodeKind } from './shapes'
2
- import { blockedCodeLetters } from './words'
3
-
4
- export type AdvancedCodeKind = CodeKind | 'event'
5
-
6
- export const ANY_CODE = /^[A-Za-z0-9]{6}$/
7
-
8
- const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
9
-
10
- export const isEventCode = (value: string): boolean => ANY_CODE.test(value) && codeKind(value) === null
11
-
12
- export function advancedCodeKind(value: string): AdvancedCodeKind | null {
13
- return codeKind(value) ?? (ANY_CODE.test(value) ? 'event' : null)
14
- }
15
-
16
- export const isAdvancedCodeOf = (kind: AdvancedCodeKind, value: string): boolean =>
17
- kind === 'event' ? isEventCode(value) : CODE_PATTERN[kind].test(value)
18
-
19
- type Random = () => number
20
-
21
- export function secureRandom(): number {
22
- const crypto = globalThis.crypto
23
- if (!crypto?.getRandomValues) return Math.random()
24
- const value = new Uint32Array(1)
25
- crypto.getRandomValues(value)
26
- return value[0] / 2 ** 32
27
- }
28
-
29
- export function eventCodeCandidate(random: Random = secureRandom): string {
30
- for (let attempt = 0; attempt < 1000; attempt++) {
31
- let code = ''
32
- for (let index = 0; index < 6; index++) code += ALPHABET[Math.floor(random() * ALPHABET.length)]
33
- if (isEventCode(code) && !blockedCodeLetters(code)) return code
34
- }
35
- throw new Error('No event code could be drawn.')
36
- }
37
-
38
- export const ADVANCED_SPACE = (() => {
39
- const letters = 52
40
- const digits = 10
41
- const all = (letters + digits) ** 6
42
- const shapes =
43
- letters ** 2 * digits ** 4 +
44
- letters ** 4 * digits ** 2 +
45
- digits ** 2 * letters ** 4 +
46
- letters ** 2 * digits ** 2 * ((letters + digits) ** 2 - digits ** 2) +
47
- digits * letters ** 5
48
- return { all, shapes, events: all - shapes } as const
49
- })()