@atcute/lex-cli 2.2.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,12 +23,38 @@ then run the tool:
23
23
  npm exec lex-cli generate -c ./lex.config.js
24
24
  ```
25
25
 
26
- highly recommend packaging the generated schemas as a publishable library for others to use.
26
+ ## publishing your schemas
27
+
28
+ if you're packaging your generated schemas as a publishable library, add the `atcute:lexicons`
29
+ field to your package.json. this allows other projects to automatically discover and import your
30
+ schemas without manual configuration.
31
+
32
+ ```json
33
+ {
34
+ "name": "@example/my-schemas",
35
+ "atcute:lexicons": {
36
+ "mappings": {
37
+ "com.example.*": {
38
+ "type": "namespace",
39
+ "path": "./types/{{nsid_remainder}}"
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ the `path` field supports several template expansions:
47
+
48
+ - `.` or `./` at the start is replaced with the package name (e.g., `./types/foo` becomes
49
+ `@example/my-schemas/types/foo`, or `.` becomes `@example/my-schemas`)
50
+ - `{{nsid}}` - the full NSID with dots replaced by slashes (e.g., `com/example/foo/bar`)
51
+ - `{{nsid_prefix}}` - the part before the wildcard (e.g., `com/example`)
52
+ - `{{nsid_remainder}}` - the part after the prefix (e.g., `foo/bar`)
27
53
 
28
54
  ## external references
29
55
 
30
56
  when your lexicons reference types from namespaces outside your configured files, you'll need to
31
- configure mappings to resolve these references.
57
+ configure how these references are resolved.
32
58
 
33
59
  for example, if your lexicon references a type from another namespace:
34
60
 
@@ -54,7 +80,25 @@ for example, if your lexicon references a type from another namespace:
54
80
  }
55
81
  ```
56
82
 
57
- define mappings in your configuration to specify how external namespaces should be imported:
83
+ the simplest way to resolve external references is using the `imports` array with packages that
84
+ provide the `atcute:lexicons` metadata:
85
+
86
+ ```ts
87
+ // file: lex.config.js
88
+ import { defineLexiconConfig } from '@atcute/lex-cli';
89
+
90
+ export default defineLexiconConfig({
91
+ files: ['lexicons/**/*.json'],
92
+ outdir: 'src/lexicons/',
93
+ imports: ['@atcute/atproto', '@atcute/bluesky'],
94
+ });
95
+ ```
96
+
97
+ the CLI will automatically discover the namespace mappings from each package's `atcute:lexicons`
98
+ field in their package.json.
99
+
100
+ for packages without metadata, or when you need more fine-grained control over import resolution,
101
+ use the `mappings` configuration instead:
58
102
 
59
103
  ```ts
60
104
  // file: lex.config.js
@@ -81,6 +125,3 @@ export default defineLexiconConfig({
81
125
  ],
82
126
  });
83
127
  ```
84
-
85
- with this configuration, any reference to a lexicon in the `com.atproto.*` or `app.bsky.*` namespace
86
- will be imported from `@atcute/atproto` or `@atcute/bluesky`, respectively.
package/dist/cli.js CHANGED
@@ -1,85 +1,167 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import * as url from 'node:url';
4
- import { Builtins, Command, Option, Program } from '@externdefs/collider';
4
+ import { object } from '@optique/core/constructs';
5
+ import { command, constant, option } from '@optique/core/primitives';
6
+ import { run } from '@optique/run';
7
+ import { path as pathParser } from '@optique/run/valueparser';
5
8
  import pc from 'picocolors';
6
9
  import { lexiconDoc } from '@atcute/lexicon-doc';
7
10
  import { generateLexiconApi } from './codegen.js';
8
- const program = new Program({ binaryName: 'lex-cli' });
9
- program.register(Builtins.HelpCommand);
10
- program.register(class GenerateCommand extends Command {
11
- static paths = [['generate']];
12
- static usage = Command.Usage({
13
- description: `Generates TypeScript schema`,
14
- });
15
- config = Option.String(['-c', '--config'], {
16
- required: true,
17
- description: `Config file`,
18
- });
19
- async execute() {
20
- const configFilename = path.resolve(this.config);
21
- const configDirname = path.dirname(configFilename);
22
- let config;
23
- try {
24
- const configURL = url.pathToFileURL(configFilename);
25
- const configMod = (await import(configURL.href));
26
- config = configMod.default;
27
- }
28
- catch (err) {
29
- console.error(pc.bold(pc.red(`failed to import config:`)));
30
- console.error(err);
31
- return 1;
32
- }
33
- const documents = [];
34
- for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
35
- let source;
36
- try {
37
- source = await fs.readFile(path.join(configDirname, filename), 'utf8');
38
- }
39
- catch (err) {
40
- console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
41
- console.error(err);
42
- return 1;
43
- }
44
- let json;
11
+ import { validatePackageJson } from './lexicon-metadata.js';
12
+ /**
13
+ * Resolves package imports to ImportMapping[]
14
+ */
15
+ const resolveImportsToMappings = async (imports, configDirname) => {
16
+ const mappings = [];
17
+ for (const packageName of imports) {
18
+ // Walk up from config directory to find package in node_modules
19
+ let packageJson;
20
+ let currentDir = configDirname;
21
+ let found = false;
22
+ while (currentDir !== path.dirname(currentDir)) {
23
+ const candidatePath = path.join(currentDir, 'node_modules', packageName, 'package.json');
45
24
  try {
46
- json = JSON.parse(source);
25
+ const content = await fs.readFile(candidatePath, 'utf8');
26
+ packageJson = JSON.parse(content);
27
+ found = true;
28
+ break;
47
29
  }
48
30
  catch (err) {
49
- console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
50
- console.error(err);
51
- return 1;
52
- }
53
- const result = lexiconDoc.try(json, { mode: 'strip' });
54
- if (!result.ok) {
55
- console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
56
- console.error(result.message);
57
- for (const issue of result.issues) {
58
- console.log(`- ${issue.code} at .${issue.path.join('.')}`);
31
+ // Only continue to parent if file not found
32
+ if (err.code !== 'ENOENT') {
33
+ console.error(pc.bold(pc.red(`failed to read package.json for "${packageName}":`)));
34
+ console.error(err);
35
+ process.exit(1);
59
36
  }
60
- return 1;
37
+ // Not found, try parent directory
38
+ currentDir = path.dirname(currentDir);
61
39
  }
62
- documents.push(result.value);
63
40
  }
64
- const result = await generateLexiconApi({
65
- documents: documents,
66
- mappings: config.mappings ?? [],
67
- modules: {
68
- importSuffix: config.modules?.importSuffix ?? '.js',
69
- },
70
- prettier: {
71
- cwd: process.cwd(),
72
- },
73
- });
74
- const outdir = path.join(configDirname, config.outdir);
75
- for (const file of result.files) {
76
- const filename = path.join(outdir, file.filename);
77
- const dirname = path.dirname(filename);
78
- await fs.mkdir(dirname, { recursive: true });
79
- await fs.writeFile(filename, file.code);
41
+ if (!found) {
42
+ console.error(pc.bold(pc.red(`failed to resolve package "${packageName}"`)));
43
+ console.error(`Could not find package in node_modules starting from ${configDirname}`);
44
+ process.exit(1);
45
+ }
46
+ // Validate package.json
47
+ const result = validatePackageJson(packageJson);
48
+ if (!result.success) {
49
+ console.error(pc.bold(pc.red(`invalid atcute:lexicons in "${packageName}":`)));
50
+ console.error(result.issues);
51
+ process.exit(1);
52
+ }
53
+ const lexicons = result.output['atcute:lexicons'];
54
+ if (!lexicons?.mappings) {
55
+ continue;
56
+ }
57
+ // Convert mapping to ImportMapping[]
58
+ for (const [pattern, entry] of Object.entries(lexicons.mappings)) {
59
+ const isWildcard = pattern.endsWith('.*');
60
+ mappings.push({
61
+ nsid: [pattern],
62
+ imports: (nsid) => {
63
+ // Check if pattern matches
64
+ if (isWildcard) {
65
+ if (!nsid.startsWith(pattern.slice(0, -1))) {
66
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
67
+ }
68
+ }
69
+ else {
70
+ if (nsid !== pattern) {
71
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
72
+ }
73
+ }
74
+ const nsidPrefix = isWildcard ? pattern.slice(0, -2) : pattern;
75
+ const nsidRemainder = isWildcard ? nsid.slice(nsidPrefix.length + 1) : '';
76
+ let expandedPath = entry.path
77
+ .replaceAll('{{nsid}}', nsid.replaceAll('.', '/'))
78
+ .replaceAll('{{nsid_remainder}}', nsidRemainder.replaceAll('.', '/'))
79
+ .replaceAll('{{nsid_prefix}}', nsidPrefix.replaceAll('.', '/'));
80
+ if (expandedPath === '.') {
81
+ expandedPath = packageName;
82
+ }
83
+ else if (expandedPath.startsWith('./')) {
84
+ expandedPath = `${packageName}/${expandedPath.slice(2)}`;
85
+ }
86
+ return {
87
+ type: entry.type,
88
+ from: expandedPath,
89
+ };
90
+ },
91
+ });
92
+ }
93
+ }
94
+ return mappings;
95
+ };
96
+ const parser = command('generate', object({
97
+ type: constant('generate'),
98
+ config: option('-c', '--config', pathParser({ metavar: 'CONFIG' })),
99
+ }));
100
+ const result = run(parser, { programName: 'lex-cli' });
101
+ if (result.type === 'generate') {
102
+ const configFilename = path.resolve(result.config);
103
+ const configDirname = path.dirname(configFilename);
104
+ let config;
105
+ try {
106
+ const configURL = url.pathToFileURL(configFilename);
107
+ const configMod = (await import(configURL.href));
108
+ config = configMod.default;
109
+ }
110
+ catch (err) {
111
+ console.error(pc.bold(pc.red(`failed to import config:`)));
112
+ console.error(err);
113
+ process.exit(1);
114
+ }
115
+ // Resolve imports to mappings
116
+ const importMappings = config.imports ? await resolveImportsToMappings(config.imports, configDirname) : [];
117
+ const allMappings = [...importMappings, ...(config.mappings ?? [])];
118
+ const documents = [];
119
+ for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
120
+ let source;
121
+ try {
122
+ source = await fs.readFile(path.join(configDirname, filename), 'utf8');
123
+ }
124
+ catch (err) {
125
+ console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
126
+ console.error(err);
127
+ process.exit(1);
128
+ }
129
+ let json;
130
+ try {
131
+ json = JSON.parse(source);
132
+ }
133
+ catch (err) {
134
+ console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
135
+ console.error(err);
136
+ process.exit(1);
80
137
  }
138
+ const result = lexiconDoc.try(json, { mode: 'strip' });
139
+ if (!result.ok) {
140
+ console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
141
+ console.error(result.message);
142
+ for (const issue of result.issues) {
143
+ console.log(`- ${issue.code} at .${issue.path.join('.')}`);
144
+ }
145
+ process.exit(1);
146
+ }
147
+ documents.push(result.value);
148
+ }
149
+ const generationResult = await generateLexiconApi({
150
+ documents: documents,
151
+ mappings: allMappings,
152
+ modules: {
153
+ importSuffix: config.modules?.importSuffix ?? '.js',
154
+ },
155
+ prettier: {
156
+ cwd: process.cwd(),
157
+ },
158
+ });
159
+ const outdir = path.join(configDirname, config.outdir);
160
+ for (const file of generationResult.files) {
161
+ const filename = path.join(outdir, file.filename);
162
+ const dirname = path.dirname(filename);
163
+ await fs.mkdir(dirname, { recursive: true });
164
+ await fs.writeFile(filename, file.code);
81
165
  }
82
- });
83
- const exitCode = await program.run(process.argv.slice(2));
84
- process.exitCode = exitCode;
166
+ }
85
167
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAEhC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,OAAO,EAAE,UAAU,EAAmB,MAAM,qBAAqB,CAAC;AAElE,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC;AAEvD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAEvC,OAAO,CAAC,QAAQ,CACf,MAAM,eAAgB,SAAQ,OAAO;IACpC,MAAM,CAAU,KAAK,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;IAEvC,MAAM,CAAU,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QACrC,WAAW,EAAE,6BAA6B;KAC1C,CAAC,CAAC;IAEH,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE;QAC1C,QAAQ,EAAE,IAAI;QACd,WAAW,EAAE,aAAa;KAC1B,CAAC,CAAC;IAEH,KAAK,CAAC,OAAO;QACZ,MAAM,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AE,CAAC,CAAC;QAC7C,MAAM,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;AACF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { ImportMapping } from './codegen.js';
2
2
  export interface LexiconConfig {
3
3
  outdir: string;
4
4
  files: string[];
5
+ imports?: string[];
5
6
  mappings?: ImportMapping[];
6
7
  modules?: {
7
8
  importSuffix?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,WAAW,aAAa;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,CAAC,EAAE;QACT,YAAY,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;CACF;AAED,eAAO,MAAM,mBAAmB,GAAI,QAAQ,aAAa,KAAG,aAE3D,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,WAAW,aAAa;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,CAAC,EAAE;QACT,YAAY,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;CACF;AAED,eAAO,MAAM,mBAAmB,GAAI,QAAQ,aAAa,KAAG,aAE3D,CAAC"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,MAAqB,EAAiB,EAAE;IAC3E,OAAO,MAAM,CAAC;AACf,CAAC,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,MAAqB,EAAiB,EAAE;IAC3E,OAAO,MAAM,CAAC;AACf,CAAC,CAAC"}
@@ -0,0 +1,37 @@
1
+ import * as v from 'valibot';
2
+ /**
3
+ * Schema for a single lexicon mapping entry
4
+ */
5
+ declare const lexiconMappingEntry: v.ObjectSchema<{
6
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
7
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
8
+ }, undefined>;
9
+ /**
10
+ * Schema for the atcute:lexicons field in package.json
11
+ */
12
+ declare const atcuteLexiconsField: v.ObjectSchema<{
13
+ readonly mappings: v.OptionalSchema<v.RecordSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "invalid NSID pattern (must be valid NSID or end with .*)">]>, v.ObjectSchema<{
14
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
15
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
16
+ }, undefined>, undefined>, undefined>;
17
+ }, undefined>;
18
+ /**
19
+ * Schema for package.json with atcute:lexicons field
20
+ */
21
+ export declare const packageJsonSchema: v.LooseObjectSchema<{
22
+ readonly 'atcute:lexicons': v.OptionalSchema<v.ObjectSchema<{
23
+ readonly mappings: v.OptionalSchema<v.RecordSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "invalid NSID pattern (must be valid NSID or end with .*)">]>, v.ObjectSchema<{
24
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
25
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
26
+ }, undefined>, undefined>, undefined>;
27
+ }, undefined>, undefined>;
28
+ }, undefined>;
29
+ export type LexiconMappingEntry = v.InferOutput<typeof lexiconMappingEntry>;
30
+ export type AtcuteLexiconsField = v.InferOutput<typeof atcuteLexiconsField>;
31
+ export type PackageJsonWithLexicons = v.InferOutput<typeof packageJsonSchema>;
32
+ /**
33
+ * Validates a package.json object against the schema
34
+ */
35
+ export declare const validatePackageJson: (data: unknown) => v.SafeParseResult<typeof packageJsonSchema>;
36
+ export {};
37
+ //# sourceMappingURL=lexicon-metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lexicon-metadata.d.ts","sourceRoot":"","sources":["../src/lexicon-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAmB7B;;GAEG;AACH,QAAA,MAAM,mBAAmB;;;aAGvB,CAAC;AAEH;;GAEG;AACH,QAAA,MAAM,mBAAmB;;;;;aAUvB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;aAE5B,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC5E,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC5E,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE9E;;GAEG;AACH,eAAO,MAAM,mBAAmB,GAAI,MAAM,OAAO,KAAG,CAAC,CAAC,eAAe,CAAC,OAAO,iBAAiB,CAE7F,CAAC"}
@@ -0,0 +1,42 @@
1
+ import * as v from 'valibot';
2
+ import { isNsid } from '@atcute/lexicons/syntax';
3
+ /**
4
+ * Validates if a string is a valid NSID pattern (exact or wildcard)
5
+ * - Exact: "com.atproto.repo.getRecord"
6
+ * - Wildcard: "com.atproto.*"
7
+ */
8
+ const isValidLexiconPattern = (pattern) => {
9
+ if (pattern.endsWith('.*')) {
10
+ // For wildcards, remove the .* and validate the prefix as an NSID segment
11
+ const prefix = pattern.slice(0, -2);
12
+ // Add a dummy segment to make it a valid NSID for validation
13
+ return isNsid(prefix + '.x');
14
+ }
15
+ return isNsid(pattern);
16
+ };
17
+ /**
18
+ * Schema for a single lexicon mapping entry
19
+ */
20
+ const lexiconMappingEntry = v.object({
21
+ type: v.picklist(['namespace', 'named']),
22
+ path: v.pipe(v.string(), v.regex(/^\.$|^\.\//, `path must be "." or start with "./"`)),
23
+ });
24
+ /**
25
+ * Schema for the atcute:lexicons field in package.json
26
+ */
27
+ const atcuteLexiconsField = v.object({
28
+ mappings: v.optional(v.record(v.pipe(v.string(), v.check(isValidLexiconPattern, `invalid NSID pattern (must be valid NSID or end with .*)`)), lexiconMappingEntry)),
29
+ });
30
+ /**
31
+ * Schema for package.json with atcute:lexicons field
32
+ */
33
+ export const packageJsonSchema = v.looseObject({
34
+ 'atcute:lexicons': v.optional(atcuteLexiconsField),
35
+ });
36
+ /**
37
+ * Validates a package.json object against the schema
38
+ */
39
+ export const validatePackageJson = (data) => {
40
+ return v.safeParse(packageJsonSchema, data);
41
+ };
42
+ //# sourceMappingURL=lexicon-metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lexicon-metadata.js","sourceRoot":"","sources":["../src/lexicon-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEjD;;;;GAIG;AACH,MAAM,qBAAqB,GAAG,CAAC,OAAe,EAAW,EAAE;IAC1D,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5B,0EAA0E;QAC1E,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACpC,6DAA6D;QAC7D,OAAO,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACxB,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IACxC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,qCAAqC,CAAC,CAAC;CACtF,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CACnB,CAAC,CAAC,MAAM,CACP,CAAC,CAAC,IAAI,CACL,CAAC,CAAC,MAAM,EAAE,EACV,CAAC,CAAC,KAAK,CAAC,qBAAqB,EAAE,0DAA0D,CAAC,CAC1F,EACD,mBAAmB,CACnB,CACD;CACD,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9C,iBAAiB,EAAE,CAAC,CAAC,QAAQ,CAAC,mBAAmB,CAAC;CAClD,CAAC,CAAC;AAMH;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,IAAa,EAA+C,EAAE;IACjG,OAAO,CAAC,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;AAC7C,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@atcute/lex-cli",
4
- "version": "2.2.2",
4
+ "version": "2.3.0",
5
5
  "description": "cli tool to generate type definitions for atcute",
6
6
  "license": "0BSD",
7
7
  "repository": {
@@ -13,7 +13,8 @@
13
13
  "src/",
14
14
  "!src/**/*.bench.ts",
15
15
  "!src/**/*.test.ts",
16
- "cli.mjs"
16
+ "cli.mjs",
17
+ "schema/"
17
18
  ],
18
19
  "bin": "./cli.mjs",
19
20
  "exports": {
@@ -21,17 +22,21 @@
21
22
  },
22
23
  "dependencies": {
23
24
  "@badrap/valita": "^0.4.6",
24
- "@externdefs/collider": "^0.3.0",
25
+ "@optique/core": "^0.6.1",
26
+ "@optique/run": "^0.6.1",
25
27
  "picocolors": "^1.1.1",
26
28
  "prettier": "^3.6.2",
27
- "@atcute/lexicon-doc": "^1.1.2"
29
+ "valibot": "^1.0.0",
30
+ "@atcute/lexicon-doc": "^1.1.3"
28
31
  },
29
32
  "devDependencies": {
30
33
  "@types/node": "^22.18.0",
34
+ "@valibot/to-json-schema": "^1.3.0",
31
35
  "@atcute/lexicons": "^1.2.2"
32
36
  },
33
37
  "scripts": {
34
- "build": "tsc",
38
+ "build": "pnpm run generate:schema && tsc",
39
+ "generate:schema": "node scripts/generate-schema.ts",
35
40
  "prepublish": "rm -rf dist; pnpm run build"
36
41
  }
37
42
  }
@@ -0,0 +1,38 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://unpkg.com/@atcute/lex-cli/schema/lexicon-package.schema.json",
4
+ "title": "package.json with atcute:lexicons",
5
+ "description": "JSON Schema for package.json with atcute:lexicons field for lexicon import mappings",
6
+ "type": "object",
7
+ "properties": {
8
+ "atcute:lexicons": {
9
+ "type": "object",
10
+ "properties": {
11
+ "mappings": {
12
+ "type": "object",
13
+ "additionalProperties": {
14
+ "type": "object",
15
+ "properties": {
16
+ "type": {
17
+ "enum": [
18
+ "namespace",
19
+ "named"
20
+ ]
21
+ },
22
+ "path": {
23
+ "type": "string",
24
+ "pattern": "^\\.$|^\\.\\/"
25
+ }
26
+ },
27
+ "required": [
28
+ "type",
29
+ "path"
30
+ ]
31
+ }
32
+ }
33
+ },
34
+ "required": []
35
+ }
36
+ },
37
+ "required": []
38
+ }
package/src/cli.ts CHANGED
@@ -2,108 +2,202 @@ import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import * as url from 'node:url';
4
4
 
5
- import { Builtins, Command, Option, Program } from '@externdefs/collider';
5
+ import { object } from '@optique/core/constructs';
6
+ import { command, constant, option } from '@optique/core/primitives';
7
+ import { run } from '@optique/run';
8
+ import { path as pathParser } from '@optique/run/valueparser';
6
9
  import pc from 'picocolors';
7
10
 
8
11
  import { lexiconDoc, type LexiconDoc } from '@atcute/lexicon-doc';
9
12
 
10
- import { generateLexiconApi } from './codegen.js';
13
+ import { generateLexiconApi, type ImportMapping } from './codegen.js';
11
14
  import type { LexiconConfig } from './index.js';
15
+ import { validatePackageJson } from './lexicon-metadata.js';
16
+
17
+ /**
18
+ * Resolves package imports to ImportMapping[]
19
+ */
20
+ const resolveImportsToMappings = async (
21
+ imports: string[],
22
+ configDirname: string,
23
+ ): Promise<ImportMapping[]> => {
24
+ const mappings: ImportMapping[] = [];
25
+
26
+ for (const packageName of imports) {
27
+ // Walk up from config directory to find package in node_modules
28
+ let packageJson: unknown;
29
+ let currentDir = configDirname;
30
+ let found = false;
31
+
32
+ while (currentDir !== path.dirname(currentDir)) {
33
+ const candidatePath = path.join(currentDir, 'node_modules', packageName, 'package.json');
34
+ try {
35
+ const content = await fs.readFile(candidatePath, 'utf8');
36
+ packageJson = JSON.parse(content);
37
+ found = true;
38
+ break;
39
+ } catch (err: any) {
40
+ // Only continue to parent if file not found
41
+ if (err.code !== 'ENOENT') {
42
+ console.error(pc.bold(pc.red(`failed to read package.json for "${packageName}":`)));
43
+ console.error(err);
44
+ process.exit(1);
45
+ }
12
46
 
13
- const program = new Program({ binaryName: 'lex-cli' });
47
+ // Not found, try parent directory
48
+ currentDir = path.dirname(currentDir);
49
+ }
50
+ }
14
51
 
15
- program.register(Builtins.HelpCommand);
52
+ if (!found) {
53
+ console.error(pc.bold(pc.red(`failed to resolve package "${packageName}"`)));
54
+ console.error(`Could not find package in node_modules starting from ${configDirname}`);
55
+ process.exit(1);
56
+ }
16
57
 
17
- program.register(
18
- class GenerateCommand extends Command {
19
- static override paths = [['generate']];
58
+ // Validate package.json
59
+ const result = validatePackageJson(packageJson);
60
+ if (!result.success) {
61
+ console.error(pc.bold(pc.red(`invalid atcute:lexicons in "${packageName}":`)));
62
+ console.error(result.issues);
63
+ process.exit(1);
64
+ }
20
65
 
21
- static override usage = Command.Usage({
22
- description: `Generates TypeScript schema`,
23
- });
66
+ const lexicons = result.output['atcute:lexicons'];
67
+ if (!lexicons?.mappings) {
68
+ continue;
69
+ }
24
70
 
25
- config = Option.String(['-c', '--config'], {
26
- required: true,
27
- description: `Config file`,
28
- });
71
+ // Convert mapping to ImportMapping[]
72
+ for (const [pattern, entry] of Object.entries(lexicons.mappings)) {
73
+ const isWildcard = pattern.endsWith('.*');
74
+
75
+ mappings.push({
76
+ nsid: [pattern],
77
+ imports: (nsid: string) => {
78
+ // Check if pattern matches
79
+ if (isWildcard) {
80
+ if (!nsid.startsWith(pattern.slice(0, -1))) {
81
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
82
+ }
83
+ } else {
84
+ if (nsid !== pattern) {
85
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
86
+ }
87
+ }
29
88
 
30
- async execute(): Promise<number | void> {
31
- const configFilename = path.resolve(this.config);
32
- const configDirname = path.dirname(configFilename);
89
+ const nsidPrefix = isWildcard ? pattern.slice(0, -2) : pattern;
90
+ const nsidRemainder = isWildcard ? nsid.slice(nsidPrefix.length + 1) : '';
33
91
 
34
- let config: LexiconConfig;
35
- try {
36
- const configURL = url.pathToFileURL(configFilename);
37
- const configMod = (await import(configURL.href)) as { default: LexiconConfig };
38
- config = configMod.default;
39
- } catch (err) {
40
- console.error(pc.bold(pc.red(`failed to import config:`)));
41
- console.error(err);
42
-
43
- return 1;
44
- }
92
+ let expandedPath = entry.path
93
+ .replaceAll('{{nsid}}', nsid.replaceAll('.', '/'))
94
+ .replaceAll('{{nsid_remainder}}', nsidRemainder.replaceAll('.', '/'))
95
+ .replaceAll('{{nsid_prefix}}', nsidPrefix.replaceAll('.', '/'));
45
96
 
46
- const documents: LexiconDoc[] = [];
97
+ if (expandedPath === '.') {
98
+ expandedPath = packageName;
99
+ } else if (expandedPath.startsWith('./')) {
100
+ expandedPath = `${packageName}/${expandedPath.slice(2)}`;
101
+ }
47
102
 
48
- for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
49
- let source: string;
50
- try {
51
- source = await fs.readFile(path.join(configDirname, filename), 'utf8');
52
- } catch (err) {
53
- console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
54
- console.error(err);
103
+ return {
104
+ type: entry.type,
105
+ from: expandedPath,
106
+ };
107
+ },
108
+ });
109
+ }
110
+ }
55
111
 
56
- return 1;
57
- }
112
+ return mappings;
113
+ };
58
114
 
59
- let json: unknown;
60
- try {
61
- json = JSON.parse(source);
62
- } catch (err) {
63
- console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
64
- console.error(err);
115
+ const parser = command(
116
+ 'generate',
117
+ object({
118
+ type: constant('generate'),
119
+ config: option('-c', '--config', pathParser({ metavar: 'CONFIG' })),
120
+ }),
121
+ );
65
122
 
66
- return 1;
67
- }
123
+ const result = run(parser, { programName: 'lex-cli' });
68
124
 
69
- const result = lexiconDoc.try(json, { mode: 'strip' });
70
- if (!result.ok) {
71
- console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
72
- console.error(result.message);
125
+ if (result.type === 'generate') {
126
+ const configFilename = path.resolve(result.config);
127
+ const configDirname = path.dirname(configFilename);
73
128
 
74
- for (const issue of result.issues) {
75
- console.log(`- ${issue.code} at .${issue.path.join('.')}`);
76
- }
129
+ let config: LexiconConfig;
130
+ try {
131
+ const configURL = url.pathToFileURL(configFilename);
132
+ const configMod = (await import(configURL.href)) as { default: LexiconConfig };
133
+ config = configMod.default;
134
+ } catch (err) {
135
+ console.error(pc.bold(pc.red(`failed to import config:`)));
136
+ console.error(err);
77
137
 
78
- return 1;
79
- }
138
+ process.exit(1);
139
+ }
80
140
 
81
- documents.push(result.value);
82
- }
141
+ // Resolve imports to mappings
142
+ const importMappings = config.imports ? await resolveImportsToMappings(config.imports, configDirname) : [];
143
+ const allMappings = [...importMappings, ...(config.mappings ?? [])];
83
144
 
84
- const result = await generateLexiconApi({
85
- documents: documents,
86
- mappings: config.mappings ?? [],
87
- modules: {
88
- importSuffix: config.modules?.importSuffix ?? '.js',
89
- },
90
- prettier: {
91
- cwd: process.cwd(),
92
- },
93
- });
145
+ const documents: LexiconDoc[] = [];
146
+
147
+ for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
148
+ let source: string;
149
+ try {
150
+ source = await fs.readFile(path.join(configDirname, filename), 'utf8');
151
+ } catch (err) {
152
+ console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
153
+ console.error(err);
154
+
155
+ process.exit(1);
156
+ }
94
157
 
95
- const outdir = path.join(configDirname, config.outdir);
158
+ let json: unknown;
159
+ try {
160
+ json = JSON.parse(source);
161
+ } catch (err) {
162
+ console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
163
+ console.error(err);
96
164
 
97
- for (const file of result.files) {
98
- const filename = path.join(outdir, file.filename);
99
- const dirname = path.dirname(filename);
165
+ process.exit(1);
166
+ }
167
+
168
+ const result = lexiconDoc.try(json, { mode: 'strip' });
169
+ if (!result.ok) {
170
+ console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
171
+ console.error(result.message);
100
172
 
101
- await fs.mkdir(dirname, { recursive: true });
102
- await fs.writeFile(filename, file.code);
173
+ for (const issue of result.issues) {
174
+ console.log(`- ${issue.code} at .${issue.path.join('.')}`);
103
175
  }
176
+
177
+ process.exit(1);
104
178
  }
105
- },
106
- );
107
179
 
108
- const exitCode = await program.run(process.argv.slice(2));
109
- process.exitCode = exitCode;
180
+ documents.push(result.value);
181
+ }
182
+
183
+ const generationResult = await generateLexiconApi({
184
+ documents: documents,
185
+ mappings: allMappings,
186
+ modules: {
187
+ importSuffix: config.modules?.importSuffix ?? '.js',
188
+ },
189
+ prettier: {
190
+ cwd: process.cwd(),
191
+ },
192
+ });
193
+
194
+ const outdir = path.join(configDirname, config.outdir);
195
+
196
+ for (const file of generationResult.files) {
197
+ const filename = path.join(outdir, file.filename);
198
+ const dirname = path.dirname(filename);
199
+
200
+ await fs.mkdir(dirname, { recursive: true });
201
+ await fs.writeFile(filename, file.code);
202
+ }
203
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import type { ImportMapping } from './codegen.js';
3
3
  export interface LexiconConfig {
4
4
  outdir: string;
5
5
  files: string[];
6
+ imports?: string[];
6
7
  mappings?: ImportMapping[];
7
8
  modules?: {
8
9
  importSuffix?: string;
@@ -0,0 +1,59 @@
1
+ import * as v from 'valibot';
2
+
3
+ import { isNsid } from '@atcute/lexicons/syntax';
4
+
5
+ /**
6
+ * Validates if a string is a valid NSID pattern (exact or wildcard)
7
+ * - Exact: "com.atproto.repo.getRecord"
8
+ * - Wildcard: "com.atproto.*"
9
+ */
10
+ const isValidLexiconPattern = (pattern: string): boolean => {
11
+ if (pattern.endsWith('.*')) {
12
+ // For wildcards, remove the .* and validate the prefix as an NSID segment
13
+ const prefix = pattern.slice(0, -2);
14
+ // Add a dummy segment to make it a valid NSID for validation
15
+ return isNsid(prefix + '.x');
16
+ }
17
+ return isNsid(pattern);
18
+ };
19
+
20
+ /**
21
+ * Schema for a single lexicon mapping entry
22
+ */
23
+ const lexiconMappingEntry = v.object({
24
+ type: v.picklist(['namespace', 'named']),
25
+ path: v.pipe(v.string(), v.regex(/^\.$|^\.\//, `path must be "." or start with "./"`)),
26
+ });
27
+
28
+ /**
29
+ * Schema for the atcute:lexicons field in package.json
30
+ */
31
+ const atcuteLexiconsField = v.object({
32
+ mappings: v.optional(
33
+ v.record(
34
+ v.pipe(
35
+ v.string(),
36
+ v.check(isValidLexiconPattern, `invalid NSID pattern (must be valid NSID or end with .*)`),
37
+ ),
38
+ lexiconMappingEntry,
39
+ ),
40
+ ),
41
+ });
42
+
43
+ /**
44
+ * Schema for package.json with atcute:lexicons field
45
+ */
46
+ export const packageJsonSchema = v.looseObject({
47
+ 'atcute:lexicons': v.optional(atcuteLexiconsField),
48
+ });
49
+
50
+ export type LexiconMappingEntry = v.InferOutput<typeof lexiconMappingEntry>;
51
+ export type AtcuteLexiconsField = v.InferOutput<typeof atcuteLexiconsField>;
52
+ export type PackageJsonWithLexicons = v.InferOutput<typeof packageJsonSchema>;
53
+
54
+ /**
55
+ * Validates a package.json object against the schema
56
+ */
57
+ export const validatePackageJson = (data: unknown): v.SafeParseResult<typeof packageJsonSchema> => {
58
+ return v.safeParse(packageJsonSchema, data);
59
+ };