@amritk/mjst 0.5.1 → 0.7.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 +42 -4
- package/dist/cli-config.d.ts +27 -3
- package/dist/cli.js +442 -250
- package/dist/combine-files.d.ts +13 -0
- package/dist/parse-cli-args.d.ts +4 -2
- package/dist/read-version.d.ts +8 -0
- package/package.json +4 -4
- package/src/cli-config.ts +27 -3
- package/src/cli.ts +269 -67
- package/src/combine-files.test.ts +49 -0
- package/src/combine-files.ts +43 -0
- package/src/load-config.test.ts +9 -0
- package/src/load-config.ts +3 -0
- package/src/parse-cli-args.test.ts +48 -0
- package/src/parse-cli-args.ts +123 -94
- package/src/read-version.test.ts +18 -0
- package/src/read-version.ts +14 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { GeneratedFile } from '@amritk/generate-parsers';
|
|
2
|
+
/**
|
|
3
|
+
* Merges the per-schema {@link GeneratedFile}s into a single self-contained
|
|
4
|
+
* TypeScript module. Each generated file imports its sibling definitions via
|
|
5
|
+
* relative paths; since everything now lives in one file those imports are
|
|
6
|
+
* dropped, while any external (package) imports are hoisted to the top and
|
|
7
|
+
* deduplicated. The `index.ts` barrel is skipped because it only re-exports the
|
|
8
|
+
* declarations that are already inlined here.
|
|
9
|
+
*
|
|
10
|
+
* Intended for types-only output, where files contain only type definitions and
|
|
11
|
+
* type-only relative imports (no runtime helpers).
|
|
12
|
+
*/
|
|
13
|
+
export declare const combineGeneratedFiles: (files: readonly GeneratedFile[]) => string;
|
package/dist/parse-cli-args.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { CliConfig } from './cli-config';
|
|
2
2
|
/**
|
|
3
3
|
* Parses command-line arguments into a partial CLI config.
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Every flag accepts both kebab-case and camelCase (e.g. `--out-dir` and `--outDir`)
|
|
5
|
+
* and supports either `--flag value` or `--flag=value` syntax. Boolean flags toggle
|
|
6
|
+
* on by presence and accept `--flag=false` to opt out. Only flags that were explicitly
|
|
7
|
+
* provided are returned so they can be layered on top of config file values.
|
|
6
8
|
*/
|
|
7
9
|
export declare const parseCliArgs: (args: readonly string[]) => Partial<CliConfig>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the CLI's own version from its `package.json`.
|
|
3
|
+
*
|
|
4
|
+
* Resolved relative to this module so it works whether the code runs from
|
|
5
|
+
* `src/` (dev) or the bundled `dist/cli.js` (published) — `package.json`
|
|
6
|
+
* sits one directory above both.
|
|
7
|
+
*/
|
|
8
|
+
export declare const readVersion: () => Promise<string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/mjst",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Generate TypeScript parsers and type definitions from JSON Schemas.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -42,10 +42,10 @@
|
|
|
42
42
|
"generate-readme": "bun run ./scripts/generate-readme.ts"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@amritk/adapters": "0.2.
|
|
46
|
-
"@amritk/generate-parsers": "0.
|
|
45
|
+
"@amritk/adapters": "0.2.3",
|
|
46
|
+
"@amritk/generate-parsers": "0.6.0",
|
|
47
47
|
"@amritk/generate-markdown": "0.2.1",
|
|
48
|
-
"@amritk/helpers": "0.
|
|
48
|
+
"@amritk/helpers": "0.6.0"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"json-schema-typed": "^8.0.1"
|
package/src/cli-config.ts
CHANGED
|
@@ -6,7 +6,15 @@ import type { SourceFormat } from '@amritk/adapters/source-format'
|
|
|
6
6
|
*/
|
|
7
7
|
export type CliConfig = {
|
|
8
8
|
/** Path to the schema to process — a JSON Schema file, or a JS/TS module when `input` is set. */
|
|
9
|
-
readonly schema
|
|
9
|
+
readonly schema?: string
|
|
10
|
+
/**
|
|
11
|
+
* Path to a directory of JSON Schema files. When set, the CLI walks the directory
|
|
12
|
+
* recursively, generates parsers for every `*.json` schema it finds, and mirrors the
|
|
13
|
+
* directory layout under `outDir`. A single shared `_helpers/` directory is emitted at
|
|
14
|
+
* the root of `outDir` (in embedded mode) and every nested parser imports from it.
|
|
15
|
+
* Mutually exclusive with `schema`; when both are present `schemaDir` wins.
|
|
16
|
+
*/
|
|
17
|
+
readonly schemaDir?: string
|
|
10
18
|
/**
|
|
11
19
|
* The source format of the schema. Defaults to `'json'` (a plain JSON Schema file).
|
|
12
20
|
* Any other format loads `schema` as a module and converts it via the matching adapter.
|
|
@@ -17,8 +25,13 @@ export type CliConfig = {
|
|
|
17
25
|
* Defaults to the default export, or the sole named export when there is exactly one.
|
|
18
26
|
*/
|
|
19
27
|
readonly export?: string
|
|
20
|
-
/** Output directory for generated TypeScript files. */
|
|
21
|
-
readonly outDir
|
|
28
|
+
/** Output directory for generated TypeScript files. Mutually exclusive with `outFile`. */
|
|
29
|
+
readonly outDir?: string
|
|
30
|
+
/**
|
|
31
|
+
* Output everything to a single TypeScript file instead of a directory of files.
|
|
32
|
+
* Mutually exclusive with `outDir`. Currently supported only with `typesOnly`.
|
|
33
|
+
*/
|
|
34
|
+
readonly outFile?: string
|
|
22
35
|
/**
|
|
23
36
|
* When true, only generate TypeScript type definitions without parser functions.
|
|
24
37
|
* Useful when you only need the type shapes and do not need runtime validation.
|
|
@@ -50,4 +63,15 @@ export type CliConfig = {
|
|
|
50
63
|
* resolves from outDir, otherwise falls back to `'embedded'`.
|
|
51
64
|
*/
|
|
52
65
|
readonly helpers?: 'package' | 'embedded'
|
|
66
|
+
/**
|
|
67
|
+
* When true, every property, array, and record in the generated type
|
|
68
|
+
* definitions is emitted as `readonly`, producing deeply immutable types.
|
|
69
|
+
*/
|
|
70
|
+
readonly readonly?: boolean
|
|
71
|
+
/**
|
|
72
|
+
* Suffix appended to every generated type name derived from a `$ref`
|
|
73
|
+
* (e.g. `'Object'` turns `Contact` into `ContactObject`). Defaults to `''`
|
|
74
|
+
* (no suffix). The root type name is used verbatim and is unaffected.
|
|
75
|
+
*/
|
|
76
|
+
readonly typeSuffix?: string
|
|
53
77
|
}
|
package/src/cli.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFile } from 'node:child_process'
|
|
3
|
-
import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
4
|
-
import { dirname, join, resolve } from 'node:path'
|
|
3
|
+
import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
|
|
5
5
|
import { promisify } from 'node:util'
|
|
6
6
|
import { getAdapter } from '@amritk/adapters/get-adapter'
|
|
7
7
|
import { buildSchema } from '@amritk/generate-parsers'
|
|
@@ -10,10 +10,17 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
|
10
10
|
|
|
11
11
|
const execFileAsync = promisify(execFile)
|
|
12
12
|
|
|
13
|
+
import type { CliConfig } from './cli-config'
|
|
14
|
+
import { combineGeneratedFiles } from './combine-files'
|
|
13
15
|
import { detectHelpersMode } from './detect-helpers-mode'
|
|
14
16
|
import { loadConfig } from './load-config'
|
|
15
17
|
import { loadSchemaModule } from './load-schema-module'
|
|
16
18
|
import { parseCliArgs } from './parse-cli-args'
|
|
19
|
+
import { readVersion } from './read-version'
|
|
20
|
+
|
|
21
|
+
/** True when the args request the CLI version (`version`, `--version`, or `-v`). */
|
|
22
|
+
const isVersionRequest = (args: readonly string[]): boolean =>
|
|
23
|
+
args[0] === 'version' || args.includes('--version') || args.includes('-v')
|
|
17
24
|
|
|
18
25
|
/**
|
|
19
26
|
* Extracts the --config flag value from process args before full parsing.
|
|
@@ -35,42 +42,93 @@ const extractConfigPath = (args: readonly string[]): string | undefined => {
|
|
|
35
42
|
return undefined
|
|
36
43
|
}
|
|
37
44
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
45
|
+
/** Reads a JSON Schema off disk, or loads a module and converts it via its adapter. */
|
|
46
|
+
const loadSchema = async (config: Partial<CliConfig>, schemaPath: string): Promise<unknown> => {
|
|
47
|
+
const inputFormat = config.input ?? 'json'
|
|
41
48
|
|
|
42
|
-
|
|
49
|
+
if (inputFormat === 'json') {
|
|
50
|
+
return JSON.parse(await readFile(schemaPath, 'utf-8'))
|
|
51
|
+
}
|
|
43
52
|
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
console.log(`Input format: ${inputFormat}`)
|
|
54
|
+
const source = await loadSchemaModule(schemaPath, config.export)
|
|
55
|
+
return getAdapter(inputFormat).toJSONSchema(source)
|
|
56
|
+
}
|
|
48
57
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
58
|
+
/** Writes a generated file, creating any parent directories the filename implies. */
|
|
59
|
+
const writeGeneratedFile = async (baseDir: string, filename: string, content: string): Promise<void> => {
|
|
60
|
+
const filePath = join(baseDir, filename)
|
|
61
|
+
await mkdir(dirname(filePath), { recursive: true })
|
|
62
|
+
await writeFile(filePath, content, 'utf-8')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Compiles the generated `.ts` files to `.js`/`.d.ts` with a temporary tsconfig,
|
|
67
|
+
* then removes the intermediate sources. `tsFiles` are paths relative to `outputDir`.
|
|
68
|
+
*/
|
|
69
|
+
const buildOutput = async (outputDir: string, tsFiles: readonly string[], typesOnly?: boolean): Promise<void> => {
|
|
70
|
+
// Write a minimal tsconfig so tsc can compile the generated files without
|
|
71
|
+
// inheriting settings like allowImportingTsExtensions that block emission.
|
|
72
|
+
// In 'package' mode tsc finds @amritk/helpers via the consumer's node_modules.
|
|
73
|
+
// In 'embedded' mode the helpers live under ./_helpers and need no resolution.
|
|
74
|
+
const tsconfigContent = JSON.stringify(
|
|
75
|
+
{
|
|
76
|
+
compilerOptions: {
|
|
77
|
+
target: 'ESNext',
|
|
78
|
+
module: 'ESNext',
|
|
79
|
+
moduleResolution: 'bundler',
|
|
80
|
+
declaration: true,
|
|
81
|
+
emitDeclarationOnly: typesOnly,
|
|
82
|
+
skipLibCheck: true,
|
|
83
|
+
},
|
|
84
|
+
include: tsFiles.map((file) => `./${file}`),
|
|
85
|
+
},
|
|
86
|
+
null,
|
|
87
|
+
2,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
const tsconfigPath = join(outputDir, '.tsconfig-mjst-build.json')
|
|
91
|
+
await writeFile(tsconfigPath, tsconfigContent, 'utf-8')
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
await execFileAsync('npx', ['tsc', '--project', tsconfigPath])
|
|
95
|
+
} catch {
|
|
96
|
+
throw new Error('TypeScript compilation failed. Check the generated files for errors.')
|
|
97
|
+
} finally {
|
|
98
|
+
await unlink(tsconfigPath)
|
|
52
99
|
}
|
|
53
100
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
101
|
+
// Remove the intermediate .ts files now that .js and .d.ts have been produced
|
|
102
|
+
for (const file of tsFiles) {
|
|
103
|
+
await unlink(join(outputDir, file))
|
|
104
|
+
console.log(`Built: ${file.replace(/\.ts$/, '.js')}`)
|
|
105
|
+
console.log(`Built: ${file.replace(/\.ts$/, '.d.ts')}`)
|
|
57
106
|
}
|
|
58
107
|
|
|
59
|
-
|
|
60
|
-
|
|
108
|
+
console.log(`\nTotal files built: ${tsFiles.length * 2}`)
|
|
109
|
+
}
|
|
61
110
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
111
|
+
/** Recursively collects every `*.json` file under `dir`, returning absolute paths. */
|
|
112
|
+
const findJsonSchemas = async (dir: string): Promise<string[]> => {
|
|
113
|
+
const entries = await readdir(dir, { withFileTypes: true })
|
|
114
|
+
const results: string[] = []
|
|
115
|
+
|
|
116
|
+
for (const entry of entries) {
|
|
117
|
+
const full = join(dir, entry.name)
|
|
118
|
+
if (entry.isDirectory()) {
|
|
119
|
+
results.push(...(await findJsonSchemas(full)))
|
|
120
|
+
} else if (entry.isFile() && entry.name.endsWith('.json')) {
|
|
121
|
+
results.push(full)
|
|
122
|
+
}
|
|
71
123
|
}
|
|
72
124
|
|
|
73
|
-
|
|
125
|
+
return results
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Generates parsers for a single schema (the original one-schema-in, one-outDir-out flow). */
|
|
129
|
+
const runSingle = async (config: Partial<CliConfig>, schemaPath: string, outputDir: string): Promise<void> => {
|
|
130
|
+
const schema = await loadSchema(config, schemaPath)
|
|
131
|
+
|
|
74
132
|
await mkdir(outputDir, { recursive: true })
|
|
75
133
|
|
|
76
134
|
const helpersMode = config.helpers ?? detectHelpersMode(outputDir)
|
|
@@ -87,61 +145,205 @@ const run = async (): Promise<void> => {
|
|
|
87
145
|
config.logWarnings,
|
|
88
146
|
config.strict,
|
|
89
147
|
helpersMode,
|
|
148
|
+
undefined,
|
|
149
|
+
config.readonly,
|
|
150
|
+
config.typeSuffix,
|
|
90
151
|
)
|
|
91
152
|
|
|
92
153
|
for (const file of files) {
|
|
93
|
-
|
|
94
|
-
// Create subdirectories if the filename contains a path
|
|
95
|
-
await mkdir(dirname(filePath), { recursive: true })
|
|
96
|
-
await writeFile(filePath, file.content, 'utf-8')
|
|
154
|
+
await writeGeneratedFile(outputDir, file.filename, file.content)
|
|
97
155
|
console.log(`Generated: ${file.filename}`)
|
|
98
156
|
}
|
|
99
157
|
|
|
100
158
|
if (config.build) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const tsconfigContent = JSON.stringify(
|
|
106
|
-
{
|
|
107
|
-
compilerOptions: {
|
|
108
|
-
target: 'ESNext',
|
|
109
|
-
module: 'ESNext',
|
|
110
|
-
moduleResolution: 'bundler',
|
|
111
|
-
declaration: true,
|
|
112
|
-
emitDeclarationOnly: config.typesOnly,
|
|
113
|
-
skipLibCheck: true,
|
|
114
|
-
},
|
|
115
|
-
include: ['./**/*.ts'],
|
|
116
|
-
},
|
|
117
|
-
null,
|
|
118
|
-
2,
|
|
159
|
+
await buildOutput(
|
|
160
|
+
outputDir,
|
|
161
|
+
files.map((f) => f.filename),
|
|
162
|
+
config.typesOnly,
|
|
119
163
|
)
|
|
164
|
+
} else {
|
|
165
|
+
console.log(`\nTotal files generated: ${files.length}`)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Generates a single self-contained file from one schema, concatenating every
|
|
171
|
+
* generated definition (and dropping the cross-file imports that are no longer
|
|
172
|
+
* needed) into `outFilePath`. Currently used for types-only output.
|
|
173
|
+
*/
|
|
174
|
+
const runSingleFile = async (config: Partial<CliConfig>, schemaPath: string, outFilePath: string): Promise<void> => {
|
|
175
|
+
const schema = await loadSchema(config, schemaPath)
|
|
176
|
+
const outputDir = dirname(outFilePath)
|
|
177
|
+
await mkdir(outputDir, { recursive: true })
|
|
120
178
|
|
|
121
|
-
|
|
122
|
-
|
|
179
|
+
const rootTypeName = deriveRootTypeName(schema)
|
|
180
|
+
console.log(`Root type: ${rootTypeName}`)
|
|
123
181
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
182
|
+
const files = await buildSchema(
|
|
183
|
+
schema as JSONSchema,
|
|
184
|
+
rootTypeName,
|
|
185
|
+
undefined,
|
|
186
|
+
config.typesOnly,
|
|
187
|
+
config.logWarnings,
|
|
188
|
+
config.strict,
|
|
189
|
+
config.helpers ?? 'package',
|
|
190
|
+
undefined,
|
|
191
|
+
config.readonly,
|
|
192
|
+
config.typeSuffix,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
await writeFile(outFilePath, combineGeneratedFiles(files), 'utf-8')
|
|
196
|
+
console.log(`Generated: ${relative(process.cwd(), outFilePath)}`)
|
|
197
|
+
|
|
198
|
+
if (config.build) {
|
|
199
|
+
await buildOutput(outputDir, [basename(outFilePath)], config.typesOnly)
|
|
200
|
+
} else {
|
|
201
|
+
console.log(`\nTotal files generated: 1`)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Generates parsers for every JSON Schema under `schemaDir`, mirroring the directory
|
|
207
|
+
* layout into `outDir`. Each schema's output lands in its own subdirectory (so files
|
|
208
|
+
* from different schemas never collide) and the runtime helpers are emitted once into a
|
|
209
|
+
* shared `outDir/_helpers/` that every nested parser imports from.
|
|
210
|
+
*/
|
|
211
|
+
const runRecursive = async (config: Partial<CliConfig>, schemaDir: string, outputDir: string): Promise<void> => {
|
|
212
|
+
if (config.input && config.input !== 'json') {
|
|
213
|
+
console.error("Error: --schemaDir only supports JSON Schema files; remove --input or set it to 'json'.")
|
|
214
|
+
process.exit(1)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const schemaFiles = await findJsonSchemas(schemaDir)
|
|
218
|
+
|
|
219
|
+
if (schemaFiles.length === 0) {
|
|
220
|
+
console.error(`Error: no .json schema files found under ${schemaDir}.`)
|
|
221
|
+
process.exit(1)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
await mkdir(outputDir, { recursive: true })
|
|
225
|
+
|
|
226
|
+
const helpersMode = config.helpers ?? detectHelpersMode(outputDir)
|
|
227
|
+
console.log(`Helpers mode: ${helpersMode}${config.helpers ? ' (explicit)' : ' (auto-detected)'}`)
|
|
228
|
+
|
|
229
|
+
// Helper sources are identical across schemas, so collect them by filename and
|
|
230
|
+
// write the deduplicated set once at the output root.
|
|
231
|
+
const sharedHelpers = new Map<string, string>()
|
|
232
|
+
const writtenTsFiles: string[] = []
|
|
233
|
+
|
|
234
|
+
for (const schemaFile of schemaFiles) {
|
|
235
|
+
const relPath = relative(schemaDir, schemaFile)
|
|
236
|
+
const relNoExt = relPath.slice(0, -'.json'.length)
|
|
237
|
+
const schemaSubDir = join(outputDir, relNoExt)
|
|
238
|
+
// Depth of the schema's output subdirectory, used to build the relative import
|
|
239
|
+
// path back to the shared `_helpers/` at the output root (../, ../../, ...).
|
|
240
|
+
const depth = relNoExt.split(sep).filter(Boolean).length
|
|
241
|
+
const helpersImportPrefix = '../'.repeat(depth)
|
|
242
|
+
|
|
243
|
+
const schema = await loadSchema(config, schemaFile)
|
|
244
|
+
const rootTypeName = deriveRootTypeName(schema)
|
|
245
|
+
console.log(`\n${relPath} → ${relNoExt}/ (root type: ${rootTypeName})`)
|
|
246
|
+
|
|
247
|
+
const files = await buildSchema(
|
|
248
|
+
schema as JSONSchema,
|
|
249
|
+
rootTypeName,
|
|
250
|
+
undefined,
|
|
251
|
+
config.typesOnly,
|
|
252
|
+
config.logWarnings,
|
|
253
|
+
config.strict,
|
|
254
|
+
helpersMode,
|
|
255
|
+
helpersImportPrefix,
|
|
256
|
+
config.readonly,
|
|
257
|
+
config.typeSuffix,
|
|
258
|
+
)
|
|
131
259
|
|
|
132
|
-
// Remove the intermediate .ts files now that .js and .d.ts have been produced
|
|
133
260
|
for (const file of files) {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
261
|
+
if (file.filename.startsWith('_helpers/')) {
|
|
262
|
+
sharedHelpers.set(file.filename, file.content)
|
|
263
|
+
continue
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
await writeGeneratedFile(schemaSubDir, file.filename, file.content)
|
|
267
|
+
const relativeFilename = join(relNoExt, file.filename)
|
|
268
|
+
writtenTsFiles.push(relativeFilename)
|
|
269
|
+
console.log(`Generated: ${relativeFilename}`)
|
|
139
270
|
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
for (const [filename, content] of sharedHelpers) {
|
|
274
|
+
await writeGeneratedFile(outputDir, filename, content)
|
|
275
|
+
writtenTsFiles.push(filename)
|
|
276
|
+
console.log(`Generated: ${filename}`)
|
|
277
|
+
}
|
|
140
278
|
|
|
141
|
-
|
|
279
|
+
if (config.build) {
|
|
280
|
+
await buildOutput(outputDir, writtenTsFiles, config.typesOnly)
|
|
142
281
|
} else {
|
|
143
|
-
console.log(`\nTotal files generated: ${
|
|
282
|
+
console.log(`\nTotal files generated: ${writtenTsFiles.length}`)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const run = async (): Promise<void> => {
|
|
287
|
+
// Skip the first two args (node executable and script path)
|
|
288
|
+
const args = process.argv.slice(2)
|
|
289
|
+
|
|
290
|
+
if (isVersionRequest(args)) {
|
|
291
|
+
console.log(await readVersion())
|
|
292
|
+
return
|
|
144
293
|
}
|
|
294
|
+
|
|
295
|
+
const configPath = extractConfigPath(args)
|
|
296
|
+
|
|
297
|
+
// Start with config file values if provided, then overlay CLI flags on top
|
|
298
|
+
const fileConfig = configPath ? await loadConfig(configPath) : {}
|
|
299
|
+
const cliConfig = parseCliArgs(args)
|
|
300
|
+
const config = { ...fileConfig, ...cliConfig }
|
|
301
|
+
|
|
302
|
+
if (config.outDir && config.outFile) {
|
|
303
|
+
console.error('Error: provide only one of --out-dir or --out-file, not both.')
|
|
304
|
+
process.exit(1)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Single-file output is the alternative to a directory of files.
|
|
308
|
+
if (config.outFile) {
|
|
309
|
+
if (!config.typesOnly) {
|
|
310
|
+
console.error('Error: --out-file currently supports only --types-only output. Add --types-only or use --out-dir.')
|
|
311
|
+
process.exit(1)
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (config.schemaDir) {
|
|
315
|
+
console.error('Error: --out-file cannot be combined with --schema-dir; use --out-dir for recursive output.')
|
|
316
|
+
process.exit(1)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (!config.schema) {
|
|
320
|
+
console.error('Error: --schema is required. Provide a path to a JSON Schema.')
|
|
321
|
+
process.exit(1)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
await runSingleFile(config, resolve(config.schema), resolve(config.outFile))
|
|
325
|
+
return
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (!config.outDir) {
|
|
329
|
+
console.error('Error: --out-dir or --out-file is required. Provide an output destination for generated files.')
|
|
330
|
+
process.exit(1)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const outputDir = resolve(config.outDir)
|
|
334
|
+
|
|
335
|
+
// schemaDir activates recursive mode and takes precedence over a single schema.
|
|
336
|
+
if (config.schemaDir) {
|
|
337
|
+
await runRecursive(config, resolve(config.schemaDir), outputDir)
|
|
338
|
+
return
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (!config.schema) {
|
|
342
|
+
console.error('Error: --schema (or --schemaDir) is required. Provide a path to a JSON Schema.')
|
|
343
|
+
process.exit(1)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
await runSingle(config, resolve(config.schema), outputDir)
|
|
145
347
|
}
|
|
146
348
|
|
|
147
349
|
run().catch((error: unknown) => {
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { GeneratedFile } from '@amritk/generate-parsers'
|
|
2
|
+
import { describe, expect, it } from 'vitest'
|
|
3
|
+
|
|
4
|
+
import { combineGeneratedFiles } from './combine-files'
|
|
5
|
+
|
|
6
|
+
describe('combineGeneratedFiles', () => {
|
|
7
|
+
it('drops relative imports and the index barrel, inlining every definition', () => {
|
|
8
|
+
const files: GeneratedFile[] = [
|
|
9
|
+
{
|
|
10
|
+
filename: 'document.ts',
|
|
11
|
+
content: "import type { Person } from './person';\n\nexport type Document = {\n owner?: Person;\n};",
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
filename: 'person.ts',
|
|
15
|
+
content: 'export type Person = {\n name: string;\n};',
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
filename: 'index.ts',
|
|
19
|
+
content: "export type { Document } from './document';\nexport type { Person } from './person';\n",
|
|
20
|
+
},
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
const result = combineGeneratedFiles(files)
|
|
24
|
+
|
|
25
|
+
expect(result).not.toContain('import')
|
|
26
|
+
expect(result).not.toContain('./document')
|
|
27
|
+
expect(result).toContain('export type Document =')
|
|
28
|
+
expect(result).toContain('export type Person =')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('hoists and deduplicates external (non-relative) imports', () => {
|
|
32
|
+
const files: GeneratedFile[] = [
|
|
33
|
+
{
|
|
34
|
+
filename: 'a.ts',
|
|
35
|
+
content: "import { isObject } from '@amritk/helpers/is-object';\n\nexport const a = isObject;",
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
filename: 'b.ts',
|
|
39
|
+
content: "import { isObject } from '@amritk/helpers/is-object';\n\nexport const b = isObject;",
|
|
40
|
+
},
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
const result = combineGeneratedFiles(files)
|
|
44
|
+
const importCount = result.split('\n').filter((line) => line.startsWith('import')).length
|
|
45
|
+
|
|
46
|
+
expect(importCount).toBe(1)
|
|
47
|
+
expect(result).toContain("import { isObject } from '@amritk/helpers/is-object';")
|
|
48
|
+
})
|
|
49
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { GeneratedFile } from '@amritk/generate-parsers'
|
|
2
|
+
|
|
3
|
+
// Require whitespace after `import` so a property literally named `import` (e.g.
|
|
4
|
+
// `import?: string`) is not mistaken for an import statement.
|
|
5
|
+
const IMPORT_RE = /^import\s/
|
|
6
|
+
const RELATIVE_IMPORT_RE = /\bfrom\s+['"]\.\.?\//
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Merges the per-schema {@link GeneratedFile}s into a single self-contained
|
|
10
|
+
* TypeScript module. Each generated file imports its sibling definitions via
|
|
11
|
+
* relative paths; since everything now lives in one file those imports are
|
|
12
|
+
* dropped, while any external (package) imports are hoisted to the top and
|
|
13
|
+
* deduplicated. The `index.ts` barrel is skipped because it only re-exports the
|
|
14
|
+
* declarations that are already inlined here.
|
|
15
|
+
*
|
|
16
|
+
* Intended for types-only output, where files contain only type definitions and
|
|
17
|
+
* type-only relative imports (no runtime helpers).
|
|
18
|
+
*/
|
|
19
|
+
export const combineGeneratedFiles = (files: readonly GeneratedFile[]): string => {
|
|
20
|
+
const externalImports = new Set<string>()
|
|
21
|
+
const bodies: string[] = []
|
|
22
|
+
|
|
23
|
+
for (const file of files) {
|
|
24
|
+
if (file.filename === 'index.ts') continue
|
|
25
|
+
|
|
26
|
+
const bodyLines: string[] = []
|
|
27
|
+
for (const line of file.content.split('\n')) {
|
|
28
|
+
if (IMPORT_RE.test(line.trimStart())) {
|
|
29
|
+
// Relative imports point at sibling files that are now inlined — drop them.
|
|
30
|
+
if (RELATIVE_IMPORT_RE.test(line)) continue
|
|
31
|
+
externalImports.add(line.trim())
|
|
32
|
+
continue
|
|
33
|
+
}
|
|
34
|
+
bodyLines.push(line)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const body = bodyLines.join('\n').trim()
|
|
38
|
+
if (body) bodies.push(body)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const importBlock = [...externalImports].sort().join('\n')
|
|
42
|
+
return [importBlock, bodies.join('\n\n')].filter(Boolean).join('\n\n') + '\n'
|
|
43
|
+
}
|
package/src/load-config.test.ts
CHANGED
|
@@ -58,6 +58,15 @@ describe('load-config', () => {
|
|
|
58
58
|
expect(result).toEqual({ schema: 's.json', outDir: 'o', strict: true })
|
|
59
59
|
})
|
|
60
60
|
|
|
61
|
+
it('loads schemaDir from a config file', async () => {
|
|
62
|
+
const configPath = join(tmpdir(), `test-config-${Date.now()}.json`)
|
|
63
|
+
await writeFile(configPath, JSON.stringify({ schemaDir: './schemas', outDir: 'output' }))
|
|
64
|
+
|
|
65
|
+
const result = await loadConfig(configPath)
|
|
66
|
+
|
|
67
|
+
expect(result).toEqual({ schemaDir: './schemas', outDir: 'output' })
|
|
68
|
+
})
|
|
69
|
+
|
|
61
70
|
it('ignores non-boolean strict value', async () => {
|
|
62
71
|
const configPath = join(tmpdir(), `test-config-${Date.now()}.json`)
|
|
63
72
|
await writeFile(configPath, JSON.stringify({ schema: 's.json', strict: 'yes' }))
|
package/src/load-config.ts
CHANGED
|
@@ -26,12 +26,15 @@ export const loadConfig = async (configPath: string): Promise<Partial<CliConfig>
|
|
|
26
26
|
|
|
27
27
|
return {
|
|
28
28
|
...(typeof obj['schema'] === 'string' && { schema: obj['schema'] }),
|
|
29
|
+
...(typeof obj['schemaDir'] === 'string' && { schemaDir: obj['schemaDir'] }),
|
|
29
30
|
...(typeof obj['outDir'] === 'string' && { outDir: obj['outDir'] }),
|
|
31
|
+
...(typeof obj['outFile'] === 'string' && { outFile: obj['outFile'] }),
|
|
30
32
|
...(isSourceFormat(obj['input']) && { input: obj['input'] }),
|
|
31
33
|
...(typeof obj['export'] === 'string' && { export: obj['export'] }),
|
|
32
34
|
...(typeof obj['typesOnly'] === 'boolean' && { typesOnly: obj['typesOnly'] }),
|
|
33
35
|
...(typeof obj['build'] === 'boolean' && { build: obj['build'] }),
|
|
34
36
|
...(typeof obj['logWarnings'] === 'boolean' && { logWarnings: obj['logWarnings'] }),
|
|
35
37
|
...(typeof obj['strict'] === 'boolean' && { strict: obj['strict'] }),
|
|
38
|
+
...(typeof obj['readonly'] === 'boolean' && { readonly: obj['readonly'] }),
|
|
36
39
|
}
|
|
37
40
|
}
|