@mgamadeus/ddd-web 0.0.0-stage → 0.2.1
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/.claude/skills/ddd-web-specialist/SKILL.md +110 -0
- package/.claude/skills/ddd-web-specialist/references/consumer.md +271 -0
- package/.claude/skills/ddd-web-specialist/references/maintaining.md +108 -0
- package/CHANGELOG.md +89 -0
- package/LICENSE +21 -0
- package/README.md +95 -2
- package/dist/api/index.d.ts +246 -0
- package/dist/api/index.js +265 -0
- package/dist/api/index.js.map +1 -0
- package/dist/auth/index.d.ts +109 -0
- package/dist/auth/index.js +146 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/chunk-OL742YG5.js +1514 -0
- package/dist/chunk-OL742YG5.js.map +1 -0
- package/dist/chunk-QLCE3QTP.js +123 -0
- package/dist/chunk-QLCE3QTP.js.map +1 -0
- package/dist/codegen/cli.js +77 -0
- package/dist/codegen/cli.js.map +1 -0
- package/dist/codegen/index.d.ts +342 -0
- package/dist/codegen/index.js +25 -0
- package/dist/codegen/index.js.map +1 -0
- package/dist/contract/index.d.ts +109 -0
- package/dist/contract/index.js +126 -0
- package/dist/contract/index.js.map +1 -0
- package/dist/errors-B4KabvNa.d.ts +22 -0
- package/dist/extensions-DToc6G5E.d.ts +208 -0
- package/dist/query/index.d.ts +372 -0
- package/dist/query/index.js +860 -0
- package/dist/query/index.js.map +1 -0
- package/dist/types-BhDMN3ZS.d.ts +35 -0
- package/package.json +93 -3
|
@@ -0,0 +1,1514 @@
|
|
|
1
|
+
// src/codegen/config.ts
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
import { createJiti } from "jiti";
|
|
5
|
+
function defineConfig(config) {
|
|
6
|
+
return config;
|
|
7
|
+
}
|
|
8
|
+
async function loadConfig(configPath) {
|
|
9
|
+
const absolute = path.resolve(configPath);
|
|
10
|
+
if (!fs.existsSync(absolute)) {
|
|
11
|
+
throw new Error(`Config file not found: ${absolute}`);
|
|
12
|
+
}
|
|
13
|
+
const jiti = createJiti(absolute, { moduleCache: false, fsCache: false });
|
|
14
|
+
const mod = await jiti.import(absolute);
|
|
15
|
+
const config = normalizeConfigModule(mod, absolute);
|
|
16
|
+
return { config, configPath: absolute, rootDir: path.dirname(absolute) };
|
|
17
|
+
}
|
|
18
|
+
function normalizeConfigModule(mod, configPath) {
|
|
19
|
+
const candidate = mod.default ?? mod.config ?? mod;
|
|
20
|
+
if (Array.isArray(candidate)) return { apis: candidate };
|
|
21
|
+
if (candidate && typeof candidate === "object" && Array.isArray(candidate.apis)) {
|
|
22
|
+
return candidate;
|
|
23
|
+
}
|
|
24
|
+
if (Array.isArray(mod.apis)) return { apis: mod.apis };
|
|
25
|
+
throw new Error(
|
|
26
|
+
`${configPath} must export a config (\`export default defineConfig({ apis: [...] })\`) or \`export const apis = [...]\`.`
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
function resolveApis(loaded) {
|
|
30
|
+
const { config, rootDir } = loaded;
|
|
31
|
+
if (!Array.isArray(config.apis) || config.apis.length === 0) {
|
|
32
|
+
throw new Error(`No apis configured in ${loaded.configPath}.`);
|
|
33
|
+
}
|
|
34
|
+
return config.apis.map((entry, index) => {
|
|
35
|
+
for (const key of ["schemaFile", "apiFile", "outputFile"]) {
|
|
36
|
+
if (typeof entry[key] !== "string" || entry[key] === "") {
|
|
37
|
+
throw new Error(`apis[${index}].${key} must be a non-empty string.`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const outputFile = path.resolve(rootDir, entry.outputFile);
|
|
41
|
+
const stem = path.basename(outputFile).replace(/\.[cm]?[jt]sx?$/, "");
|
|
42
|
+
return {
|
|
43
|
+
config: entry,
|
|
44
|
+
stem,
|
|
45
|
+
exportName: typeof entry.exportName === "string" ? entry.exportName : stem,
|
|
46
|
+
audience: entry.audience ?? stem.replace(/Api$/, ""),
|
|
47
|
+
schemaSource: isUrl(entry.schemaFile) ? entry.schemaFile : path.resolve(rootDir, entry.schemaFile),
|
|
48
|
+
outputFile,
|
|
49
|
+
apiFile: isPathLike(entry.apiFile) ? path.resolve(rootDir, entry.apiFile) : entry.apiFile,
|
|
50
|
+
outputDir: path.dirname(outputFile),
|
|
51
|
+
skipUpdatePostTwins: entry.skipUpdatePostTwins ?? config.skipUpdatePostTwins ?? false,
|
|
52
|
+
sideEffects: [...entry.sideEffects ?? [], ...config.sideEffects ?? []],
|
|
53
|
+
responseHandlers: [...entry.responseHandlers ?? [], ...config.responseHandlers ?? []]
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function resolveModelsDir(loaded, apis) {
|
|
58
|
+
if (loaded.config.modelsDir) return path.resolve(loaded.rootDir, loaded.config.modelsDir);
|
|
59
|
+
const first = apis[0];
|
|
60
|
+
if (!first) throw new Error("No apis configured.");
|
|
61
|
+
for (const api of apis) {
|
|
62
|
+
if (api.outputDir !== first.outputDir) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`All apis must share one output directory when modelsDir is not set (got ${api.outputFile} next to ${first.outputFile}).`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return path.resolve(first.outputDir, "..", "models");
|
|
69
|
+
}
|
|
70
|
+
function isPathLike(value) {
|
|
71
|
+
return value.startsWith(".") || path.isAbsolute(value);
|
|
72
|
+
}
|
|
73
|
+
function isUrl(value) {
|
|
74
|
+
return /^https?:\/\//i.test(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/codegen/log.ts
|
|
78
|
+
var PREFIX = "[ddd-web-sdk]";
|
|
79
|
+
var consoleLogger = {
|
|
80
|
+
info: (message) => console.log(`${PREFIX} ${message}`),
|
|
81
|
+
warn: (message) => console.warn(`${PREFIX} ${message}`),
|
|
82
|
+
error: (message) => console.error(`${PREFIX} ${message}`)
|
|
83
|
+
};
|
|
84
|
+
var silentLogger = { info: () => {
|
|
85
|
+
}, warn: () => {
|
|
86
|
+
}, error: () => {
|
|
87
|
+
} };
|
|
88
|
+
var SdkGenerationError = class extends Error {
|
|
89
|
+
name = "SdkGenerationError";
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// src/codegen/spec.ts
|
|
93
|
+
import * as fs2 from "fs";
|
|
94
|
+
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
95
|
+
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
96
|
+
async function loadSpec(source, timeoutMs = 6e4) {
|
|
97
|
+
let text;
|
|
98
|
+
if (isUrl(source)) {
|
|
99
|
+
let response;
|
|
100
|
+
try {
|
|
101
|
+
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
104
|
+
}
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
107
|
+
}
|
|
108
|
+
text = await response.text();
|
|
109
|
+
} else {
|
|
110
|
+
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
111
|
+
text = fs2.readFileSync(source, "utf-8");
|
|
112
|
+
}
|
|
113
|
+
let parsed;
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(text);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
118
|
+
}
|
|
119
|
+
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
120
|
+
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
121
|
+
}
|
|
122
|
+
return parsed;
|
|
123
|
+
}
|
|
124
|
+
function validateSpec(doc, source, logger) {
|
|
125
|
+
const contract = doc.info?.["x-ddd-contract"];
|
|
126
|
+
if (contract === void 0) {
|
|
127
|
+
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
128
|
+
} else {
|
|
129
|
+
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
130
|
+
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
131
|
+
throw new SdkGenerationError(
|
|
132
|
+
`${source}: DDD contract ${JSON.stringify(number ?? contract)} is not supported by this @mgamadeus/ddd-web (supported: ${SUPPORTED_CONTRACT.min}\u2013${SUPPORTED_CONTRACT.max}). Update @mgamadeus/ddd-web or the backend.`
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));
|
|
137
|
+
if (!hasSchemaTags) {
|
|
138
|
+
throw new SdkGenerationError(
|
|
139
|
+
`${source}: no <SchemaDefinition schemaRef="\u2026"/> markup in tags[].description. The codegen needs it to place models into namespace folders \u2014 fetch the spec without removeSchemaTags=1.`
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/codegen/generate.ts
|
|
145
|
+
import * as fs8 from "fs";
|
|
146
|
+
import * as os from "os";
|
|
147
|
+
import * as path8 from "path";
|
|
148
|
+
|
|
149
|
+
// src/codegen/openapi.ts
|
|
150
|
+
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
151
|
+
function listOperations(doc) {
|
|
152
|
+
const result = [];
|
|
153
|
+
for (const [path10, item] of Object.entries(doc.paths ?? {})) {
|
|
154
|
+
if (!item) continue;
|
|
155
|
+
for (const method of HTTP_METHODS) {
|
|
156
|
+
const operation = item[method];
|
|
157
|
+
if (operation) result.push({ method, path: path10, operation });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
function operationKey(method, path10) {
|
|
163
|
+
return `${method.toUpperCase()} ${path10}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/codegen/tags.ts
|
|
167
|
+
var GENERATED_HEADER = "// AUTO-GENERATED by @mgamadeus/ddd-web (ddd-web-sdk) \u2014 do not edit manually.";
|
|
168
|
+
function normalizeTag(tag, audiencePrefix) {
|
|
169
|
+
const parts = tag.trim().split(/\s+/);
|
|
170
|
+
const filtered = audiencePrefix && parts[0]?.toLowerCase() === audiencePrefix.toLowerCase() ? parts.slice(1) : parts;
|
|
171
|
+
return filtered.filter(Boolean).map((part) => {
|
|
172
|
+
if (part === part.toUpperCase() && part.length > 1) return part;
|
|
173
|
+
return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();
|
|
174
|
+
}).join("");
|
|
175
|
+
}
|
|
176
|
+
function collectOperationTags(doc, audience) {
|
|
177
|
+
const raw = /* @__PURE__ */ new Set();
|
|
178
|
+
for (const { operation } of listOperations(doc)) {
|
|
179
|
+
for (const tag of operation.tags ?? []) raw.add(tag);
|
|
180
|
+
}
|
|
181
|
+
return [...new Set([...raw].map((tag) => normalizeTag(tag, audience)).filter(Boolean))].sort();
|
|
182
|
+
}
|
|
183
|
+
function entityTag(schema, knownTags) {
|
|
184
|
+
const parts = schema.replace("#/components/schemas/", "").split(".");
|
|
185
|
+
const leaf = parts[parts.length - 1] ?? schema;
|
|
186
|
+
const folder = parts.length > 1 ? parts[parts.length - 2] : void 0;
|
|
187
|
+
const candidates = [folder, `${leaf}s`, leaf].filter((value) => !!value);
|
|
188
|
+
for (const candidate of candidates) {
|
|
189
|
+
const known = knownTags.get(normalizeTag(candidate).toLowerCase());
|
|
190
|
+
if (known) return known;
|
|
191
|
+
}
|
|
192
|
+
return normalizeTag(folder && folder !== "Entities" ? folder : leaf);
|
|
193
|
+
}
|
|
194
|
+
function tagFileNames(stem) {
|
|
195
|
+
return {
|
|
196
|
+
constName: `${stem}TagTypes`,
|
|
197
|
+
typeName: `${stem.charAt(0).toUpperCase()}${stem.slice(1)}TagType`
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function renderTagsFile(stem, tags) {
|
|
201
|
+
const { constName, typeName } = tagFileNames(stem);
|
|
202
|
+
return [
|
|
203
|
+
GENERATED_HEADER,
|
|
204
|
+
"",
|
|
205
|
+
`export const ${constName} = [`,
|
|
206
|
+
...tags.map((tag) => ` '${tag}',`),
|
|
207
|
+
"] as const;",
|
|
208
|
+
"",
|
|
209
|
+
`export type ${typeName} = (typeof ${constName})[number];`,
|
|
210
|
+
""
|
|
211
|
+
].join("\n");
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/codegen/enhance.ts
|
|
215
|
+
function segmentToPascal(segment) {
|
|
216
|
+
if (!segment) return "";
|
|
217
|
+
if (/[A-Z]/.test(segment)) return segment;
|
|
218
|
+
return segment.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
219
|
+
}
|
|
220
|
+
function tagFromPath(path10, lookup) {
|
|
221
|
+
let matched = null;
|
|
222
|
+
for (const segment of path10.replace(/\{[^}]+\}/g, "").split("/").filter(Boolean)) {
|
|
223
|
+
matched = lookup.get(segmentToPascal(segment).toLowerCase()) ?? matched;
|
|
224
|
+
}
|
|
225
|
+
return matched;
|
|
226
|
+
}
|
|
227
|
+
function tagFromOperation(info, audience, lookup) {
|
|
228
|
+
for (const raw of info?.operation.tags ?? []) {
|
|
229
|
+
const found = lookup.get(normalizeTag(raw, audience).toLowerCase());
|
|
230
|
+
if (found) return found;
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
function trailingPlaceholder(path10) {
|
|
235
|
+
return path10.match(/\{([^}]+)\}\/?$/)?.[1] ?? null;
|
|
236
|
+
}
|
|
237
|
+
function isPrimaryEntityPath(path10, tag) {
|
|
238
|
+
const segments = path10.replace(/\{[^}]+\}\/?$/, "").split("/").filter(Boolean);
|
|
239
|
+
const last = segments[segments.length - 1];
|
|
240
|
+
return last !== void 0 && segmentToPascal(last).toLowerCase() === tag.toLowerCase();
|
|
241
|
+
}
|
|
242
|
+
var list = (tag) => `{ type: '${tag}' as const, id: 'LIST' }`;
|
|
243
|
+
var broad = (tag) => `{ type: '${tag}' as const }`;
|
|
244
|
+
var byArg = (tag, accessor) => `{ type: '${tag}' as const, id: ${accessor} }`;
|
|
245
|
+
var withArg = (items) => `(_result: unknown, _error: unknown, arg: any) => [${items}]`;
|
|
246
|
+
function entityTagExpression(endpoint, info, tag) {
|
|
247
|
+
const identity = info.entity?.identity?.startsWith("path:") ? info.entity.identity.slice("path:".length) : null;
|
|
248
|
+
const pathIdentity = identity ? endpoint.pathArgs[identity] ?? null : null;
|
|
249
|
+
if (endpoint.buildType === "query") {
|
|
250
|
+
if (pathIdentity && info.entity?.action !== "list") {
|
|
251
|
+
return { key: "providesTags", line: withArg(byArg(tag, pathIdentity)) };
|
|
252
|
+
}
|
|
253
|
+
return { key: "providesTags", line: `[${list(tag)}]` };
|
|
254
|
+
}
|
|
255
|
+
if (pathIdentity && (info.entity?.action === "upsert" || info.entity?.action === "delete")) {
|
|
256
|
+
return { key: "invalidatesTags", line: withArg(`${byArg(tag, pathIdentity)}, ${list(tag)}`) };
|
|
257
|
+
}
|
|
258
|
+
return { key: "invalidatesTags", line: `[${list(tag)}, ${broad(tag)}]` };
|
|
259
|
+
}
|
|
260
|
+
function heuristicTagExpression(endpoint, tag) {
|
|
261
|
+
const trailing = trailingPlaceholder(endpoint.path);
|
|
262
|
+
const single = trailing !== null && isPrimaryEntityPath(endpoint.path, tag) ? endpoint.pathArgs[trailing] ?? null : null;
|
|
263
|
+
if (endpoint.buildType === "query") {
|
|
264
|
+
return single ? { key: "providesTags", line: withArg(byArg(tag, single)) } : { key: "providesTags", line: `[${list(tag)}]` };
|
|
265
|
+
}
|
|
266
|
+
return { key: "invalidatesTags", line: `[${list(tag)}, ${broad(tag)}]` };
|
|
267
|
+
}
|
|
268
|
+
function buildEnhancedEndpoints(input) {
|
|
269
|
+
const { endpoints, index, audience, logger } = input;
|
|
270
|
+
const lookup = new Map(input.operationTags.map((tag) => [tag.toLowerCase(), tag]));
|
|
271
|
+
const allTags = new Set(input.operationTags);
|
|
272
|
+
const used = /* @__PURE__ */ new Set();
|
|
273
|
+
const lines = [];
|
|
274
|
+
let skipped = 0;
|
|
275
|
+
let urlFallbacks = 0;
|
|
276
|
+
for (const endpoint of endpoints) {
|
|
277
|
+
const info = index.byKey.get(operationKey(endpoint.method, endpoint.path));
|
|
278
|
+
let tag;
|
|
279
|
+
if (info?.entity) {
|
|
280
|
+
tag = entityTag(info.entity.schema, lookup);
|
|
281
|
+
allTags.add(tag);
|
|
282
|
+
lookup.set(tag.toLowerCase(), tag);
|
|
283
|
+
} else {
|
|
284
|
+
tag = tagFromOperation(info, audience, lookup);
|
|
285
|
+
if (!tag) {
|
|
286
|
+
tag = tagFromPath(endpoint.path, lookup);
|
|
287
|
+
if (tag) urlFallbacks++;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (!tag) {
|
|
291
|
+
logger.warn(`No tag for ${endpoint.key} (${endpoint.url}) \u2014 no cache tags generated.`);
|
|
292
|
+
skipped++;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
let expression;
|
|
296
|
+
if (endpoint.buildType === "mutation" && info && !info.sideEffects) {
|
|
297
|
+
expression = { key: "invalidatesTags", line: "[]" };
|
|
298
|
+
} else if (info?.entity) {
|
|
299
|
+
expression = entityTagExpression(endpoint, info, tag);
|
|
300
|
+
} else {
|
|
301
|
+
expression = heuristicTagExpression(endpoint, tag);
|
|
302
|
+
}
|
|
303
|
+
lines.push(` ${endpoint.key}: {`, ` ${expression.key}: ${expression.line},`, " },");
|
|
304
|
+
used.add(tag);
|
|
305
|
+
}
|
|
306
|
+
const varName = `${input.stem}Enhanced`;
|
|
307
|
+
const source = [
|
|
308
|
+
GENERATED_HEADER,
|
|
309
|
+
"",
|
|
310
|
+
`// Import ${input.stem} first (side effect: registers its endpoints on the base api).`,
|
|
311
|
+
`import '${input.apiModuleImport}';`,
|
|
312
|
+
`import { ${input.baseApiName} } from '${input.baseApiImport}';`,
|
|
313
|
+
"",
|
|
314
|
+
"// enhanceEndpoints mutates the endpoint definitions in place: import this file once (e.g. in the store)",
|
|
315
|
+
`// and keep using the hooks from ${input.stem} \u2014 they pick up the tags.`,
|
|
316
|
+
`export const ${varName} = ${input.baseApiName}.enhanceEndpoints({`,
|
|
317
|
+
` addTagTypes: [${[...used].sort().map((tag) => `'${tag}'`).join(", ")}],`,
|
|
318
|
+
" endpoints: {",
|
|
319
|
+
...lines,
|
|
320
|
+
" },",
|
|
321
|
+
"});",
|
|
322
|
+
""
|
|
323
|
+
].join("\n");
|
|
324
|
+
logger.info(
|
|
325
|
+
` enhanced ${endpoints.length - skipped} endpoints (${skipped} without tag, ${urlFallbacks} via URL fallback, ${used.size} tag types)`
|
|
326
|
+
);
|
|
327
|
+
return { source, tagTypes: [...allTags].sort() };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/codegen/typescript.ts
|
|
331
|
+
import { createRequire } from "module";
|
|
332
|
+
var cached;
|
|
333
|
+
function loadTypeScript() {
|
|
334
|
+
if (cached) return cached;
|
|
335
|
+
const require2 = createRequire(import.meta.url);
|
|
336
|
+
const codegenEntry = require2.resolve("@rtk-query/codegen-openapi");
|
|
337
|
+
cached = createRequire(codegenEntry)("typescript");
|
|
338
|
+
return cached;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/codegen/endpoints.ts
|
|
342
|
+
function toOpenApiPath(url) {
|
|
343
|
+
return url.replace(/\$\{encodeURIComponent\(String\(queryArg\.([A-Za-z0-9_]+)\)\)\}/g, "{$1}").replace(/\$\{queryArg\.([A-Za-z0-9_]+)\}/g, "{$1}");
|
|
344
|
+
}
|
|
345
|
+
function objectReturnedBy(ts, fn) {
|
|
346
|
+
const body = fn.body;
|
|
347
|
+
if (ts.isParenthesizedExpression(body) && ts.isObjectLiteralExpression(body.expression)) return body.expression;
|
|
348
|
+
if (ts.isObjectLiteralExpression(body)) return body;
|
|
349
|
+
if (ts.isBlock(body)) {
|
|
350
|
+
for (const statement of body.statements) {
|
|
351
|
+
if (ts.isReturnStatement(statement) && statement.expression) {
|
|
352
|
+
let expression = statement.expression;
|
|
353
|
+
if (ts.isParenthesizedExpression(expression)) expression = expression.expression;
|
|
354
|
+
if (ts.isObjectLiteralExpression(expression)) return expression;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
function unwrapEncoding(ts, expression) {
|
|
361
|
+
let current = expression;
|
|
362
|
+
while (ts.isCallExpression(current) && ts.isIdentifier(current.expression) && (current.expression.text === "encodeURIComponent" || current.expression.text === "String") && current.arguments.length === 1) {
|
|
363
|
+
current = current.arguments[0];
|
|
364
|
+
}
|
|
365
|
+
return current;
|
|
366
|
+
}
|
|
367
|
+
function templateAccessors(ts, init, sourceFile) {
|
|
368
|
+
return init.templateSpans.map((span) => unwrapEncoding(ts, span.expression).getText(sourceFile).replace(/^queryArg\b/, "arg"));
|
|
369
|
+
}
|
|
370
|
+
function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
371
|
+
const definition = call.arguments[0];
|
|
372
|
+
if (!definition || !ts.isObjectLiteralExpression(definition)) return null;
|
|
373
|
+
const responseTypeNode = call.typeArguments?.[0];
|
|
374
|
+
const responseType = responseTypeNode && ts.isTypeReferenceNode(responseTypeNode) && ts.isIdentifier(responseTypeNode.typeName) ? responseTypeNode.typeName.text : void 0;
|
|
375
|
+
for (const property of definition.properties) {
|
|
376
|
+
if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) || property.name.text !== "query") continue;
|
|
377
|
+
if (!ts.isArrowFunction(property.initializer)) continue;
|
|
378
|
+
const returned = objectReturnedBy(ts, property.initializer);
|
|
379
|
+
if (!returned) continue;
|
|
380
|
+
let url;
|
|
381
|
+
let method;
|
|
382
|
+
let accessors = [];
|
|
383
|
+
for (const member of returned.properties) {
|
|
384
|
+
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
385
|
+
const init = member.initializer;
|
|
386
|
+
if (member.name.text === "url") {
|
|
387
|
+
if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;
|
|
388
|
+
else if (ts.isTemplateExpression(init)) {
|
|
389
|
+
url = init.getText(sourceFile).slice(1, -1);
|
|
390
|
+
accessors = templateAccessors(ts, init, sourceFile);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
394
|
+
}
|
|
395
|
+
if (url === void 0) {
|
|
396
|
+
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
const path10 = location?.path ?? toOpenApiPath(url);
|
|
400
|
+
const placeholders = [...path10.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
401
|
+
const pathArgs = {};
|
|
402
|
+
placeholders.forEach((name, index) => {
|
|
403
|
+
const accessor = accessors[index];
|
|
404
|
+
if (accessor !== void 0) pathArgs[name] = accessor;
|
|
405
|
+
});
|
|
406
|
+
return {
|
|
407
|
+
key,
|
|
408
|
+
buildType,
|
|
409
|
+
url,
|
|
410
|
+
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
411
|
+
path: path10,
|
|
412
|
+
pathArgs,
|
|
413
|
+
...responseType ? { responseType } : {}
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
function parseApiEndpoints(source, logger, locations = /* @__PURE__ */ new Map()) {
|
|
419
|
+
const ts = loadTypeScript();
|
|
420
|
+
const sourceFile = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true);
|
|
421
|
+
const results = [];
|
|
422
|
+
const visit = (node) => {
|
|
423
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {
|
|
424
|
+
const callee = node.initializer.expression;
|
|
425
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === "build") {
|
|
426
|
+
const buildType = callee.name.text;
|
|
427
|
+
if (buildType === "query" || buildType === "mutation") {
|
|
428
|
+
const key = node.name.text;
|
|
429
|
+
const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);
|
|
430
|
+
if (info) results.push(info);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
ts.forEachChild(node, visit);
|
|
436
|
+
};
|
|
437
|
+
ts.forEachChild(sourceFile, visit);
|
|
438
|
+
return results;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// src/codegen/files.ts
|
|
442
|
+
import * as fs3 from "fs";
|
|
443
|
+
import * as path2 from "path";
|
|
444
|
+
var OutputFiles = class {
|
|
445
|
+
files = /* @__PURE__ */ new Map();
|
|
446
|
+
lowerCaseIndex = /* @__PURE__ */ new Map();
|
|
447
|
+
set(filePath, content) {
|
|
448
|
+
const absolute = path2.resolve(filePath);
|
|
449
|
+
this.files.set(absolute, { content, generatedThisRun: true });
|
|
450
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
451
|
+
}
|
|
452
|
+
get(filePath) {
|
|
453
|
+
return this.files.get(path2.resolve(filePath))?.content;
|
|
454
|
+
}
|
|
455
|
+
isGeneratedThisRun(filePath) {
|
|
456
|
+
return this.files.get(path2.resolve(filePath))?.generatedThisRun ?? false;
|
|
457
|
+
}
|
|
458
|
+
/** Case-insensitive lookup; returns the stored path spelling. */
|
|
459
|
+
findPath(filePath) {
|
|
460
|
+
return this.lowerCaseIndex.get(path2.resolve(filePath).toLowerCase());
|
|
461
|
+
}
|
|
462
|
+
paths() {
|
|
463
|
+
return [...this.files.keys()];
|
|
464
|
+
}
|
|
465
|
+
/** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */
|
|
466
|
+
seedFromDisk(dir) {
|
|
467
|
+
for (const absolute of listTsFiles(dir)) {
|
|
468
|
+
this.files.set(absolute, { content: fs3.readFileSync(absolute, "utf-8"), generatedThisRun: false });
|
|
469
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
function listTsFiles(dir) {
|
|
474
|
+
if (!fs3.existsSync(dir)) return [];
|
|
475
|
+
const result = [];
|
|
476
|
+
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
477
|
+
const absolute = path2.join(dir, entry.name);
|
|
478
|
+
if (entry.isDirectory()) result.push(...listTsFiles(absolute));
|
|
479
|
+
else if (entry.isFile() && entry.name.endsWith(".ts")) result.push(absolute);
|
|
480
|
+
}
|
|
481
|
+
return result;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/codegen/format.ts
|
|
485
|
+
import { execFileSync } from "child_process";
|
|
486
|
+
import * as fs4 from "fs";
|
|
487
|
+
import { createRequire as createRequire2 } from "module";
|
|
488
|
+
import * as path3 from "path";
|
|
489
|
+
import prettier from "prettier";
|
|
490
|
+
async function formatFiles(files) {
|
|
491
|
+
for (const filePath of files.paths()) {
|
|
492
|
+
const options = await prettier.resolveConfig(filePath, { editorconfig: true }) ?? {};
|
|
493
|
+
files.set(filePath, await prettier.format(files.get(filePath), { ...options, filepath: filePath }));
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
function resolveTsc(rootDir) {
|
|
497
|
+
const candidates = [path3.join(rootDir, "package.json"), import.meta.url];
|
|
498
|
+
for (const base of candidates) {
|
|
499
|
+
try {
|
|
500
|
+
return createRequire2(base).resolve("typescript/bin/tsc");
|
|
501
|
+
} catch {
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const codegen = createRequire2(import.meta.url).resolve("@rtk-query/codegen-openapi");
|
|
505
|
+
return createRequire2(codegen).resolve("typescript/bin/tsc");
|
|
506
|
+
}
|
|
507
|
+
function typecheck(rootDir, tsconfig, logger) {
|
|
508
|
+
if (!fs4.existsSync(tsconfig)) {
|
|
509
|
+
logger.warn(`No ${path3.relative(rootDir, tsconfig) || tsconfig} \u2014 skipping the type check.`);
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
try {
|
|
513
|
+
execFileSync(process.execPath, [resolveTsc(rootDir), "--noEmit", "-p", tsconfig], {
|
|
514
|
+
cwd: rootDir,
|
|
515
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
516
|
+
encoding: "utf-8"
|
|
517
|
+
});
|
|
518
|
+
} catch (error) {
|
|
519
|
+
const output = error.stdout ?? "";
|
|
520
|
+
throw new SdkGenerationError(`Type check failed:
|
|
521
|
+
${output.split("\n").slice(0, 40).join("\n")}`);
|
|
522
|
+
}
|
|
523
|
+
return true;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// src/codegen/models.ts
|
|
527
|
+
import * as path4 from "path";
|
|
528
|
+
|
|
529
|
+
// src/contract/extensions.ts
|
|
530
|
+
function hasSideEffects(method, operation) {
|
|
531
|
+
const explicit = operation?.["x-ddd-side-effects"];
|
|
532
|
+
if (typeof explicit === "boolean") {
|
|
533
|
+
return explicit;
|
|
534
|
+
}
|
|
535
|
+
return !["get", "head", "options", "trace"].includes(method.toLowerCase());
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/codegen/operations.ts
|
|
539
|
+
function testPattern(pattern, value) {
|
|
540
|
+
pattern.lastIndex = 0;
|
|
541
|
+
const result = pattern.test(value);
|
|
542
|
+
pattern.lastIndex = 0;
|
|
543
|
+
return result;
|
|
544
|
+
}
|
|
545
|
+
function matchesOperation(override, method, path10) {
|
|
546
|
+
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
547
|
+
return typeof override.path === "string" ? override.path === path10 : testPattern(override.path, path10);
|
|
548
|
+
}
|
|
549
|
+
function canonical(value) {
|
|
550
|
+
return JSON.stringify(
|
|
551
|
+
value,
|
|
552
|
+
(_key, inner) => inner && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner
|
|
553
|
+
) ?? "undefined";
|
|
554
|
+
}
|
|
555
|
+
function isUpsertTwin(post, patch) {
|
|
556
|
+
if (post["x-ddd-side-effects"] !== patch["x-ddd-side-effects"]) return false;
|
|
557
|
+
const postEntity = isEntityExtension(post["x-ddd-entity"]) ? post["x-ddd-entity"] : void 0;
|
|
558
|
+
const patchEntity = isEntityExtension(patch["x-ddd-entity"]) ? patch["x-ddd-entity"] : void 0;
|
|
559
|
+
if (postEntity && patchEntity) {
|
|
560
|
+
return postEntity.action === "upsert" && patchEntity.action === "upsert" && postEntity.schema === patchEntity.schema;
|
|
561
|
+
}
|
|
562
|
+
if (postEntity && postEntity.action !== "upsert" || patchEntity && patchEntity.action !== "upsert") return false;
|
|
563
|
+
if (post.summary === void 0 || post.summary !== patch.summary) return false;
|
|
564
|
+
return ["parameters", "requestBody", "responses"].every((key) => canonical(post[key]) === canonical(patch[key]));
|
|
565
|
+
}
|
|
566
|
+
function isEntityExtension(value) {
|
|
567
|
+
return !!value && typeof value === "object" && typeof value.schema === "string" && typeof value.action === "string";
|
|
568
|
+
}
|
|
569
|
+
function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
570
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
571
|
+
for (const { method, path: path10, operation } of listOperations(doc)) {
|
|
572
|
+
const extension = operation["x-ddd-side-effects"];
|
|
573
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path10));
|
|
574
|
+
let sideEffects = hasSideEffects(method, operation);
|
|
575
|
+
let explicit = false;
|
|
576
|
+
if (typeof extension === "boolean") {
|
|
577
|
+
sideEffects = extension;
|
|
578
|
+
explicit = true;
|
|
579
|
+
} else if (override) {
|
|
580
|
+
sideEffects = override.sideEffects;
|
|
581
|
+
explicit = true;
|
|
582
|
+
}
|
|
583
|
+
const naturalType = method === "get" ? "query" : "mutation";
|
|
584
|
+
const classifiedType = explicit ? sideEffects ? "mutation" : "query" : naturalType;
|
|
585
|
+
const endpointType = typeof extension !== "boolean" && override?.endpointType || classifiedType;
|
|
586
|
+
const entity = isEntityExtension(operation["x-ddd-entity"]) ? operation["x-ddd-entity"] : void 0;
|
|
587
|
+
byKey.set(operationKey(method, path10), {
|
|
588
|
+
method,
|
|
589
|
+
path: path10,
|
|
590
|
+
operation,
|
|
591
|
+
sideEffects,
|
|
592
|
+
sideEffectsExplicit: explicit,
|
|
593
|
+
endpointType,
|
|
594
|
+
...entity ? { entity } : {}
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
const skippedTwins = /* @__PURE__ */ new Set();
|
|
598
|
+
if (skipUpdatePostTwins) {
|
|
599
|
+
for (const [path10, item] of Object.entries(doc.paths ?? {})) {
|
|
600
|
+
const post = item?.post;
|
|
601
|
+
const patch = item?.patch;
|
|
602
|
+
if (post && patch && isUpsertTwin(post, patch)) {
|
|
603
|
+
skippedTwins.add(operationKey("post", path10));
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return { byKey, skippedTwins };
|
|
608
|
+
}
|
|
609
|
+
function endpointTypeOverrides(index) {
|
|
610
|
+
const result = [];
|
|
611
|
+
for (const info of index.byKey.values()) {
|
|
612
|
+
const rtkDefault = info.method === "get" ? "query" : "mutation";
|
|
613
|
+
if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });
|
|
614
|
+
}
|
|
615
|
+
return result;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// src/codegen/response-handlers.ts
|
|
619
|
+
var DDD_WEB_API_IMPORT = "@mgamadeus/ddd-web/api";
|
|
620
|
+
var TEXT_CONTENT_TYPES = ["text/html", "text/plain", "text/xml"];
|
|
621
|
+
var FILE_CONTENT_TYPES = [
|
|
622
|
+
"application/octet-stream",
|
|
623
|
+
"application/zip",
|
|
624
|
+
"application/x-zip-compressed",
|
|
625
|
+
"application/gzip",
|
|
626
|
+
"application/x-gzip",
|
|
627
|
+
"application/x-tar",
|
|
628
|
+
"application/x-7z-compressed",
|
|
629
|
+
"application/pdf",
|
|
630
|
+
"application/msword",
|
|
631
|
+
"application/vnd.",
|
|
632
|
+
"text/csv",
|
|
633
|
+
"image/",
|
|
634
|
+
"audio/",
|
|
635
|
+
"video/",
|
|
636
|
+
"font/"
|
|
637
|
+
];
|
|
638
|
+
var mediaType = (type) => type.split(";")[0].trim().toLowerCase();
|
|
639
|
+
var isJsonType = (type) => /(^|\/|\+)json$/.test(mediaType(type));
|
|
640
|
+
var isTextContentType = (type) => !isJsonType(type) && TEXT_CONTENT_TYPES.some((text) => mediaType(type).startsWith(text));
|
|
641
|
+
var isFileContentType = (type) => !isJsonType(type) && FILE_CONTENT_TYPES.some((file) => mediaType(type).startsWith(file));
|
|
642
|
+
function detectResponseKind(responses) {
|
|
643
|
+
let kind = "json";
|
|
644
|
+
for (const [status, response] of Object.entries(responses ?? {})) {
|
|
645
|
+
const code = Number.parseInt(status, 10);
|
|
646
|
+
if (Number.isNaN(code) || code < 200 || code >= 300) continue;
|
|
647
|
+
const types = Object.keys(response?.content ?? {});
|
|
648
|
+
if (types.length === 0) continue;
|
|
649
|
+
if (!types.every((type) => isFileContentType(type) || isTextContentType(type))) continue;
|
|
650
|
+
if (types.some(isFileContentType)) return "blob";
|
|
651
|
+
kind = "text";
|
|
652
|
+
}
|
|
653
|
+
return kind;
|
|
654
|
+
}
|
|
655
|
+
function detectResponseHandlerEndpoints(doc, endpoints, overrides = []) {
|
|
656
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
657
|
+
for (const { method, path: path10, operation } of listOperations(doc)) {
|
|
658
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path10));
|
|
659
|
+
const kind = override ? override.handler : detectResponseKind(operation.responses);
|
|
660
|
+
if (kind !== "json") kinds.set(operationKey(method, path10), kind);
|
|
661
|
+
}
|
|
662
|
+
const keys = /* @__PURE__ */ new Map();
|
|
663
|
+
if (kinds.size === 0) return keys;
|
|
664
|
+
for (const endpoint of endpoints) {
|
|
665
|
+
const kind = kinds.get(operationKey(endpoint.method, endpoint.path));
|
|
666
|
+
if (kind === "text" || kind === "blob") keys.set(endpoint.key, kind);
|
|
667
|
+
}
|
|
668
|
+
return keys;
|
|
669
|
+
}
|
|
670
|
+
var HANDLER_EXPRESSION = {
|
|
671
|
+
text: '"text"',
|
|
672
|
+
blob: "blobResponseHandler"
|
|
673
|
+
};
|
|
674
|
+
function injectResponseHandlers(source, endpointKinds) {
|
|
675
|
+
if (endpointKinds.size === 0) return source;
|
|
676
|
+
const ts = loadTypeScript();
|
|
677
|
+
const file = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
678
|
+
const edits = [];
|
|
679
|
+
const found = /* @__PURE__ */ new Set();
|
|
680
|
+
const failed = /* @__PURE__ */ new Map();
|
|
681
|
+
let usesBlob = false;
|
|
682
|
+
const visit = (node) => {
|
|
683
|
+
if (ts.isPropertyAssignment(node)) {
|
|
684
|
+
const key = propertyName(ts, node.name);
|
|
685
|
+
const kind = key === void 0 ? void 0 : endpointKinds.get(key);
|
|
686
|
+
if (key !== void 0 && kind && isBuildCall(ts, node.initializer)) {
|
|
687
|
+
if (found.has(key)) {
|
|
688
|
+
failed.set(key, "defined more than once");
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
found.add(key);
|
|
692
|
+
const target = queryReturnObject(ts, node.initializer);
|
|
693
|
+
if (typeof target === "string") {
|
|
694
|
+
failed.set(key, target);
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const edit = insertProperty(source, target, `responseHandler: ${HANDLER_EXPRESSION[kind]}`);
|
|
698
|
+
if (typeof edit === "string") {
|
|
699
|
+
failed.set(key, edit);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
edits.push(...edit);
|
|
703
|
+
if (kind === "blob") usesBlob = true;
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
ts.forEachChild(node, visit);
|
|
708
|
+
};
|
|
709
|
+
visit(file);
|
|
710
|
+
for (const key of endpointKinds.keys()) {
|
|
711
|
+
if (!found.has(key) && !failed.has(key)) failed.set(key, "no `build.query` / `build.mutation` definition found");
|
|
712
|
+
}
|
|
713
|
+
if (failed.size > 0) {
|
|
714
|
+
const list2 = [...failed].map(([key, reason]) => ` - ${key} (${endpointKinds.get(key)}): ${reason}`).join("\n");
|
|
715
|
+
throw new SdkGenerationError(`Could not inject the responseHandler into ${failed.size} endpoint(s):
|
|
716
|
+
${list2}`);
|
|
717
|
+
}
|
|
718
|
+
let result = source;
|
|
719
|
+
for (const { position, text } of edits.sort((a, b) => b.position - a.position)) {
|
|
720
|
+
result = result.slice(0, position) + text + result.slice(position);
|
|
721
|
+
}
|
|
722
|
+
return usesBlob ? `import { blobResponseHandler } from '${DDD_WEB_API_IMPORT}';
|
|
723
|
+
${result}` : result;
|
|
724
|
+
}
|
|
725
|
+
function propertyName(ts, name) {
|
|
726
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;
|
|
727
|
+
return void 0;
|
|
728
|
+
}
|
|
729
|
+
function isBuildCall(ts, node) {
|
|
730
|
+
return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && (node.expression.name.text === "query" || node.expression.name.text === "mutation");
|
|
731
|
+
}
|
|
732
|
+
function queryReturnObject(ts, call) {
|
|
733
|
+
const definition = call.arguments[0];
|
|
734
|
+
if (!definition || !ts.isObjectLiteralExpression(definition)) return "endpoint definition is not an object literal";
|
|
735
|
+
const query = definition.properties.find(
|
|
736
|
+
(property) => property.name !== void 0 && propertyName(ts, property.name) === "query"
|
|
737
|
+
);
|
|
738
|
+
if (!query) return "no `query` property";
|
|
739
|
+
let fn;
|
|
740
|
+
if (ts.isPropertyAssignment(query)) fn = query.initializer;
|
|
741
|
+
if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return "`query` is not a function";
|
|
742
|
+
let body = fn.body;
|
|
743
|
+
if (ts.isBlock(body)) {
|
|
744
|
+
const returns = body.statements.filter(ts.isReturnStatement);
|
|
745
|
+
if (returns.length !== 1 || !returns[0].expression) return "`query` does not have exactly one return statement";
|
|
746
|
+
body = returns[0].expression;
|
|
747
|
+
}
|
|
748
|
+
while (ts.isParenthesizedExpression(body)) body = body.expression;
|
|
749
|
+
if (!ts.isObjectLiteralExpression(body)) return "`query` does not return an object literal";
|
|
750
|
+
if (body.properties.some((property) => property.name !== void 0 && propertyName(ts, property.name) === "responseHandler")) {
|
|
751
|
+
return "`query` already returns a responseHandler";
|
|
752
|
+
}
|
|
753
|
+
return body;
|
|
754
|
+
}
|
|
755
|
+
function insertProperty(source, object, property) {
|
|
756
|
+
const close = object.end - 1;
|
|
757
|
+
if (source[close] !== "}") return "unexpected object literal end";
|
|
758
|
+
const last = object.properties[object.properties.length - 1];
|
|
759
|
+
if (!last) return [{ position: close, text: ` ${property} ` }];
|
|
760
|
+
const trailingComma = object.properties.hasTrailingComma === true;
|
|
761
|
+
const lineStart = source.lastIndexOf("\n", close) + 1;
|
|
762
|
+
const indent = source.slice(lineStart, close);
|
|
763
|
+
if (lineStart > last.end && /^[ \t]*$/.test(indent)) {
|
|
764
|
+
const edits = [{ position: lineStart, text: `${indent} ${property},
|
|
765
|
+
` }];
|
|
766
|
+
if (!trailingComma) edits.push({ position: last.end, text: "," });
|
|
767
|
+
return edits;
|
|
768
|
+
}
|
|
769
|
+
return trailingComma ? [{ position: close, text: `${property} ` }] : [{ position: last.end, text: `, ${property}` }];
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/codegen/models.ts
|
|
773
|
+
function hasExport(ts, statement) {
|
|
774
|
+
if (!ts.canHaveModifiers(statement)) return false;
|
|
775
|
+
return ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false;
|
|
776
|
+
}
|
|
777
|
+
function exportedTypeDeclarations(source) {
|
|
778
|
+
const ts = loadTypeScript();
|
|
779
|
+
const sourceFile = ts.createSourceFile("input.ts", source, ts.ScriptTarget.Latest, true);
|
|
780
|
+
const result = [];
|
|
781
|
+
for (const statement of sourceFile.statements) {
|
|
782
|
+
if (!hasExport(ts, statement)) continue;
|
|
783
|
+
if (ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) {
|
|
784
|
+
const start = statement.getFullStart();
|
|
785
|
+
const end = statement.getEnd();
|
|
786
|
+
result.push({ name: statement.name.text, text: source.slice(start, end), start, end });
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
return result;
|
|
790
|
+
}
|
|
791
|
+
function stripDeclarations(source, declarations) {
|
|
792
|
+
let result = source;
|
|
793
|
+
for (const { start, end } of [...declarations].sort((a, b) => b.start - a.start)) {
|
|
794
|
+
result = result.slice(0, start) + result.slice(end);
|
|
795
|
+
}
|
|
796
|
+
return result.trim();
|
|
797
|
+
}
|
|
798
|
+
function parseTypeMembers(source) {
|
|
799
|
+
const ts = loadTypeScript();
|
|
800
|
+
const sourceFile = ts.createSourceFile("type.ts", source, ts.ScriptTarget.Latest, true);
|
|
801
|
+
const declaration = sourceFile.statements.find(
|
|
802
|
+
(statement) => ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)
|
|
803
|
+
);
|
|
804
|
+
if (!declaration) return null;
|
|
805
|
+
const isInterface = ts.isInterfaceDeclaration(declaration);
|
|
806
|
+
const header = isInterface ? `export interface ${declaration.name.text} {` : `export type ${declaration.name.text} = {`;
|
|
807
|
+
const elements = isInterface ? declaration.members : ts.isTypeLiteralNode(declaration.type) ? declaration.type.members : [];
|
|
808
|
+
const members = /* @__PURE__ */ new Map();
|
|
809
|
+
for (const member of elements) {
|
|
810
|
+
let key;
|
|
811
|
+
if (ts.isPropertySignature(member) && member.name) {
|
|
812
|
+
key = ts.isIdentifier(member.name) ? member.name.text : member.name.getText(sourceFile);
|
|
813
|
+
} else if (ts.isIndexSignatureDeclaration(member)) {
|
|
814
|
+
key = "__index__";
|
|
815
|
+
} else {
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
members.set(key, source.slice(member.getFullStart(), member.getEnd()));
|
|
819
|
+
}
|
|
820
|
+
return { header, members };
|
|
821
|
+
}
|
|
822
|
+
function parseImportLines(source) {
|
|
823
|
+
const ts = loadTypeScript();
|
|
824
|
+
const sourceFile = ts.createSourceFile("imports.ts", source, ts.ScriptTarget.Latest, true);
|
|
825
|
+
const imports = /* @__PURE__ */ new Map();
|
|
826
|
+
for (const statement of sourceFile.statements) {
|
|
827
|
+
if (!ts.isImportDeclaration(statement)) continue;
|
|
828
|
+
const bindings = statement.importClause?.namedBindings;
|
|
829
|
+
if (!bindings || !ts.isNamedImports(bindings)) continue;
|
|
830
|
+
const line = source.slice(statement.getStart(sourceFile), statement.getEnd());
|
|
831
|
+
for (const element of bindings.elements) imports.set(element.name.text, line);
|
|
832
|
+
}
|
|
833
|
+
return imports;
|
|
834
|
+
}
|
|
835
|
+
function mergeModel(existing, body, importLines, name, logger) {
|
|
836
|
+
const existingParsed = parseTypeMembers(existing);
|
|
837
|
+
const incoming = parseTypeMembers(body);
|
|
838
|
+
if (!existingParsed || !incoming) {
|
|
839
|
+
return (importLines ? `${importLines}
|
|
840
|
+
|
|
841
|
+
` : "") + `${body}
|
|
842
|
+
|
|
843
|
+
export default ${name};
|
|
844
|
+
`;
|
|
845
|
+
}
|
|
846
|
+
const merged = new Map(existingParsed.members);
|
|
847
|
+
let added = 0;
|
|
848
|
+
for (const [key, text] of incoming.members) {
|
|
849
|
+
if (!merged.has(key)) {
|
|
850
|
+
merged.set(key, text);
|
|
851
|
+
added++;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (added === 0) return existing;
|
|
855
|
+
const imports = parseImportLines(existing);
|
|
856
|
+
for (const [symbol, line] of parseImportLines(importLines)) if (!imports.has(symbol)) imports.set(symbol, line);
|
|
857
|
+
const importBlock = imports.size > 0 ? `${[...imports.values()].join("\n")}
|
|
858
|
+
|
|
859
|
+
` : "";
|
|
860
|
+
logger.info(` merged ${added} new propert${added === 1 ? "y" : "ies"} into ${name}`);
|
|
861
|
+
return `${importBlock}${existingParsed.header}
|
|
862
|
+
${[...merged.values()].join("\n")}
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
export default ${name};
|
|
866
|
+
`;
|
|
867
|
+
}
|
|
868
|
+
var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
869
|
+
function alternation(names) {
|
|
870
|
+
if (names.length === 0) return null;
|
|
871
|
+
const sorted = [...names].sort((a, b) => b.length - a.length).map(escapeRegExp);
|
|
872
|
+
return new RegExp(`(?<![A-Za-z0-9])(${sorted.join("|")})(?![A-Za-z0-9])`, "g");
|
|
873
|
+
}
|
|
874
|
+
function registryMatch(name, registry) {
|
|
875
|
+
const lower = name.toLowerCase();
|
|
876
|
+
for (const [prefix, segments] of registry) {
|
|
877
|
+
if (lower.startsWith(prefix.toLowerCase())) {
|
|
878
|
+
const leafName = name.slice(prefix.length);
|
|
879
|
+
if (leafName.length > 0 && /^[A-Z]/.test(leafName)) return { segments, leafName };
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
return null;
|
|
883
|
+
}
|
|
884
|
+
function importSpecifier(fromFile, toFile, esm) {
|
|
885
|
+
let relative6 = path4.relative(path4.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
|
|
886
|
+
if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
|
|
887
|
+
return esm ? `${relative6}.js` : relative6;
|
|
888
|
+
}
|
|
889
|
+
var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
|
|
890
|
+
function extractModels(input) {
|
|
891
|
+
const { modelsDir, registry, files, logger } = input;
|
|
892
|
+
const esm = input.esm === true;
|
|
893
|
+
const responseKinds = input.responseKinds ?? /* @__PURE__ */ new Map();
|
|
894
|
+
const indexPath = path4.join(modelsDir, "index.ts");
|
|
895
|
+
const nameOwners = /* @__PURE__ */ new Map();
|
|
896
|
+
for (const filePath of files.paths()) {
|
|
897
|
+
const relative6 = path4.relative(modelsDir, filePath);
|
|
898
|
+
if (relative6.startsWith("..") || path4.isAbsolute(relative6) || path4.resolve(filePath) === path4.resolve(indexPath)) continue;
|
|
899
|
+
const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
|
|
900
|
+
if (name && !nameOwners.has(name)) nameOwners.set(name, path4.resolve(filePath).toLowerCase());
|
|
901
|
+
}
|
|
902
|
+
const placement = (oldName) => {
|
|
903
|
+
const match = registryMatch(oldName, registry);
|
|
904
|
+
if (match) {
|
|
905
|
+
const planned = path4.join(modelsDir, ...match.segments, `${match.leafName}.ts`);
|
|
906
|
+
return { filePath: files.findPath(planned) ?? planned, leafName: match.leafName, segments: match.segments };
|
|
907
|
+
}
|
|
908
|
+
const folder = /^(Get|Post|Put|Patch|Delete)/.test(oldName) ? "_endpoints" : "_others";
|
|
909
|
+
return { filePath: path4.join(modelsDir, folder, `${oldName}.ts`), leafName: oldName, segments: [] };
|
|
910
|
+
};
|
|
911
|
+
const originalNames = exportedTypeDeclarations(input.apiSource).map((declaration) => declaration.name);
|
|
912
|
+
const renameMap = /* @__PURE__ */ new Map();
|
|
913
|
+
const targetByNewName = /* @__PURE__ */ new Map();
|
|
914
|
+
const nameByPath = /* @__PURE__ */ new Map();
|
|
915
|
+
for (const oldName of originalNames) {
|
|
916
|
+
const { filePath, leafName, segments } = placement(oldName);
|
|
917
|
+
const pathKey = path4.resolve(filePath).toLowerCase();
|
|
918
|
+
let name = nameByPath.get(pathKey) ?? files.get(filePath)?.match(EXPORTED_NAME)?.[1];
|
|
919
|
+
if (!name) {
|
|
920
|
+
const owner = (candidate) => nameOwners.get(candidate);
|
|
921
|
+
name = leafName;
|
|
922
|
+
for (let depth = 1; owner(name) !== void 0 && owner(name) !== pathKey && depth <= segments.length; depth++) {
|
|
923
|
+
name = segments.slice(-depth).join("") + leafName;
|
|
924
|
+
}
|
|
925
|
+
if (owner(name) !== void 0 && owner(name) !== pathKey) name = oldName;
|
|
926
|
+
if (name !== leafName) logger.info(` ${oldName}: leaf name ${leafName} is taken \u2014 exported as ${name}`);
|
|
927
|
+
}
|
|
928
|
+
nameOwners.set(name, pathKey);
|
|
929
|
+
nameByPath.set(pathKey, name);
|
|
930
|
+
renameMap.set(oldName, name);
|
|
931
|
+
targetByNewName.set(name, filePath);
|
|
932
|
+
}
|
|
933
|
+
const renameRegex = alternation([...renameMap.keys()]);
|
|
934
|
+
const renamedSource = renameRegex ? input.apiSource.replace(renameRegex, (_, name) => renameMap.get(name) ?? name) : input.apiSource;
|
|
935
|
+
const kindByName = new Map([...responseKinds].map(([name, kind]) => [renameMap.get(name) ?? name, kind]));
|
|
936
|
+
const renamedDeclarations = exportedTypeDeclarations(renamedSource);
|
|
937
|
+
const entries = [];
|
|
938
|
+
for (const { name, text } of renamedDeclarations) {
|
|
939
|
+
const filePath = targetByNewName.get(name);
|
|
940
|
+
if (!filePath) {
|
|
941
|
+
logger.warn(`Re-extracted type "${name}" not in rename map \u2014 skipping.`);
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
944
|
+
entries.push({ name, body: text, filePath });
|
|
945
|
+
}
|
|
946
|
+
const pathByName = new Map(entries.map((entry) => [entry.name, entry.filePath]));
|
|
947
|
+
const dependencyRegex = alternation([...pathByName.keys()]);
|
|
948
|
+
const strippedSource = stripDeclarations(renamedSource, renamedDeclarations);
|
|
949
|
+
const usedInApi = [...new Set(entries.map((entry) => entry.name))].filter(
|
|
950
|
+
(name) => new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(name)}(?![A-Za-z0-9_$])`).test(strippedSource)
|
|
951
|
+
);
|
|
952
|
+
const isPresentation = (filePath) => filePath.split(path4.sep).includes("Presentation");
|
|
953
|
+
const barrelEntries = [];
|
|
954
|
+
for (const { name, body, filePath } of entries) {
|
|
955
|
+
const dependencies = /* @__PURE__ */ new Set();
|
|
956
|
+
if (dependencyRegex) {
|
|
957
|
+
for (const match of body.matchAll(new RegExp(dependencyRegex.source, "g"))) {
|
|
958
|
+
if (match[1] && match[1] !== name) dependencies.add(match[1]);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const kind = kindByName.get(name);
|
|
962
|
+
let typedBody = body;
|
|
963
|
+
if (kind === "text") {
|
|
964
|
+
const replaced = body.replace(/(=\s*\/\*\* status \d+[^*]*\*\/)\s*\{\}/g, "$1 string");
|
|
965
|
+
typedBody = replaced !== body ? replaced : `export type ${name} = string;`;
|
|
966
|
+
dependencies.clear();
|
|
967
|
+
} else if (kind === "blob") {
|
|
968
|
+
typedBody = `export type ${name} = DddFileResponse;`;
|
|
969
|
+
dependencies.clear();
|
|
970
|
+
}
|
|
971
|
+
const importLines = [
|
|
972
|
+
...kind === "blob" ? [`import type { DddFileResponse } from '${DDD_WEB_API_IMPORT}';`] : [],
|
|
973
|
+
...[...dependencies].map(
|
|
974
|
+
(dependency) => `import { ${dependency} } from '${importSpecifier(filePath, pathByName.get(dependency), esm)}';`
|
|
975
|
+
)
|
|
976
|
+
].join("\n");
|
|
977
|
+
const existing = files.isGeneratedThisRun(filePath) ? files.get(filePath) : void 0;
|
|
978
|
+
const content = existing !== void 0 ? mergeModel(existing, typedBody, importLines, name, logger) : (importLines ? `${importLines}
|
|
979
|
+
|
|
980
|
+
` : "") + `${typedBody}
|
|
981
|
+
|
|
982
|
+
export default ${name};
|
|
983
|
+
`;
|
|
984
|
+
files.set(filePath, content);
|
|
985
|
+
if (isPresentation(path4.relative(modelsDir, filePath))) continue;
|
|
986
|
+
barrelEntries.push(`export * from '${importSpecifier(indexPath, filePath, esm)}';`);
|
|
987
|
+
}
|
|
988
|
+
writeBarrel(files, indexPath, barrelEntries);
|
|
989
|
+
const others = entries.filter((entry) => path4.relative(modelsDir, entry.filePath).split(path4.sep)[0] === "_others");
|
|
990
|
+
if (others.length > 0) {
|
|
991
|
+
logger.warn(`${others.length} type(s) without a namespace match placed in _others/: ${others.map((e) => e.name).join(", ")}`);
|
|
992
|
+
}
|
|
993
|
+
logger.info(` extracted ${entries.length} types`);
|
|
994
|
+
const modelsImport = esm ? importSpecifier(input.apiFilePath, indexPath, true) : importSpecifier(input.apiFilePath, indexPath, false).replace(/\/index$/, "");
|
|
995
|
+
return `import {
|
|
996
|
+
${usedInApi.join(",\n ")}
|
|
997
|
+
} from '${modelsImport}';
|
|
998
|
+
|
|
999
|
+
${strippedSource}`;
|
|
1000
|
+
}
|
|
1001
|
+
function writeBarrel(files, indexPath, newEntries) {
|
|
1002
|
+
const existing = (files.get(indexPath) ?? "").split("\n").map((line) => line.trim()).filter((line) => line.startsWith("export *"));
|
|
1003
|
+
const merged = [];
|
|
1004
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1005
|
+
for (const entry of [...existing, ...newEntries]) {
|
|
1006
|
+
const specifier = entry.match(/from ['"](.+)['"];?\s*$/)?.[1];
|
|
1007
|
+
if (!specifier) continue;
|
|
1008
|
+
const target = path4.resolve(path4.dirname(indexPath), specifier.replace(/\.js$/, "")) + ".ts";
|
|
1009
|
+
const key = target.toLowerCase();
|
|
1010
|
+
if (seen.has(key) || !files.findPath(target)) continue;
|
|
1011
|
+
seen.add(key);
|
|
1012
|
+
merged.push(entry);
|
|
1013
|
+
}
|
|
1014
|
+
files.set(indexPath, `${merged.join("\n")}
|
|
1015
|
+
`);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// src/codegen/output.ts
|
|
1019
|
+
import * as fs5 from "fs";
|
|
1020
|
+
import * as path5 from "path";
|
|
1021
|
+
function defaultMove(from, to) {
|
|
1022
|
+
fs5.mkdirSync(path5.dirname(to), { recursive: true });
|
|
1023
|
+
try {
|
|
1024
|
+
fs5.renameSync(from, to);
|
|
1025
|
+
} catch (error) {
|
|
1026
|
+
if (error.code !== "EXDEV") throw error;
|
|
1027
|
+
fs5.cpSync(from, to, { recursive: true });
|
|
1028
|
+
fs5.rmSync(from, { recursive: true, force: true });
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
1032
|
+
const move = options.move ?? defaultMove;
|
|
1033
|
+
fs5.mkdirSync(stagingParent, { recursive: true });
|
|
1034
|
+
const staging = fs5.mkdtempSync(path5.join(stagingParent, ".ddd-web-sdk-"));
|
|
1035
|
+
const stagedModels = path5.join(staging, "models");
|
|
1036
|
+
const backupModels = path5.join(staging, "models.previous");
|
|
1037
|
+
const singles = [];
|
|
1038
|
+
try {
|
|
1039
|
+
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
1040
|
+
for (const filePath of files.paths()) {
|
|
1041
|
+
const content = files.get(filePath);
|
|
1042
|
+
const relative6 = path5.relative(modelsDir, filePath);
|
|
1043
|
+
if (!relative6.startsWith("..") && !path5.isAbsolute(relative6)) {
|
|
1044
|
+
const staged = path5.join(stagedModels, relative6);
|
|
1045
|
+
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1046
|
+
fs5.writeFileSync(staged, content);
|
|
1047
|
+
} else {
|
|
1048
|
+
const staged = path5.join(staging, "files", String(singles.length));
|
|
1049
|
+
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1050
|
+
fs5.writeFileSync(staged, content);
|
|
1051
|
+
singles.push({ target: filePath, staged, backup: path5.join(staging, "files.previous", String(singles.length)) });
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
} catch (error) {
|
|
1055
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1056
|
+
throw error;
|
|
1057
|
+
}
|
|
1058
|
+
const undo = [];
|
|
1059
|
+
const rollback = () => {
|
|
1060
|
+
const failures = [];
|
|
1061
|
+
for (const step of undo.reverse()) {
|
|
1062
|
+
try {
|
|
1063
|
+
step();
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
failures.push(error);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
undo.length = 0;
|
|
1069
|
+
if (failures.length > 0) {
|
|
1070
|
+
throw new SdkGenerationError(
|
|
1071
|
+
`Could not restore the previous output; the previous output is kept in ${staging} (models.previous/, files.previous/): ${failures.map((failure) => failure.message).join("; ")}`
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1075
|
+
};
|
|
1076
|
+
const swap = (target, staged, backup, removeTarget) => {
|
|
1077
|
+
const state = { backedUp: false, movedIn: false };
|
|
1078
|
+
undo.push(() => {
|
|
1079
|
+
if (state.movedIn) removeTarget();
|
|
1080
|
+
if (state.backedUp) move(backup, target);
|
|
1081
|
+
});
|
|
1082
|
+
if (fs5.existsSync(target)) {
|
|
1083
|
+
move(target, backup);
|
|
1084
|
+
state.backedUp = true;
|
|
1085
|
+
}
|
|
1086
|
+
move(staged, target);
|
|
1087
|
+
state.movedIn = true;
|
|
1088
|
+
};
|
|
1089
|
+
try {
|
|
1090
|
+
swap(modelsDir, stagedModels, backupModels, () => fs5.rmSync(modelsDir, { recursive: true, force: true }));
|
|
1091
|
+
for (const single of singles) {
|
|
1092
|
+
swap(single.target, single.staged, single.backup, () => fs5.rmSync(single.target, { force: true }));
|
|
1093
|
+
}
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
rollback();
|
|
1096
|
+
throw error;
|
|
1097
|
+
}
|
|
1098
|
+
return {
|
|
1099
|
+
rollback,
|
|
1100
|
+
finalize: () => fs5.rmSync(staging, { recursive: true, force: true })
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// src/codegen/registry.ts
|
|
1105
|
+
function normalizeSegment(segment) {
|
|
1106
|
+
return segment.replace(/([A-Z])([A-Z]+)/g, (_, first, rest) => first + rest.toLowerCase());
|
|
1107
|
+
}
|
|
1108
|
+
function extractSchemaRef(description) {
|
|
1109
|
+
return description.match(/schemaRef="([^"]+)"/)?.[1] ?? null;
|
|
1110
|
+
}
|
|
1111
|
+
function parseSchemaRef(ref) {
|
|
1112
|
+
const parts = ref.replace("#/components/schemas/", "").split(".");
|
|
1113
|
+
const folders = parts.slice(0, -1);
|
|
1114
|
+
if (folders.length === 0) return null;
|
|
1115
|
+
return [folders.map(normalizeSegment).join(""), folders];
|
|
1116
|
+
}
|
|
1117
|
+
function buildRegistry(docs, logger) {
|
|
1118
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1119
|
+
for (const doc of docs) {
|
|
1120
|
+
for (const tag of doc.tags ?? []) {
|
|
1121
|
+
if (!tag.description?.includes("SchemaDefinition")) continue;
|
|
1122
|
+
const ref = extractSchemaRef(tag.description);
|
|
1123
|
+
const entry = ref ? parseSchemaRef(ref) : null;
|
|
1124
|
+
if (!entry) continue;
|
|
1125
|
+
const [key, segments] = entry;
|
|
1126
|
+
const existing = registry.get(key);
|
|
1127
|
+
if (existing) {
|
|
1128
|
+
if (existing.join(".") !== segments.join(".")) {
|
|
1129
|
+
logger.warn(`Registry key collision for "${key}" \u2014 keeping ${existing.join(".")}, skipping ${ref}`);
|
|
1130
|
+
}
|
|
1131
|
+
continue;
|
|
1132
|
+
}
|
|
1133
|
+
registry.set(key, segments);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
return [...registry.entries()].sort((a, b) => b[0].length - a[0].length);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// src/codegen/repair.ts
|
|
1140
|
+
function resolveParameter(doc, parameter) {
|
|
1141
|
+
let current = parameter;
|
|
1142
|
+
for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
|
|
1143
|
+
const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
|
|
1144
|
+
if (!match) return null;
|
|
1145
|
+
const name = match[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1146
|
+
current = doc.components?.parameters?.[name];
|
|
1147
|
+
}
|
|
1148
|
+
return current && current.$ref === void 0 ? current : null;
|
|
1149
|
+
}
|
|
1150
|
+
function repairMissingPathParameters(doc, logger) {
|
|
1151
|
+
const repairs = [];
|
|
1152
|
+
for (const { method, path: path10, operation } of listOperations(doc)) {
|
|
1153
|
+
const placeholders = [...path10.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1154
|
+
if (placeholders.length === 0) continue;
|
|
1155
|
+
const pathLevel = doc.paths?.[path10]?.parameters ?? [];
|
|
1156
|
+
const declared = new Set(
|
|
1157
|
+
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
1158
|
+
);
|
|
1159
|
+
const missing = placeholders.filter((name) => !declared.has(name));
|
|
1160
|
+
if (missing.length > 0) repairs.push({ path: path10, method, names: missing });
|
|
1161
|
+
}
|
|
1162
|
+
if (repairs.length === 0) return doc;
|
|
1163
|
+
const copy = structuredClone(doc);
|
|
1164
|
+
for (const { path: path10, method, names } of repairs) {
|
|
1165
|
+
const operation = copy.paths[path10][method];
|
|
1166
|
+
operation.parameters = [
|
|
1167
|
+
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
1168
|
+
...operation.parameters ?? []
|
|
1169
|
+
];
|
|
1170
|
+
logger.warn(`${method.toUpperCase()} ${path10}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
1171
|
+
}
|
|
1172
|
+
return copy;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// src/codegen/rtk.ts
|
|
1176
|
+
import * as fs6 from "fs";
|
|
1177
|
+
import * as path6 from "path";
|
|
1178
|
+
import { generateEndpoints } from "@rtk-query/codegen-openapi";
|
|
1179
|
+
import prettier2 from "prettier";
|
|
1180
|
+
var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers"]);
|
|
1181
|
+
function matches(matcher, name, definition) {
|
|
1182
|
+
if (matcher === void 0) return true;
|
|
1183
|
+
if (typeof matcher === "function") return matcher(name, definition);
|
|
1184
|
+
const list2 = Array.isArray(matcher) ? matcher : [matcher];
|
|
1185
|
+
return list2.some((entry) => typeof entry === "string" ? entry === name : testPattern(entry, name));
|
|
1186
|
+
}
|
|
1187
|
+
var capitalize = (value) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
1188
|
+
function mergeEndpointOverrides(userOverrides, typeOverrides) {
|
|
1189
|
+
const merged = [];
|
|
1190
|
+
for (const operation of typeOverrides) {
|
|
1191
|
+
const isOperation = (definition) => definition.verb === operation.method && definition.path === operation.path;
|
|
1192
|
+
for (const user of userOverrides) {
|
|
1193
|
+
merged.push({
|
|
1194
|
+
...user,
|
|
1195
|
+
type: user.type ?? operation.type,
|
|
1196
|
+
pattern: (name, definition) => isOperation(definition) && matches(user.pattern, name, definition)
|
|
1197
|
+
});
|
|
1198
|
+
}
|
|
1199
|
+
merged.push({ pattern: (_name, definition) => isOperation(definition), type: operation.type });
|
|
1200
|
+
}
|
|
1201
|
+
return [...merged, ...userOverrides];
|
|
1202
|
+
}
|
|
1203
|
+
function relativeImport(fromDir, target) {
|
|
1204
|
+
if (!isPathLike(target)) return target;
|
|
1205
|
+
let relative6 = path6.relative(fromDir, target).replace(/\\/g, "/");
|
|
1206
|
+
if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
|
|
1207
|
+
return relative6;
|
|
1208
|
+
}
|
|
1209
|
+
async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile) {
|
|
1210
|
+
fs6.writeFileSync(specFile, JSON.stringify(doc));
|
|
1211
|
+
const passthrough = {};
|
|
1212
|
+
for (const [key, value] of Object.entries(api.config)) if (!OWN_KEYS.has(key)) passthrough[key] = value;
|
|
1213
|
+
const userOverrides = passthrough.endpointOverrides ?? [];
|
|
1214
|
+
const endpointOverrides = mergeEndpointOverrides(userOverrides, endpointTypeOverrides(index));
|
|
1215
|
+
const suffix = typeof passthrough.operationNameSuffix === "string" ? passthrough.operationNameSuffix : "";
|
|
1216
|
+
const locations = /* @__PURE__ */ new Map();
|
|
1217
|
+
const userFilter = passthrough.filterEndpoints;
|
|
1218
|
+
const filterEndpoints = (name, definition) => {
|
|
1219
|
+
const included = !index.skippedTwins.has(operationKey(definition.verb, definition.path)) && (userFilter === void 0 || matches(userFilter, name, definition));
|
|
1220
|
+
if (included) {
|
|
1221
|
+
locations.set(suffix ? capitalize(name + suffix) : name, { method: definition.verb, path: definition.path });
|
|
1222
|
+
}
|
|
1223
|
+
return included;
|
|
1224
|
+
};
|
|
1225
|
+
const options = {
|
|
1226
|
+
...passthrough,
|
|
1227
|
+
schemaFile: specFile,
|
|
1228
|
+
apiFile: relativeImport(api.outputDir, api.apiFile),
|
|
1229
|
+
apiImport: api.config.apiImport ?? "api",
|
|
1230
|
+
exportName: api.exportName,
|
|
1231
|
+
endpointOverrides,
|
|
1232
|
+
filterEndpoints,
|
|
1233
|
+
...prettierConfigFile ? { prettierConfigFile } : {}
|
|
1234
|
+
};
|
|
1235
|
+
const code = await generateEndpoints(options);
|
|
1236
|
+
if (typeof code !== "string") throw new Error(`RTK codegen returned no code for ${api.stem}.`);
|
|
1237
|
+
return { code, locations };
|
|
1238
|
+
}
|
|
1239
|
+
async function findPrettierConfigFile(rootDir) {
|
|
1240
|
+
return await prettier2.resolveConfigFile(path6.join(rootDir, "openapi-config.ts")) ?? void 0;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// src/codegen/workspace.ts
|
|
1244
|
+
import * as fs7 from "fs";
|
|
1245
|
+
import * as path7 from "path";
|
|
1246
|
+
import * as readline from "readline";
|
|
1247
|
+
var DEFAULT_ENV_FILES = [".env", ".env.local"];
|
|
1248
|
+
var DEFAULT_URL_KEYS = ["NEXT_PUBLIC_API_URL", "EXPO_PUBLIC_API_URL", "VITE_API_URL", "VITE_API_ENDPOINT", "API_URL"];
|
|
1249
|
+
function parseEnvFile(filePath) {
|
|
1250
|
+
if (!fs7.existsSync(filePath)) return {};
|
|
1251
|
+
const vars = {};
|
|
1252
|
+
for (const line of fs7.readFileSync(filePath, "utf-8").split("\n")) {
|
|
1253
|
+
const trimmed = line.trim();
|
|
1254
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
1255
|
+
const eq = trimmed.indexOf("=");
|
|
1256
|
+
if (eq < 1) continue;
|
|
1257
|
+
vars[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, "");
|
|
1258
|
+
}
|
|
1259
|
+
return vars;
|
|
1260
|
+
}
|
|
1261
|
+
function firstHostLabel(url) {
|
|
1262
|
+
try {
|
|
1263
|
+
return new URL(url).hostname.split(".")[0] || null;
|
|
1264
|
+
} catch {
|
|
1265
|
+
return null;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
function sniffWorkspace(rootDir, options) {
|
|
1269
|
+
for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {
|
|
1270
|
+
const vars = parseEnvFile(path7.join(rootDir, file));
|
|
1271
|
+
for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
|
|
1272
|
+
const value = vars[key];
|
|
1273
|
+
const label = value ? firstHostLabel(value) : null;
|
|
1274
|
+
if (label) return label;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return null;
|
|
1278
|
+
}
|
|
1279
|
+
function ask(question) {
|
|
1280
|
+
return new Promise((resolve6) => {
|
|
1281
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
1282
|
+
rl.on("close", () => resolve6(""));
|
|
1283
|
+
rl.question(question, (answer) => {
|
|
1284
|
+
resolve6(answer.trim());
|
|
1285
|
+
rl.close();
|
|
1286
|
+
});
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
async function resolveWorkspace(rootDir, options, explicit, logger) {
|
|
1290
|
+
let value = explicit?.trim() || process.env[options.envVar]?.trim() || null;
|
|
1291
|
+
const sniffed = value ? null : sniffWorkspace(rootDir, options);
|
|
1292
|
+
if (!value && process.stdin.isTTY && options.prompt !== false) {
|
|
1293
|
+
const hint = sniffed ? ` [${sniffed}]` : "";
|
|
1294
|
+
value = await ask(`[ddd-web-sdk] ${options.envVar}${hint}: `) || sniffed;
|
|
1295
|
+
} else if (!value) {
|
|
1296
|
+
value = sniffed;
|
|
1297
|
+
}
|
|
1298
|
+
if (value) {
|
|
1299
|
+
process.env[options.envVar] = value;
|
|
1300
|
+
logger.info(`${options.envVar}=${value}`);
|
|
1301
|
+
} else {
|
|
1302
|
+
logger.warn(`${options.envVar} not set and not resolvable \u2014 using the config's own default.`);
|
|
1303
|
+
}
|
|
1304
|
+
return value;
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
// src/codegen/generate.ts
|
|
1308
|
+
async function load(options, cwd) {
|
|
1309
|
+
if (options.config && typeof options.config === "object") {
|
|
1310
|
+
return { config: options.config, configPath: path8.join(cwd, "<inline config>"), rootDir: cwd };
|
|
1311
|
+
}
|
|
1312
|
+
return loadConfig(path8.resolve(cwd, options.config ?? "openapi-config.ts"));
|
|
1313
|
+
}
|
|
1314
|
+
function selectApis(all, options) {
|
|
1315
|
+
let selected = all;
|
|
1316
|
+
if (options.api) {
|
|
1317
|
+
selected = all.filter((api) => api.exportName === options.api || api.stem === options.api);
|
|
1318
|
+
if (selected.length === 0) {
|
|
1319
|
+
throw new SdkGenerationError(`No api "${options.api}" in the config (have: ${all.map((api) => api.exportName).join(", ")}).`);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
if (options.schema) {
|
|
1323
|
+
if (selected.length !== 1) throw new SdkGenerationError("--schema needs exactly one api (use --api).");
|
|
1324
|
+
const schemaSource = isUrl(options.schema) ? options.schema : path8.resolve(options.cwd ?? process.cwd(), options.schema);
|
|
1325
|
+
selected = [{ ...selected[0], schemaSource }];
|
|
1326
|
+
}
|
|
1327
|
+
return selected;
|
|
1328
|
+
}
|
|
1329
|
+
async function generateSdk(options = {}) {
|
|
1330
|
+
const logger = options.logger ?? consoleLogger;
|
|
1331
|
+
const cwd = path8.resolve(options.cwd ?? process.cwd());
|
|
1332
|
+
let loaded = await load(options, cwd);
|
|
1333
|
+
if (loaded.config.workspace) {
|
|
1334
|
+
const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);
|
|
1335
|
+
if (value && typeof options.config !== "object") loaded = await loadConfig(loaded.configPath);
|
|
1336
|
+
}
|
|
1337
|
+
const allApis = resolveApis(loaded);
|
|
1338
|
+
const apis = selectApis(allApis, options);
|
|
1339
|
+
const modelsDir = resolveModelsDir(loaded, allApis);
|
|
1340
|
+
const partial = apis.length < allApis.length;
|
|
1341
|
+
logger.info(`${apis.length} api(s): ${apis.map((api) => api.exportName).join(", ")}${partial ? " (partial run)" : ""}`);
|
|
1342
|
+
const selected = new Set(apis.map((api) => api.stem));
|
|
1343
|
+
const pipeline = allApis.map((api) => ({
|
|
1344
|
+
api: apis.find((candidate) => candidate.stem === api.stem) ?? api,
|
|
1345
|
+
write: selected.has(api.stem)
|
|
1346
|
+
}));
|
|
1347
|
+
const specCache = /* @__PURE__ */ new Map();
|
|
1348
|
+
const loadOnce = (api) => {
|
|
1349
|
+
if (!specCache.has(api.schemaSource)) {
|
|
1350
|
+
logger.info(`loading ${api.schemaSource}`);
|
|
1351
|
+
specCache.set(api.schemaSource, loadSpec(api.schemaSource));
|
|
1352
|
+
}
|
|
1353
|
+
return specCache.get(api.schemaSource);
|
|
1354
|
+
};
|
|
1355
|
+
const loadedSpecs = await Promise.all(
|
|
1356
|
+
pipeline.map(async ({ api, write }) => {
|
|
1357
|
+
if (write) return loadOnce(api);
|
|
1358
|
+
try {
|
|
1359
|
+
return await loadOnce(api);
|
|
1360
|
+
} catch (error) {
|
|
1361
|
+
logger.warn(
|
|
1362
|
+
`${api.exportName}: spec not loadable (${error.message}) \u2014 its models are kept from the previous output; models it shares with the selected apis may lose its fields until a full run.`
|
|
1363
|
+
);
|
|
1364
|
+
return null;
|
|
1365
|
+
}
|
|
1366
|
+
})
|
|
1367
|
+
);
|
|
1368
|
+
const steps = pipeline.map((step, i) => ({ ...step, doc: loadedSpecs[i] })).filter((step) => step.doc !== null);
|
|
1369
|
+
steps.forEach(({ api, doc }) => validateSpec(doc, api.schemaSource, logger));
|
|
1370
|
+
const registry = buildRegistry(
|
|
1371
|
+
steps.map((step) => step.doc),
|
|
1372
|
+
logger
|
|
1373
|
+
);
|
|
1374
|
+
logger.info(`registry: ${registry.length} namespaces`);
|
|
1375
|
+
const files = new OutputFiles();
|
|
1376
|
+
if (steps.length < pipeline.length) files.seedFromDisk(modelsDir);
|
|
1377
|
+
const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);
|
|
1378
|
+
const specDir = fs8.mkdtempSync(path8.join(os.tmpdir(), "ddd-web-spec-"));
|
|
1379
|
+
try {
|
|
1380
|
+
for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {
|
|
1381
|
+
const doc = repairMissingPathParameters(rawDoc, logger);
|
|
1382
|
+
logger.info(`\u2500\u2500 ${api.stem} (${i + 1}/${steps.length})${write ? "" : " (models only)"}`);
|
|
1383
|
+
const index = indexOperations(doc, api.sideEffects, api.skipUpdatePostTwins);
|
|
1384
|
+
if (index.skippedTwins.size > 0) logger.info(` skipping ${index.skippedTwins.size} POST twin(s) of PATCH upserts`);
|
|
1385
|
+
const rtk = await runRtkCodegen(api, doc, index, path8.join(specDir, `${i}.json`), prettierConfigFile);
|
|
1386
|
+
const endpoints = parseApiEndpoints(rtk.code, logger, rtk.locations);
|
|
1387
|
+
const handlerEndpoints = detectResponseHandlerEndpoints(doc, endpoints, api.responseHandlers);
|
|
1388
|
+
const responseKinds = /* @__PURE__ */ new Map();
|
|
1389
|
+
for (const endpoint of endpoints) {
|
|
1390
|
+
const kind = handlerEndpoints.get(endpoint.key);
|
|
1391
|
+
if (kind && endpoint.responseType) responseKinds.set(endpoint.responseType, kind);
|
|
1392
|
+
}
|
|
1393
|
+
const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
|
|
1394
|
+
if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
|
|
1395
|
+
const esm = api.config.esmExtensions === true;
|
|
1396
|
+
const apiSource = extractModels({
|
|
1397
|
+
apiSource: rtk.code,
|
|
1398
|
+
apiFilePath: api.outputFile,
|
|
1399
|
+
modelsDir,
|
|
1400
|
+
registry,
|
|
1401
|
+
files,
|
|
1402
|
+
logger,
|
|
1403
|
+
esm,
|
|
1404
|
+
responseKinds
|
|
1405
|
+
});
|
|
1406
|
+
if (!write) continue;
|
|
1407
|
+
files.set(api.outputFile, injectResponseHandlers(apiSource, handlerEndpoints));
|
|
1408
|
+
const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
|
|
1409
|
+
const enhanced = buildEnhancedEndpoints({
|
|
1410
|
+
stem: api.stem,
|
|
1411
|
+
apiModuleImport: withExtension(`./${api.stem}`),
|
|
1412
|
+
baseApiImport: api.config.baseApiImport ?? withExtension(relativeImport(api.outputDir, api.apiFile).replace(/\.[cm]?[jt]sx?$/, "")),
|
|
1413
|
+
baseApiName: api.config.apiImport ?? "api",
|
|
1414
|
+
audience: api.audience,
|
|
1415
|
+
endpoints,
|
|
1416
|
+
index,
|
|
1417
|
+
operationTags: collectOperationTags(doc, api.audience),
|
|
1418
|
+
logger
|
|
1419
|
+
});
|
|
1420
|
+
files.set(path8.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);
|
|
1421
|
+
files.set(path8.join(api.outputDir, `${api.stem}Tags.ts`), renderTagsFile(api.stem, enhanced.tagTypes));
|
|
1422
|
+
}
|
|
1423
|
+
} finally {
|
|
1424
|
+
fs8.rmSync(specDir, { recursive: true, force: true });
|
|
1425
|
+
}
|
|
1426
|
+
if (!options.skipPrettier) {
|
|
1427
|
+
logger.info("formatting with prettier");
|
|
1428
|
+
await formatFiles(files);
|
|
1429
|
+
}
|
|
1430
|
+
const committed = commitOutput(files, modelsDir, loaded.rootDir);
|
|
1431
|
+
let typechecked = false;
|
|
1432
|
+
if (!options.skipTsc) {
|
|
1433
|
+
logger.info("type check (tsc --noEmit)");
|
|
1434
|
+
try {
|
|
1435
|
+
typechecked = typecheck(loaded.rootDir, path8.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
committed.rollback();
|
|
1438
|
+
logger.error("type check failed \u2014 previous output restored");
|
|
1439
|
+
throw error;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
committed.finalize();
|
|
1443
|
+
logger.info(`done: ${files.paths().length} files`);
|
|
1444
|
+
return { apis: apis.map((api) => api.exportName), files: files.paths(), modelsDir, typechecked };
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
// src/codegen/link-skills.ts
|
|
1448
|
+
import * as fs9 from "fs";
|
|
1449
|
+
import * as path9 from "path";
|
|
1450
|
+
function packageLabel(packageDir) {
|
|
1451
|
+
if (packageDir) {
|
|
1452
|
+
try {
|
|
1453
|
+
const version = JSON.parse(fs9.readFileSync(path9.join(packageDir, "package.json"), "utf-8")).version;
|
|
1454
|
+
if (typeof version === "string") return `@mgamadeus/ddd-web ${version}`;
|
|
1455
|
+
} catch {
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
return "@mgamadeus/ddd-web";
|
|
1459
|
+
}
|
|
1460
|
+
function linkSkills(options = {}) {
|
|
1461
|
+
const cwd = path9.resolve(options.cwd ?? process.cwd());
|
|
1462
|
+
const logger = options.logger ?? consoleLogger;
|
|
1463
|
+
const packageDir = path9.join(cwd, "node_modules", "@mgamadeus", "ddd-web");
|
|
1464
|
+
const sourceDir = options.sourceDir ? path9.resolve(cwd, options.sourceDir) : path9.join(packageDir, ".claude", "skills");
|
|
1465
|
+
if (!options.sourceDir && !fs9.existsSync(packageDir)) {
|
|
1466
|
+
logger.warn(`@mgamadeus/ddd-web is not installed in ${cwd} (no ${packageDir}) \u2014 nothing to link.`);
|
|
1467
|
+
return [];
|
|
1468
|
+
}
|
|
1469
|
+
const skills = fs9.existsSync(sourceDir) ? fs9.readdirSync(sourceDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()) : [];
|
|
1470
|
+
if (skills.length === 0) {
|
|
1471
|
+
logger.info(`${packageLabel(options.sourceDir ? void 0 : packageDir)} ships no agent skills (${sourceDir}) \u2014 nothing to link.`);
|
|
1472
|
+
return [];
|
|
1473
|
+
}
|
|
1474
|
+
const targetDir = path9.join(cwd, ".claude", "skills");
|
|
1475
|
+
fs9.mkdirSync(targetDir, { recursive: true });
|
|
1476
|
+
const results = [];
|
|
1477
|
+
for (const entry of skills) {
|
|
1478
|
+
const linkPath = path9.join(targetDir, entry.name);
|
|
1479
|
+
const linkTarget = path9.relative(targetDir, path9.join(sourceDir, entry.name));
|
|
1480
|
+
let action;
|
|
1481
|
+
const existing = fs9.lstatSync(linkPath, { throwIfNoEntry: false });
|
|
1482
|
+
if (!existing) {
|
|
1483
|
+
fs9.symlinkSync(linkTarget, linkPath, "dir");
|
|
1484
|
+
action = "linked";
|
|
1485
|
+
} else if (!existing.isSymbolicLink()) {
|
|
1486
|
+
action = "skipped";
|
|
1487
|
+
} else if (fs9.readlinkSync(linkPath) === linkTarget) {
|
|
1488
|
+
action = "unchanged";
|
|
1489
|
+
} else {
|
|
1490
|
+
fs9.unlinkSync(linkPath);
|
|
1491
|
+
fs9.symlinkSync(linkTarget, linkPath, "dir");
|
|
1492
|
+
action = "relinked";
|
|
1493
|
+
}
|
|
1494
|
+
const message = `${action.padEnd(9)} .claude/skills/${entry.name} \u2192 ${linkTarget}`;
|
|
1495
|
+
if (action === "skipped") logger.warn(`${message} (exists and is not a symlink \u2014 left as is)`);
|
|
1496
|
+
else logger.info(message);
|
|
1497
|
+
results.push({ skill: entry.name, action, target: linkTarget });
|
|
1498
|
+
}
|
|
1499
|
+
return results;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
export {
|
|
1503
|
+
defineConfig,
|
|
1504
|
+
loadConfig,
|
|
1505
|
+
consoleLogger,
|
|
1506
|
+
silentLogger,
|
|
1507
|
+
SdkGenerationError,
|
|
1508
|
+
SUPPORTED_CONTRACT,
|
|
1509
|
+
loadSpec,
|
|
1510
|
+
validateSpec,
|
|
1511
|
+
generateSdk,
|
|
1512
|
+
linkSkills
|
|
1513
|
+
};
|
|
1514
|
+
//# sourceMappingURL=chunk-OL742YG5.js.map
|