@0001-labs/idv1 0.3.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,74 +7,34 @@ 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: use a unique constraint or a transaction to claim a candidate in your app.
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
+ ## Upgrading from 0.3.x to Release 1
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
+ Release 1 uses five shapes. Here `L` is an ASCII letter and `N` is a digit.
31
25
 
32
- ### Building a template
26
+ | Kind | Shape |
27
+ | --- | --- |
28
+ | Account | `LLNNNN` |
29
+ | List | `NNLLLL` |
30
+ | Project | `LLLLNN`, formerly also accepted as Account |
31
+ | Item | `LLNN` followed by two ASCII letters or digits, with at least one letter |
32
+ | Event | Any remaining string of exactly six ASCII letters or digits |
33
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`.
34
+ 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.
38
35
 
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.
36
+ ## Documentation
40
37
 
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
- | Issue tags | event | `ixxxxx` | `iImpro` |
63
- | Engineers | account | `LLNNNN` | `Le0125` |
64
- | Agents | account | `aLNNNN` | `aG4008` |
65
- | Harnesses | product | `hLLLNN` | `hCla01` |
66
-
67
- 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.
68
-
69
- ### Junctions
70
-
71
- 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, `1Syste-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.
72
-
73
- ### Rules every template keeps
74
-
75
- - **Six characters**, letters `A–Z a–z` and digits only.
76
- - **Its shape.** Every code a template makes passes `isCodeOf(shape, code)`, and `codeKind(code)` reads it back as that shape.
77
- - **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.
78
- - **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.
38
+ 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.
79
39
 
80
40
  [MIT license](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0001-labs/idv1",
3
- "version": "0.3.4",
3
+ "version": "1.0.0",
4
4
  "description": "An ID system for short, memorable IDs that are easy to keep unique.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -14,8 +14,7 @@
14
14
  ],
15
15
  "type": "module",
16
16
  "exports": {
17
- ".": "./src/index.ts",
18
- "./advanced": "./src/advanced.ts"
17
+ ".": "./src/index.ts"
19
18
  },
20
19
  "devDependencies": {
21
20
  "@types/node": "^22.13.1",
@@ -38,6 +37,7 @@
38
37
  "scripts": {
39
38
  "check": "vp exec tsc --noEmit",
40
39
  "test": "vp test run",
41
- "release": "node scripts/release.mjs"
40
+ "release": "node scripts/release.mjs",
41
+ "release:pilot": "node scripts/release-pilot.mjs"
42
42
  }
43
43
  }
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,79 +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 RESERVED_ACCOUNT_EMAILS = {
65
- 'jaa90@icloud.com': 'owner',
66
- 'joachim@0001.dev': 'studio',
67
- 'joachim+onboarding@0001.dev': 'onboarding',
68
- 'joachim+test@0001.dev': 'test',
69
- } as const satisfies Record<string, ReservedRole>
70
-
71
- export const FORMER_RESERVED_ACCOUNT_CODES = ['On4713'] as const
72
-
73
- let reserved: Set<string> | undefined
74
-
75
- export const isReservedAccountCode = (code: string): boolean =>
76
- (reserved ??= new Set([...Object.values(RESERVED_ACCOUNT_CODES), ...FORMER_RESERVED_ACCOUNT_CODES].map(kept => kept.toLowerCase()))).has(code.toLowerCase())
77
-
78
- export function reservedAccountCode(email: string | null | undefined): string | null {
79
- const key = email?.trim().toLowerCase() as keyof typeof RESERVED_ACCOUNT_EMAILS | undefined
80
- return key && key in RESERVED_ACCOUNT_EMAILS ? RESERVED_ACCOUNT_CODES[RESERVED_ACCOUNT_EMAILS[key]] : null
81
- }
82
-
83
- export function productCodeCandidate(random: Random = Math.random): string {
84
- for (let attempt = 0; attempt < 1000; attempt++) {
85
- const code = Array.from({ length: 4 }, () => pick(LETTERS, random)).join('') + String(Math.floor(random() * 100)).padStart(2, '0')
86
- 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.')
87
81
  }
88
- throw new Error('No product code could be drawn.')
89
- }
90
-
91
- export function listCodeCandidate(random: Random = Math.random): string {
92
- return pick(DIGITS, random) + pick(DIGITS, random) + Array.from({ length: 4 }, () => pick(CAPITALS, random)).join('')
93
- }
94
-
95
- export function itemCodeCandidate(random: Random = Math.random): string {
96
- const start = pick(LETTERS, random) + pick(LETTERS, random) + pick(DIGITS, random) + pick(DIGITS, random)
97
- const first = pick(LETTERS + DIGITS, random)
98
- const second = pick(LETTERS + DIGITS, random)
99
- return start + (/\d/.test(first) && /\d/.test(second) ? pick(LETTERS, random) : first) + second
100
- }
101
-
102
- export function projectCodeCandidate(letters: string | null = null, random: Random = Math.random): string {
103
- const named = letters ? latinLetters(letters) : ''
104
82
  for (let attempt = 0; attempt < 1000; attempt++) {
105
- const drawn = (named + Array.from({ length: 5 }, () => pick(CAPITALS, random).toLowerCase()).join('')).slice(0, 5)
106
- const tail = attempt && named ? named.slice(0, 4) + pick(CAPITALS, random).toLowerCase() : drawn
107
- const code = pick(DIGITS, random) + tail[0].toUpperCase() + tail.slice(1)
108
- 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>
109
94
  }
110
- throw new Error('No project code could be drawn.')
95
+ throw new Error(`No ${kind} code could be drawn.`)
111
96
  }
112
97
 
113
- export const CODE_PATTERN: Record<CodeKind, RegExp> = { account: ACCOUNT_CODE, product: PRODUCT_CODE, list: LIST_CODE, item: ITEM_CODE, project: PROJECT_CODE }
114
-
115
- export const isCodeOf = (kind: CodeKind, value: string): boolean => CODE_PATTERN[kind].test(value)
116
-
117
- export function codeCandidate(kind: CodeKind, options: { letters?: string | null; random?: Random } = {}): string {
118
- const random = options.random ?? Math.random
119
- if (kind === 'account') return accountCodeCandidate(options.letters ?? null, random)
120
- if (kind === 'product') return productCodeCandidate(random)
121
- if (kind === 'list') return listCodeCandidate(random)
122
- if (kind === 'project') return projectCodeCandidate(options.letters ?? null, random)
123
- return itemCodeCandidate(random)
124
- }
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 })
125
103
 
126
104
  export function accountCodeCaseVariants(code: string): string[] {
127
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
- })()