@toolproof-core/schema 1.0.1 → 1.0.2

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.
@@ -1,175 +1,175 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { getConfig } from './_lib/config.js';
4
-
5
- /**
6
- * Create a standalone JSON Schema for a single $defs entry under Genesis.json,
7
- * embedding all direct & transitive local $defs dependencies.
8
- *
9
- * Usage:
10
- * node ./dist/scripts/generateStandaloneSchema.js --name <DefName>
11
- */
12
-
13
- /**
14
- * Pure function to extract a subschema and its dependencies from a flattened genesis schema.
15
- * Performs no I/O operations.
16
- */
17
- function extractStandaloneSubschemaLogic(genesis: any, name: string): any {
18
- const rootDefs: Record<string, any> | undefined = genesis.$defs;
19
- if (!rootDefs || typeof rootDefs !== 'object') {
20
- throw new Error('No $defs object found in Genesis.json');
21
- }
22
-
23
- const target = rootDefs[name];
24
- if (!target) {
25
- throw new Error(`Subschema named '${name}' not found under $defs in Genesis.json`);
26
- }
27
-
28
- const needed = collectLocalDefClosure(target, rootDefs);
29
-
30
- const targetClone = deepClone(target);
31
- const defsOut: Record<string, any> = {};
32
- for (const defName of needed) {
33
- if (defName === name) continue;
34
- const defSchema = rootDefs[defName];
35
- if (defSchema === undefined) {
36
- console.warn(`Warning: referenced def '${defName}' missing in root $defs (skipped).`);
37
- continue;
38
- }
39
- defsOut[defName] = deepClone(defSchema);
40
- }
41
-
42
- const existingInner = isObject(targetClone.$defs) ? targetClone.$defs : {};
43
- targetClone.$defs = { ...existingInner, ...defsOut };
44
-
45
- return targetClone;
46
- }
47
-
48
- async function main() {
49
- const config = getConfig();
50
- const { name } = parseArgs(process.argv.slice(2));
51
- if (!name) {
52
- console.error('Missing --name <DefName> argument');
53
- process.exit(1);
54
- }
55
-
56
- const schemasDir = config.getSchemasDir();
57
- const genesisPath = path.join(schemasDir, config.getSourceFile());
58
- const outPath = config.getSchemaStandalonePath(`${name}.json`);
59
-
60
- if (!fs.existsSync(genesisPath)) {
61
- console.error(`Genesis.json not found at ${genesisPath}. Run extractSchemasFromResourceTypeShells first.`);
62
- process.exit(1);
63
- }
64
-
65
- const raw = fs.readFileSync(genesisPath, 'utf-8');
66
- const genesis = JSON.parse(raw);
67
-
68
- try {
69
- const result = extractStandaloneSubschemaLogic(genesis, name);
70
-
71
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
72
- fs.writeFileSync(outPath, JSON.stringify(result, null, 2) + '\n');
73
- console.log(`Created standalone subschema '${name}' -> ${outPath}`);
74
- } catch (error: any) {
75
- console.error(error.message);
76
- process.exit(1);
77
- }
78
- }
79
-
80
- function parseArgs(args: string[]): { name?: string } {
81
- let name: string | undefined;
82
- for (let i = 0; i < args.length; i++) {
83
- const a = args[i];
84
- if (a === '--name') {
85
- name = args[i + 1];
86
- i++;
87
- } else if (a.startsWith('--name=')) {
88
- name = a.split('=')[1];
89
- }
90
- }
91
- return { name };
92
- }
93
-
94
- function isObject(v: any): v is Record<string, any> {
95
- return v !== null && typeof v === 'object' && !Array.isArray(v);
96
- }
97
-
98
- function deepClone<T>(v: T): T {
99
- if (Array.isArray(v)) return v.map((x) => deepClone(x)) as any;
100
- if (isObject(v)) {
101
- const out: Record<string, any> = {};
102
- for (const k of Object.keys(v)) out[k] = deepClone((v as any)[k]);
103
- return out as any;
104
- }
105
- return v;
106
- }
107
-
108
- function extractPointerDefName(ref: string): string | null {
109
- if (!ref || !ref.startsWith('#/')) return null;
110
- const parts = ref.slice(2).split('/');
111
- if (parts.length !== 2) return null;
112
- if (parts[0] !== '$defs') return null;
113
- const name = parts[1].replace(/~1/g, '/').replace(/~0/g, '~');
114
- return name;
115
- }
116
-
117
- function resolveRefToDefName(ref: string, rootDefs: Record<string, any>): string | null {
118
- if (!ref) return null;
119
- const byPointer = extractPointerDefName(ref);
120
- if (byPointer) return byPointer;
121
-
122
- if (ref.startsWith('#') && !ref.startsWith('#/')) {
123
- const anchor = ref.slice(1);
124
- if (!anchor) return null;
125
- for (const [defName, defSchema] of Object.entries(rootDefs)) {
126
- if (!defSchema || typeof defSchema !== 'object') continue;
127
- const topLevelAnchor = (defSchema as any).$anchor;
128
- const nested = (defSchema as any).nucleusSchema;
129
- const nestedAnchor = nested && typeof nested === 'object' ? nested.$anchor : undefined;
130
- const defAnchor = typeof topLevelAnchor === 'string' ? topLevelAnchor : (typeof nestedAnchor === 'string' ? nestedAnchor : undefined);
131
- if (defAnchor === anchor) {
132
- return defName;
133
- }
134
- }
135
- }
136
-
137
- return null;
138
- }
139
-
140
- function collectLocalDefClosure(node: any, rootDefs: Record<string, any>): Set<string> {
141
- const needed = new Set<string>();
142
- const queue: string[] = [];
143
-
144
- function visit(n: any) {
145
- if (Array.isArray(n)) {
146
- for (const item of n) visit(item);
147
- return;
148
- }
149
- if (!isObject(n)) return;
150
- if (typeof n.$ref === 'string') {
151
- const name = resolveRefToDefName(n.$ref, rootDefs);
152
- if (name && !needed.has(name)) {
153
- needed.add(name);
154
- queue.push(name);
155
- }
156
- }
157
- for (const val of Object.values(n)) visit(val);
158
- }
159
-
160
- visit(node);
161
-
162
- while (queue.length > 0) {
163
- const name = queue.shift()!;
164
- const def = rootDefs[name];
165
- if (!def) continue;
166
- visit(def);
167
- }
168
-
169
- return needed;
170
- }
171
-
172
- main().catch((e) => {
173
- console.error(e);
174
- process.exit(1);
175
- });
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { getConfig } from './_lib/config.js';
4
+
5
+ /**
6
+ * Create a standalone JSON Schema for a single $defs entry under Genesis.json,
7
+ * embedding all direct & transitive local $defs dependencies.
8
+ *
9
+ * Usage:
10
+ * node ./dist/scripts/generateStandaloneSchema.js --name <DefName>
11
+ */
12
+
13
+ /**
14
+ * Pure function to extract a subschema and its dependencies from a flattened genesis schema.
15
+ * Performs no I/O operations.
16
+ */
17
+ function extractStandaloneSubschemaLogic(genesis: any, name: string): any {
18
+ const rootDefs: Record<string, any> | undefined = genesis.$defs;
19
+ if (!rootDefs || typeof rootDefs !== 'object') {
20
+ throw new Error('No $defs object found in Genesis.json');
21
+ }
22
+
23
+ const target = rootDefs[name];
24
+ if (!target) {
25
+ throw new Error(`Subschema named '${name}' not found under $defs in Genesis.json`);
26
+ }
27
+
28
+ const needed = collectLocalDefClosure(target, rootDefs);
29
+
30
+ const targetClone = deepClone(target);
31
+ const defsOut: Record<string, any> = {};
32
+ for (const defName of needed) {
33
+ if (defName === name) continue;
34
+ const defSchema = rootDefs[defName];
35
+ if (defSchema === undefined) {
36
+ console.warn(`Warning: referenced def '${defName}' missing in root $defs (skipped).`);
37
+ continue;
38
+ }
39
+ defsOut[defName] = deepClone(defSchema);
40
+ }
41
+
42
+ const existingInner = isObject(targetClone.$defs) ? targetClone.$defs : {};
43
+ targetClone.$defs = { ...existingInner, ...defsOut };
44
+
45
+ return targetClone;
46
+ }
47
+
48
+ async function main() {
49
+ const config = getConfig();
50
+ const { name } = parseArgs(process.argv.slice(2));
51
+ if (!name) {
52
+ console.error('Missing --name <DefName> argument');
53
+ process.exit(1);
54
+ }
55
+
56
+ const schemasDir = config.getSchemasDir();
57
+ const genesisPath = path.join(schemasDir, config.getSourceFile());
58
+ const outPath = config.getSchemaStandalonePath(`${name}.json`);
59
+
60
+ if (!fs.existsSync(genesisPath)) {
61
+ console.error(`Genesis.json not found at ${genesisPath}. Run extractSchemasFromResourceTypeShells first.`);
62
+ process.exit(1);
63
+ }
64
+
65
+ const raw = fs.readFileSync(genesisPath, 'utf-8');
66
+ const genesis = JSON.parse(raw);
67
+
68
+ try {
69
+ const result = extractStandaloneSubschemaLogic(genesis, name);
70
+
71
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
72
+ fs.writeFileSync(outPath, JSON.stringify(result, null, 2) + '\n');
73
+ console.log(`Created standalone subschema '${name}' -> ${outPath}`);
74
+ } catch (error: any) {
75
+ console.error(error.message);
76
+ process.exit(1);
77
+ }
78
+ }
79
+
80
+ function parseArgs(args: string[]): { name?: string } {
81
+ let name: string | undefined;
82
+ for (let i = 0; i < args.length; i++) {
83
+ const a = args[i];
84
+ if (a === '--name') {
85
+ name = args[i + 1];
86
+ i++;
87
+ } else if (a.startsWith('--name=')) {
88
+ name = a.split('=')[1];
89
+ }
90
+ }
91
+ return { name };
92
+ }
93
+
94
+ function isObject(v: any): v is Record<string, any> {
95
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
96
+ }
97
+
98
+ function deepClone<T>(v: T): T {
99
+ if (Array.isArray(v)) return v.map((x) => deepClone(x)) as any;
100
+ if (isObject(v)) {
101
+ const out: Record<string, any> = {};
102
+ for (const k of Object.keys(v)) out[k] = deepClone((v as any)[k]);
103
+ return out as any;
104
+ }
105
+ return v;
106
+ }
107
+
108
+ function extractPointerDefName(ref: string): string | null {
109
+ if (!ref || !ref.startsWith('#/')) return null;
110
+ const parts = ref.slice(2).split('/');
111
+ if (parts.length !== 2) return null;
112
+ if (parts[0] !== '$defs') return null;
113
+ const name = parts[1].replace(/~1/g, '/').replace(/~0/g, '~');
114
+ return name;
115
+ }
116
+
117
+ function resolveRefToDefName(ref: string, rootDefs: Record<string, any>): string | null {
118
+ if (!ref) return null;
119
+ const byPointer = extractPointerDefName(ref);
120
+ if (byPointer) return byPointer;
121
+
122
+ if (ref.startsWith('#') && !ref.startsWith('#/')) {
123
+ const anchor = ref.slice(1);
124
+ if (!anchor) return null;
125
+ for (const [defName, defSchema] of Object.entries(rootDefs)) {
126
+ if (!defSchema || typeof defSchema !== 'object') continue;
127
+ const topLevelAnchor = (defSchema as any).$anchor;
128
+ const nested = (defSchema as any).nucleusSchema;
129
+ const nestedAnchor = nested && typeof nested === 'object' ? nested.$anchor : undefined;
130
+ const defAnchor = typeof topLevelAnchor === 'string' ? topLevelAnchor : (typeof nestedAnchor === 'string' ? nestedAnchor : undefined);
131
+ if (defAnchor === anchor) {
132
+ return defName;
133
+ }
134
+ }
135
+ }
136
+
137
+ return null;
138
+ }
139
+
140
+ function collectLocalDefClosure(node: any, rootDefs: Record<string, any>): Set<string> {
141
+ const needed = new Set<string>();
142
+ const queue: string[] = [];
143
+
144
+ function visit(n: any) {
145
+ if (Array.isArray(n)) {
146
+ for (const item of n) visit(item);
147
+ return;
148
+ }
149
+ if (!isObject(n)) return;
150
+ if (typeof n.$ref === 'string') {
151
+ const name = resolveRefToDefName(n.$ref, rootDefs);
152
+ if (name && !needed.has(name)) {
153
+ needed.add(name);
154
+ queue.push(name);
155
+ }
156
+ }
157
+ for (const val of Object.values(n)) visit(val);
158
+ }
159
+
160
+ visit(node);
161
+
162
+ while (queue.length > 0) {
163
+ const name = queue.shift()!;
164
+ const def = rootDefs[name];
165
+ if (!def) continue;
166
+ visit(def);
167
+ }
168
+
169
+ return needed;
170
+ }
171
+
172
+ main().catch((e) => {
173
+ console.error(e);
174
+ process.exit(1);
175
+ });
@@ -1,119 +1,119 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { getConfig } from './_lib/config.js';
4
-
5
- /**
6
- * Generate a typed Resource variant where `nucleus` is typed to a specific schema
7
- * extracted under the configured output directory.
8
- *
9
- * Usage: node ./dist/scripts/generateStandaloneType.js --name Job
10
- */
11
- /**
12
- * Pure function to generate the typed Resource D.TS content.
13
- *
14
- * @param name The name of the schema
15
- * @returns The TypeScript D.TS file content
16
- */
17
- function generateStandaloneTypeLogic(name: string): string {
18
- const header = '// Auto-generated strict composite type. Do not edit.\n';
19
- const ts =
20
- `import type { ShellMaterializedBase, ${name} as NucleusSchema } from '../types.js';\n` +
21
- `export type Resource_${name} = ShellMaterializedBase & { nucleus: NucleusSchema };\n`;
22
- return header + ts;
23
- }
24
-
25
- async function main() {
26
- const config = getConfig();
27
- const { name } = parseArgs(process.argv.slice(2));
28
- if (!name) {
29
- console.error('Missing --name <SchemaBasename> argument');
30
- process.exit(1);
31
- }
32
-
33
- const inPath =
34
- name === 'Genesis'
35
- ? config.getSchemaPath('Genesis.json')
36
- : config.getSchemaStandalonePath(`${name}.json`);
37
-
38
- if (!fs.existsSync(inPath)) {
39
- if (name === 'Genesis') {
40
- console.error(`Schema file not found: ${inPath}`);
41
- console.error('Run extractSchemasFromResourceTypeShells first.');
42
- } else {
43
- console.error(`Standalone schema file not found: ${inPath}`);
44
- console.error(`Run generateStandaloneSchema -- --name ${name} first.`);
45
- }
46
- process.exit(1);
47
- }
48
-
49
- // Basic validation against the expected shape of nucleusSchema.
50
- const raw = fs.readFileSync(inPath, 'utf8');
51
- let parsed: any = null;
52
- try {
53
- parsed = JSON.parse(raw);
54
- } catch (e) {
55
- console.error(`Failed to parse JSON schema ${inPath}:`, e);
56
- process.exit(1);
57
- }
58
-
59
- // Minimal checks that roughly match the nucleusSchema constraints used elsewhere.
60
- if (parsed.$schema && parsed.$schema !== 'https://json-schema.org/draft/2020-12/schema') {
61
- console.warn(`Warning: schema $schema is '${parsed.$schema}', expected draft 2020-12. Proceeding anyway.`);
62
- }
63
- if (parsed.type && parsed.type !== 'object') {
64
- console.warn(`Warning: nucleusSchema usually has type: 'object' but this schema has type: '${parsed.type}'. Proceeding.`);
65
- }
66
-
67
- const tsContent = generateStandaloneTypeLogic(name);
68
- const jsContent = 'export {}\n';
69
-
70
- // Output setup
71
- const outName = `Resource_${name}.d.ts`;
72
- const outJsName = `Resource_${name}.js`;
73
-
74
- // Process src output
75
- const outDir = config.getTypesStandaloneSrcDir();
76
- fs.mkdirSync(outDir, { recursive: true });
77
-
78
- const outPath = config.getTypesStandaloneSrcPath(outName);
79
- const outJsPath = config.getTypesStandaloneSrcPath(outJsName);
80
-
81
- fs.writeFileSync(outPath, tsContent, 'utf8');
82
- console.log(`Wrote ${outPath}`);
83
-
84
- if (!fs.existsSync(outJsPath)) {
85
- fs.writeFileSync(outJsPath, jsContent, 'utf8');
86
- console.log(`Wrote ${outJsPath}`);
87
- }
88
-
89
- // Process dist output
90
- const distLibDir = config.getTypesStandaloneDistDir();
91
- fs.mkdirSync(distLibDir, { recursive: true });
92
-
93
- const distDtsPath = config.getTypesStandaloneDistPath(outName);
94
- const distJsPath = config.getTypesStandaloneDistPath(outJsName);
95
-
96
- fs.writeFileSync(distDtsPath, tsContent, 'utf8');
97
- fs.writeFileSync(distJsPath, jsContent, 'utf8');
98
- console.log(`Wrote ${distDtsPath}`);
99
- console.log(`Wrote ${distJsPath}`);
100
- }
101
-
102
- function parseArgs(args: string[]): { name?: string } {
103
- let name: string | undefined;
104
- for (let i = 0; i < args.length; i++) {
105
- const a = args[i];
106
- if (a === '--name') {
107
- name = args[i + 1];
108
- i++;
109
- } else if (a.startsWith('--name=')) {
110
- name = a.split('=')[1];
111
- }
112
- }
113
- return { name };
114
- }
115
-
116
- main().catch((e) => {
117
- console.error(e);
118
- process.exit(1);
119
- });
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { getConfig } from './_lib/config.js';
4
+
5
+ /**
6
+ * Generate a typed Resource variant where `nucleus` is typed to a specific schema
7
+ * extracted under the configured output directory.
8
+ *
9
+ * Usage: node ./dist/scripts/generateStandaloneType.js --name Job
10
+ */
11
+ /**
12
+ * Pure function to generate the typed Resource D.TS content.
13
+ *
14
+ * @param name The name of the schema
15
+ * @returns The TypeScript D.TS file content
16
+ */
17
+ function generateStandaloneTypeLogic(name: string): string {
18
+ const header = '// Auto-generated strict composite type. Do not edit.\n';
19
+ const ts =
20
+ `import type { ShellMaterializedBase, ${name} as NucleusSchema } from '../types.js';\n` +
21
+ `export type Resource_${name} = ShellMaterializedBase & { nucleus: NucleusSchema };\n`;
22
+ return header + ts;
23
+ }
24
+
25
+ async function main() {
26
+ const config = getConfig();
27
+ const { name } = parseArgs(process.argv.slice(2));
28
+ if (!name) {
29
+ console.error('Missing --name <SchemaBasename> argument');
30
+ process.exit(1);
31
+ }
32
+
33
+ const inPath =
34
+ name === 'Genesis'
35
+ ? config.getSchemaPath('Genesis.json')
36
+ : config.getSchemaStandalonePath(`${name}.json`);
37
+
38
+ if (!fs.existsSync(inPath)) {
39
+ if (name === 'Genesis') {
40
+ console.error(`Schema file not found: ${inPath}`);
41
+ console.error('Run extractSchemasFromResourceTypeShells first.');
42
+ } else {
43
+ console.error(`Standalone schema file not found: ${inPath}`);
44
+ console.error(`Run generateStandaloneSchema -- --name ${name} first.`);
45
+ }
46
+ process.exit(1);
47
+ }
48
+
49
+ // Basic validation against the expected shape of nucleusSchema.
50
+ const raw = fs.readFileSync(inPath, 'utf8');
51
+ let parsed: any = null;
52
+ try {
53
+ parsed = JSON.parse(raw);
54
+ } catch (e) {
55
+ console.error(`Failed to parse JSON schema ${inPath}:`, e);
56
+ process.exit(1);
57
+ }
58
+
59
+ // Minimal checks that roughly match the nucleusSchema constraints used elsewhere.
60
+ if (parsed.$schema && parsed.$schema !== 'https://json-schema.org/draft/2020-12/schema') {
61
+ console.warn(`Warning: schema $schema is '${parsed.$schema}', expected draft 2020-12. Proceeding anyway.`);
62
+ }
63
+ if (parsed.type && parsed.type !== 'object') {
64
+ console.warn(`Warning: nucleusSchema usually has type: 'object' but this schema has type: '${parsed.type}'. Proceeding.`);
65
+ }
66
+
67
+ const tsContent = generateStandaloneTypeLogic(name);
68
+ const jsContent = 'export {}\n';
69
+
70
+ // Output setup
71
+ const outName = `Resource_${name}.d.ts`;
72
+ const outJsName = `Resource_${name}.js`;
73
+
74
+ // Process src output
75
+ const outDir = config.getTypesStandaloneSrcDir();
76
+ fs.mkdirSync(outDir, { recursive: true });
77
+
78
+ const outPath = config.getTypesStandaloneSrcPath(outName);
79
+ const outJsPath = config.getTypesStandaloneSrcPath(outJsName);
80
+
81
+ fs.writeFileSync(outPath, tsContent, 'utf8');
82
+ console.log(`Wrote ${outPath}`);
83
+
84
+ if (!fs.existsSync(outJsPath)) {
85
+ fs.writeFileSync(outJsPath, jsContent, 'utf8');
86
+ console.log(`Wrote ${outJsPath}`);
87
+ }
88
+
89
+ // Process dist output
90
+ const distLibDir = config.getTypesStandaloneDistDir();
91
+ fs.mkdirSync(distLibDir, { recursive: true });
92
+
93
+ const distDtsPath = config.getTypesStandaloneDistPath(outName);
94
+ const distJsPath = config.getTypesStandaloneDistPath(outJsName);
95
+
96
+ fs.writeFileSync(distDtsPath, tsContent, 'utf8');
97
+ fs.writeFileSync(distJsPath, jsContent, 'utf8');
98
+ console.log(`Wrote ${distDtsPath}`);
99
+ console.log(`Wrote ${distJsPath}`);
100
+ }
101
+
102
+ function parseArgs(args: string[]): { name?: string } {
103
+ let name: string | undefined;
104
+ for (let i = 0; i < args.length; i++) {
105
+ const a = args[i];
106
+ if (a === '--name') {
107
+ name = args[i + 1];
108
+ i++;
109
+ } else if (a.startsWith('--name=')) {
110
+ name = a.split('=')[1];
111
+ }
112
+ }
113
+ return { name };
114
+ }
115
+
116
+ main().catch((e) => {
117
+ console.error(e);
118
+ process.exit(1);
119
+ });