@brickkit/cli 0.7.1 → 0.7.3
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 +30 -0
- package/dist/app-entry.js +1 -0
- package/dist/app-entry2.js +12 -0
- package/dist/app-entry2.js.map +1 -0
- package/dist/bin.js +8 -30
- package/dist/bin.js.map +1 -1
- package/dist/build.js +2 -9
- package/dist/build.js.map +1 -1
- package/dist/client-contract-file.js +1 -0
- package/dist/client-contract-file2.js +34 -0
- package/dist/client-contract-file2.js.map +1 -0
- package/dist/client-contract.js +1 -268
- package/dist/client-contract2.js +268 -0
- package/dist/client-contract2.js.map +1 -0
- package/dist/dev-worker.js +25 -1
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/runner.js +64 -5
- package/dist/runner.js.map +1 -1
- package/dist/vite.js +31 -12
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
- package/dist/client-contract.js.map +0 -1
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { getPluginActionRoute } from "@brickkit/core";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
//#region src/client-contract.ts
|
|
4
|
+
/** Generate browser metadata and transport types from the app's selected services. */
|
|
5
|
+
function generateClientContract(app) {
|
|
6
|
+
const { services, prefix } = app.definition;
|
|
7
|
+
const contract = Object.create(null);
|
|
8
|
+
const types = Object.create(null);
|
|
9
|
+
const schemas = new SchemaTypes();
|
|
10
|
+
for (const service of services) addServiceActions(service, prefix, contract, types, schemas);
|
|
11
|
+
return `// Generated by the Brick Vite plugin. Do not edit.
|
|
12
|
+
import type { BrickClientAction } from "@brickkit/core/client";
|
|
13
|
+
|
|
14
|
+
${schemas.renderContract(namespaceType(types))}
|
|
15
|
+
|
|
16
|
+
export const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});
|
|
17
|
+
`;
|
|
18
|
+
}
|
|
19
|
+
function addServiceActions(service, prefix, contract, types, schemas) {
|
|
20
|
+
const namespace = contract[service.name] ?? Object.create(null);
|
|
21
|
+
const namespaceTypes = types[service.name] ?? Object.create(null);
|
|
22
|
+
contract[service.name] = namespace;
|
|
23
|
+
types[service.name] = namespaceTypes;
|
|
24
|
+
for (const action of service.listActions()) {
|
|
25
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
26
|
+
if (pluginRoute === false) continue;
|
|
27
|
+
const { input, output, errors, path, method } = action.config;
|
|
28
|
+
let inputType;
|
|
29
|
+
let outputType;
|
|
30
|
+
try {
|
|
31
|
+
inputType = input ? schemas.generate(input) : "unknown";
|
|
32
|
+
outputType = output ? schemas.generate(output) : "unknown";
|
|
33
|
+
} catch (error) {
|
|
34
|
+
throw new Error(`Brick client: cannot generate '${service.name}.${action.name}': ${error.message}`);
|
|
35
|
+
}
|
|
36
|
+
const metadata = {
|
|
37
|
+
kind: "action",
|
|
38
|
+
name: action.name,
|
|
39
|
+
serviceName: service.name,
|
|
40
|
+
...action.plugin ? { plugin: action.plugin } : pluginRoute?.plugin ? { plugin: pluginRoute.plugin } : {},
|
|
41
|
+
...action.resource ? { resource: action.resource } : pluginRoute?.resource ? { resource: pluginRoute.resource } : {},
|
|
42
|
+
config: {
|
|
43
|
+
path: pluginRoute?.path ?? path ?? `${prefix}/${service.name}/${action.name}`,
|
|
44
|
+
method: pluginRoute?.method ?? method ?? "POST"
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
insertAction(pluginRoute?.clientPath ? contract : namespace, pluginRoute?.clientPath ? types : namespaceTypes, metadata, actionType(inputType, outputType, errors), pluginRoute?.clientPath);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function insertAction(node, typeNode, metadata, type, clientPath) {
|
|
51
|
+
const segments = clientPath ?? metadata.name.split(".");
|
|
52
|
+
for (const segment of segments.slice(0, -1)) {
|
|
53
|
+
if (Object.hasOwn(typeNode, segment) && typeof typeNode[segment] === "string") throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
|
|
54
|
+
node[segment] ??= Object.create(null);
|
|
55
|
+
typeNode[segment] ??= Object.create(null);
|
|
56
|
+
node = node[segment];
|
|
57
|
+
typeNode = typeNode[segment];
|
|
58
|
+
}
|
|
59
|
+
const leaf = segments.at(-1);
|
|
60
|
+
if (Object.hasOwn(node, leaf)) throw new Error(`Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`);
|
|
61
|
+
node[leaf] = metadata;
|
|
62
|
+
typeNode[leaf] = type;
|
|
63
|
+
}
|
|
64
|
+
function actionType(input, output, errors) {
|
|
65
|
+
const codes = Object.keys(errors ?? {});
|
|
66
|
+
return `BrickClientAction<${input}, ${output}, ${codes.length ? `Record<${codes.map((code) => JSON.stringify(code)).join(" | ")}, { message: string; status?: number }>` : "{}"}>`;
|
|
67
|
+
}
|
|
68
|
+
function namespaceType(node) {
|
|
69
|
+
return `{\n${Object.entries(node).map(([key, value]) => ` ${JSON.stringify(key)}: ${typeof value === "string" ? value : namespaceType(value)};`).join("\n")}\n}`;
|
|
70
|
+
}
|
|
71
|
+
var SchemaTypes = class {
|
|
72
|
+
aliases = /* @__PURE__ */ new Map();
|
|
73
|
+
names = /* @__PURE__ */ new Set([
|
|
74
|
+
"AppContract",
|
|
75
|
+
"BrickClientAction",
|
|
76
|
+
"contract"
|
|
77
|
+
]);
|
|
78
|
+
fragments = [];
|
|
79
|
+
fragmentIds = /* @__PURE__ */ new Map();
|
|
80
|
+
fragment(body) {
|
|
81
|
+
let id = this.fragmentIds.get(body);
|
|
82
|
+
if (id === void 0) {
|
|
83
|
+
id = this.fragments.length;
|
|
84
|
+
const size = body.replace(/\0(\d+)\0/g, "").length + [...body.matchAll(/\0(\d+)\0/g)].reduce((total, match) => total + this.fragments[Number(match[1])].size, 0);
|
|
85
|
+
const shape = body.replace(/\0(\d+)\0/g, (_, child) => this.fragments[Number(child)].hash);
|
|
86
|
+
const hash = createHash("sha256").update(shape).digest("hex");
|
|
87
|
+
this.fragments.push({
|
|
88
|
+
body,
|
|
89
|
+
size,
|
|
90
|
+
hash
|
|
91
|
+
});
|
|
92
|
+
this.fragmentIds.set(body, id);
|
|
93
|
+
}
|
|
94
|
+
return `\0${id}\0`;
|
|
95
|
+
}
|
|
96
|
+
renderContract(contract) {
|
|
97
|
+
const uses = this.fragments.map(() => 0);
|
|
98
|
+
const count = (body, multiplier) => {
|
|
99
|
+
for (const match of body.matchAll(/\0(\d+)\0/g)) uses[Number(match[1])] += multiplier;
|
|
100
|
+
};
|
|
101
|
+
count(contract, 1);
|
|
102
|
+
for (const body of this.aliases.values()) count(body, 1);
|
|
103
|
+
const shared = /* @__PURE__ */ new Map();
|
|
104
|
+
for (let id = this.fragments.length - 1; id >= 0; id--) {
|
|
105
|
+
const { body, size, hash } = this.fragments[id];
|
|
106
|
+
const nameBase = `BrickSchema_${hash.slice(0, 12)}`;
|
|
107
|
+
let name = nameBase;
|
|
108
|
+
let suffix = 2;
|
|
109
|
+
while (this.names.has(name)) name = `${nameBase}_${suffix++}`;
|
|
110
|
+
const declarationCost = `export type ${name} = ;\n\n`.length;
|
|
111
|
+
if (uses[id] > 1 && (uses[id] - 1) * size > uses[id] * name.length + declarationCost) {
|
|
112
|
+
this.names.add(name);
|
|
113
|
+
shared.set(id, name);
|
|
114
|
+
}
|
|
115
|
+
count(body, shared.has(id) ? 1 : uses[id]);
|
|
116
|
+
}
|
|
117
|
+
const rendered = [];
|
|
118
|
+
const declarations = [];
|
|
119
|
+
for (let id = 0; id < this.fragments.length; id++) {
|
|
120
|
+
const body = this.fragments[id].body.replace(/\0(\d+)\0/g, (_, child) => rendered[Number(child)]);
|
|
121
|
+
const name = shared.get(id);
|
|
122
|
+
if (name && (uses[id] - 1) * body.length > uses[id] * name.length + `export type ${name} = ;\n\n`.length) {
|
|
123
|
+
declarations.push(`export type ${name} = ${body};\n\n`);
|
|
124
|
+
rendered.push(name);
|
|
125
|
+
} else rendered.push(body);
|
|
126
|
+
}
|
|
127
|
+
const render = (body) => body.replace(/\0(\d+)\0/g, (_, id) => rendered[Number(id)]);
|
|
128
|
+
return declarations.join("") + [...this.aliases].map(([name, type]) => `export type ${name} = ${render(type)};\n\n`).join("") + `export type AppContract = ${render(contract)};`;
|
|
129
|
+
}
|
|
130
|
+
generate(root) {
|
|
131
|
+
const ids = /* @__PURE__ */ new Map();
|
|
132
|
+
const references = [];
|
|
133
|
+
const resources = /* @__PURE__ */ new Map();
|
|
134
|
+
const active = /* @__PURE__ */ new Set();
|
|
135
|
+
const visit = (schema, base) => {
|
|
136
|
+
if (!schema || typeof schema !== "object" || active.has(schema)) return;
|
|
137
|
+
const currentBase = typeof schema.$id === "string" && schema.$id ? schema : base;
|
|
138
|
+
if (!resources.has(schema)) resources.set(schema, currentBase);
|
|
139
|
+
if (typeof schema.$ref === "string") references.push({
|
|
140
|
+
ref: schema.$ref,
|
|
141
|
+
base: currentBase
|
|
142
|
+
});
|
|
143
|
+
active.add(schema);
|
|
144
|
+
try {
|
|
145
|
+
if (typeof schema.$id === "string" && schema.$id) ids.set(schema.$id, schema);
|
|
146
|
+
for (const key of [
|
|
147
|
+
"properties",
|
|
148
|
+
"patternProperties",
|
|
149
|
+
"$defs",
|
|
150
|
+
"definitions"
|
|
151
|
+
]) for (const child of Object.values(schema[key] ?? {})) visit(child, currentBase);
|
|
152
|
+
for (const key of [
|
|
153
|
+
"anyOf",
|
|
154
|
+
"oneOf",
|
|
155
|
+
"allOf",
|
|
156
|
+
"prefixItems"
|
|
157
|
+
]) for (const child of schema[key] ?? []) visit(child, currentBase);
|
|
158
|
+
for (const key of [
|
|
159
|
+
"items",
|
|
160
|
+
"additionalProperties",
|
|
161
|
+
"not"
|
|
162
|
+
]) if (Array.isArray(schema[key])) schema[key].forEach((child) => visit(child, currentBase));
|
|
163
|
+
else visit(schema[key], currentBase);
|
|
164
|
+
} finally {
|
|
165
|
+
active.delete(schema);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
visit(root, root);
|
|
169
|
+
const resolve = (reference, base) => {
|
|
170
|
+
const hashIndex = reference.indexOf("#");
|
|
171
|
+
const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);
|
|
172
|
+
const fragment = hashIndex === -1 ? void 0 : reference.slice(hashIndex + 1);
|
|
173
|
+
let target = id ? ids.get(id) : base;
|
|
174
|
+
if (fragment) {
|
|
175
|
+
if (!fragment.startsWith("/")) return void 0;
|
|
176
|
+
try {
|
|
177
|
+
for (const part of decodeURIComponent(fragment).slice(1).split("/")) {
|
|
178
|
+
const key = part.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
179
|
+
if (!target || !Object.hasOwn(target, key)) return void 0;
|
|
180
|
+
target = target[key];
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return typeof target === "boolean" || target && typeof target === "object" ? target : void 0;
|
|
187
|
+
};
|
|
188
|
+
const targets = new Set(references.map(({ ref, base }) => resolve(ref, base)).filter((value) => value !== void 0));
|
|
189
|
+
const names = /* @__PURE__ */ new Map();
|
|
190
|
+
const emit = (schema, inline = false, base = root) => {
|
|
191
|
+
const body = emitInline(schema, inline, base);
|
|
192
|
+
if (schema && !schema.$ref && !Object.hasOwn(schema, "const") && (schema.anyOf || schema.oneOf || schema.allOf || schema.enum?.length > 1 || schema.type === "array" || schema.type === "object")) return this.fragment(body);
|
|
193
|
+
return body;
|
|
194
|
+
};
|
|
195
|
+
const emitInline = (schema, inline, base) => {
|
|
196
|
+
if (schema === void 0 || schema === true) return "unknown";
|
|
197
|
+
if (schema === false || schema.not && !Object.keys(schema.not).length) return "never";
|
|
198
|
+
const currentBase = schema && typeof schema === "object" && typeof schema.$id === "string" && schema.$id ? schema : base;
|
|
199
|
+
if (!inline && targets.has(schema)) {
|
|
200
|
+
const existing = names.get(schema);
|
|
201
|
+
if (existing) return existing;
|
|
202
|
+
const hint = schema.title ?? schema.$id ?? "Schema";
|
|
203
|
+
let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, "_");
|
|
204
|
+
if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;
|
|
205
|
+
nameBase = `Brick${nameBase}`;
|
|
206
|
+
let name = nameBase;
|
|
207
|
+
let suffix = 2;
|
|
208
|
+
while (this.names.has(name)) {
|
|
209
|
+
name = `${nameBase}_${suffix}`;
|
|
210
|
+
suffix += 1;
|
|
211
|
+
}
|
|
212
|
+
this.names.add(name);
|
|
213
|
+
names.set(schema, name);
|
|
214
|
+
this.aliases.set(name, emit(schema, true, currentBase));
|
|
215
|
+
return name;
|
|
216
|
+
}
|
|
217
|
+
if (schema.$ref) {
|
|
218
|
+
const target = resolve(schema.$ref, currentBase);
|
|
219
|
+
if (target === void 0) throw new Error(`unresolved schema reference '${schema.$ref}'`);
|
|
220
|
+
const targetBase = target && typeof target === "object" ? resources.get(target) ?? root : currentBase;
|
|
221
|
+
return emit(target, false, targetBase);
|
|
222
|
+
}
|
|
223
|
+
if (Object.hasOwn(schema, "const")) return JSON.stringify(schema.const);
|
|
224
|
+
if (schema.enum) return schema.enum.map((value) => JSON.stringify(value)).join(" | ") || "never";
|
|
225
|
+
if (schema.anyOf || schema.oneOf) return `(${(schema.anyOf ?? schema.oneOf).map((child) => emit(child, false, currentBase)).join(" | ")})`;
|
|
226
|
+
if (schema.allOf) return `(${schema.allOf.map((child) => emit(child, false, currentBase)).join(" & ")})`;
|
|
227
|
+
switch (schema.type) {
|
|
228
|
+
case "string": return "string";
|
|
229
|
+
case "number":
|
|
230
|
+
case "integer": return "number";
|
|
231
|
+
case "boolean": return "boolean";
|
|
232
|
+
case "null": return "null";
|
|
233
|
+
case "undefined":
|
|
234
|
+
case "void": return "undefined";
|
|
235
|
+
case "array":
|
|
236
|
+
if (Array.isArray(schema.items)) return `[${schema.items.map((child) => emit(child, false, currentBase)).join(", ")}]`;
|
|
237
|
+
return `Array<${emit(schema.items, false, currentBase)}>`;
|
|
238
|
+
case "object": {
|
|
239
|
+
const entries = Object.entries(schema.properties ?? {});
|
|
240
|
+
const properties = entries.map(([key, value]) => `${JSON.stringify(key)}${schema.required?.includes(key) ? "" : "?"}: ${emit(value, false, currentBase)};`);
|
|
241
|
+
const indexParts = Object.values(schema.patternProperties ?? {}).map((child) => emit(child, false, currentBase));
|
|
242
|
+
if (schema.additionalProperties) indexParts.push(emit(schema.additionalProperties, false, currentBase));
|
|
243
|
+
let indexType;
|
|
244
|
+
if (indexParts.length) {
|
|
245
|
+
for (const [, value] of entries) {
|
|
246
|
+
const propType = emit(value, false, currentBase);
|
|
247
|
+
if (!indexParts.includes(propType)) indexParts.push(propType);
|
|
248
|
+
}
|
|
249
|
+
indexType = indexParts.join(" | ");
|
|
250
|
+
}
|
|
251
|
+
const object = `{ ${properties.join(" ")} }`;
|
|
252
|
+
if (indexType) {
|
|
253
|
+
const index = `{ [key: string]: ${indexType} }`;
|
|
254
|
+
return properties.length ? `${object} & ${index}` : index;
|
|
255
|
+
}
|
|
256
|
+
return object;
|
|
257
|
+
}
|
|
258
|
+
case void 0: return "unknown";
|
|
259
|
+
default: throw new Error(`unsupported transport schema type '${schema.type}'`);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
return emit(root);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
//#endregion
|
|
266
|
+
export { generateClientContract as t };
|
|
267
|
+
|
|
268
|
+
//# sourceMappingURL=client-contract2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-contract2.js","names":[],"sources":["../src/client-contract.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { getPluginActionRoute, type Service } from \"@brickkit/core\";\nimport type { BrickClientAction } from \"@brickkit/core/client\";\nimport type { BrickApp } from \"./endpoints\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const schemas = new SchemaTypes();\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, schemas);\n }\n return `// Generated by the Brick Vite plugin. Do not edit.\nimport type { BrickClientAction } from \"@brickkit/core/client\";\n\n${schemas.renderContract(namespaceType(types))}\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n`;\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n schemas: SchemaTypes,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n const pluginRoute = getPluginActionRoute(action, prefix);\n if (pluginRoute === false) continue;\n const { input, output, errors, path, method } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemas.generate(input) : \"unknown\";\n outputType = output ? schemas.generate(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n ...((action as { plugin?: string }).plugin\n ? { plugin: (action as { plugin?: string }).plugin }\n : pluginRoute?.plugin\n ? { plugin: pluginRoute.plugin }\n : {}),\n ...((action as { resource?: string }).resource\n ? { resource: (action as { resource?: string }).resource }\n : pluginRoute?.resource\n ? { resource: pluginRoute.resource }\n : {}),\n config: {\n path:\n pluginRoute?.path ??\n path ??\n `${prefix}/${service.name}/${action.name}`,\n method: pluginRoute?.method ?? method ?? \"POST\",\n },\n };\n insertAction(\n pluginRoute?.clientPath ? contract : namespace,\n pluginRoute?.clientPath ? types : namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n pluginRoute?.clientPath,\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction,\n type: string,\n clientPath?: readonly string[],\n) {\n const segments = clientPath ?? metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n const codes = Object.keys(errors ?? {});\n const errorsType = codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n return `BrickClientAction<${input}, ${output}, ${errorsType}>`;\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nclass SchemaTypes {\n private readonly aliases = new Map<string, string>();\n private readonly names = new Set([\n \"AppContract\",\n \"BrickClientAction\",\n \"contract\",\n ]);\n\n // Internal tokens cannot occur in JSON-escaped property names or literals.\n private readonly fragments: { body: string; size: number; hash: string }[] =\n [];\n private readonly fragmentIds = new Map<string, number>();\n\n private fragment(body: string): string {\n let id = this.fragmentIds.get(body);\n if (id === undefined) {\n id = this.fragments.length;\n const size =\n body.replace(/\\0(\\d+)\\0/g, \"\").length +\n [...body.matchAll(/\\0(\\d+)\\0/g)].reduce(\n (total, match) => total + this.fragments[Number(match[1])]!.size,\n 0,\n );\n const shape = body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => this.fragments[Number(child)]!.hash,\n );\n const hash = createHash(\"sha256\").update(shape).digest(\"hex\");\n this.fragments.push({ body, size, hash });\n this.fragmentIds.set(body, id);\n }\n return `\\0${id}\\0`;\n }\n\n renderContract(contract: string): string {\n const uses = this.fragments.map(() => 0);\n const count = (body: string, multiplier: number) => {\n for (const match of body.matchAll(/\\0(\\d+)\\0/g))\n uses[Number(match[1])]! += multiplier;\n };\n count(contract, 1);\n for (const body of this.aliases.values()) count(body, 1);\n const shared = new Map<number, string>();\n // Parents are interned after their children. Once a parent is shared, its\n // children occur only once in its declaration, avoiding overlapping savings.\n for (let id = this.fragments.length - 1; id >= 0; id--) {\n const { body, size, hash } = this.fragments[id]!;\n const nameBase = `BrickSchema_${hash.slice(0, 12)}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) name = `${nameBase}_${suffix++}`;\n const declarationCost = `export type ${name} = ;\\n\\n`.length;\n if (\n uses[id]! > 1 &&\n (uses[id]! - 1) * size > uses[id]! * name.length + declarationCost\n ) {\n this.names.add(name);\n shared.set(id, name);\n }\n count(body, shared.has(id) ? 1 : uses[id]!);\n }\n const rendered: string[] = [];\n const declarations: string[] = [];\n for (let id = 0; id < this.fragments.length; id++) {\n const body = this.fragments[id]!.body.replace(\n /\\0(\\d+)\\0/g,\n (_, child) => rendered[Number(child)]!,\n );\n const name = shared.get(id);\n // Child aliases can make a parent too small to justify sharing it.\n if (\n name &&\n (uses[id]! - 1) * body.length >\n uses[id]! * name.length + `export type ${name} = ;\\n\\n`.length\n ) {\n declarations.push(`export type ${name} = ${body};\\n\\n`);\n rendered.push(name);\n } else rendered.push(body);\n }\n const render = (body: string) =>\n body.replace(/\\0(\\d+)\\0/g, (_, id) => rendered[Number(id)]!);\n return (\n declarations.join(\"\") +\n [...this.aliases]\n .map(([name, type]) => `export type ${name} = ${render(type)};\\n\\n`)\n .join(\"\") +\n `export type AppContract = ${render(contract)};`\n );\n }\n\n generate(root: any): string {\n // IDs belong to this schema document. Separate actions may reuse the same ID.\n const ids = new Map<string, any>();\n const references: { ref: string; base: any }[] = [];\n const resources = new Map<unknown, any>();\n const active = new Set<unknown>();\n const visit = (schema: any, base: any) => {\n if (!schema || typeof schema !== \"object\" || active.has(schema)) return;\n const currentBase =\n typeof schema.$id === \"string\" && schema.$id ? schema : base;\n if (!resources.has(schema)) resources.set(schema, currentBase);\n if (typeof schema.$ref === \"string\")\n references.push({ ref: schema.$ref, base: currentBase });\n active.add(schema);\n try {\n if (typeof schema.$id === \"string\" && schema.$id)\n ids.set(schema.$id, schema);\n for (const key of [\n \"properties\",\n \"patternProperties\",\n \"$defs\",\n \"definitions\",\n ]) {\n for (const child of Object.values(schema[key] ?? {}))\n visit(child, currentBase);\n }\n for (const key of [\"anyOf\", \"oneOf\", \"allOf\", \"prefixItems\"]) {\n for (const child of schema[key] ?? []) visit(child, currentBase);\n }\n for (const key of [\"items\", \"additionalProperties\", \"not\"]) {\n if (Array.isArray(schema[key]))\n schema[key].forEach((child: any) => visit(child, currentBase));\n else visit(schema[key], currentBase);\n }\n } finally {\n active.delete(schema);\n }\n };\n visit(root, root);\n\n const resolve = (reference: string, base: any): any => {\n const hashIndex = reference.indexOf(\"#\");\n const id = hashIndex === -1 ? reference : reference.slice(0, hashIndex);\n const fragment =\n hashIndex === -1 ? undefined : reference.slice(hashIndex + 1);\n let target = id ? ids.get(id) : base;\n if (fragment) {\n if (!fragment.startsWith(\"/\")) return undefined;\n try {\n for (const part of decodeURIComponent(fragment).slice(1).split(\"/\")) {\n const key = part.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (!target || !Object.hasOwn(target, key)) return undefined;\n target = target[key];\n }\n } catch {\n return undefined;\n }\n }\n return typeof target === \"boolean\" ||\n (target && typeof target === \"object\")\n ? target\n : undefined;\n };\n const targets = new Set(\n references\n .map(({ ref, base }) => resolve(ref, base))\n .filter((value) => value !== undefined),\n );\n const names = new Map<any, string>();\n const emit = (schema: any, inline = false, base: any = root): string => {\n const body = emitInline(schema, inline, base);\n // References already have document-scoped aliases; scalars stay inline.\n if (\n schema &&\n !schema.$ref &&\n !Object.hasOwn(schema, \"const\") &&\n (schema.anyOf ||\n schema.oneOf ||\n schema.allOf ||\n schema.enum?.length > 1 ||\n schema.type === \"array\" ||\n schema.type === \"object\")\n )\n return this.fragment(body);\n return body;\n };\n const emitInline = (schema: any, inline: boolean, base: any): string => {\n if (schema === undefined || schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n const currentBase =\n schema &&\n typeof schema === \"object\" &&\n typeof schema.$id === \"string\" &&\n schema.$id\n ? schema\n : base;\n if (!inline && targets.has(schema)) {\n const existing = names.get(schema);\n if (existing) return existing;\n // Titles provide readable names; generated TypeBox IDs remain usable fallbacks.\n const hint = schema.title ?? schema.$id ?? \"Schema\";\n let nameBase = String(hint).replace(/[^a-zA-Z0-9_$]/g, \"_\");\n if (!/^[a-zA-Z_$]/.test(nameBase)) nameBase = `Schema_${nameBase}`;\n nameBase = `Brick${nameBase}`;\n let name = nameBase;\n let suffix = 2;\n while (this.names.has(name)) {\n name = `${nameBase}_${suffix}`;\n suffix += 1;\n }\n this.names.add(name);\n names.set(schema, name);\n // names is reserved before the body is rendered, so recursive refs terminate.\n this.aliases.set(name, emit(schema, true, currentBase));\n return name;\n }\n if (schema.$ref) {\n const target = resolve(schema.$ref, currentBase);\n if (target === undefined)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n const targetBase =\n target && typeof target === \"object\"\n ? (resources.get(target) ?? root)\n : currentBase;\n return emit(target, false, targetBase);\n }\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \") || \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map((child: any) => emit(child, false, currentBase)).join(\" | \")})`;\n if (schema.allOf)\n return `(${schema.allOf.map((child: any) => emit(child, false, currentBase)).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n if (Array.isArray(schema.items))\n return `[${schema.items.map((child: any) => emit(child, false, currentBase)).join(\", \")}]`;\n return `Array<${emit(schema.items, false, currentBase)}>`;\n case \"object\": {\n const entries = Object.entries(schema.properties ?? {});\n const properties = entries.map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${emit(value, false, currentBase)};`,\n );\n // additionalProperties applies to keys matched by neither properties\n // nor patternProperties, so union it instead of discarding it.\n const indexParts = Object.values(schema.patternProperties ?? {}).map(\n (child) => emit(child, false, currentBase),\n );\n if (schema.additionalProperties) {\n indexParts.push(\n emit(schema.additionalProperties, false, currentBase),\n );\n }\n let indexType: string | undefined;\n if (indexParts.length) {\n // TS index signatures must also cover declared keys, so widen\n // with their types; otherwise the intersection below rejects\n // valid values. Over-approximating is safe: the server validates.\n for (const [, value] of entries) {\n const propType = emit(value, false, currentBase);\n if (!indexParts.includes(propType)) indexParts.push(propType);\n }\n indexType = indexParts.join(\" | \");\n }\n const object = `{ ${properties.join(\" \")} }`;\n if (indexType) {\n const index = `{ [key: string]: ${indexType} }`;\n return properties.length ? `${object} & ${index}` : index;\n }\n return object;\n }\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n };\n return emit(root);\n }\n}\n"],"mappings":";;;;AAMA,SAAgB,uBAAuB,KAAuB;CAC5D,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,MAAM,WAAgC,OAAO,OAAO,IAAI;CACxD,MAAM,QAA6B,OAAO,OAAO,IAAI;CACrD,MAAM,UAAU,IAAI,YAAY;CAChC,KAAK,MAAM,WAAW,UACpB,kBAAkB,SA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,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;KAC1F,OAAO,SAAS,KAAK,OAAO,OAAO,OAAO,WAAW,EAAE;IACzD,KAAK,UAAU;KACb,MAAM,UAAU,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC;KACtD,MAAM,aAAa,QAAQ,KACxB,CAAC,KAAK,WACL,GAAG,KAAK,UAAU,GAAG,IAAI,OAAO,UAAU,SAAS,GAAG,IAAI,KAAK,IAAI,IAAI,KAAK,OAAO,OAAO,WAAW,EAAE,EAC3G;KAGA,MAAM,aAAa,OAAO,OAAO,OAAO,qBAAqB,CAAC,CAAC,CAAC,CAAC,KAC9D,UAAU,KAAK,OAAO,OAAO,WAAW,CAC3C;KACA,IAAI,OAAO,sBACT,WAAW,KACT,KAAK,OAAO,sBAAsB,OAAO,WAAW,CACtD;KAEF,IAAI;KACJ,IAAI,WAAW,QAAQ;MAIrB,KAAK,MAAM,GAAG,UAAU,SAAS;OAC/B,MAAM,WAAW,KAAK,OAAO,OAAO,WAAW;OAC/C,IAAI,CAAC,WAAW,SAAS,QAAQ,GAAG,WAAW,KAAK,QAAQ;MAC9D;MACA,YAAY,WAAW,KAAK,KAAK;KACnC;KACA,MAAM,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE;KACzC,IAAI,WAAW;MACb,MAAM,QAAQ,oBAAoB,UAAU;MAC5C,OAAO,WAAW,SAAS,GAAG,OAAO,KAAK,UAAU;KACtD;KACA,OAAO;IACT;IACA,KAAK,KAAA,GACH,OAAO;IACT,SACE,MAAM,IAAI,MAAM,sCAAsC,OAAO,KAAK,EAAE;GACxE;EACF;EACA,OAAO,KAAK,IAAI;CAClB;AACF"}
|
package/dist/dev-worker.js
CHANGED
|
@@ -1,10 +1,34 @@
|
|
|
1
1
|
import { t as startDevApplication } from "./runner.js";
|
|
2
2
|
import { t as parsePort } from "./port-utils.js";
|
|
3
3
|
//#region src/dev-worker.ts
|
|
4
|
+
if (process.argv[5] && process.argv[2]) {
|
|
5
|
+
const files = /* @__PURE__ */ new Set();
|
|
6
|
+
try {
|
|
7
|
+
await Bun.build({
|
|
8
|
+
entrypoints: [process.argv[2]],
|
|
9
|
+
target: "bun",
|
|
10
|
+
packages: "external",
|
|
11
|
+
plugins: [{
|
|
12
|
+
name: "brick:dependencies",
|
|
13
|
+
setup(build) {
|
|
14
|
+
build.onLoad({ filter: /./ }, (args) => {
|
|
15
|
+
files.add(args.path);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}]
|
|
19
|
+
});
|
|
20
|
+
} finally {
|
|
21
|
+
process.send?.({
|
|
22
|
+
type: "brick:dependencies",
|
|
23
|
+
files: [...files]
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
4
27
|
await startDevApplication({
|
|
5
28
|
entry: process.argv[2],
|
|
6
29
|
port: parsePort(process.argv[3] || void 0, process.env.PORT),
|
|
7
|
-
prefix: process.argv[4] || void 0
|
|
30
|
+
prefix: process.argv[4] || void 0,
|
|
31
|
+
clientOutput: process.argv[5] || void 0
|
|
8
32
|
});
|
|
9
33
|
//#endregion
|
|
10
34
|
export {};
|
package/dist/dev-worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\n\nawait startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n prefix: process.argv[4] || undefined,\n});\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\n\n// Scan local imports so dependencies outside the app directory are watched too.\nif (process.argv[5] && process.argv[2]) {\n const files = new Set<string>();\n try {\n await Bun.build({\n entrypoints: [process.argv[2]],\n target: \"bun\",\n packages: \"external\",\n plugins: [\n {\n name: \"brick:dependencies\",\n setup(build) {\n build.onLoad({ filter: /./ }, (args) => {\n files.add(args.path);\n return undefined;\n });\n },\n },\n ],\n });\n } finally {\n process.send?.({ type: \"brick:dependencies\", files: [...files] });\n }\n}\n\nawait startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n prefix: process.argv[4] || undefined,\n clientOutput: process.argv[5] || undefined,\n});\n"],"mappings":";;;AAIA,IAAI,QAAQ,KAAK,MAAM,QAAQ,KAAK,IAAI;CACtC,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI;EACF,MAAM,IAAI,MAAM;GACd,aAAa,CAAC,QAAQ,KAAK,EAAE;GAC7B,QAAQ;GACR,UAAU;GACV,SAAS,CACP;IACE,MAAM;IACN,MAAM,OAAO;KACX,MAAM,OAAO,EAAE,QAAQ,IAAI,IAAI,SAAS;MACtC,MAAM,IAAI,KAAK,IAAI;KAErB,CAAC;IACH;GACF,CACF;EACF,CAAC;CACH,UAAU;EACR,QAAQ,OAAO;GAAE,MAAM;GAAsB,OAAO,CAAC,GAAG,KAAK;EAAE,CAAC;CAClE;AACF;AAEA,MAAM,oBAAoB;CACxB,OAAO,QAAQ,KAAK;CACpB,MAAM,UAAU,QAAQ,KAAK,MAAM,KAAA,GAAW,QAAQ,IAAI,IAAI;CAC9D,QAAQ,QAAQ,KAAK,MAAM,KAAA;CAC3B,cAAc,QAAQ,KAAK,MAAM,KAAA;AACnC,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ interface DevServerOptions {
|
|
|
5
5
|
port?: number;
|
|
6
6
|
entry?: string;
|
|
7
7
|
prefix?: string;
|
|
8
|
+
/** Generate a browser contract before starting the backend and frontend. */
|
|
9
|
+
clientOutput?: string;
|
|
10
|
+
/** Frontend command, launched once after the first successful generation. */
|
|
11
|
+
frontend?: string;
|
|
8
12
|
}
|
|
9
13
|
export declare function startDevServer(options?: DevServerOptions): Promise<BrickApp$1 | {
|
|
10
14
|
stop: () => void;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["BrickApp","BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UAWiB;EACf;EACA;EACA;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["BrickApp","BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UAWiB;EACf;EACA;EACA;;EAEA;;EAEA;;wBA8JoB,eAAe,UAAS,mBAAqB,QAAAA;;;;;UC1KlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCVvD,uBAAuB,KAAKC"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as startDevServer } from "./runner.js";
|
|
2
2
|
import { a as emitHandlerFactory, i as emitCompiledApplication } from "./compiler2.js";
|
|
3
3
|
import { t as buildApplication } from "./build.js";
|
|
4
|
-
import { t as generateClientContract } from "./client-
|
|
4
|
+
import { t as generateClientContract } from "./client-contract2.js";
|
|
5
5
|
import { bindCompiledApplication, brick, compileBrickApplication, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML } from "@brickkit/core";
|
|
6
6
|
export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, generateClientContract, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
|
package/dist/runner.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { brick, getPluginActionRoute, isBrickApp } from "@brickkit/core";
|
|
2
2
|
import { existsSync, watch } from "fs";
|
|
3
|
-
import { resolve } from "path";
|
|
3
|
+
import { basename, dirname, resolve } from "path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
//#region src/runner.ts
|
|
6
6
|
async function createServer(options, label, application) {
|
|
@@ -75,10 +75,21 @@ async function startProdServer(options = {}) {
|
|
|
75
75
|
async function startDevApplication(options) {
|
|
76
76
|
const module = options.entry ? await import(resolve(options.entry)) : void 0;
|
|
77
77
|
if (isBrickApp(module?.default) && options.prefix !== void 0) console.warn(`[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`);
|
|
78
|
+
if (options.clientOutput) {
|
|
79
|
+
if (!isBrickApp(module?.default)) throw new Error("Brick: client generation requires a default-exported BrickApp.");
|
|
80
|
+
const { generateClientContract } = await import("./client-contract.js");
|
|
81
|
+
const { writeContractSource } = await import("./client-contract-file.js");
|
|
82
|
+
const { requireBrickApp } = await import("./app-entry.js");
|
|
83
|
+
const output = resolve(options.clientOutput);
|
|
84
|
+
if (output === resolve(options.entry)) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
85
|
+
await writeContractSource(output, generateClientContract(requireBrickApp(module.default)));
|
|
86
|
+
process.send?.({ type: "brick:contract-ready" });
|
|
87
|
+
}
|
|
78
88
|
return createServer(options, "Development", isBrickApp(module?.default) ? module.default : void 0);
|
|
79
89
|
}
|
|
80
90
|
async function startDevServer(options = {}) {
|
|
81
91
|
const entry = options.entry;
|
|
92
|
+
if (!entry && (options.clientOutput || options.frontend)) throw new Error("Brick: --client and --frontend require an app entry.");
|
|
82
93
|
if (!entry) return createServer(options, "Development");
|
|
83
94
|
const resolvedEntry = resolve(entry);
|
|
84
95
|
if (!existsSync(resolvedEntry)) {
|
|
@@ -86,6 +97,10 @@ async function startDevServer(options = {}) {
|
|
|
86
97
|
process.exit(1);
|
|
87
98
|
}
|
|
88
99
|
const worker = new URL(import.meta.url.endsWith(".ts") ? "./dev-worker.ts" : "./dev-worker.js", import.meta.url);
|
|
100
|
+
if (options.frontend && !options.clientOutput) throw new Error("Brick: --frontend requires --client <file>.");
|
|
101
|
+
let frontend;
|
|
102
|
+
const dependencyFiles = /* @__PURE__ */ new Set();
|
|
103
|
+
const dependencyWatchers = /* @__PURE__ */ new Map();
|
|
89
104
|
let stopped = false;
|
|
90
105
|
const intentionalExits = /* @__PURE__ */ new WeakSet();
|
|
91
106
|
const launch = () => {
|
|
@@ -94,11 +109,34 @@ async function startDevServer(options = {}) {
|
|
|
94
109
|
fileURLToPath(worker),
|
|
95
110
|
resolvedEntry,
|
|
96
111
|
String(options.port ?? ""),
|
|
97
|
-
options.prefix ?? ""
|
|
112
|
+
options.prefix ?? "",
|
|
113
|
+
options.clientOutput ? resolve(options.clientOutput) : ""
|
|
98
114
|
], {
|
|
99
115
|
cwd: process.cwd(),
|
|
100
116
|
stdout: "inherit",
|
|
101
|
-
stderr: "inherit"
|
|
117
|
+
stderr: "inherit",
|
|
118
|
+
ipc(message) {
|
|
119
|
+
if (!message || typeof message !== "object" || !("type" in message)) return;
|
|
120
|
+
if (message.type === "brick:contract-ready" && options.frontend && !frontend && !stopped) frontend = Bun.spawn([
|
|
121
|
+
process.env.SHELL ?? "/bin/sh",
|
|
122
|
+
"-c",
|
|
123
|
+
options.frontend
|
|
124
|
+
], {
|
|
125
|
+
detached: true,
|
|
126
|
+
cwd: process.cwd(),
|
|
127
|
+
stdout: "inherit",
|
|
128
|
+
stderr: "inherit"
|
|
129
|
+
});
|
|
130
|
+
if (message.type === "brick:dependencies" && "files" in message && Array.isArray(message.files)) for (const file of message.files) {
|
|
131
|
+
if (typeof file !== "string" || file === resolve(options.clientOutput ?? "_brick/contract.ts")) continue;
|
|
132
|
+
dependencyFiles.add(file);
|
|
133
|
+
const directory = dirname(file);
|
|
134
|
+
if (!dependencyWatchers.has(directory)) dependencyWatchers.set(directory, watch(directory, (_event, filename) => {
|
|
135
|
+
if (!filename || !dependencyFiles.has(resolve(directory, filename))) return;
|
|
136
|
+
scheduleRestart();
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
102
140
|
});
|
|
103
141
|
application.exited.then((code) => {
|
|
104
142
|
if (!stopped && !intentionalExits.has(application)) console.error(`[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`);
|
|
@@ -131,17 +169,38 @@ async function startDevServer(options = {}) {
|
|
|
131
169
|
restarting = false;
|
|
132
170
|
}
|
|
133
171
|
}
|
|
134
|
-
|
|
135
|
-
if (!filename || filename.split(/[\\/]/).includes("node_modules")) return;
|
|
172
|
+
function scheduleRestart() {
|
|
136
173
|
clearTimeout(pending);
|
|
137
174
|
pending = setTimeout(() => {
|
|
138
175
|
restart();
|
|
139
176
|
}, 100);
|
|
177
|
+
}
|
|
178
|
+
const watchers = watchDirs.map((dir) => watch(dir, { recursive: true }, (_event, filename) => {
|
|
179
|
+
if (!filename || filename.split(/[\\/]/).includes("node_modules")) return;
|
|
180
|
+
const file = resolve(dir, filename);
|
|
181
|
+
if (file === resolve(options.clientOutput ?? "_brick/contract.ts") || basename(file).startsWith(".brick-contract-")) return;
|
|
182
|
+
scheduleRestart();
|
|
140
183
|
}));
|
|
141
184
|
const stop = () => {
|
|
185
|
+
if (stopped) return;
|
|
142
186
|
stopped = true;
|
|
143
187
|
clearTimeout(pending);
|
|
144
188
|
for (const watcher of watchers) watcher.close();
|
|
189
|
+
for (const watcher of dependencyWatchers.values()) watcher.close();
|
|
190
|
+
if (frontend) {
|
|
191
|
+
if (process.platform === "win32") Bun.spawnSync([
|
|
192
|
+
"taskkill",
|
|
193
|
+
"/pid",
|
|
194
|
+
String(frontend.pid),
|
|
195
|
+
"/t",
|
|
196
|
+
"/f"
|
|
197
|
+
]);
|
|
198
|
+
else try {
|
|
199
|
+
process.kill(-frontend.pid, "SIGTERM");
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
145
204
|
child.kill();
|
|
146
205
|
process.off("SIGINT", onSignal);
|
|
147
206
|
process.off("SIGTERM", onSignal);
|
package/dist/runner.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.js","names":[],"sources":["../src/runner.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve } from \"path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n brick,\n getPluginActionRoute,\n isBrickApp,\n type BrickApp,\n} from \"@brickkit/core\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n}\n\nasync function createServer(\n options: DevServerOptions,\n label: string,\n application?: BrickApp,\n) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n application ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n await app.listen({ port });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startDevApplication(options: DevServerOptions) {\n const module = options.entry\n ? await import(resolve(options.entry))\n : undefined;\n if (isBrickApp(module?.default) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`,\n );\n }\n return createServer(\n options,\n \"Development\",\n isBrickApp(module?.default) ? module.default : undefined,\n );\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry) return createServer(options, \"Development\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const launch = () => {\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n options.prefix ?? \"\",\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n void application.exited.then((code) => {\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n }\n });\n return application;\n };\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart() {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\"\\n📝 Changes detected. Restarting server...\");\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }),\n );\n const stop = () => {\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = () => {\n stop();\n process.exit(0);\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n"],"mappings":";;;;;AAiBA,eAAe,aACb,SACA,OACA,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AAI,QAAQ;CAEZ,eAAe,UAAU;EACvB,QAAQ;EACR,IAAI,cAAc,SAAS;EAC3B,aAAa;EACb,IAAI;GACF,OAAO,SAAS,CAAC,SAAS;IACxB,QAAQ;IACR,QAAQ,IAAI,6CAA6C;IACzD,iBAAiB,IAAI,KAAK;IAC1B,MAAM,KAAK;IACX,MAAM,MAAM;IACZ,IAAI,CAAC,SAAS,QAAQ,OAAO;GAC/B;EACF,UAAU;GACR,aAAa;EACf;CACF;CAEA,MAAM,WAAW,UAAU,KAAK,QAC9B,MAAM,KAAK,EAAE,WAAW,KAAK,IAAI,QAAQ,aAAa;EACpD,IAAI,CAAC,YAAY,SAAS,MAAM,OAAO,CAAC,CAAC,SAAS,cAAc,GAAG;EACnE,aAAa,OAAO;EACpB,UAAU,iBAAiB;GACzB,QAAa;EACf,GAAG,GAAG;CACR,CAAC,CACH;CACA,MAAM,aAAa;EACjB,UAAU;EACV,aAAa,OAAO;EACpB,KAAK,MAAM,WAAW,UAAU,QAAQ,MAAM;EAC9C,MAAM,KAAK;EACX,QAAQ,IAAI,UAAU,QAAQ;EAC9B,QAAQ,IAAI,WAAW,QAAQ;EAC/B,QAAQ,IAAI,QAAQ,IAAI;CAC1B;CACA,MAAM,iBAAiB;EACrB,KAAK;EACL,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,UAAU,QAAQ;CAC7B,QAAQ,GAAG,WAAW,QAAQ;CAC9B,QAAQ,GAAG,QAAQ,IAAI;CACvB,QAAQ,IAAI,iCAAiC,UAAU,KAAK,IAAI,GAAG;CACnE,OAAO,EAAE,KAAK;AAChB"}
|
|
1
|
+
{"version":3,"file":"runner.js","names":[],"sources":["../src/runner.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve, dirname, basename } from \"path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n brick,\n getPluginActionRoute,\n isBrickApp,\n type BrickApp,\n} from \"@brickkit/core\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n}\n\nasync function createServer(\n options: DevServerOptions,\n label: string,\n application?: BrickApp,\n) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n application ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n await app.listen({ port });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await import(resolvedEntry);\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app = brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startDevApplication(options: DevServerOptions) {\n const module = options.entry\n ? await import(resolve(options.entry))\n : undefined;\n if (isBrickApp(module?.default) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`,\n );\n }\n if (options.clientOutput) {\n if (!isBrickApp(module?.default))\n throw new Error(\n \"Brick: client generation requires a default-exported BrickApp.\",\n );\n const { generateClientContract } = await import(\"./client-contract\");\n const { writeContractSource } = await import(\"./client-contract-file\");\n const { requireBrickApp } = await import(\"./app-entry\");\n const output = resolve(options.clientOutput);\n if (output === resolve(options.entry!))\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n await writeContractSource(\n output,\n generateClientContract(requireBrickApp(module.default)),\n );\n process.send?.({ type: \"brick:contract-ready\" });\n }\n return createServer(\n options,\n \"Development\",\n isBrickApp(module?.default) ? module.default : undefined,\n );\n}\n\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new Error(\"Brick: --client and --frontend require an app entry.\");\n if (!entry) return createServer(options, \"Development\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n if (options.frontend && !options.clientOutput)\n throw new Error(\"Brick: --frontend requires --client <file>.\");\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const launch = () => {\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n options.prefix ?? \"\",\n options.clientOutput ? resolve(options.clientOutput) : \"\",\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc(message) {\n if (!message || typeof message !== \"object\" || !(\"type\" in message))\n return;\n if (\n message.type === \"brick:contract-ready\" &&\n options.frontend &&\n !frontend &&\n !stopped\n ) {\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n }\n if (\n message.type === \"brick:dependencies\" &&\n \"files\" in message &&\n Array.isArray(message.files)\n ) {\n for (const file of message.files) {\n if (\n typeof file !== \"string\" ||\n file === resolve(options.clientOutput ?? \"_brick/contract.ts\")\n )\n continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n }\n },\n },\n );\n void application.exited.then((code) => {\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n }\n });\n return application;\n };\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart() {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\"\\n📝 Changes detected. Restarting server...\");\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === resolve(options.clientOutput ?? \"_brick/contract.ts\") ||\n basename(file).startsWith(\".brick-contract-\")\n )\n return;\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = () => {\n stop();\n process.exit(0);\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n"],"mappings":";;;;;AAqBA,eAAe,aACb,SACA,OACA,aACA;CACA,IAAI;CACJ,IAAI,QAAQ,SAAS,KAAA,GACnB,OAAO,QAAQ;MACV,IAAI,QAAQ,IAAI,SAAS,KAAA,KAAa,QAAQ,IAAI,SAAS,IAChE,OAAO,OAAO,QAAQ,IAAI,IAAI;MAE9B,OAAO;CAET,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,iBAAiB,KAAK,8CACxB;CAGF,MAAM,MACJ,eACA,MAAM;EACJ;EACA,QAAQ,QAAQ;CAClB,CAAC;CAEH,MAAM,IAAI,OAAO,EAAE,KAAK,CAAC;CAEzB,MAAM,SAAS,IAAI,WAAW;CAC9B,MAAM,WAAW,IAAI,WAAW;CAEhC,QAAQ,IAAI,iBAAiB,MAAM,QAAQ;CAC3C,QAAQ,IAAI,2BAA2B,SAAS,QAAQ;CAExD,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,UAAU,IAAI,YAAY;EAChC,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,QAAQ,OAAO,UAAU;EAC1D,KAAK,MAAM,OAAO,SAAS;GACzB,MAAM,cAAc,qBAAqB,KAAK,MAAM;GACpD,IAAI,gBAAgB,OAAO;GAC3B,MAAM,SAAS,aAAa,UAAU,IAAI,OAAO,UAAU;GAC3D,MAAM,OACJ,aAAa,QACb,IAAI,OAAO,QACX,GAAG,OAAO,GAAG,IAAI,KAAK,GAAG,IAAI;GAC/B,QAAQ,IAAI,WAAW,OAAO,OAAO,CAAC,EAAE,GAAG,MAAM;EACnD;CACF;CAEA,QAAQ,IAAI,gDAAgD,MAAM;CAClE,QAAQ,IAAI,4CAA4C,KAAK,SAAS;CAC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