@wry-smile/lexid 0.0.0-stage → 0.1.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.
@@ -0,0 +1,37 @@
1
+ //#region src/types.d.ts
2
+ type Dictionary = readonly string[];
3
+ type Segments = readonly Dictionary[];
4
+ type Pattern = Segments;
5
+ type Patterns = readonly Pattern[];
6
+ interface RandomUtils {
7
+ int(max: number): number;
8
+ pick<T>(items: readonly T[]): T;
9
+ string(alphabet: string, length: number): string;
10
+ numeric(length: number): string;
11
+ alphabetic(length: number): string;
12
+ alphanumeric(length: number): string;
13
+ hexadecimal(length: number): string;
14
+ }
15
+ interface SuffixContext {
16
+ readonly words: readonly string[];
17
+ readonly random: RandomUtils;
18
+ }
19
+ type SuffixGenerator = (context: SuffixContext) => string;
20
+ interface LexidOptions {
21
+ /** Ordered word dictionaries. Defaults to a randomly selected built-in pattern. */
22
+ segments?: Segments;
23
+ /** Separator between all segments. Defaults to '-'. */
24
+ separator?: string;
25
+ /** Set to false to omit the suffix, or pass a callback. Defaults to six lowercase alphanumeric characters. */
26
+ suffix?: SuffixGenerator | false;
27
+ /** Maximum length including separators and suffix. Defaults to 63. */
28
+ maxLength?: number;
29
+ }
30
+ interface LexidValidateOptions {
31
+ separator?: string;
32
+ maxLength?: number;
33
+ /** Whether to expect a final suffix segment. Defaults to true. */
34
+ hasSuffix?: boolean;
35
+ }
36
+ //#endregion
37
+ export { Patterns as a, SuffixContext as c, Pattern as i, SuffixGenerator as l, LexidOptions as n, RandomUtils as o, LexidValidateOptions as r, Segments as s, Dictionary as t };
package/package.json CHANGED
@@ -1,6 +1,100 @@
1
1
  {
2
2
  "name": "@wry-smile/lexid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Composable human-readable identifiers powered by semantic dictionaries and secure randomness.",
5
+ "keywords": [
6
+ "dictionary",
7
+ "human-readable-id",
8
+ "identifier",
9
+ "random-name",
10
+ "slug",
11
+ "typescript"
12
+ ],
13
+ "homepage": "https://github.com/wry-smile/lexid#readme",
14
+ "bugs": "https://github.com/wry-smile/lexid/issues",
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/wry-smile/lexid.git"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "skills",
23
+ "README.md",
24
+ "README.zh-CN.md",
25
+ "LICENSE"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "types": "./dist/index.d.mts",
30
+ "exports": {
31
+ ".": {
32
+ "import": {
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
35
+ },
36
+ "require": {
37
+ "types": "./dist/index.d.cts",
38
+ "default": "./dist/index.cjs"
39
+ }
40
+ },
41
+ "./dictionaries": {
42
+ "import": {
43
+ "types": "./dist/dictionaries.d.mts",
44
+ "default": "./dist/dictionaries.mjs"
45
+ },
46
+ "require": {
47
+ "types": "./dist/dictionaries.d.cts",
48
+ "default": "./dist/dictionaries.cjs"
49
+ }
50
+ },
51
+ "./patterns": {
52
+ "import": {
53
+ "types": "./dist/patterns.d.mts",
54
+ "default": "./dist/patterns.mjs"
55
+ },
56
+ "require": {
57
+ "types": "./dist/patterns.d.cts",
58
+ "default": "./dist/patterns.cjs"
59
+ }
60
+ },
61
+ "./random": {
62
+ "import": {
63
+ "types": "./dist/random.d.mts",
64
+ "default": "./dist/random.mjs"
65
+ },
66
+ "require": {
67
+ "types": "./dist/random.d.cts",
68
+ "default": "./dist/random.cjs"
69
+ }
70
+ }
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "devDependencies": {
76
+ "@types/node": "^22.0.0",
77
+ "bumpp": "^12.3.0",
78
+ "oxfmt": "^0.80.0",
79
+ "oxlint": "^1.95.0",
80
+ "tsdown": "^0.21.0",
81
+ "typescript": "~5.9.3",
82
+ "vitest": "^4.0.0",
83
+ "yaml": "^2.8.0"
84
+ },
85
+ "engines": {
86
+ "node": ">=22"
87
+ },
88
+ "scripts": {
89
+ "build": "tsdown",
90
+ "typecheck": "tsc --noEmit",
91
+ "test": "vitest run",
92
+ "test:watch": "vitest",
93
+ "test:package": "node tests/pack-smoke.mjs",
94
+ "format": "oxfmt --write",
95
+ "format:check": "oxfmt --check",
96
+ "lint": "oxlint --deny-warnings",
97
+ "release": "bumpp --no-push",
98
+ "release:publish": "pnpm publish"
99
+ }
6
100
  }
@@ -0,0 +1,65 @@
1
+ ---
2
+ name: lexid
3
+ description: Integrate the LexID TypeScript library into Node.js or browser projects that need human-readable resource identifiers, service or instance names, URL slugs, semantic naming patterns, or custom dictionaries.
4
+ ---
5
+
6
+ # LexID Library Integration
7
+
8
+ Use LexID in Node.js 22+ or ES2022-capable browsers for new resource identifiers,
9
+ containers, service names, workspace slugs, and test fixtures. Use ESM in browsers.
10
+ The library uses `crypto.getRandomValues()`, which works on plain HTTP. Use a slugifier
11
+ for transforming existing text.
12
+
13
+ Use the host project's package manager to add the library when needed, for
14
+ example `pnpm add @wry-smile/lexid` after it is published. Reuse any existing LexID
15
+ dependency. Skill installation provides integration documentation only.
16
+
17
+ ```ts
18
+ import { lexid } from '@wry-smile/lexid'
19
+
20
+ const instanceName = lexid()
21
+ ```
22
+
23
+ ## Choose an API
24
+
25
+ | Need | API or composition |
26
+ | ------------------------------------------------------ | --------------------------------------------------------------------------------- |
27
+ | Default semantic identifier | `lexid()` |
28
+ | Fixed order or custom segment count | `lexid({ segments })` |
29
+ | Three or four word segments | `pickPattern(threeWordPatterns)` or `pickPattern(fourWordPatterns)` as `segments` |
30
+ | Fixed word, positional constraint, or mixed dictionary | Single-element array, `Array.filter`, or array spread |
31
+ | Custom templates | `pickPattern(patterns)` as `segments` |
32
+ | Custom separator or suffix | `separator` or a synchronous `suffix` callback |
33
+ | Batch or format check | `lexids(count, options)` or `isLexid(value, options)` |
34
+ | Standalone secure sampling | `random` from `@wry-smile/lexid/random` |
35
+
36
+ ## Customize with arrays and functions
37
+
38
+ Pass ordered arrays of candidate words to `segments`. The default suffix adds one
39
+ segment. Set `suffix: false` to omit it and validate with `hasSuffix: false`. Compose frozen built-in dictionaries using filtering and spreading.
40
+ Check that filtered dictionaries have candidates, or use `pickPattern` to skip
41
+ templates containing empty dictionaries. Supply fixed words in single-element
42
+ arrays and keep each candidate intact.
43
+
44
+ ## Common mistakes
45
+
46
+ `segments: 5` is invalid. Pass `pickPattern(fourWordPatterns)` to obtain
47
+ four word segments plus the default suffix. Apply filters directly to the dictionary arrays. Supply
48
+ a callback such as `({ random }) => random.numeric(8)` for a numeric suffix.
49
+ For a custom separator or length limit, use matching options in `isLexid`.
50
+
51
+ ## Security and uniqueness
52
+
53
+ Use identifiers as public names. Generate passwords, access tokens, session
54
+ tokens, and secrets with tools designed for credentials. Keep sensitive data
55
+ out of identifiers and enforce authorization separately. Enforce uniqueness through a
56
+ database constraint and bounded retries for identifier collisions. Custom
57
+ suffix randomness depends on the callback implementation.
58
+
59
+ ## References
60
+
61
+ - [API contracts](references/api.md)
62
+ - [Dictionary categories and composition](references/dictionaries.md)
63
+ - [Default and custom patterns](references/patterns.md)
64
+ - [Business constraints and suffix callbacks](references/customization.md)
65
+ - [Application integration examples](references/examples.md)
@@ -0,0 +1,69 @@
1
+ # Public API
2
+
3
+ The root entry exports the functions, data, and types below. Use
4
+ `@wry-smile/lexid/dictionaries`, `@wry-smile/lexid/patterns`, and `@wry-smile/lexid/random` to import those
5
+ modules independently. Both ESM and CommonJS are supported.
6
+
7
+ | Export | Contract |
8
+ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
+ | `lexid(options?: LexidOptions): string` | Samples an ordered set of word dictionaries and appends a suffix by default. Defaults to a uniformly chosen built-in template. |
10
+ | `lexids(count: number, options?: LexidOptions): string[]` | Generates independently per entry, with a fresh default pattern and one suffix invocation per entry when enabled. Count must be a nonnegative safe integer and fit in a JavaScript array. Zero returns an empty array. Duplicates are possible. |
11
+ | `isLexid(value: string, options?: LexidValidateOptions): boolean` | Checks at least one lowercase ASCII word, one lowercase ASCII alphanumeric suffix by default, plus separators and total length. Invalid values return false. Invalid options throw. |
12
+ | `pickPattern(patterns: Patterns): Pattern` | Uniformly selects an original nonempty template with nonempty dictionary arrays. Throws if no eligible pattern exists. The generator validates the words. |
13
+ | `defaultSuffix: SuffixGenerator` | Generates six lowercase alphanumeric characters with the context's random tools. |
14
+ | `defaultPatterns`, `threeWordPatterns`, `fourWordPatterns` | Frozen collections of frozen dictionary combinations. |
15
+ | Dictionary exports | Frozen arrays of lowercase ASCII words. See [dictionary categories](dictionaries.md). |
16
+
17
+ ```ts
18
+ import type {
19
+ Dictionary,
20
+ LexidOptions,
21
+ LexidValidateOptions,
22
+ Pattern,
23
+ Patterns,
24
+ RandomUtils,
25
+ Segments,
26
+ SuffixContext,
27
+ SuffixGenerator,
28
+ } from '@wry-smile/lexid'
29
+
30
+ const sample: Dictionary = ['worker']
31
+ const segments: Segments = [sample]
32
+ const pattern: Pattern = segments
33
+ const patterns: Patterns = [pattern]
34
+ const suffix: SuffixGenerator = ({ random }: SuffixContext) => random.numeric(8)
35
+ const format: LexidValidateOptions = { separator: '_', maxLength: 40 }
36
+ const options: LexidOptions = { segments, suffix, ...format }
37
+ const sampleDigit = (random: RandomUtils) => random.int(10)
38
+ void [patterns, options, sampleDigit]
39
+ ```
40
+
41
+ `Dictionary` is `readonly string[]`. `Segments` and `Pattern` are
42
+ `readonly Dictionary[]`. `Patterns` is `readonly Pattern[]`. Both options
43
+ types accept a separator (default `-`, also accepts `_`, `.`, and `~`)
44
+ and a positive safe integer maximum length (default 63). Generation options
45
+ also accept `segments` and a synchronous `suffix` callback. Set `suffix: false`
46
+ to omit the suffix. For validation, set `hasSuffix: false` to require only
47
+ word segments.
48
+
49
+ The deprecated names `fourSegmentPatterns` and `fiveSegmentPatterns` are aliases
50
+ for `threeWordPatterns` and `fourWordPatterns`, respectively.
51
+
52
+ The generator checks every candidate, including holes in arrays. When enabled,
53
+ it invokes the suffix once after selecting words, passing a frozen context with a frozen word
54
+ snapshot and the public `random` object. Empty or malformed suffixes and
55
+ oversized results throw. Callback exceptions propagate directly.
56
+
57
+ | Random method | Contract |
58
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
59
+ | `int(max: number): number` | Uniform integer in `[0, max)`, with integer `max` from 1 through `2**48 - 1`. |
60
+ | `pick<T>(items: readonly T[]): T` | Uniform array index. Rejects empty or sparse arrays. Repeated values retain their weight. |
61
+ | `string(alphabet: string, length: number): string` | Samples from a nonempty alphabet deduplicated by Unicode code point. Length is a nonnegative safe integer counted in code points. |
62
+ | `numeric(length: number): string` | Uses digits 0–9. |
63
+ | `alphabetic(length: number): string` | Uses lowercase ASCII a–z. |
64
+ | `alphanumeric(length: number): string` | Uses lowercase ASCII letters and digits. |
65
+ | `hexadecimal(length: number): string` | Uses digits and lowercase a–f. |
66
+
67
+ Invalid argument types and formats generally throw `TypeError`. Invalid
68
+ numeric ranges, overlong identifiers, and collections with no eligible
69
+ pattern throw `RangeError`.
@@ -0,0 +1,66 @@
1
+ # Customization
2
+
3
+ Use one or more dictionaries and expect `segments.length + 1` total segments by default.
4
+ With `suffix: false`, the result contains exactly `segments.length` word segments.
5
+ Validate it with `isLexid(value, { hasSuffix: false })`.
6
+ A one-word dictionary fixes that segment. Filter words by position or length
7
+ using normal array methods. Restrict the longest allowed candidate per segment
8
+ and budget for the separators and suffix when every result must fit.
9
+
10
+ ```ts
11
+ import { adjectives, isLexid, lexid, lexids, technologies } from '@wry-smile/lexid'
12
+ import type { LexidOptions } from '@wry-smile/lexid'
13
+
14
+ const options: LexidOptions = {
15
+ segments: [
16
+ adjectives.filter((word) => word.startsWith('s') && word.length <= 6),
17
+ technologies.filter((word) => word[1] === 'l'),
18
+ ['worker'],
19
+ ],
20
+ separator: '_',
21
+ maxLength: 40,
22
+ suffix: ({ words, random }) =>
23
+ words.map((word) => word.charAt(0)).join('') + random.string('23456789abcdef', 6),
24
+ }
25
+
26
+ const name = lexid(options)
27
+ isLexid(name, options)
28
+ lexids(5, options)
29
+ ```
30
+
31
+ Choose `-` for ordinary DNS-label-compatible identifiers with the default
32
+ length cap. The other supported separators are `_`, `.`, and `~`. Custom
33
+ suffixes can combine fixed characters, initials, and random characters. Return
34
+ a nonempty lowercase ASCII alphanumeric string synchronously.
35
+
36
+ ## Replace one dictionary in a preset
37
+
38
+ Select a preset, then copy its dictionaries while replacing the target position.
39
+ The other positions retain the candidate dictionaries from that preset.
40
+
41
+ ```ts
42
+ import { threeWordPatterns, lexid, pickPattern } from '@wry-smile/lexid'
43
+
44
+ const [first, , third] = pickPattern(threeWordPatterns)
45
+ lexid({ segments: [first, ['worker', 'gateway'], third] })
46
+ ```
47
+
48
+ ## Filter built-in templates by position
49
+
50
+ Filter every candidate template before calling `pickPattern`. It skips templates
51
+ where filtering empties a dictionary and throws if no template remains. For three word segments, use `threeWordPatterns` and three word limits.
52
+ The suffix is generated separately.
53
+
54
+ ```ts
55
+ import { fourWordPatterns, lexid, pickPattern } from '@wry-smile/lexid'
56
+
57
+ const limits = [6, 5, 7, 8]
58
+ const candidates = fourWordPatterns.map((pattern) =>
59
+ pattern.map((dictionary, index) => dictionary.filter((word) => word.length <= limits[index])),
60
+ )
61
+
62
+ const id = lexid({ segments: pickPattern(candidates) })
63
+ ```
64
+
65
+ Reuse the filtered candidates when generating multiple names with the same
66
+ limits. Call `pickPattern(candidates)` again for each name to vary the template.
@@ -0,0 +1,33 @@
1
+ # Dictionaries
2
+
3
+ Import the named exports from `@wry-smile/lexid` or `@wry-smile/lexid/dictionaries`.
4
+
5
+ | Category | Dictionary exports |
6
+ | ------------------- | ------------------------------------------------------------------------------ |
7
+ | Language | `adjectives`, `nouns`, `verbs`, `adverbs`, `modifiers` |
8
+ | Wildlife | `animals`, `birds`, `insects` |
9
+ | Plants | `plants`, `flowers`, `trees` |
10
+ | Outdoors | `nature`, `elements`, `space`, `weather`, `directions`, `seasons`, `geography` |
11
+ | Technology | `technologies`, `domains`, `categories`, `instruments` |
12
+ | Visual and cultural | `colors`, `materials`, `gemstones`, `mythology`, `music`, `architecture` |
13
+
14
+ Each built-in list is independently maintained, sorted, frozen, and contains
15
+ unique lowercase ASCII words. Prefer familiar, public-facing words of 3–12
16
+ characters. Common shorter words can be valid. Check licensing and attribution
17
+ before importing external word lists.
18
+
19
+ Custom dictionaries can contain any nonempty lowercase ASCII words. Duplicate
20
+ values in custom lists act as weights.
21
+
22
+ ```ts
23
+ import { lexid } from '@wry-smile/lexid'
24
+ import { adjectives, animals, birds } from '@wry-smile/lexid/dictionaries'
25
+
26
+ lexid({
27
+ segments: [
28
+ adjectives.filter((word) => word.startsWith('s')),
29
+ [...animals, ...birds],
30
+ ['gateway', 'worker'],
31
+ ],
32
+ })
33
+ ```
@@ -0,0 +1,54 @@
1
+ # Integration examples
2
+
3
+ ## Node.js instances, workspaces, routes, and test data
4
+
5
+ ```ts
6
+ import { adjectives, domains, isLexid, lexid, lexids, technologies } from '@wry-smile/lexid'
7
+
8
+ const instanceName = lexid()
9
+ const serviceName = lexid({ segments: [adjectives, technologies, ['worker']] })
10
+ const workspace = lexid({ segments: [adjectives, domains] })
11
+ const workspacePath = isLexid(workspace) ? `/workspaces/${workspace}` : undefined
12
+ const testNames = lexids(20)
13
+ void [instanceName, serviceName, workspacePath, testNames]
14
+ ```
15
+
16
+ ## NestJS service and storage
17
+
18
+ Define a naming provider and register it in the Nest module that creates
19
+ resources. The example is a dependency-free provider object. Import it into
20
+ the module's `providers` array and inject `namingProvider.provide` where needed.
21
+
22
+ ```ts
23
+ import { lexid } from '@wry-smile/lexid'
24
+
25
+ const namingProvider = {
26
+ provide: Symbol('resource-name'),
27
+ useValue: () => lexid(),
28
+ }
29
+ void namingProvider
30
+ ```
31
+
32
+ Apply a database UNIQUE constraint to the identifier column. Retry only
33
+ collisions from that constraint, with a bounded attempt count.
34
+
35
+ ```ts
36
+ import { lexid } from '@wry-smile/lexid'
37
+
38
+ async function createWorkspace(
39
+ insert: (id: string) => Promise<void>,
40
+ isIdentifierCollision: (error: unknown) => boolean,
41
+ ): Promise<string> {
42
+ for (let attempt = 0; attempt < 3; attempt++) {
43
+ const id = lexid()
44
+ try {
45
+ await insert(id)
46
+ return id
47
+ } catch (error) {
48
+ if (!isIdentifierCollision(error) || attempt === 2) throw error
49
+ }
50
+ }
51
+ throw new Error('Could not allocate workspace identifier')
52
+ }
53
+ void createWorkspace
54
+ ```
@@ -0,0 +1,45 @@
1
+ # Semantic patterns
2
+
3
+ A pattern is an ordered array of dictionaries. `threeWordPatterns` has
4
+ three dictionaries per pattern and `fourWordPatterns` has four. The suffix
5
+ completes the identifier by default. With `suffix: false`, the same templates
6
+ produce exactly three or four word segments. The older names
7
+ `fourSegmentPatterns` and `fiveSegmentPatterns` remain as deprecated aliases
8
+ that count the default suffix. Default styles include colors and wildlife,
9
+ materials and objects, and technologies and domains. `defaultPatterns`
10
+ combines both sets. Selection is uniform across eligible patterns.
11
+
12
+ ```ts
13
+ import { adjectives, domains, lexid } from '@wry-smile/lexid'
14
+ import { fourWordPatterns, threeWordPatterns, pickPattern } from '@wry-smile/lexid/patterns'
15
+
16
+ lexid({ segments: pickPattern(threeWordPatterns) })
17
+ lexid({ segments: pickPattern(fourWordPatterns) })
18
+ lexid({
19
+ segments: pickPattern([
20
+ [adjectives, domains],
21
+ [['local'], ['worker']],
22
+ ]),
23
+ })
24
+
25
+ const candidates = fourWordPatterns.map((pattern) =>
26
+ pattern.map((dictionary, index) =>
27
+ index === 0 ? dictionary.filter((word) => word.startsWith('s')) : dictionary,
28
+ ),
29
+ )
30
+ lexid({ segments: pickPattern(candidates) })
31
+ ```
32
+
33
+ Filter before choosing a template. `pickPattern` skips empty templates and
34
+ templates containing empty dictionaries. Handle its error if all candidates
35
+ are eliminated.
36
+
37
+ ## Order custom word segments
38
+
39
+ For a readable English-style name, move from descriptors to the object being
40
+ named. For example, use `[adjectives, technologies, domains]` for service names
41
+ or `[colors, nature, animals]` for nature-inspired names.
42
+
43
+ For names scanned in a resource list, put the primary grouping key first.
44
+ Use a single-word dictionary for a fixed key, and apply length filters only
45
+ to the positions that need them.