@acid-cat/cli 0.19.0 → 0.20.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 +32 -2
- package/conformance/fixture.acidcat.json +96 -0
- package/dist/conform-LH9KgQ9-.js +5045 -0
- package/dist/index.d.ts +164 -4
- package/dist/index.js +96 -4
- package/dist/main.d.ts +1 -2
- package/dist/main.js +1090 -7
- package/package.json +4 -3
- package/dist/catalog.d.ts +0 -12
- package/dist/catalog.js +0 -149
- package/dist/conform/check.d.ts +0 -47
- package/dist/conform/check.js +0 -178
- package/dist/conform/cli.d.ts +0 -5
- package/dist/conform/cli.js +0 -721
- package/dist/conform/http.d.ts +0 -6
- package/dist/conform/http.js +0 -297
- package/dist/conform/index.d.ts +0 -69
- package/dist/conform/index.js +0 -80
- package/dist/conform/mcp-stdio.d.ts +0 -7
- package/dist/conform/mcp-stdio.js +0 -291
- package/dist/conform/mcp.d.ts +0 -47
- package/dist/conform/mcp.js +0 -754
- package/dist/conform/poll.d.ts +0 -13
- package/dist/conform/poll.js +0 -295
- package/dist/conform/properties.d.ts +0 -12
- package/dist/conform/properties.js +0 -151
- package/dist/conform/serve.d.ts +0 -12
- package/dist/conform/serve.js +0 -96
- package/dist/conform/server-card.d.ts +0 -5
- package/dist/conform/server-card.js +0 -142
- package/dist/conform/sse.d.ts +0 -9
- package/dist/conform/sse.js +0 -53
- package/dist/conform/webhook.d.ts +0 -30
- package/dist/conform/webhook.js +0 -481
- package/dist/conform/webmcp.d.ts +0 -53
- package/dist/conform/webmcp.js +0 -232
- package/dist/json/catalog.schema.json.js +0 -170
- package/dist/json/fixture.acidcat.json.js +0 -396
- package/dist/json/package.json.js +0 -3
- package/dist/json/server-card.schema.json.js +0 -281
- package/dist/json.d.ts +0 -11
- package/dist/json.js +0 -13
package/dist/main.js
CHANGED
|
@@ -1,13 +1,1059 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import { check, isCatalog, targetCatalog } from "./catalog.js";
|
|
4
|
-
import { DEADLINE } from "./conform/check.js";
|
|
5
|
-
import { conform } from "./conform/index.js";
|
|
6
|
-
import { parseJson } from "./json.js";
|
|
2
|
+
import { a as catalogSchemas, c as readSchemas, l as targetCatalog$1, n as DEADLINE, o as check, s as isCatalog, t as conform, u as parseJson } from "./conform-LH9KgQ9-.js";
|
|
7
3
|
import { canonicalText } from "@acid-cat/catalog";
|
|
8
|
-
import {
|
|
4
|
+
import { REFERENCE, isJsonObject, typesUsedBy, visitObjects } from "@acid-cat/spec-ts";
|
|
5
|
+
import { Console, Data, Effect, FileSystem, Option, SchemaRepresentation } from "effect";
|
|
9
6
|
import { NodeRuntime, NodeServices } from "@effect/platform-node";
|
|
10
7
|
import { Argument, Command, Flag } from "effect/cli";
|
|
8
|
+
// package.json
|
|
9
|
+
var version = "0.20.0";
|
|
10
|
+
// src/generate/model.ts
|
|
11
|
+
var GenerateError = class extends Error {};
|
|
12
|
+
const upperFirst = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
13
|
+
const words = (text) => text.split(/[^A-Za-z0-9]+/u).map(upperFirst).join("");
|
|
14
|
+
const camelCase = (id) => id.replace(/[.-]([a-z0-9])/gu, (_, next) => next.toUpperCase());
|
|
15
|
+
function uniqueNames(reserved) {
|
|
16
|
+
const used = new Set(reserved);
|
|
17
|
+
return (base) => {
|
|
18
|
+
let name = base;
|
|
19
|
+
for (let index = 2; used.has(name); index++) name = base + index;
|
|
20
|
+
used.add(name);
|
|
21
|
+
return name;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function declarationsOf(catalog, reserved) {
|
|
25
|
+
const definitions = catalog.$defs ?? {};
|
|
26
|
+
const unique = uniqueNames(reserved);
|
|
27
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
28
|
+
const register = (name, schema, extra) => {
|
|
29
|
+
const key = JSON.stringify([schema, extra.tag]);
|
|
30
|
+
const known = schemas.get(key);
|
|
31
|
+
if (known !== void 0) return known.name;
|
|
32
|
+
const named = {
|
|
33
|
+
name: extra.definition ?? unique(name),
|
|
34
|
+
schema,
|
|
35
|
+
...extra
|
|
36
|
+
};
|
|
37
|
+
schemas.set(key, named);
|
|
38
|
+
return named.name;
|
|
39
|
+
};
|
|
40
|
+
for (const name of Object.keys(definitions)) if (unique(name) !== name) throw new GenerateError(`type ${name}: the generated file uses this name for its own code; give the type another name`);
|
|
41
|
+
for (const name of Object.keys(definitions)) register(name, { $ref: `#/$defs/${name}` }, { definition: name });
|
|
42
|
+
const members = /* @__PURE__ */ new Map();
|
|
43
|
+
const failures = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const [id, member, schema] of catalogSchemas(catalog)) {
|
|
45
|
+
const tag = member.startsWith("failure ") ? member.slice(8) : void 0;
|
|
46
|
+
if (tag === void 0) {
|
|
47
|
+
const name = register(words(id) + upperFirst(member), schema, {});
|
|
48
|
+
members.set(id, [...members.get(id) ?? [], [member, name]]);
|
|
49
|
+
} else {
|
|
50
|
+
const name = register(`Failure${words(tag)}`, schema, { tag });
|
|
51
|
+
failures.set(id, [...failures.get(id) ?? [], [tag, name]]);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const declaration = (member, id, metadata) => ({
|
|
55
|
+
member,
|
|
56
|
+
id,
|
|
57
|
+
name: unique(camelCase(id)),
|
|
58
|
+
metadata,
|
|
59
|
+
members: members.get(id) ?? [],
|
|
60
|
+
failures: failures.get(id) ?? []
|
|
61
|
+
});
|
|
62
|
+
const declarations = [...Object.entries(catalog.capabilities).map(([id, { input: _input, output: _output, failures: _failures, state: _state, audience = [], ...metadata }]) => declaration("capability", id, {
|
|
63
|
+
...metadata,
|
|
64
|
+
audience
|
|
65
|
+
})), ...Object.entries(catalog.events ?? {}).map(([id, { input: _input, payload: _payload, audience = [], ...metadata }]) => declaration("event", id, {
|
|
66
|
+
...metadata,
|
|
67
|
+
audience
|
|
68
|
+
}))];
|
|
69
|
+
const { title, description, targets } = catalog;
|
|
70
|
+
return {
|
|
71
|
+
definitions,
|
|
72
|
+
schemas: [...schemas.values()],
|
|
73
|
+
declarations,
|
|
74
|
+
application: {
|
|
75
|
+
title,
|
|
76
|
+
description,
|
|
77
|
+
targets
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
// src/generate/typescript.ts
|
|
82
|
+
/** A `__proto__` key in an object literal sets the prototype. */
|
|
83
|
+
function literal(value, indent) {
|
|
84
|
+
return JSON.stringify(value, null, indent).replace(/"__proto__":/gu, "[\"__proto__\"]:");
|
|
85
|
+
}
|
|
86
|
+
const definitionsBlock = ({ definitions }) => Object.keys(definitions).length === 0 ? void 0 : `export const $defs = ${literal(definitions, 2)} as const;`;
|
|
87
|
+
function carried({ definitions }, schema) {
|
|
88
|
+
if (Object.keys(definitions).length === 0) return literal(schema);
|
|
89
|
+
return `{ ${literal(schema).slice(1, -1)}${Object.keys(schema).length > 0 ? ", " : ""}$defs }`;
|
|
90
|
+
}
|
|
91
|
+
function declarationBlock({ id, name, metadata, members, failures }, failuresOf) {
|
|
92
|
+
const fields = [` id: ${literal(id)},`];
|
|
93
|
+
for (const [key, value] of Object.entries(metadata)) fields.push(` ${literal(key)}: ${literal(value)},`);
|
|
94
|
+
for (const [member, schema] of members) fields.push(` ${member}: ${member === "state" ? `{ schema: ${schema} }` : schema},`);
|
|
95
|
+
if (failures.length > 0) fields.push(` failures: ${failuresOf(failures)},`);
|
|
96
|
+
return `export const ${name} = {\n${fields.join("\n")}\n} as const;`;
|
|
97
|
+
}
|
|
98
|
+
function declarationsBlock({ declarations }) {
|
|
99
|
+
const names = (member) => declarations.filter((each) => each.member === member).map(({ name }) => name);
|
|
100
|
+
const events = names("event");
|
|
101
|
+
return `export const declarations = {\n${[` capabilities: [${names("capability").join(", ")}],`, ...events.length === 0 ? [] : [` events: [${events.join(", ")}],`]].join("\n")}\n} as const;`;
|
|
102
|
+
}
|
|
103
|
+
const applicationBlock = ({ application }) => `export const application = ${literal(application, 2)} as const;`;
|
|
104
|
+
const sourceOf = (imports, blocks) => [...imports.length > 0 ? [imports.join("\n")] : [], ...blocks.filter((block) => block !== void 0)].join("\n\n") + "\n";
|
|
105
|
+
const CHECK_HELPERS = [
|
|
106
|
+
[
|
|
107
|
+
"Path",
|
|
108
|
+
"type Path = readonly PropertyKey[];",
|
|
109
|
+
[]
|
|
110
|
+
],
|
|
111
|
+
[
|
|
112
|
+
"Issues",
|
|
113
|
+
"type Issues = { readonly message: string; readonly path: Path }[];",
|
|
114
|
+
["Path"]
|
|
115
|
+
],
|
|
116
|
+
[
|
|
117
|
+
"report",
|
|
118
|
+
`function report(issues: Issues, path: Path, message: string): void {
|
|
119
|
+
issues.push({ message, path });
|
|
120
|
+
}`,
|
|
121
|
+
["Issues", "Path"]
|
|
122
|
+
],
|
|
123
|
+
[
|
|
124
|
+
"isJsonObject",
|
|
125
|
+
`function isJsonObject(value: unknown): value is { readonly [key: string]: unknown } {
|
|
126
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
127
|
+
}`,
|
|
128
|
+
[]
|
|
129
|
+
],
|
|
130
|
+
[
|
|
131
|
+
"equalJson",
|
|
132
|
+
`function equalJson(left: unknown, right: unknown): boolean {
|
|
133
|
+
if (Array.isArray(left)) {
|
|
134
|
+
if (!Array.isArray(right) || left.length !== right.length) return false;
|
|
135
|
+
for (let index = 0; index < left.length; index++) if (!equalJson(left[index], right[index])) return false;
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
if (!isJsonObject(left)) return left === right;
|
|
139
|
+
const prototype: unknown = Object.getPrototypeOf(left);
|
|
140
|
+
if (!isJsonObject(right) || (prototype !== null && !(isJsonObject(prototype) && prototype.constructor === Object))) return false;
|
|
141
|
+
const keys = Object.keys(left);
|
|
142
|
+
return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalJson(left[key], right[key]));
|
|
143
|
+
}`,
|
|
144
|
+
["isJsonObject"]
|
|
145
|
+
],
|
|
146
|
+
[
|
|
147
|
+
"equalsOneOf",
|
|
148
|
+
`function equalsOneOf(value: unknown, values: readonly unknown[]): boolean {
|
|
149
|
+
return values.some((each) => equalJson(value, each));
|
|
150
|
+
}`,
|
|
151
|
+
["equalJson"]
|
|
152
|
+
],
|
|
153
|
+
[
|
|
154
|
+
"withoutTag",
|
|
155
|
+
`function withoutTag(value: unknown): unknown {
|
|
156
|
+
if (!isJsonObject(value)) return value;
|
|
157
|
+
const { _tag: _, ...data } = value;
|
|
158
|
+
return data;
|
|
159
|
+
}`,
|
|
160
|
+
["isJsonObject"]
|
|
161
|
+
]
|
|
162
|
+
];
|
|
163
|
+
function helperCode(helpers, needed) {
|
|
164
|
+
const used = /* @__PURE__ */ new Set();
|
|
165
|
+
const add = (name) => {
|
|
166
|
+
if (used.has(name)) return;
|
|
167
|
+
used.add(name);
|
|
168
|
+
for (const each of helpers.find(([helper]) => helper === name)?.[2] ?? []) add(each);
|
|
169
|
+
};
|
|
170
|
+
needed.forEach(add);
|
|
171
|
+
const code = helpers.filter(([name]) => used.has(name)).map(([, each]) => each);
|
|
172
|
+
return {
|
|
173
|
+
used,
|
|
174
|
+
code: code.length === 0 ? void 0 : code.join("\n\n")
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/** JSON Schema 2020-12 treats `format` as an annotation by default. */
|
|
178
|
+
const ANNOTATIONS = /* @__PURE__ */ new Set([
|
|
179
|
+
"$comment",
|
|
180
|
+
"$schema",
|
|
181
|
+
"contentEncoding",
|
|
182
|
+
"contentMediaType",
|
|
183
|
+
"contentSchema",
|
|
184
|
+
"default",
|
|
185
|
+
"deprecated",
|
|
186
|
+
"description",
|
|
187
|
+
"examples",
|
|
188
|
+
"format",
|
|
189
|
+
"readOnly",
|
|
190
|
+
"title",
|
|
191
|
+
"writeOnly"
|
|
192
|
+
]);
|
|
193
|
+
const TYPES = {
|
|
194
|
+
string: {
|
|
195
|
+
test: (value) => `typeof ${value} === "string"`,
|
|
196
|
+
noun: "a string"
|
|
197
|
+
},
|
|
198
|
+
number: {
|
|
199
|
+
test: (value) => `Number.isFinite(${value})`,
|
|
200
|
+
noun: "a number"
|
|
201
|
+
},
|
|
202
|
+
integer: {
|
|
203
|
+
test: (value) => `Number.isInteger(${value})`,
|
|
204
|
+
noun: "an integer"
|
|
205
|
+
},
|
|
206
|
+
boolean: {
|
|
207
|
+
test: (value) => `typeof ${value} === "boolean"`,
|
|
208
|
+
noun: "a boolean"
|
|
209
|
+
},
|
|
210
|
+
null: {
|
|
211
|
+
test: (value) => `${value} === null`,
|
|
212
|
+
noun: "null"
|
|
213
|
+
},
|
|
214
|
+
object: {
|
|
215
|
+
test: (value) => `isJsonObject(${value})`,
|
|
216
|
+
noun: "an object"
|
|
217
|
+
},
|
|
218
|
+
array: {
|
|
219
|
+
test: (value) => `Array.isArray(${value})`,
|
|
220
|
+
noun: "an array"
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const KEYWORDS$1 = /* @__PURE__ */ new Set([
|
|
224
|
+
"$ref",
|
|
225
|
+
"type",
|
|
226
|
+
"enum",
|
|
227
|
+
"const",
|
|
228
|
+
"allOf",
|
|
229
|
+
"anyOf",
|
|
230
|
+
"oneOf",
|
|
231
|
+
"not",
|
|
232
|
+
"minimum",
|
|
233
|
+
"maximum",
|
|
234
|
+
"exclusiveMinimum",
|
|
235
|
+
"exclusiveMaximum",
|
|
236
|
+
"minLength",
|
|
237
|
+
"maxLength",
|
|
238
|
+
"pattern",
|
|
239
|
+
"properties",
|
|
240
|
+
"required",
|
|
241
|
+
"additionalProperties",
|
|
242
|
+
"items",
|
|
243
|
+
"minItems",
|
|
244
|
+
"maxItems"
|
|
245
|
+
]);
|
|
246
|
+
const checkName = (type) => `check${type}`;
|
|
247
|
+
const mentions = (lines, name) => lines.some((line) => new RegExp(`\\b${name}\\b`, "u").test(line));
|
|
248
|
+
const isNumber = (value) => typeof value === "number";
|
|
249
|
+
const isCount = (value) => Number.isInteger(value) && isNumber(value) && value >= 0;
|
|
250
|
+
const definitionNamesOf = ({ schemas }) => new Map(schemas.flatMap(({ definition, name }) => definition === void 0 ? [] : [[definition, name]]));
|
|
251
|
+
const ownSchema = ({ definitions }, { definition, schema }) => definition === void 0 ? schema : definitions[definition] ?? {};
|
|
252
|
+
function referencedType(definitionNames, where, schema) {
|
|
253
|
+
const name = typeof schema.$ref === "string" ? REFERENCE.exec(schema.$ref)?.[1] : void 0;
|
|
254
|
+
const type = name === void 0 ? void 0 : definitionNames.get(name);
|
|
255
|
+
if (type === void 0) throw new GenerateError(`${where}: $ref ${literal(schema.$ref)} does not name a type of the catalog`);
|
|
256
|
+
return type;
|
|
257
|
+
}
|
|
258
|
+
function typeNames$1(type) {
|
|
259
|
+
return Array.isArray(type) ? type.filter((each) => typeof each === "string") : typeof type === "string" ? [type] : [];
|
|
260
|
+
}
|
|
261
|
+
function checkWriter(core, definitionNames, needed) {
|
|
262
|
+
function checks(where, schema, value, path, issues, fresh) {
|
|
263
|
+
const pathText = path.length === 0 ? "path" : `[...path, ${path.join(", ")}]`;
|
|
264
|
+
const reported = (message) => {
|
|
265
|
+
needed.add("report");
|
|
266
|
+
return `report(${issues}, ${pathText}, ${literal(message)});`;
|
|
267
|
+
};
|
|
268
|
+
if (schema === true) return [];
|
|
269
|
+
if (schema === false) return [reported("must not be present")];
|
|
270
|
+
if (!isJsonObject(schema)) throw new GenerateError(`${where}: a schema is not an object or a boolean`);
|
|
271
|
+
for (const keyword of Object.keys(schema)) if (!KEYWORDS$1.has(keyword) && !ANNOTATIONS.has(keyword) && !keyword.startsWith("x-")) throw new GenerateError(`${where}: acid-cat generate --core ${core} cannot check the keyword ${keyword}`);
|
|
272
|
+
const invalid = (keyword) => {
|
|
273
|
+
throw new GenerateError(`${where}: the value of the keyword ${keyword} is not valid`);
|
|
274
|
+
};
|
|
275
|
+
const lines = [];
|
|
276
|
+
const nested = (child, childValue, childPath, childIssues = issues) => checks(where, child, childValue, childPath, childIssues, fresh).map((line) => ` ${line}`);
|
|
277
|
+
if (schema.$ref !== void 0) lines.push(`${checkName(referencedType(definitionNames, where, schema))}(${value}, ${pathText}, ${issues});`);
|
|
278
|
+
if (schema.type !== void 0) {
|
|
279
|
+
const types = typeNames$1(schema.type);
|
|
280
|
+
if (types.length === 0 || types.length !== (Array.isArray(schema.type) ? schema.type.length : 1)) invalid("type");
|
|
281
|
+
const tests = types.map((type) => TYPES[type] ?? invalid("type"));
|
|
282
|
+
if (types.includes("object")) needed.add("isJsonObject");
|
|
283
|
+
const test = tests.map((each) => each.test(value)).join(" || ");
|
|
284
|
+
lines.push(`if (!${test.includes(" ") ? `(${test})` : test}) ${reported(`must be ${tests.map(({ noun }) => noun).join(" or ")}`)}`);
|
|
285
|
+
}
|
|
286
|
+
if (schema.enum !== void 0) {
|
|
287
|
+
const values = Array.isArray(schema.enum) ? schema.enum : invalid("enum");
|
|
288
|
+
needed.add("equalsOneOf");
|
|
289
|
+
lines.push(`if (!equalsOneOf(${value}, ${literal(values)})) ${reported(`must be one of ${values.map((each) => JSON.stringify(each)).join(", ")}`)}`);
|
|
290
|
+
}
|
|
291
|
+
if (Object.hasOwn(schema, "const")) needed.add("equalsOneOf");
|
|
292
|
+
if (Object.hasOwn(schema, "const")) lines.push(`if (!equalsOneOf(${value}, [${literal(schema.const)}])) ${reported(`must be ${JSON.stringify(schema.const)}`)}`);
|
|
293
|
+
for (const member of Array.isArray(schema.allOf) ? schema.allOf : schema.allOf === void 0 ? [] : invalid("allOf")) lines.push(...nested(member, value, path).map((line) => line.slice(2)));
|
|
294
|
+
for (const keyword of ["anyOf", "oneOf"]) {
|
|
295
|
+
const union = schema[keyword];
|
|
296
|
+
if (union === void 0) continue;
|
|
297
|
+
const members = Array.isArray(union) && union.length > 0 ? union : invalid(keyword);
|
|
298
|
+
const matched = fresh("matched");
|
|
299
|
+
lines.push(`let ${matched} = 0;`);
|
|
300
|
+
for (const member of members) {
|
|
301
|
+
const memberIssues = fresh("issues");
|
|
302
|
+
lines.push("{", ` const ${memberIssues}: Issues = [];`, ...nested(member, value, path, memberIssues), ` if (${memberIssues}.length === 0) ${matched} += 1;`, "}");
|
|
303
|
+
}
|
|
304
|
+
lines.push(keyword === "anyOf" ? `if (${matched} === 0) ${reported("must match at least one schema of anyOf")}` : `if (${matched} !== 1) ${reported("must match exactly one schema of oneOf")}`);
|
|
305
|
+
}
|
|
306
|
+
if (schema.not !== void 0) {
|
|
307
|
+
const notIssues = fresh("issues");
|
|
308
|
+
lines.push("{", ` const ${notIssues}: Issues = [];`, ...nested(schema.not, value, path, notIssues), ` if (${notIssues}.length === 0) ${reported("must not match the schema of not")}`, "}");
|
|
309
|
+
}
|
|
310
|
+
const numbers = [];
|
|
311
|
+
const bound = (keyword, failsWhen, message) => {
|
|
312
|
+
const limit = schema[keyword];
|
|
313
|
+
if (limit === void 0) return;
|
|
314
|
+
if (!isNumber(limit)) return invalid(keyword);
|
|
315
|
+
numbers.push(` if (${value} ${failsWhen} ${limit}) ${reported(`${message} ${limit}`)}`);
|
|
316
|
+
};
|
|
317
|
+
bound("minimum", "<", "must be at least");
|
|
318
|
+
bound("maximum", ">", "must be at most");
|
|
319
|
+
bound("exclusiveMinimum", "<=", "must be more than");
|
|
320
|
+
bound("exclusiveMaximum", ">=", "must be less than");
|
|
321
|
+
if (numbers.length > 0) lines.push(`if (typeof ${value} === "number") {`, ...numbers, "}");
|
|
322
|
+
const strings = [];
|
|
323
|
+
const length = (keyword, failsWhen, message) => {
|
|
324
|
+
const limit = schema[keyword];
|
|
325
|
+
if (limit === void 0) return;
|
|
326
|
+
if (!isCount(limit)) return invalid(keyword);
|
|
327
|
+
strings.push(` if (Array.from(${value}).length ${failsWhen} ${limit}) ${reported(`${message} ${limit} characters`)}`);
|
|
328
|
+
};
|
|
329
|
+
length("minLength", "<", "must have at least");
|
|
330
|
+
length("maxLength", ">", "must have at most");
|
|
331
|
+
if (schema.pattern !== void 0) {
|
|
332
|
+
const { pattern } = schema;
|
|
333
|
+
if (typeof pattern !== "string") return invalid("pattern");
|
|
334
|
+
try {
|
|
335
|
+
new RegExp(pattern, "u");
|
|
336
|
+
} catch {
|
|
337
|
+
invalid("pattern");
|
|
338
|
+
}
|
|
339
|
+
strings.push(` if (!new RegExp(${literal(pattern)}, "u").test(${value})) ${reported(`must match the pattern ${pattern}`)}`);
|
|
340
|
+
}
|
|
341
|
+
if (strings.length > 0) lines.push(`if (typeof ${value} === "string") {`, ...strings, "}");
|
|
342
|
+
const objects = [];
|
|
343
|
+
const properties = schema.properties === void 0 ? {} : isJsonObject(schema.properties) ? schema.properties : invalid("properties");
|
|
344
|
+
const required = schema.required === void 0 ? [] : Array.isArray(schema.required) ? schema.required : invalid("required");
|
|
345
|
+
for (const name of required) {
|
|
346
|
+
if (typeof name !== "string") return invalid("required");
|
|
347
|
+
objects.push(` if (!Object.hasOwn(${value}, ${literal(name)})) ${reported(`must have the property ${JSON.stringify(name)}`)}`);
|
|
348
|
+
}
|
|
349
|
+
for (const [name, property] of Object.entries(properties)) {
|
|
350
|
+
const child = fresh("value");
|
|
351
|
+
const inner = nested(property, child, [...path, literal(name)]);
|
|
352
|
+
const read = mentions(inner, child) ? [` const ${child} = ${value}[${literal(name)}];`] : [];
|
|
353
|
+
if (inner.length > 0) objects.push(` if (Object.hasOwn(${value}, ${literal(name)})) {`, ...read, ...inner.map((line) => ` ${line}`), " }");
|
|
354
|
+
}
|
|
355
|
+
const additional = schema.additionalProperties;
|
|
356
|
+
if (additional !== void 0 && additional !== true) {
|
|
357
|
+
const key = fresh("key");
|
|
358
|
+
const child = fresh("value");
|
|
359
|
+
const inner = nested(additional, child, [...path, key]);
|
|
360
|
+
const known = Object.keys(properties);
|
|
361
|
+
const entries = mentions(inner, child) ? `const [${key}, ${child}] of Object.entries(${value})` : `const ${key} of Object.keys(${value})`;
|
|
362
|
+
const body = known.length === 0 ? inner.map((line) => ` ${line}`) : [
|
|
363
|
+
` if (!${literal(known)}.includes(${key})) {`,
|
|
364
|
+
...inner.map((line) => ` ${line}`),
|
|
365
|
+
" }"
|
|
366
|
+
];
|
|
367
|
+
if (inner.length > 0) objects.push(` for (${entries}) {`, ...body, " }");
|
|
368
|
+
}
|
|
369
|
+
if (objects.length > 0) {
|
|
370
|
+
needed.add("isJsonObject");
|
|
371
|
+
lines.push(`if (isJsonObject(${value})) {`, ...objects, "}");
|
|
372
|
+
}
|
|
373
|
+
const arrays = [];
|
|
374
|
+
const items = (keyword, failsWhen, message) => {
|
|
375
|
+
const limit = schema[keyword];
|
|
376
|
+
if (limit === void 0) return;
|
|
377
|
+
if (!isCount(limit)) return invalid(keyword);
|
|
378
|
+
arrays.push(` if (${value}.length ${failsWhen} ${limit}) ${reported(`${message} ${limit} items`)}`);
|
|
379
|
+
};
|
|
380
|
+
items("minItems", "<", "must have at least");
|
|
381
|
+
items("maxItems", ">", "must have at most");
|
|
382
|
+
if (schema.items !== void 0) {
|
|
383
|
+
const index = fresh("index");
|
|
384
|
+
const child = fresh("item");
|
|
385
|
+
const inner = nested(schema.items, child, [...path, index]);
|
|
386
|
+
const entries = mentions(inner, child) ? `const [${index}, ${child}] of ${value}.entries()` : `const ${index} of ${value}.keys()`;
|
|
387
|
+
if (inner.length > 0) arrays.push(` for (${entries}) {`, ...inner.map((line) => ` ${line}`), " }");
|
|
388
|
+
}
|
|
389
|
+
if (arrays.length > 0) lines.push(`if (Array.isArray(${value})) {`, ...arrays, "}");
|
|
390
|
+
return lines;
|
|
391
|
+
}
|
|
392
|
+
return function checkFunction(where, name, schema, guard) {
|
|
393
|
+
let count = 0;
|
|
394
|
+
const fresh = (prefix) => `${prefix}${++count}`;
|
|
395
|
+
const body = checks(where, schema, "value", [], "issues", fresh);
|
|
396
|
+
needed.add("Path");
|
|
397
|
+
needed.add("Issues");
|
|
398
|
+
const parameter = (each) => mentions(body, each) ? each : `_${each}`;
|
|
399
|
+
const value = parameter("value");
|
|
400
|
+
const signature = `function ${checkName(name)}(${value}: unknown, ${parameter("path")}: Path, ${parameter("issues")}: Issues): ${guard === void 0 ? "boolean" : `${value} is ${guard}`}`;
|
|
401
|
+
if (body.length === 0) return `${signature} {\n return true;\n}`;
|
|
402
|
+
return `${signature} {\n const count = issues.length;\n${body.map((line) => ` ${line}`).join("\n")}\n return issues.length === count;\n}`;
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function placesOf({ declarations }) {
|
|
406
|
+
const places = /* @__PURE__ */ new Map();
|
|
407
|
+
for (const { id, members, failures } of declarations) {
|
|
408
|
+
for (const [member, name] of members) if (!places.has(name)) places.set(name, `${id} ${member}`);
|
|
409
|
+
for (const [tag, name] of failures) if (!places.has(name)) places.set(name, `${id} failure ${tag}`);
|
|
410
|
+
}
|
|
411
|
+
return (schema) => schema.definition === void 0 ? places.get(schema.name) ?? schema.name : `type ${schema.definition}`;
|
|
412
|
+
}
|
|
413
|
+
// src/generate/effect.ts
|
|
414
|
+
/** An Effect struct removes the properties that it does not name, when it decodes and when it encodes. */
|
|
415
|
+
const HELPERS$1 = [
|
|
416
|
+
...CHECK_HELPERS,
|
|
417
|
+
[
|
|
418
|
+
"checked",
|
|
419
|
+
`function checked<S extends Schema.Top>(schema: S, check: (value: unknown, path: Path, issues: Issues) => boolean) {
|
|
420
|
+
const filter = Schema.makeFilter((value) => {
|
|
421
|
+
const issues: Issues = [];
|
|
422
|
+
check(value, [], issues);
|
|
423
|
+
return issues.map(({ path, message }) => ({ path, issue: message }));
|
|
424
|
+
});
|
|
425
|
+
return Schema.declare(Schema.is(Schema.toEncoded(schema))).check(filter).pipe(Schema.decodeTo(schema.check(filter)));
|
|
426
|
+
}`,
|
|
427
|
+
["Path", "Issues"]
|
|
428
|
+
],
|
|
429
|
+
[
|
|
430
|
+
"checkedFailure",
|
|
431
|
+
`function checkedFailure<S extends Schema.Top>(schema: S, check: (value: unknown, path: Path, issues: Issues) => boolean) {
|
|
432
|
+
return checked(schema, (value, path, issues) => check(withoutTag(value), path, issues));
|
|
433
|
+
}`,
|
|
434
|
+
["checked", "withoutTag"]
|
|
435
|
+
]
|
|
436
|
+
];
|
|
437
|
+
function closedObject(root, definitions) {
|
|
438
|
+
let closed = false;
|
|
439
|
+
const check = (node) => {
|
|
440
|
+
if (node.additionalProperties === false) closed = true;
|
|
441
|
+
};
|
|
442
|
+
visitObjects(root.schema, check);
|
|
443
|
+
for (const type of typesUsedBy(root.schema, definitions).values()) visitObjects(type, check);
|
|
444
|
+
return closed;
|
|
445
|
+
}
|
|
446
|
+
/** A failure that has a closed object reads as an empty schema in Effect, because its `_tag` is not a property of it. */
|
|
447
|
+
function schemaCode(roots, definitions) {
|
|
448
|
+
const fallback = /* @__PURE__ */ new Set();
|
|
449
|
+
const safeDefinitions = { ...definitions };
|
|
450
|
+
const accepts = (schema) => {
|
|
451
|
+
try {
|
|
452
|
+
readSchemas([schema], definitions, "apply");
|
|
453
|
+
return true;
|
|
454
|
+
} catch {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
for (const name of Object.keys(definitions)) if (!accepts({ $ref: `#/$defs/${name}` })) safeDefinitions[name] = {};
|
|
459
|
+
const [first = {}, ...rest] = roots.map((root) => {
|
|
460
|
+
const tagged = {
|
|
461
|
+
type: "object",
|
|
462
|
+
properties: { _tag: { const: root.tag } },
|
|
463
|
+
required: ["_tag"]
|
|
464
|
+
};
|
|
465
|
+
const schema = root.tag === void 0 ? root.schema : { allOf: [root.schema, tagged] };
|
|
466
|
+
if ((root.tag === void 0 || !closedObject(root, definitions)) && accepts(schema)) return schema;
|
|
467
|
+
fallback.add(root);
|
|
468
|
+
if (root.tag !== void 0) return tagged;
|
|
469
|
+
return typeof schema.$ref === "string" ? { $ref: schema.$ref } : {};
|
|
470
|
+
});
|
|
471
|
+
const [head, ...tail] = readSchemas([first, ...rest], safeDefinitions, "apply");
|
|
472
|
+
return {
|
|
473
|
+
document: SchemaRepresentation.toCodeDocument(SchemaRepresentation.toRepresentations([head.ast, ...tail.map((schema) => schema.ast)])),
|
|
474
|
+
fallback
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function generateEffect(catalog) {
|
|
478
|
+
const model = declarationsOf(catalog, [
|
|
479
|
+
"$defs",
|
|
480
|
+
"application",
|
|
481
|
+
"declarations",
|
|
482
|
+
"app",
|
|
483
|
+
"Schema",
|
|
484
|
+
...HELPERS$1.map(([name]) => name)
|
|
485
|
+
]);
|
|
486
|
+
const { definitions, schemas } = model;
|
|
487
|
+
const { document, fallback } = schemaCode(schemas, definitions);
|
|
488
|
+
const needsCheck = (root) => fallback.has(root) || closedObject(root, definitions);
|
|
489
|
+
const definitionNames = definitionNamesOf(model);
|
|
490
|
+
const whereOf = placesOf(model);
|
|
491
|
+
const needed = /* @__PURE__ */ new Set();
|
|
492
|
+
const checkFunction = checkWriter("effect", definitionNames, needed);
|
|
493
|
+
const checks = /* @__PURE__ */ new Map();
|
|
494
|
+
for (const root of schemas.filter(needsCheck)) {
|
|
495
|
+
const own = ownSchema(model, root);
|
|
496
|
+
if (!checks.has(root.name)) checks.set(root.name, checkFunction(whereOf(root), root.name, own));
|
|
497
|
+
for (const [definition, schema] of typesUsedBy(own, definitions)) {
|
|
498
|
+
const name = definitionNames.get(definition) ?? definition;
|
|
499
|
+
if (!checks.has(name)) checks.set(name, checkFunction(`type ${definition}`, name, schema));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const blocks = [definitionsBlock(model), ...checks.values()];
|
|
503
|
+
function expression(root, runtime) {
|
|
504
|
+
const helper = root.tag === void 0 ? "checked" : "checkedFailure";
|
|
505
|
+
if (needsCheck(root)) needed.add(helper);
|
|
506
|
+
return `app.withJsonSchema(
|
|
507
|
+
${needsCheck(root) ? `${helper}(${runtime}, ${checkName(root.name)})` : runtime},
|
|
508
|
+
${carried(model, root.schema)},
|
|
509
|
+
)`;
|
|
510
|
+
}
|
|
511
|
+
const byDefinition = new Map(schemas.flatMap((root) => root.definition === void 0 ? [] : [[root.definition, root]]));
|
|
512
|
+
const references = [...Object.entries(document.references.recursives).map(([$ref, code]) => ({
|
|
513
|
+
$ref,
|
|
514
|
+
code,
|
|
515
|
+
recursive: true
|
|
516
|
+
})), ...document.references.nonRecursives.map((reference) => ({
|
|
517
|
+
...reference,
|
|
518
|
+
recursive: false
|
|
519
|
+
}))];
|
|
520
|
+
for (const { $ref, code, recursive } of references) {
|
|
521
|
+
const root = byDefinition.get($ref);
|
|
522
|
+
const runtime = recursive ? `Schema.suspend((): Schema.Codec<${$ref}> => ${code.runtime})` : code.runtime;
|
|
523
|
+
const schema = root === void 0 ? runtime : expression(root, runtime);
|
|
524
|
+
blocks.push(`export type ${$ref} = ${code.Type};\nexport const ${$ref} = ${schema};`);
|
|
525
|
+
}
|
|
526
|
+
for (const [index, root] of schemas.entries()) {
|
|
527
|
+
const code = document.codes[index];
|
|
528
|
+
if (code === void 0) throw new Error(`Missing schema for ${root.name}.`);
|
|
529
|
+
if (root.definition !== void 0) {
|
|
530
|
+
if (code.runtime !== root.name) throw new Error(`Effect names the type ${root.name} ${code.runtime}.`);
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
blocks.push(`export const ${root.name} = ${expression(root, code.runtime)};\nexport type ${root.name} = typeof ${root.name}.Type;`);
|
|
534
|
+
}
|
|
535
|
+
for (const declaration of model.declarations) blocks.push(declarationBlock(declaration, (failures) => `[${failures.map(([, name]) => name).join(", ")}]`));
|
|
536
|
+
blocks.push(declarationsBlock(model), applicationBlock(model));
|
|
537
|
+
const imports = schemas.length === 0 ? [] : ["import * as app from \"@acid-cat/core-effect/App\";", "import { Schema } from \"effect\";"];
|
|
538
|
+
return sourceOf(imports, [helperCode(HELPERS$1, needed).code, ...blocks]);
|
|
539
|
+
}
|
|
540
|
+
// src/generate/rust.ts
|
|
541
|
+
const KEYWORDS = /* @__PURE__ */ new Set([
|
|
542
|
+
"abstract",
|
|
543
|
+
"as",
|
|
544
|
+
"async",
|
|
545
|
+
"await",
|
|
546
|
+
"become",
|
|
547
|
+
"box",
|
|
548
|
+
"break",
|
|
549
|
+
"const",
|
|
550
|
+
"continue",
|
|
551
|
+
"crate",
|
|
552
|
+
"do",
|
|
553
|
+
"dyn",
|
|
554
|
+
"else",
|
|
555
|
+
"enum",
|
|
556
|
+
"extern",
|
|
557
|
+
"false",
|
|
558
|
+
"final",
|
|
559
|
+
"fn",
|
|
560
|
+
"for",
|
|
561
|
+
"gen",
|
|
562
|
+
"if",
|
|
563
|
+
"impl",
|
|
564
|
+
"in",
|
|
565
|
+
"let",
|
|
566
|
+
"loop",
|
|
567
|
+
"macro",
|
|
568
|
+
"match",
|
|
569
|
+
"mod",
|
|
570
|
+
"move",
|
|
571
|
+
"mut",
|
|
572
|
+
"override",
|
|
573
|
+
"priv",
|
|
574
|
+
"pub",
|
|
575
|
+
"ref",
|
|
576
|
+
"return",
|
|
577
|
+
"self",
|
|
578
|
+
"Self",
|
|
579
|
+
"static",
|
|
580
|
+
"struct",
|
|
581
|
+
"super",
|
|
582
|
+
"trait",
|
|
583
|
+
"true",
|
|
584
|
+
"try",
|
|
585
|
+
"type",
|
|
586
|
+
"typeof",
|
|
587
|
+
"unsafe",
|
|
588
|
+
"unsized",
|
|
589
|
+
"use",
|
|
590
|
+
"virtual",
|
|
591
|
+
"where",
|
|
592
|
+
"while",
|
|
593
|
+
"yield"
|
|
594
|
+
]);
|
|
595
|
+
const NOT_RAW = /* @__PURE__ */ new Set([
|
|
596
|
+
"crate",
|
|
597
|
+
"self",
|
|
598
|
+
"Self",
|
|
599
|
+
"super"
|
|
600
|
+
]);
|
|
601
|
+
const VALUE_ONLY_KEYWORDS = /* @__PURE__ */ new Set([
|
|
602
|
+
"$comment",
|
|
603
|
+
"$schema",
|
|
604
|
+
"default",
|
|
605
|
+
"deprecated",
|
|
606
|
+
"description",
|
|
607
|
+
"examples",
|
|
608
|
+
"format",
|
|
609
|
+
"readOnly",
|
|
610
|
+
"title",
|
|
611
|
+
"writeOnly",
|
|
612
|
+
"minimum",
|
|
613
|
+
"maximum",
|
|
614
|
+
"exclusiveMinimum",
|
|
615
|
+
"exclusiveMaximum",
|
|
616
|
+
"multipleOf",
|
|
617
|
+
"minLength",
|
|
618
|
+
"maxLength",
|
|
619
|
+
"pattern",
|
|
620
|
+
"minItems",
|
|
621
|
+
"maxItems",
|
|
622
|
+
"uniqueItems",
|
|
623
|
+
"minProperties",
|
|
624
|
+
"maxProperties",
|
|
625
|
+
"contentEncoding",
|
|
626
|
+
"contentMediaType",
|
|
627
|
+
"contentSchema"
|
|
628
|
+
]);
|
|
629
|
+
const SHAPE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
630
|
+
"$ref",
|
|
631
|
+
"type",
|
|
632
|
+
"enum",
|
|
633
|
+
"properties",
|
|
634
|
+
"required",
|
|
635
|
+
"items",
|
|
636
|
+
"additionalProperties"
|
|
637
|
+
]);
|
|
638
|
+
const VALUE = "serde_json::Value";
|
|
639
|
+
const OBJECT = "serde_json::Map<String, serde_json::Value>";
|
|
640
|
+
const DERIVE = "#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]";
|
|
641
|
+
const DERIVE_ENUM = "#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]";
|
|
642
|
+
const PRIMITIVES = /* @__PURE__ */ new Map([
|
|
643
|
+
["string", "String"],
|
|
644
|
+
["boolean", "bool"],
|
|
645
|
+
["integer", "i64"],
|
|
646
|
+
["number", "f64"],
|
|
647
|
+
["null", "()"]
|
|
648
|
+
]);
|
|
649
|
+
const ESCAPES = {
|
|
650
|
+
"\\": "\\\\",
|
|
651
|
+
"\"": "\\\"",
|
|
652
|
+
"\n": "\\n",
|
|
653
|
+
"\r": "\\r",
|
|
654
|
+
" ": "\\t"
|
|
655
|
+
};
|
|
656
|
+
function rustString(text) {
|
|
657
|
+
let escaped = "";
|
|
658
|
+
for (const character of text) {
|
|
659
|
+
const code = character.codePointAt(0) ?? 0;
|
|
660
|
+
escaped += ESCAPES[character] ?? (code < 32 || code === 127 ? `\\u{${code.toString(16)}}` : character);
|
|
661
|
+
}
|
|
662
|
+
return `"${escaped}"`;
|
|
663
|
+
}
|
|
664
|
+
function json(value, indent) {
|
|
665
|
+
const inner = `${indent} `;
|
|
666
|
+
if (typeof value === "string") return rustString(value);
|
|
667
|
+
if (Array.isArray(value)) {
|
|
668
|
+
if (value.length === 0) return "[]";
|
|
669
|
+
return `[\n${value.map((item) => inner + json(item, inner)).join(",\n")}\n${indent}]`;
|
|
670
|
+
}
|
|
671
|
+
if (isJsonObject(value)) {
|
|
672
|
+
const entries = Object.entries(value);
|
|
673
|
+
if (entries.length === 0) return "{}";
|
|
674
|
+
return `{\n${entries.map(([key, item]) => `${inner}${rustString(key)}: ${json(item, inner)}`).join(",\n")}\n${indent}}`;
|
|
675
|
+
}
|
|
676
|
+
return JSON.stringify(value);
|
|
677
|
+
}
|
|
678
|
+
const jsonMacro = (value, indent) => `serde_json::json!(${json(value, indent)})`;
|
|
679
|
+
const identifier = (name) => KEYWORDS.has(name) ? NOT_RAW.has(name) ? `${name}_` : `r#${name}` : name;
|
|
680
|
+
function snakeCase(text) {
|
|
681
|
+
const snake = text.replace(/([a-z0-9])([A-Z])/gu, "$1_$2").replace(/[^A-Za-z0-9]+/gu, "_").replace(/^_+|_+$/gu, "").toLowerCase();
|
|
682
|
+
if (snake === "") return "value";
|
|
683
|
+
return /^[0-9]/u.test(snake) ? `_${snake}` : snake;
|
|
684
|
+
}
|
|
685
|
+
const typeNames = (schema) => typeof schema.type === "string" ? schema.type : void 0;
|
|
686
|
+
function isPlain(schema) {
|
|
687
|
+
return Object.keys(schema).every((keyword) => SHAPE_KEYWORDS.has(keyword) || VALUE_ONLY_KEYWORDS.has(keyword) || keyword.startsWith("x-"));
|
|
688
|
+
}
|
|
689
|
+
function objectShape(schema) {
|
|
690
|
+
if (typeNames(schema) !== "object" || !isPlain(schema)) return void 0;
|
|
691
|
+
if (schema.additionalProperties !== void 0 && typeof schema.additionalProperties !== "boolean") return void 0;
|
|
692
|
+
const properties = schema.properties === void 0 ? {} : isJsonObject(schema.properties) ? schema.properties : void 0;
|
|
693
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
694
|
+
if (properties === void 0 || required.some((name) => typeof name !== "string" || !Object.hasOwn(properties, name))) return void 0;
|
|
695
|
+
return {
|
|
696
|
+
properties,
|
|
697
|
+
required
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
const isStruct = (schema) => Object.hasOwn(schema, "properties") && objectShape(schema) !== void 0;
|
|
701
|
+
function variantsOf(schema) {
|
|
702
|
+
if (!Array.isArray(schema.enum) || !isPlain(schema) || schema.type !== void 0 && schema.type !== "string") return void 0;
|
|
703
|
+
if (Object.keys(schema).some((keyword) => SHAPE_KEYWORDS.has(keyword) && keyword !== "enum" && keyword !== "type")) return void 0;
|
|
704
|
+
const variants = [];
|
|
705
|
+
for (const value of schema.enum) {
|
|
706
|
+
const variant = typeof value === "string" ? words(value) : "";
|
|
707
|
+
if (typeof value !== "string" || !/^[A-Za-z]/u.test(variant) || KEYWORDS.has(variant) || variants.some(([used]) => used === variant)) return void 0;
|
|
708
|
+
variants.push([variant, value]);
|
|
709
|
+
}
|
|
710
|
+
return variants.length === 0 ? void 0 : variants;
|
|
711
|
+
}
|
|
712
|
+
function rustTypes(definitionNames, unique) {
|
|
713
|
+
const blocks = [];
|
|
714
|
+
function fieldsOf(owner, schema, visibility = "pub ") {
|
|
715
|
+
const { properties, required } = objectShape(schema) ?? {
|
|
716
|
+
properties: {},
|
|
717
|
+
required: []
|
|
718
|
+
};
|
|
719
|
+
const fieldName = uniqueNames([]);
|
|
720
|
+
return Object.entries(properties).flatMap(([property, child]) => {
|
|
721
|
+
const name = fieldName(snakeCase(property));
|
|
722
|
+
const type = formOf(child, owner + words(property));
|
|
723
|
+
const optional = !required.includes(property);
|
|
724
|
+
return [
|
|
725
|
+
...name === property ? [] : [`#[serde(rename = ${rustString(property)})]`],
|
|
726
|
+
...optional ? ["#[serde(skip_serializing_if = \"Option::is_none\")]"] : [],
|
|
727
|
+
`${visibility}${identifier(name)}: ${optional ? `Option<${type}>` : type},`
|
|
728
|
+
];
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
const braced = (head, lines, indent) => lines.length === 0 ? `${head} {}` : `${head} {\n${lines.map((line) => indent + " " + line).join("\n")}\n${indent}}`;
|
|
732
|
+
function referenced(schema) {
|
|
733
|
+
const name = typeof schema.$ref === "string" ? REFERENCE.exec(schema.$ref)?.[1] : void 0;
|
|
734
|
+
const others = Object.keys(schema).some((keyword) => SHAPE_KEYWORDS.has(keyword) && keyword !== "$ref");
|
|
735
|
+
return name !== void 0 && definitionNames.has(name) && isPlain(schema) && !others ? name : void 0;
|
|
736
|
+
}
|
|
737
|
+
function declare(name, schema) {
|
|
738
|
+
const slot = blocks.push("") - 1;
|
|
739
|
+
const object = isJsonObject(schema) ? schema : {};
|
|
740
|
+
const variants = variantsOf(object);
|
|
741
|
+
if (isStruct(object)) blocks[slot] = `${DERIVE}\n${braced(`pub struct ${name}`, fieldsOf(name, object), "")}`;
|
|
742
|
+
else if (variants !== void 0) {
|
|
743
|
+
const lines = variants.flatMap(([variant, value]) => [`#[serde(rename = ${rustString(value)})]`, `${variant},`]);
|
|
744
|
+
blocks[slot] = `${DERIVE_ENUM}\n${braced(`pub enum ${name}`, lines, "")}`;
|
|
745
|
+
} else blocks[slot] = `pub type ${name} = ${inlineForm(schema, name)};`;
|
|
746
|
+
}
|
|
747
|
+
function inlineForm(schema, hint) {
|
|
748
|
+
if (!isJsonObject(schema) || !isPlain(schema)) return VALUE;
|
|
749
|
+
const name = referenced(schema);
|
|
750
|
+
if (name !== void 0) return name;
|
|
751
|
+
if (schema.$ref !== void 0 || schema.enum !== void 0) return VALUE;
|
|
752
|
+
const type = typeNames(schema);
|
|
753
|
+
if (type === void 0) return VALUE;
|
|
754
|
+
const primitive = PRIMITIVES.get(type);
|
|
755
|
+
if (primitive !== void 0) return primitive;
|
|
756
|
+
if (type === "array") return `Vec<${schema.items === void 0 ? VALUE : formOf(schema.items, `${hint}Item`)}>`;
|
|
757
|
+
if (type === "object" && objectShape(schema) !== void 0 && !Object.hasOwn(schema, "required")) return OBJECT;
|
|
758
|
+
return VALUE;
|
|
759
|
+
}
|
|
760
|
+
function formOf(schema, hint) {
|
|
761
|
+
const object = isJsonObject(schema) ? schema : {};
|
|
762
|
+
if (!isStruct(object) && variantsOf(object) === void 0) return inlineForm(schema, hint);
|
|
763
|
+
const name = unique(hint);
|
|
764
|
+
declare(name, schema);
|
|
765
|
+
return name;
|
|
766
|
+
}
|
|
767
|
+
return {
|
|
768
|
+
blocks,
|
|
769
|
+
declare,
|
|
770
|
+
fieldsOf,
|
|
771
|
+
braced,
|
|
772
|
+
referenced
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
function failureSets(declarations, unique) {
|
|
776
|
+
const sets = /* @__PURE__ */ new Map();
|
|
777
|
+
const nameOf = /* @__PURE__ */ new Map();
|
|
778
|
+
for (const { id, failures } of declarations) {
|
|
779
|
+
if (failures.length === 0) continue;
|
|
780
|
+
const key = JSON.stringify(failures);
|
|
781
|
+
const known = sets.get(key) ?? {
|
|
782
|
+
name: unique(`Failure${failures.map(([tag]) => words(tag)).join("Or")}`),
|
|
783
|
+
failures
|
|
784
|
+
};
|
|
785
|
+
sets.set(key, known);
|
|
786
|
+
nameOf.set(id, known.name);
|
|
787
|
+
}
|
|
788
|
+
return {
|
|
789
|
+
sets: [...sets.values()],
|
|
790
|
+
nameOf
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
const capabilityMembers = /* @__PURE__ */ new Set([
|
|
794
|
+
"description",
|
|
795
|
+
"audience",
|
|
796
|
+
"readOnly",
|
|
797
|
+
"destructive",
|
|
798
|
+
"idempotent"
|
|
799
|
+
]);
|
|
800
|
+
function metadataCalls(id, metadata) {
|
|
801
|
+
const calls = [];
|
|
802
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
803
|
+
if (!capabilityMembers.has(key)) throw new GenerateError(`${id}: acid-cat generate --core rust cannot write the member ${key}`);
|
|
804
|
+
if (key === "audience" && Array.isArray(value) && value.length > 0) calls.push(`.audience([${value.map((target) => rustString(String(target))).join(", ")}])`);
|
|
805
|
+
if (key === "readOnly" && value === true) calls.push(".read_only()");
|
|
806
|
+
if ((key === "destructive" || key === "idempotent") && typeof value === "boolean") calls.push(`.${key}(${value})`);
|
|
807
|
+
}
|
|
808
|
+
return calls;
|
|
809
|
+
}
|
|
810
|
+
const chain = (head, calls) => [` ${head}`, ...calls.map((call) => ` ${call}`)].join("\n");
|
|
811
|
+
function generateRust(catalog) {
|
|
812
|
+
const { definitions, schemas, declarations, application } = declarationsOf(catalog, [
|
|
813
|
+
"Option",
|
|
814
|
+
"String",
|
|
815
|
+
"Vec"
|
|
816
|
+
]);
|
|
817
|
+
for (const name of Object.keys(definitions)) if (KEYWORDS.has(name)) throw new GenerateError(`type ${name}: the name is a Rust keyword; give the type another name`);
|
|
818
|
+
const unique = uniqueNames([
|
|
819
|
+
"Option",
|
|
820
|
+
"String",
|
|
821
|
+
"Vec",
|
|
822
|
+
...schemas.filter((schema) => schema.tag === void 0).map((schema) => schema.name)
|
|
823
|
+
]);
|
|
824
|
+
const types = rustTypes(new Set(Object.keys(definitions)), unique);
|
|
825
|
+
const schemaOf = new Map(schemas.map((schema) => [schema.name, schema.schema]));
|
|
826
|
+
for (const schema of schemas) {
|
|
827
|
+
if (schema.tag !== void 0) continue;
|
|
828
|
+
types.declare(schema.name, schema.definition === void 0 ? schema.schema : definitions[schema.definition]);
|
|
829
|
+
}
|
|
830
|
+
const { sets, nameOf } = failureSets(declarations, unique);
|
|
831
|
+
for (const { name, failures } of sets) {
|
|
832
|
+
const variants = [];
|
|
833
|
+
const conversions = [];
|
|
834
|
+
for (const [tag, schemaName] of failures) {
|
|
835
|
+
const schema = schemaOf.get(schemaName) ?? {};
|
|
836
|
+
const variant = words(tag);
|
|
837
|
+
const rename = variant === tag ? [] : [` #[serde(rename = ${rustString(tag)})]`];
|
|
838
|
+
const reference = types.referenced(schema);
|
|
839
|
+
const definition = reference === void 0 ? void 0 : definitions[reference];
|
|
840
|
+
if (reference !== void 0 && definition !== void 0 && objectShape(definition) !== void 0) {
|
|
841
|
+
variants.push(...rename, ` ${variant}(${reference}),`);
|
|
842
|
+
if (failures.filter(([, other]) => types.referenced(schemaOf.get(other) ?? {}) === reference).length === 1) conversions.push(`impl From<${reference}> for ${name} {\n fn from(failure: ${reference}) -> Self {\n ${name}::${variant}(failure)\n }\n}`);
|
|
843
|
+
} else if (reference === void 0 && objectShape(schema) !== void 0) variants.push(...rename, ` ${types.braced(variant, types.fieldsOf(name + variant, schema, ""), " ")},`);
|
|
844
|
+
else variants.push(...rename, ` ${variant}(${OBJECT}),`);
|
|
845
|
+
}
|
|
846
|
+
types.blocks.push(`${DERIVE}\n#[serde(tag = "_tag")]\npub enum ${name} {\n${variants.join("\n")}\n}`, ...conversions);
|
|
847
|
+
}
|
|
848
|
+
const functionName = uniqueNames(["application", "declarations"]);
|
|
849
|
+
const blocks = [...types.blocks];
|
|
850
|
+
const listed = [];
|
|
851
|
+
for (const declaration of declarations) {
|
|
852
|
+
const { id, metadata, members } = declaration;
|
|
853
|
+
const name = identifier(functionName(snakeCase(id)));
|
|
854
|
+
const member = (key) => members.find(([each]) => each === key)?.[1];
|
|
855
|
+
const carried = (key) => jsonMacro(schemaOf.get(member(key) ?? "") ?? {}, " ");
|
|
856
|
+
const { description, ...rest } = metadata;
|
|
857
|
+
const head = (kind) => `acid_cat_core::${kind}::new(${rustString(id)}, ${rustString(String(description))})`;
|
|
858
|
+
const calls = metadataCalls(id, rest);
|
|
859
|
+
const input = member("input");
|
|
860
|
+
const fixed = input ?? "acid_cat_core::NoInput";
|
|
861
|
+
if (input !== void 0) calls.push(`.input_schema::<${input}>(${carried("input")})`);
|
|
862
|
+
if (Object.hasOwn(catalog.capabilities, id)) {
|
|
863
|
+
const output = member("output") ?? "()";
|
|
864
|
+
const failures = nameOf.get(id) ?? "acid_cat_core::NoFailure";
|
|
865
|
+
if (member("output") !== void 0) calls.push(`.output_schema::<${output}>(${carried("output")})`);
|
|
866
|
+
if (declaration.failures.length > 0) {
|
|
867
|
+
const pairs = declaration.failures.map(([tag, schemaName]) => ` (${rustString(tag)}, ${jsonMacro(schemaOf.get(schemaName), " ")}),`);
|
|
868
|
+
calls.push(`.failure_schemas::<${failures}, &str>([\n${pairs.join("\n")}\n ])`);
|
|
869
|
+
}
|
|
870
|
+
const returned = `acid_cat_core::Capability<C, ${input ?? "()"}, ${output}, ${failures}, ${fixed}>`;
|
|
871
|
+
const state = member("state");
|
|
872
|
+
if (state === void 0) {
|
|
873
|
+
blocks.push(`pub fn ${name}<C>() -> ${returned} {\n${chain(head("Capability"), calls)}\n}`);
|
|
874
|
+
listed.push(`.capability(${name}())`);
|
|
875
|
+
} else {
|
|
876
|
+
const declared = identifier(functionName(`${snakeCase(id)}_declared`));
|
|
877
|
+
calls.push(`.declared_state(${carried("state")})`);
|
|
878
|
+
const parameter = `\n state: impl Fn(&C) -> tokio::sync::watch::Receiver<${state}> + Send + Sync + 'static,\n`;
|
|
879
|
+
blocks.push(`pub fn ${name}<C>(${parameter}) -> ${returned} {\n ${declared}().state_source(state)\n}`);
|
|
880
|
+
blocks.push(`fn ${declared}<C>() -> ${returned} {\n${chain(head("Capability"), calls)}\n}`);
|
|
881
|
+
listed.push(`.capability(${declared}())`);
|
|
882
|
+
}
|
|
883
|
+
} else {
|
|
884
|
+
const payload = member("payload") ?? "acid_cat_core::NoPayload";
|
|
885
|
+
if (member("payload") !== void 0) calls.push(`.payload_schema::<${payload}>(${carried("payload")})`);
|
|
886
|
+
blocks.push(`pub fn ${name}<C>() -> acid_cat_core::Event<C, ${input ?? "()"}, ${payload}, ${fixed}> {\n${chain(head("Event"), calls)}\n}`);
|
|
887
|
+
listed.push(`.event(${name}())`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
blocks.push(`pub fn declarations<C>() -> acid_cat_core::Declarations<C> {\n${chain("acid_cat_core::Declarations::new()", listed)}\n}`);
|
|
891
|
+
const settings = [];
|
|
892
|
+
if (typeof application.title === "string") settings.push(`.title(${rustString(application.title)})`);
|
|
893
|
+
if (typeof application.description === "string") settings.push(`.description(${rustString(application.description)})`);
|
|
894
|
+
for (const [target, value] of Object.entries(catalog.targets)) {
|
|
895
|
+
const { surfaces, description, options, ...extra } = value;
|
|
896
|
+
const unknown = Object.keys(extra)[0];
|
|
897
|
+
if (unknown !== void 0) throw new GenerateError(`target ${target}: acid-cat generate --core rust cannot write the member ${unknown}`);
|
|
898
|
+
const members = [
|
|
899
|
+
`surfaces: vec![${surfaces.map((surface) => `${rustString(surface)}.into()`).join(", ")}],`,
|
|
900
|
+
`description: ${typeof description === "string" ? `Some(${rustString(description)}.into())` : "None"},`,
|
|
901
|
+
`options: ${options === void 0 ? "None" : `Some(${jsonMacro(options, " ")})`},`
|
|
902
|
+
];
|
|
903
|
+
settings.push(`.target_with(\n ${rustString(target)},\n acid_cat_core::Target {\n${members.map((line) => ` ${line}`).join("\n")}\n },\n )`);
|
|
904
|
+
}
|
|
905
|
+
for (const [name, schema] of Object.entries(definitions)) settings.push(`.r#type(${rustString(name)}, ${jsonMacro(schema, " ")})`);
|
|
906
|
+
blocks.push(`pub fn application<C: Send + Sync + 'static>() -> acid_cat_core::App<C> {\n${chain("acid_cat_core::App::new()", settings)}\n}`);
|
|
907
|
+
return `${blocks.join("\n\n")}\n`;
|
|
908
|
+
}
|
|
909
|
+
// src/generate/ts.ts
|
|
910
|
+
const HELPERS = [
|
|
911
|
+
...CHECK_HELPERS,
|
|
912
|
+
[
|
|
913
|
+
"Check",
|
|
914
|
+
"type Check<T> = (value: unknown, path: Path, issues: Issues) => value is T;",
|
|
915
|
+
["Path", "Issues"]
|
|
916
|
+
],
|
|
917
|
+
[
|
|
918
|
+
"standard",
|
|
919
|
+
`function standard<T>(check: Check<T>, jsonSchema: JsonObject) {
|
|
920
|
+
const schema: StandardSchemaV1<T> = {
|
|
921
|
+
"~standard": {
|
|
922
|
+
version: 1,
|
|
923
|
+
vendor: "acid-cat",
|
|
924
|
+
validate: (value) => {
|
|
925
|
+
const issues: Issues = [];
|
|
926
|
+
return check(value, [], issues) ? { value } : { issues };
|
|
927
|
+
},
|
|
928
|
+
},
|
|
929
|
+
};
|
|
930
|
+
return withJsonSchema(schema, jsonSchema);
|
|
931
|
+
}`,
|
|
932
|
+
[
|
|
933
|
+
"Check",
|
|
934
|
+
"Issues",
|
|
935
|
+
"StandardSchemaV1",
|
|
936
|
+
"JsonObject",
|
|
937
|
+
"withJsonSchema"
|
|
938
|
+
]
|
|
939
|
+
],
|
|
940
|
+
[
|
|
941
|
+
"failure",
|
|
942
|
+
`function failure<T>(check: Check<T>, jsonSchema: JsonObject) {
|
|
943
|
+
const schema: StandardSchemaV1<T> = {
|
|
944
|
+
"~standard": {
|
|
945
|
+
version: 1,
|
|
946
|
+
vendor: "acid-cat",
|
|
947
|
+
validate: (value) => {
|
|
948
|
+
const issues: Issues = [];
|
|
949
|
+
const data = withoutTag(value);
|
|
950
|
+
return check(data, [], issues) ? { value: data } : { issues };
|
|
951
|
+
},
|
|
952
|
+
},
|
|
953
|
+
};
|
|
954
|
+
return withJsonSchema(schema, jsonSchema);
|
|
955
|
+
}`,
|
|
956
|
+
[
|
|
957
|
+
"Check",
|
|
958
|
+
"Issues",
|
|
959
|
+
"StandardSchemaV1",
|
|
960
|
+
"JsonObject",
|
|
961
|
+
"withJsonSchema",
|
|
962
|
+
"withoutTag"
|
|
963
|
+
]
|
|
964
|
+
]
|
|
965
|
+
];
|
|
966
|
+
const IMPORTS = [
|
|
967
|
+
[
|
|
968
|
+
"withJsonSchema",
|
|
969
|
+
"@acid-cat/core-ts",
|
|
970
|
+
false
|
|
971
|
+
],
|
|
972
|
+
[
|
|
973
|
+
"StandardSchemaV1",
|
|
974
|
+
"@acid-cat/core-ts",
|
|
975
|
+
true
|
|
976
|
+
],
|
|
977
|
+
[
|
|
978
|
+
"JsonObject",
|
|
979
|
+
"@acid-cat/spec-ts",
|
|
980
|
+
true
|
|
981
|
+
]
|
|
982
|
+
];
|
|
983
|
+
function importsOf(used) {
|
|
984
|
+
const imports = [];
|
|
985
|
+
for (const module of ["@acid-cat/core-ts", "@acid-cat/spec-ts"]) {
|
|
986
|
+
const of = IMPORTS.filter(([name, from]) => from === module && used.has(name));
|
|
987
|
+
const values = of.filter(([, , typeOnly]) => !typeOnly).map(([name]) => name);
|
|
988
|
+
const types = of.filter(([, , typeOnly]) => typeOnly).map(([name]) => name);
|
|
989
|
+
if (values.length > 0) imports.push(`import { ${values.join(", ")} } from "${module}";`);
|
|
990
|
+
if (types.length > 0) imports.push(`import type { ${types.join(", ")} } from "${module}";`);
|
|
991
|
+
}
|
|
992
|
+
return imports;
|
|
993
|
+
}
|
|
994
|
+
function typeWriter(definitionNames, needed) {
|
|
995
|
+
function typeOf(where, schema) {
|
|
996
|
+
if (schema === true) return "unknown";
|
|
997
|
+
if (schema === false) return "never";
|
|
998
|
+
if (!isJsonObject(schema)) throw new GenerateError(`${where}: a schema is not an object or a boolean`);
|
|
999
|
+
const parts = [];
|
|
1000
|
+
if (schema.$ref !== void 0) parts.push(referencedType(definitionNames, where, schema));
|
|
1001
|
+
if (Array.isArray(schema.enum)) parts.push(schema.enum.map((value) => literal(value)).join(" | ") || "never");
|
|
1002
|
+
else if (Object.hasOwn(schema, "const")) parts.push(literal(schema.const));
|
|
1003
|
+
else if (schema.type !== void 0) parts.push(typeNames$1(schema.type).map((type) => valueType(where, schema, type)).join(" | "));
|
|
1004
|
+
if (Array.isArray(schema.allOf)) parts.push(...schema.allOf.map((member) => typeOf(where, member)));
|
|
1005
|
+
for (const union of [schema.anyOf, schema.oneOf]) {
|
|
1006
|
+
if (!Array.isArray(union)) continue;
|
|
1007
|
+
const members = union.map((member) => typeOf(where, member));
|
|
1008
|
+
if (!members.includes("unknown")) parts.push(members.join(" | "));
|
|
1009
|
+
}
|
|
1010
|
+
const known = parts.filter((part) => part !== "unknown");
|
|
1011
|
+
if (known.length === 0) return "unknown";
|
|
1012
|
+
return known.length === 1 ? known[0] ?? "unknown" : known.map((part) => part.includes("|") ? `(${part})` : part).join(" & ");
|
|
1013
|
+
}
|
|
1014
|
+
function valueType(where, schema, type) {
|
|
1015
|
+
if (type === "integer") return "number";
|
|
1016
|
+
if (type === "array") return `ReadonlyArray<${schema.items === void 0 ? "unknown" : typeOf(where, schema.items)}>`;
|
|
1017
|
+
if (type !== "object") return type;
|
|
1018
|
+
const properties = isJsonObject(schema.properties) ? schema.properties : {};
|
|
1019
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name === "string") : [];
|
|
1020
|
+
const fields = Object.entries(properties).map(([name, property]) => `readonly ${literal(name)}${required.includes(name) ? "" : "?"}: ${typeOf(where, property)}`);
|
|
1021
|
+
for (const name of required) if (!Object.hasOwn(properties, name)) fields.push(`readonly ${literal(name)}: unknown`);
|
|
1022
|
+
if (fields.length > 0) return `{ ${fields.join("; ")} }`;
|
|
1023
|
+
needed.add("JsonObject");
|
|
1024
|
+
return "JsonObject";
|
|
1025
|
+
}
|
|
1026
|
+
return typeOf;
|
|
1027
|
+
}
|
|
1028
|
+
function generateTs(catalog) {
|
|
1029
|
+
const model = declarationsOf(catalog, [
|
|
1030
|
+
"$defs",
|
|
1031
|
+
"application",
|
|
1032
|
+
"declarations",
|
|
1033
|
+
...HELPERS.map(([name]) => name),
|
|
1034
|
+
...IMPORTS.map(([name]) => name)
|
|
1035
|
+
]);
|
|
1036
|
+
const definitionNames = definitionNamesOf(model);
|
|
1037
|
+
const whereOf = placesOf(model);
|
|
1038
|
+
const needed = /* @__PURE__ */ new Set();
|
|
1039
|
+
const typeOf = typeWriter(definitionNames, needed);
|
|
1040
|
+
const checkFunction = checkWriter("ts", definitionNames, needed);
|
|
1041
|
+
const blocks = [definitionsBlock(model)];
|
|
1042
|
+
for (const schema of model.schemas) {
|
|
1043
|
+
const own = ownSchema(model, schema);
|
|
1044
|
+
const where = whereOf(schema);
|
|
1045
|
+
const wrapper = schema.tag === void 0 ? "standard" : "failure";
|
|
1046
|
+
needed.add(wrapper);
|
|
1047
|
+
const check = checkFunction(where, schema.name, own, schema.name);
|
|
1048
|
+
blocks.push(`export type ${schema.name} = ${typeOf(where, own)};
|
|
1049
|
+
${check}
|
|
1050
|
+
export const ${schema.name} = ${wrapper}(${checkName(schema.name)}, ${carried(model, schema.schema)});`);
|
|
1051
|
+
}
|
|
1052
|
+
for (const declaration of model.declarations) blocks.push(declarationBlock(declaration, (failures) => `{ ${failures.map(([tag, name]) => `${literal(tag)}: ${name}`).join(", ")} }`));
|
|
1053
|
+
blocks.push(declarationsBlock(model), applicationBlock(model));
|
|
1054
|
+
const { used, code } = helperCode(HELPERS, needed);
|
|
1055
|
+
return sourceOf(importsOf(used), [code, ...blocks]);
|
|
1056
|
+
}
|
|
11
1057
|
// src/main.ts
|
|
12
1058
|
var UnreadableFile = class extends Data.TaggedError("UnreadableFile") {};
|
|
13
1059
|
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
@@ -82,6 +1128,42 @@ const formatCommand = Command.make("format", {
|
|
|
82
1128
|
else yield* Effect.sync(() => process.stdout.write(text));
|
|
83
1129
|
}
|
|
84
1130
|
}, Effect.catchTag("UnreadableFile", reportUnreadable))).pipe(Command.withDescription("Write catalogs in canonical form."));
|
|
1131
|
+
const generators = {
|
|
1132
|
+
effect: generateEffect,
|
|
1133
|
+
ts: generateTs,
|
|
1134
|
+
rust: generateRust
|
|
1135
|
+
};
|
|
1136
|
+
const generateCommand = Command.make("generate", {
|
|
1137
|
+
file: Argument.String("catalog"),
|
|
1138
|
+
core: Flag.Literals("core", [
|
|
1139
|
+
"effect",
|
|
1140
|
+
"ts",
|
|
1141
|
+
"rust"
|
|
1142
|
+
]),
|
|
1143
|
+
out: Flag.String("out"),
|
|
1144
|
+
checkOnly: Flag.Boolean("check").pipe(Flag.withDescription("Check the generated file without writing it"), Flag.withDefault(false))
|
|
1145
|
+
}, Effect.fn(function* ({ file, core, out, checkOnly }) {
|
|
1146
|
+
const { document } = yield* readCatalog(file);
|
|
1147
|
+
const { errors } = check(document);
|
|
1148
|
+
if (errors.length > 0 || !isCatalog(document)) {
|
|
1149
|
+
yield* Console.error(`${file}: ${errors.join("\n")}`);
|
|
1150
|
+
return yield* fail;
|
|
1151
|
+
}
|
|
1152
|
+
let source;
|
|
1153
|
+
try {
|
|
1154
|
+
source = generators[core](document);
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
if (!(error instanceof GenerateError)) throw error;
|
|
1157
|
+
yield* Console.error(`${file}: ${error.message}`);
|
|
1158
|
+
return yield* fail;
|
|
1159
|
+
}
|
|
1160
|
+
if (checkOnly) {
|
|
1161
|
+
if ((yield* readText(out)) === source) return;
|
|
1162
|
+
yield* Console.error(`${out}: stale; run acid-cat generate without --check`);
|
|
1163
|
+
return yield* fail;
|
|
1164
|
+
}
|
|
1165
|
+
yield* (yield* FileSystem.FileSystem).writeFileString(out, source);
|
|
1166
|
+
}, Effect.catchTag("UnreadableFile", reportUnreadable))).pipe(Command.withDescription("Write the declarations and types of a catalog for a core."));
|
|
85
1167
|
const targetCommand = Command.make("target", {
|
|
86
1168
|
file: Argument.String("catalog").pipe(Argument.withDescription("A catalog file")),
|
|
87
1169
|
target: Argument.String("target").pipe(Argument.withDescription("The name of a target in the catalog"))
|
|
@@ -95,7 +1177,7 @@ const targetCommand = Command.make("target", {
|
|
|
95
1177
|
yield* Console.error(`${file}: error: there is no target ${target}`);
|
|
96
1178
|
return yield* fail;
|
|
97
1179
|
}
|
|
98
|
-
yield* Effect.sync(() => process.stdout.write(canonicalText(targetCatalog(catalog, target))));
|
|
1180
|
+
yield* Effect.sync(() => process.stdout.write(canonicalText(targetCatalog$1(catalog, target))));
|
|
99
1181
|
}, Effect.catchTag("UnreadableFile", reportUnreadable))).pipe(Command.withDescription("Print the catalog of one target."));
|
|
100
1182
|
const url = (name, description) => Flag.String(name).pipe(Flag.withDescription(description), Flag.optional);
|
|
101
1183
|
const conformCommand = Command.make("conform", {
|
|
@@ -193,6 +1275,7 @@ const conformCommand = Command.make("conform", {
|
|
|
193
1275
|
const acidCat = Command.make("acid-cat").pipe(Command.withDescription("Check and format AcidCat catalogs, print the catalog of a target, and test implementations."), Command.withSubcommands([
|
|
194
1276
|
checkCommand,
|
|
195
1277
|
formatCommand,
|
|
1278
|
+
generateCommand,
|
|
196
1279
|
targetCommand,
|
|
197
1280
|
conformCommand
|
|
198
1281
|
]));
|