@mgamadeus/ddd-web 0.17.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/ddd-web-specialist/SKILL.md +9 -2
- package/.claude/skills/ddd-web-specialist/references/consumer.md +15 -0
- package/CHANGELOG.md +17 -0
- package/README.md +15 -0
- package/dist/{chunk-3V22MYDI.js → chunk-AGECBV52.js} +816 -606
- package/dist/chunk-AGECBV52.js.map +1 -0
- package/dist/codegen/cli.js +9 -2
- package/dist/codegen/cli.js.map +1 -1
- package/dist/codegen/index.d.ts +53 -2
- package/dist/codegen/index.js +3 -1
- package/package.json +1 -1
- package/dist/chunk-3V22MYDI.js.map +0 -1
|
@@ -99,17 +99,17 @@ var SdkGenerationError = class extends Error {
|
|
|
99
99
|
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
100
100
|
function listOperations(doc) {
|
|
101
101
|
const result = [];
|
|
102
|
-
for (const [
|
|
102
|
+
for (const [path12, item] of Object.entries(doc.paths ?? {})) {
|
|
103
103
|
if (!item) continue;
|
|
104
104
|
for (const method of HTTP_METHODS) {
|
|
105
105
|
const operation = item[method];
|
|
106
|
-
if (operation) result.push({ method, path:
|
|
106
|
+
if (operation) result.push({ method, path: path12, operation });
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
return result;
|
|
110
110
|
}
|
|
111
|
-
function operationKey(method,
|
|
112
|
-
return `${method.toUpperCase()} ${
|
|
111
|
+
function operationKey(method, path12) {
|
|
112
|
+
return `${method.toUpperCase()} ${path12}`;
|
|
113
113
|
}
|
|
114
114
|
|
|
115
115
|
// src/codegen/tags.ts
|
|
@@ -166,9 +166,9 @@ function segmentToPascal(segment) {
|
|
|
166
166
|
if (/[A-Z]/.test(segment)) return segment;
|
|
167
167
|
return segment.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
168
168
|
}
|
|
169
|
-
function tagFromPath(
|
|
169
|
+
function tagFromPath(path12, lookup) {
|
|
170
170
|
let matched = null;
|
|
171
|
-
for (const segment of
|
|
171
|
+
for (const segment of path12.replace(/\{[^}]+\}/g, "").split("/").filter(Boolean)) {
|
|
172
172
|
matched = lookup.get(segmentToPascal(segment).toLowerCase()) ?? matched;
|
|
173
173
|
}
|
|
174
174
|
return matched;
|
|
@@ -180,11 +180,11 @@ function tagFromOperation(info, audience, lookup) {
|
|
|
180
180
|
}
|
|
181
181
|
return null;
|
|
182
182
|
}
|
|
183
|
-
function trailingPlaceholder(
|
|
184
|
-
return
|
|
183
|
+
function trailingPlaceholder(path12) {
|
|
184
|
+
return path12.match(/\{([^}]+)\}\/?$/)?.[1] ?? null;
|
|
185
185
|
}
|
|
186
|
-
function isPrimaryEntityPath(
|
|
187
|
-
const segments =
|
|
186
|
+
function isPrimaryEntityPath(path12, tag) {
|
|
187
|
+
const segments = path12.replace(/\{[^}]+\}\/?$/, "").split("/").filter(Boolean);
|
|
188
188
|
const last = segments[segments.length - 1];
|
|
189
189
|
return last !== void 0 && segmentToPascal(last).toLowerCase() === tag.toLowerCase();
|
|
190
190
|
}
|
|
@@ -223,9 +223,9 @@ function singularForms(tag) {
|
|
|
223
223
|
if (lower.endsWith("s")) forms.add(lower.slice(0, -1));
|
|
224
224
|
return [...forms];
|
|
225
225
|
}
|
|
226
|
-
function identityPathParameter(
|
|
226
|
+
function identityPathParameter(path12, tag) {
|
|
227
227
|
const singulars = singularForms(tag);
|
|
228
|
-
const segments =
|
|
228
|
+
const segments = path12.split("/").filter(Boolean);
|
|
229
229
|
let found = null;
|
|
230
230
|
segments.forEach((segment, index) => {
|
|
231
231
|
const name = segment.match(/^\{([^}]+)\}$/)?.[1];
|
|
@@ -292,8 +292,8 @@ function entityInvalidation(endpoint, info, tag) {
|
|
|
292
292
|
if (action === "upsert" || action === "delete") {
|
|
293
293
|
if (identity.startsWith("path:")) {
|
|
294
294
|
const accessor = endpoint.pathArgs[identity.slice("path:".length)];
|
|
295
|
-
const
|
|
296
|
-
if (
|
|
295
|
+
const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
296
|
+
if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
|
|
297
297
|
}
|
|
298
298
|
if (identity.startsWith("body:") && endpoint.bodyArg !== void 0) {
|
|
299
299
|
const body = relativeAccessor(endpoint.bodyArg);
|
|
@@ -306,8 +306,8 @@ function entityInvalidation(endpoint, info, tag) {
|
|
|
306
306
|
function heuristicInvalidation(endpoint, info, tag, doc, lookup) {
|
|
307
307
|
const parameter = identityPathParameter(endpoint.path, tag);
|
|
308
308
|
const accessor = parameter ? endpoint.pathArgs[parameter] : void 0;
|
|
309
|
-
const
|
|
310
|
-
if (
|
|
309
|
+
const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
310
|
+
if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
|
|
311
311
|
if (info && endpoint.bodyArg !== void 0) {
|
|
312
312
|
const body = relativeAccessor(endpoint.bodyArg);
|
|
313
313
|
const inner = identityBodyPath(doc, info.operation, tag, lookup);
|
|
@@ -418,8 +418,8 @@ function buildEnhancedEndpoints(input) {
|
|
|
418
418
|
sideEffects: info?.sideEffects ?? true,
|
|
419
419
|
pathArgs: Object.fromEntries(
|
|
420
420
|
Object.entries(endpoint.pathArgs).flatMap(([name, accessor]) => {
|
|
421
|
-
const
|
|
422
|
-
return
|
|
421
|
+
const relative6 = relativeAccessor(accessor);
|
|
422
|
+
return relative6 === null ? [] : [[name, relative6]];
|
|
423
423
|
})
|
|
424
424
|
),
|
|
425
425
|
...endpoint.bodyArg !== void 0 && relativeAccessor(endpoint.bodyArg) !== null ? { bodyArg: relativeAccessor(endpoint.bodyArg) } : {},
|
|
@@ -476,12 +476,586 @@ function buildEnhancedEndpoints(input) {
|
|
|
476
476
|
return { source, tagTypes: [...allTags].sort() };
|
|
477
477
|
}
|
|
478
478
|
|
|
479
|
+
// src/codegen/spec.ts
|
|
480
|
+
import * as fs2 from "fs";
|
|
481
|
+
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
482
|
+
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
483
|
+
async function loadSpec(source, timeoutMs = 6e4) {
|
|
484
|
+
let text;
|
|
485
|
+
if (isUrl(source)) {
|
|
486
|
+
let response;
|
|
487
|
+
try {
|
|
488
|
+
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
489
|
+
} catch (error) {
|
|
490
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
491
|
+
}
|
|
492
|
+
if (!response.ok) {
|
|
493
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
494
|
+
}
|
|
495
|
+
text = await response.text();
|
|
496
|
+
} else {
|
|
497
|
+
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
498
|
+
text = fs2.readFileSync(source, "utf-8");
|
|
499
|
+
}
|
|
500
|
+
let parsed;
|
|
501
|
+
try {
|
|
502
|
+
parsed = JSON.parse(text);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
505
|
+
}
|
|
506
|
+
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
507
|
+
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
508
|
+
}
|
|
509
|
+
return parsed;
|
|
510
|
+
}
|
|
511
|
+
function validateSpec(doc, source, logger) {
|
|
512
|
+
const contract = doc.info?.["x-ddd-contract"];
|
|
513
|
+
if (contract === void 0) {
|
|
514
|
+
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
515
|
+
} else {
|
|
516
|
+
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
517
|
+
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
518
|
+
throw new SdkGenerationError(
|
|
519
|
+
`${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.`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));
|
|
524
|
+
if (!hasSchemaTags) {
|
|
525
|
+
throw new SdkGenerationError(
|
|
526
|
+
`${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.`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/codegen/delegated-sdk.ts
|
|
532
|
+
import * as fs6 from "fs";
|
|
533
|
+
import { createRequire as createRequire2 } from "module";
|
|
534
|
+
import * as os from "os";
|
|
535
|
+
import * as path5 from "path";
|
|
536
|
+
|
|
537
|
+
// src/codegen/files.ts
|
|
538
|
+
import * as fs3 from "fs";
|
|
539
|
+
import * as path2 from "path";
|
|
540
|
+
var OutputFiles = class {
|
|
541
|
+
files = /* @__PURE__ */ new Map();
|
|
542
|
+
lowerCaseIndex = /* @__PURE__ */ new Map();
|
|
543
|
+
set(filePath, content) {
|
|
544
|
+
const absolute = path2.resolve(filePath);
|
|
545
|
+
this.files.set(absolute, { content, generatedThisRun: true });
|
|
546
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
547
|
+
}
|
|
548
|
+
get(filePath) {
|
|
549
|
+
return this.files.get(path2.resolve(filePath))?.content;
|
|
550
|
+
}
|
|
551
|
+
isGeneratedThisRun(filePath) {
|
|
552
|
+
return this.files.get(path2.resolve(filePath))?.generatedThisRun ?? false;
|
|
553
|
+
}
|
|
554
|
+
/** Case-insensitive lookup; returns the stored path spelling. */
|
|
555
|
+
findPath(filePath) {
|
|
556
|
+
return this.lowerCaseIndex.get(path2.resolve(filePath).toLowerCase());
|
|
557
|
+
}
|
|
558
|
+
paths() {
|
|
559
|
+
return [...this.files.keys()];
|
|
560
|
+
}
|
|
561
|
+
/** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */
|
|
562
|
+
seedFromDisk(dir) {
|
|
563
|
+
for (const absolute of listTsFiles(dir)) {
|
|
564
|
+
this.files.set(absolute, { content: fs3.readFileSync(absolute, "utf-8"), generatedThisRun: false });
|
|
565
|
+
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
function listTsFiles(dir) {
|
|
570
|
+
if (!fs3.existsSync(dir)) return [];
|
|
571
|
+
const result = [];
|
|
572
|
+
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
573
|
+
const absolute = path2.join(dir, entry.name);
|
|
574
|
+
if (entry.isDirectory()) result.push(...listTsFiles(absolute));
|
|
575
|
+
else if (entry.isFile() && entry.name.endsWith(".ts")) result.push(absolute);
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// src/codegen/format.ts
|
|
581
|
+
import { execFileSync } from "child_process";
|
|
582
|
+
import * as fs4 from "fs";
|
|
583
|
+
import { createRequire } from "module";
|
|
584
|
+
import * as path3 from "path";
|
|
585
|
+
import prettier from "prettier";
|
|
586
|
+
async function formatFiles(files) {
|
|
587
|
+
for (const filePath of files.paths()) {
|
|
588
|
+
const options = await prettier.resolveConfig(filePath, { editorconfig: true }) ?? {};
|
|
589
|
+
files.set(filePath, await prettier.format(files.get(filePath), { ...options, filepath: filePath }));
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
function resolveTscOfInstallation(base) {
|
|
593
|
+
let packageJsonPath;
|
|
594
|
+
try {
|
|
595
|
+
packageJsonPath = createRequire(base).resolve("typescript/package.json");
|
|
596
|
+
} catch {
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
const packageJson = JSON.parse(fs4.readFileSync(packageJsonPath, "utf-8"));
|
|
600
|
+
const binEntry = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.tsc;
|
|
601
|
+
if (!binEntry) return null;
|
|
602
|
+
const executable = path3.resolve(path3.dirname(packageJsonPath), binEntry);
|
|
603
|
+
return fs4.existsSync(executable) ? { executable, version: packageJson.version ?? "unknown" } : null;
|
|
604
|
+
}
|
|
605
|
+
function resolveTypeScriptCompiler(rootDir) {
|
|
606
|
+
const projectCompiler = resolveTscOfInstallation(path3.join(rootDir, "package.json"));
|
|
607
|
+
if (projectCompiler) return { ...projectCompiler, origin: "project" };
|
|
608
|
+
const ownRequire = createRequire(import.meta.url);
|
|
609
|
+
for (const base of [import.meta.url, ownRequire.resolve("@rtk-query/codegen-openapi")]) {
|
|
610
|
+
const generatorCompiler = resolveTscOfInstallation(base);
|
|
611
|
+
if (generatorCompiler) return { ...generatorCompiler, origin: "generator" };
|
|
612
|
+
}
|
|
613
|
+
throw new SdkGenerationError("No TypeScript compiler found for the type check (install typescript in the project, or pass --skip-tsc).");
|
|
614
|
+
}
|
|
615
|
+
function buildCompilerCommand(executable, args) {
|
|
616
|
+
if (/\.(c|m)?js$/.test(executable)) return [process.execPath, [executable, ...args]];
|
|
617
|
+
const head = fs4.readFileSync(executable).subarray(0, 100).toString("latin1");
|
|
618
|
+
return head.startsWith("#!") && head.split("\n", 1)[0].includes("node") ? [process.execPath, [executable, ...args]] : [executable, args];
|
|
619
|
+
}
|
|
620
|
+
function typecheck(rootDir, tsconfig, logger) {
|
|
621
|
+
if (!fs4.existsSync(tsconfig)) {
|
|
622
|
+
logger.warn(`No ${path3.relative(rootDir, tsconfig) || tsconfig} \u2014 skipping the type check.`);
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
const compiler = resolveTypeScriptCompiler(rootDir);
|
|
626
|
+
logger.info(
|
|
627
|
+
`Type check with TypeScript ${compiler.version} (${compiler.origin === "project" ? "the project's compiler" : "the generator's own compiler \u2014 the project has no typescript"}).`
|
|
628
|
+
);
|
|
629
|
+
const [command, args] = buildCompilerCommand(compiler.executable, ["--noEmit", "-p", tsconfig]);
|
|
630
|
+
try {
|
|
631
|
+
execFileSync(command, args, {
|
|
632
|
+
cwd: rootDir,
|
|
633
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
634
|
+
encoding: "utf-8"
|
|
635
|
+
});
|
|
636
|
+
} catch (error) {
|
|
637
|
+
const output = error.stdout ?? "";
|
|
638
|
+
throw new SdkGenerationError(`Type check failed:
|
|
639
|
+
${output.split("\n").slice(0, 40).join("\n")}`);
|
|
640
|
+
}
|
|
641
|
+
return true;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/contract/extensions.ts
|
|
645
|
+
function hasSideEffects(method, operation) {
|
|
646
|
+
const explicit = operation?.["x-ddd-side-effects"];
|
|
647
|
+
if (typeof explicit === "boolean") {
|
|
648
|
+
return explicit;
|
|
649
|
+
}
|
|
650
|
+
return !["get", "head", "options", "trace"].includes(method.toLowerCase());
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// src/codegen/operations.ts
|
|
654
|
+
function testPattern(pattern, value) {
|
|
655
|
+
pattern.lastIndex = 0;
|
|
656
|
+
const result = pattern.test(value);
|
|
657
|
+
pattern.lastIndex = 0;
|
|
658
|
+
return result;
|
|
659
|
+
}
|
|
660
|
+
function matchesOperation(override, method, path12) {
|
|
661
|
+
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
662
|
+
return typeof override.path === "string" ? override.path === path12 : testPattern(override.path, path12);
|
|
663
|
+
}
|
|
664
|
+
function canonical(value) {
|
|
665
|
+
return JSON.stringify(
|
|
666
|
+
value,
|
|
667
|
+
(_key, inner) => inner && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner
|
|
668
|
+
) ?? "undefined";
|
|
669
|
+
}
|
|
670
|
+
function isUpsertTwin(post, patch) {
|
|
671
|
+
if (post["x-ddd-side-effects"] !== patch["x-ddd-side-effects"]) return false;
|
|
672
|
+
const postEntity = isEntityExtension(post["x-ddd-entity"]) ? post["x-ddd-entity"] : void 0;
|
|
673
|
+
const patchEntity = isEntityExtension(patch["x-ddd-entity"]) ? patch["x-ddd-entity"] : void 0;
|
|
674
|
+
if (postEntity && patchEntity) {
|
|
675
|
+
return postEntity.action === "upsert" && patchEntity.action === "upsert" && postEntity.schema === patchEntity.schema;
|
|
676
|
+
}
|
|
677
|
+
if (postEntity && postEntity.action !== "upsert" || patchEntity && patchEntity.action !== "upsert") return false;
|
|
678
|
+
if (post.summary === void 0 || post.summary !== patch.summary) return false;
|
|
679
|
+
return ["parameters", "requestBody", "responses"].every((key) => canonical(post[key]) === canonical(patch[key]));
|
|
680
|
+
}
|
|
681
|
+
function isEntityExtension(value) {
|
|
682
|
+
return !!value && typeof value === "object" && typeof value.schema === "string" && typeof value.action === "string";
|
|
683
|
+
}
|
|
684
|
+
function indexOperations(doc, overrides, skipUpdatePostTwins) {
|
|
685
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
686
|
+
for (const { method, path: path12, operation } of listOperations(doc)) {
|
|
687
|
+
const extension = operation["x-ddd-side-effects"];
|
|
688
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path12));
|
|
689
|
+
let sideEffects = hasSideEffects(method, operation);
|
|
690
|
+
let explicit = false;
|
|
691
|
+
if (typeof extension === "boolean") {
|
|
692
|
+
sideEffects = extension;
|
|
693
|
+
explicit = true;
|
|
694
|
+
} else if (override) {
|
|
695
|
+
sideEffects = override.sideEffects;
|
|
696
|
+
explicit = true;
|
|
697
|
+
}
|
|
698
|
+
const naturalType = method === "get" ? "query" : "mutation";
|
|
699
|
+
const classifiedType = explicit ? sideEffects ? "mutation" : "query" : naturalType;
|
|
700
|
+
const endpointType = typeof extension !== "boolean" && override?.endpointType || classifiedType;
|
|
701
|
+
const entity = isEntityExtension(operation["x-ddd-entity"]) ? operation["x-ddd-entity"] : void 0;
|
|
702
|
+
byKey.set(operationKey(method, path12), {
|
|
703
|
+
method,
|
|
704
|
+
path: path12,
|
|
705
|
+
operation,
|
|
706
|
+
sideEffects,
|
|
707
|
+
sideEffectsExplicit: explicit,
|
|
708
|
+
endpointType,
|
|
709
|
+
...entity ? { entity } : {}
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
const skippedTwins = /* @__PURE__ */ new Set();
|
|
713
|
+
if (skipUpdatePostTwins) {
|
|
714
|
+
for (const [path12, item] of Object.entries(doc.paths ?? {})) {
|
|
715
|
+
const post = item?.post;
|
|
716
|
+
const patch = item?.patch;
|
|
717
|
+
if (post && patch && isUpsertTwin(post, patch)) {
|
|
718
|
+
skippedTwins.add(operationKey("post", path12));
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return { byKey, skippedTwins };
|
|
723
|
+
}
|
|
724
|
+
function endpointTypeOverrides(index) {
|
|
725
|
+
const result = [];
|
|
726
|
+
for (const info of index.byKey.values()) {
|
|
727
|
+
const rtkDefault = info.method === "get" ? "query" : "mutation";
|
|
728
|
+
if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });
|
|
729
|
+
}
|
|
730
|
+
return result;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// src/codegen/output.ts
|
|
734
|
+
import * as fs5 from "fs";
|
|
735
|
+
import * as path4 from "path";
|
|
736
|
+
function defaultMove(from, to) {
|
|
737
|
+
fs5.mkdirSync(path4.dirname(to), { recursive: true });
|
|
738
|
+
try {
|
|
739
|
+
fs5.renameSync(from, to);
|
|
740
|
+
} catch (error) {
|
|
741
|
+
if (error.code !== "EXDEV") throw error;
|
|
742
|
+
fs5.cpSync(from, to, { recursive: true });
|
|
743
|
+
fs5.rmSync(from, { recursive: true, force: true });
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
747
|
+
const move = options.move ?? defaultMove;
|
|
748
|
+
fs5.mkdirSync(stagingParent, { recursive: true });
|
|
749
|
+
const staging = fs5.mkdtempSync(path4.join(stagingParent, ".ddd-web-sdk-"));
|
|
750
|
+
const stagedModels = path4.join(staging, "models");
|
|
751
|
+
const backupModels = path4.join(staging, "models.previous");
|
|
752
|
+
const singles = [];
|
|
753
|
+
try {
|
|
754
|
+
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
755
|
+
for (const filePath of files.paths()) {
|
|
756
|
+
const content = files.get(filePath);
|
|
757
|
+
const relative6 = modelsDir === void 0 ? void 0 : path4.relative(modelsDir, filePath);
|
|
758
|
+
if (relative6 !== void 0 && !relative6.startsWith("..") && !path4.isAbsolute(relative6)) {
|
|
759
|
+
const staged = path4.join(stagedModels, relative6);
|
|
760
|
+
fs5.mkdirSync(path4.dirname(staged), { recursive: true });
|
|
761
|
+
fs5.writeFileSync(staged, content);
|
|
762
|
+
} else {
|
|
763
|
+
const staged = path4.join(staging, "files", String(singles.length));
|
|
764
|
+
fs5.mkdirSync(path4.dirname(staged), { recursive: true });
|
|
765
|
+
fs5.writeFileSync(staged, content);
|
|
766
|
+
singles.push({ target: filePath, staged, backup: path4.join(staging, "files.previous", String(singles.length)) });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
} catch (error) {
|
|
770
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
771
|
+
throw error;
|
|
772
|
+
}
|
|
773
|
+
const undo = [];
|
|
774
|
+
const rollback = () => {
|
|
775
|
+
const failures = [];
|
|
776
|
+
for (const step of undo.reverse()) {
|
|
777
|
+
try {
|
|
778
|
+
step();
|
|
779
|
+
} catch (error) {
|
|
780
|
+
failures.push(error);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
undo.length = 0;
|
|
784
|
+
if (failures.length > 0) {
|
|
785
|
+
throw new SdkGenerationError(
|
|
786
|
+
`Could not restore the previous output; the previous output is kept in ${staging} (models.previous/, files.previous/): ${failures.map((failure) => failure.message).join("; ")}`
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
fs5.rmSync(staging, { recursive: true, force: true });
|
|
790
|
+
};
|
|
791
|
+
const swap = (target, staged, backup, removeTarget) => {
|
|
792
|
+
const state = { backedUp: false, movedIn: false };
|
|
793
|
+
undo.push(() => {
|
|
794
|
+
if (state.movedIn) removeTarget();
|
|
795
|
+
if (state.backedUp) move(backup, target);
|
|
796
|
+
});
|
|
797
|
+
if (fs5.existsSync(target)) {
|
|
798
|
+
move(target, backup);
|
|
799
|
+
state.backedUp = true;
|
|
800
|
+
}
|
|
801
|
+
move(staged, target);
|
|
802
|
+
state.movedIn = true;
|
|
803
|
+
};
|
|
804
|
+
try {
|
|
805
|
+
if (modelsDir !== void 0) {
|
|
806
|
+
swap(modelsDir, stagedModels, backupModels, () => fs5.rmSync(modelsDir, { recursive: true, force: true }));
|
|
807
|
+
}
|
|
808
|
+
for (const single of singles) {
|
|
809
|
+
swap(single.target, single.staged, single.backup, () => fs5.rmSync(single.target, { force: true }));
|
|
810
|
+
}
|
|
811
|
+
} catch (error) {
|
|
812
|
+
rollback();
|
|
813
|
+
throw error;
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
rollback,
|
|
817
|
+
finalize: () => fs5.rmSync(staging, { recursive: true, force: true })
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// src/codegen/repair.ts
|
|
822
|
+
function resolveParameter(doc, parameter) {
|
|
823
|
+
let current = parameter;
|
|
824
|
+
for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
|
|
825
|
+
const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
|
|
826
|
+
if (!match) return null;
|
|
827
|
+
const name = match[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
828
|
+
current = doc.components?.parameters?.[name];
|
|
829
|
+
}
|
|
830
|
+
return current && current.$ref === void 0 ? current : null;
|
|
831
|
+
}
|
|
832
|
+
function repairMissingPathParameters(doc, logger) {
|
|
833
|
+
const repairs = [];
|
|
834
|
+
for (const { method, path: path12, operation } of listOperations(doc)) {
|
|
835
|
+
const placeholders = [...path12.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
836
|
+
if (placeholders.length === 0) continue;
|
|
837
|
+
const pathLevel = doc.paths?.[path12]?.parameters ?? [];
|
|
838
|
+
const declared = new Set(
|
|
839
|
+
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
840
|
+
);
|
|
841
|
+
const missing = placeholders.filter((name) => !declared.has(name));
|
|
842
|
+
if (missing.length > 0) repairs.push({ path: path12, method, names: missing });
|
|
843
|
+
}
|
|
844
|
+
if (repairs.length === 0) return doc;
|
|
845
|
+
const copy = structuredClone(doc);
|
|
846
|
+
for (const { path: path12, method, names } of repairs) {
|
|
847
|
+
const operation = copy.paths[path12][method];
|
|
848
|
+
operation.parameters = [
|
|
849
|
+
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
850
|
+
...operation.parameters ?? []
|
|
851
|
+
];
|
|
852
|
+
logger.warn(`${method.toUpperCase()} ${path12}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
853
|
+
}
|
|
854
|
+
return copy;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// src/codegen/delegated-sdk.ts
|
|
858
|
+
var packageName = "swagger-sdk-generator";
|
|
859
|
+
var ownershipMarker = ".ddd-web-sdk.json";
|
|
860
|
+
function loadGenerator(rootDir, mode) {
|
|
861
|
+
const require2 = createRequire2(path5.join(rootDir, "package.json"));
|
|
862
|
+
const dependency = packageName + (mode === "legacy" ? "@^3.1" : "@^3");
|
|
863
|
+
let entry;
|
|
864
|
+
try {
|
|
865
|
+
entry = require2.resolve(packageName);
|
|
866
|
+
if (mode === "legacy") {
|
|
867
|
+
require2.resolve(packageName + "/runtime/stores");
|
|
868
|
+
require2.resolve(packageName + "/runtime/mocks");
|
|
869
|
+
}
|
|
870
|
+
} catch {
|
|
871
|
+
throw new SdkGenerationError("Install " + dependency + " in the consuming project to use SDK mode " + mode + ".");
|
|
872
|
+
}
|
|
873
|
+
const engine = require2(entry);
|
|
874
|
+
if (typeof engine.generate !== "function") {
|
|
875
|
+
throw new SdkGenerationError(packageName + " must export generate() to use SDK mode " + mode + ".");
|
|
876
|
+
}
|
|
877
|
+
return { generate: engine.generate };
|
|
878
|
+
}
|
|
879
|
+
async function generateLegacySdk(options) {
|
|
880
|
+
const cwd = path5.resolve(options.cwd ?? process.cwd());
|
|
881
|
+
const engine = loadGenerator(cwd, "legacy");
|
|
882
|
+
const logger = options.logger ?? consoleLogger;
|
|
883
|
+
const results = await engine.generate({
|
|
884
|
+
version: 4,
|
|
885
|
+
mode: "legacy",
|
|
886
|
+
targetOptions: options.targetOptions ?? {},
|
|
887
|
+
sources: options.sources,
|
|
888
|
+
prune: false
|
|
889
|
+
}, { cwd, dryRun: true, log: { ...logger, debug() {
|
|
890
|
+
} } });
|
|
891
|
+
const files = new OutputFiles();
|
|
892
|
+
for (const source of options.sources) {
|
|
893
|
+
const result = results.find((candidate) => candidate.source === source.name);
|
|
894
|
+
if (!result?.ok) throw new SdkGenerationError(source.name + ": " + (result?.error?.message ?? "SDK generator returned no result."));
|
|
895
|
+
if (result.skipped) continue;
|
|
896
|
+
if (!result.planned) throw new SdkGenerationError(source.name + ": SDK generator returned no output plan.");
|
|
897
|
+
const roots = Object.values(source.outputs).map(({ dir }) => path5.resolve(cwd, String(dir)));
|
|
898
|
+
for (const output of result.planned) {
|
|
899
|
+
if (!roots.includes(output.dir)) {
|
|
900
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an unexpected output directory.");
|
|
901
|
+
}
|
|
902
|
+
for (const file of output.files) {
|
|
903
|
+
const target = path5.resolve(output.dir, file.path);
|
|
904
|
+
if (path5.isAbsolute(file.path) || target === output.dir || !contains(output.dir, target)) {
|
|
905
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an invalid file path: " + file.path);
|
|
906
|
+
}
|
|
907
|
+
files.set(target, file.content);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
if (!options.dryRun && files.paths().length) commitOutput(files, void 0, cwd).finalize();
|
|
912
|
+
return results;
|
|
913
|
+
}
|
|
914
|
+
function contains(parent, child) {
|
|
915
|
+
const relative6 = path5.relative(parent, child);
|
|
916
|
+
return relative6 !== ".." && !relative6.startsWith(".." + path5.sep) && !path5.isAbsolute(relative6);
|
|
917
|
+
}
|
|
918
|
+
function assertGeneratedDirectory(directory) {
|
|
919
|
+
const entry = fs6.lstatSync(directory, { throwIfNoEntry: false });
|
|
920
|
+
if (entry && (!entry.isDirectory() || fs6.readdirSync(directory).length > 0 && !fs6.existsSync(path5.join(directory, ownershipMarker)))) {
|
|
921
|
+
throw new SdkGenerationError("Choose an empty generated SDK directory. DDD Web does not own " + directory + ".");
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
function prepareSpec(document, api, logger) {
|
|
925
|
+
const repaired = repairMissingPathParameters(document, logger);
|
|
926
|
+
if (!api.skipUpdatePostTwins) return repaired;
|
|
927
|
+
const { skippedTwins } = indexOperations(repaired, api.sideEffects, true);
|
|
928
|
+
return {
|
|
929
|
+
...repaired,
|
|
930
|
+
paths: Object.fromEntries(Object.entries(repaired.paths ?? {}).map(([url, item]) => {
|
|
931
|
+
if (!item || !skippedTwins.has(operationKey("post", url))) return [url, item];
|
|
932
|
+
const { post: _post, ...remaining } = item;
|
|
933
|
+
return [url, remaining];
|
|
934
|
+
}))
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
async function generateDelegatedSdk(mode, loaded, allApis, apis, options, logger) {
|
|
938
|
+
const { rootDir, config } = loaded;
|
|
939
|
+
const generator = config.generator?.mode === mode ? config.generator : void 0;
|
|
940
|
+
const modeDir = path5.resolve(rootDir, generator?.outputDir ?? "./src/generated-sdk", mode);
|
|
941
|
+
const outputOptions = generator?.outputs ?? {};
|
|
942
|
+
const outputNames = mode === "legacy" ? ["models", "stores", "mocks"] : ["models", "client"];
|
|
943
|
+
if (mode === "future" && outputOptions.mocks) outputNames.push("mocks");
|
|
944
|
+
const unsupported = Object.keys(outputOptions).filter((name) => !outputNames.includes(name));
|
|
945
|
+
if (unsupported.length) throw new SdkGenerationError("Unsupported " + mode + " SDK outputs: " + unsupported.join(", ") + ".");
|
|
946
|
+
const stems = /* @__PURE__ */ new Set();
|
|
947
|
+
const defaultModels = config.modelsDir ? [path5.resolve(rootDir, config.modelsDir)] : allApis.map((api) => path5.resolve(api.outputDir, "..", "models"));
|
|
948
|
+
const defaultPaths = [...defaultModels, ...allApis.flatMap((api) => [
|
|
949
|
+
api.outputFile,
|
|
950
|
+
...["Enhanced", "Tags", "Requests"].map((suffix) => path5.join(api.outputDir, api.stem + suffix + ".ts"))
|
|
951
|
+
])].map((file) => file.toLowerCase());
|
|
952
|
+
for (const api of allApis) {
|
|
953
|
+
const key = api.stem.toLowerCase();
|
|
954
|
+
if (!/^[a-z\d][a-z\d._-]*$/i.test(api.stem) || stems.has(key)) {
|
|
955
|
+
throw new SdkGenerationError("Opt-in SDKs need unique API output file stems made of letters, digits, dots, dashes or underscores.");
|
|
956
|
+
}
|
|
957
|
+
stems.add(key);
|
|
958
|
+
const directory = path5.join(modeDir, api.stem);
|
|
959
|
+
if (defaultPaths.some((file) => contains(directory.toLowerCase(), file) || contains(file, directory.toLowerCase()))) {
|
|
960
|
+
throw new SdkGenerationError("Opt-in SDK output overlaps the default SDK at " + directory + ". Choose another generator.outputDir.");
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const engine = loadGenerator(rootDir, mode);
|
|
964
|
+
const plans = new Map(apis.map((api) => {
|
|
965
|
+
const directory = path5.join(modeDir, api.stem);
|
|
966
|
+
assertGeneratedDirectory(directory);
|
|
967
|
+
const outputDirs = outputNames.map((name) => [name, path5.join(directory, name)]);
|
|
968
|
+
return [api.stem, { directory, outputDirs, files: new OutputFiles() }];
|
|
969
|
+
}));
|
|
970
|
+
const specDir = fs6.mkdtempSync(path5.join(os.tmpdir(), "ddd-web-spec-"));
|
|
971
|
+
try {
|
|
972
|
+
const specs = /* @__PURE__ */ new Map();
|
|
973
|
+
const sources = await Promise.all(apis.map(async (api) => {
|
|
974
|
+
if (!specs.has(api.schemaSource)) {
|
|
975
|
+
logger.info("loading " + api.schemaSource);
|
|
976
|
+
specs.set(api.schemaSource, loadSpec(api.schemaSource));
|
|
977
|
+
}
|
|
978
|
+
const document = await specs.get(api.schemaSource);
|
|
979
|
+
validateSpec(document, api.schemaSource, logger);
|
|
980
|
+
const file = path5.join(specDir, api.stem + ".json");
|
|
981
|
+
fs6.writeFileSync(file, JSON.stringify(prepareSpec(document, api, logger)));
|
|
982
|
+
const outputs = Object.fromEntries(plans.get(api.stem).outputDirs.map(([name, dir]) => [
|
|
983
|
+
name,
|
|
984
|
+
{ ...outputOptions[name], dir }
|
|
985
|
+
]));
|
|
986
|
+
return { name: api.stem, file, outputs };
|
|
987
|
+
}));
|
|
988
|
+
const results = await engine.generate({
|
|
989
|
+
version: 4,
|
|
990
|
+
mode,
|
|
991
|
+
sources,
|
|
992
|
+
targetOptions: { prettier: options.skipPrettier ? false : { resolveFrom: rootDir } }
|
|
993
|
+
}, { cwd: rootDir, dryRun: true, log: { ...logger, debug() {
|
|
994
|
+
} } });
|
|
995
|
+
for (const source of sources) {
|
|
996
|
+
const result = results.find((candidate) => candidate.source === source.name);
|
|
997
|
+
if (!result?.ok || !result.planned?.length) {
|
|
998
|
+
throw new SdkGenerationError(source.name + ": " + (result?.error?.message ?? "SDK generator returned no output plan."));
|
|
999
|
+
}
|
|
1000
|
+
const plan = plans.get(source.name);
|
|
1001
|
+
for (const run of result.planned) {
|
|
1002
|
+
if (!plan.outputDirs.some(([, dir]) => dir === run.dir)) {
|
|
1003
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an unexpected output directory.");
|
|
1004
|
+
}
|
|
1005
|
+
for (const file of run.files) {
|
|
1006
|
+
const target = path5.resolve(run.dir, file.path);
|
|
1007
|
+
if (path5.isAbsolute(file.path) || target === run.dir || !contains(run.dir, target) || plan.files.findPath(target)) {
|
|
1008
|
+
throw new SdkGenerationError(source.name + ": SDK generator returned an invalid or duplicate file path: " + file.path);
|
|
1009
|
+
}
|
|
1010
|
+
plan.files.set(target, file.content);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
} finally {
|
|
1015
|
+
fs6.rmSync(specDir, { recursive: true, force: true });
|
|
1016
|
+
}
|
|
1017
|
+
const writtenFiles = [...plans.values()].flatMap((plan) => plan.files.paths());
|
|
1018
|
+
const committed = [];
|
|
1019
|
+
let typechecked = false;
|
|
1020
|
+
try {
|
|
1021
|
+
for (const { directory, files } of plans.values()) {
|
|
1022
|
+
assertGeneratedDirectory(directory);
|
|
1023
|
+
files.set(path5.join(directory, ownershipMarker), '{"version":1}\n');
|
|
1024
|
+
committed.push(commitOutput(files, directory, rootDir));
|
|
1025
|
+
}
|
|
1026
|
+
if (!options.skipTsc) {
|
|
1027
|
+
typechecked = typecheck(rootDir, path5.resolve(rootDir, config.tsconfig ?? "tsconfig.json"), logger);
|
|
1028
|
+
}
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
const failures = [];
|
|
1031
|
+
for (const output of committed.reverse()) {
|
|
1032
|
+
try {
|
|
1033
|
+
output.rollback();
|
|
1034
|
+
} catch (failure) {
|
|
1035
|
+
failures.push(failure);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
if (failures.length) throw new AggregateError([error, ...failures], "SDK generation failed and some output could not be restored.");
|
|
1039
|
+
throw error;
|
|
1040
|
+
}
|
|
1041
|
+
committed.forEach((output) => output.finalize());
|
|
1042
|
+
logger.info("done: " + writtenFiles.length + " files (" + mode + " mode)");
|
|
1043
|
+
const modelsByApi = Object.fromEntries(apis.map((api) => [api.exportName, path5.join(modeDir, api.stem, "models")]));
|
|
1044
|
+
return {
|
|
1045
|
+
apis: apis.map((api) => api.exportName),
|
|
1046
|
+
files: writtenFiles,
|
|
1047
|
+
modelsDir: apis.length === 1 ? Object.values(modelsByApi)[0] : modeDir,
|
|
1048
|
+
modelsByApi,
|
|
1049
|
+
typechecked
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
|
|
479
1053
|
// src/codegen/document-endpoints.ts
|
|
480
1054
|
var REQUEST_BODY_ARG = "requestBody";
|
|
481
1055
|
var DEFAULT_STRIP_PATH_PREFIX = /^\/(?:app\/)?api(?=\/)/;
|
|
482
1056
|
var upperFirst = (value) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
483
|
-
function buildEndpointNameFromPath(method,
|
|
484
|
-
const stripped = typeof stripPathPrefix === "string" ?
|
|
1057
|
+
function buildEndpointNameFromPath(method, path12, stripPathPrefix = DEFAULT_STRIP_PATH_PREFIX) {
|
|
1058
|
+
const stripped = typeof stripPathPrefix === "string" ? path12.startsWith(stripPathPrefix) ? path12.slice(stripPathPrefix.length) : path12 : path12.replace(stripPathPrefix, "");
|
|
485
1059
|
let lastInnerParameter = null;
|
|
486
1060
|
const withoutInnerParameters = stripped.replace(/\{([^}]+)\}\//g, (_, parameter) => {
|
|
487
1061
|
lastInnerParameter = parameter;
|
|
@@ -502,21 +1076,21 @@ function prepareDocumentForEndpoints(doc, options) {
|
|
|
502
1076
|
const prepared = structuredClone(doc);
|
|
503
1077
|
if (dropsCookieParameters) dropCookieParameters(prepared);
|
|
504
1078
|
const pathByName = /* @__PURE__ */ new Map();
|
|
505
|
-
for (const [
|
|
1079
|
+
for (const [path12, item] of Object.entries(prepared.paths ?? {})) {
|
|
506
1080
|
if (!item) continue;
|
|
507
1081
|
for (const method of HTTP_METHODS) {
|
|
508
1082
|
const operation = item[method];
|
|
509
1083
|
if (!operation) continue;
|
|
510
1084
|
if (naming !== "rtk") {
|
|
511
|
-
const name = naming === "path" ? buildEndpointNameFromPath(method,
|
|
1085
|
+
const name = naming === "path" ? buildEndpointNameFromPath(method, path12, options.stripPathPrefix) : naming({ method, path: path12, operation });
|
|
512
1086
|
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
|
|
513
|
-
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${
|
|
1087
|
+
throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path12}) is no identifier.`);
|
|
514
1088
|
}
|
|
515
1089
|
const other = pathByName.get(name);
|
|
516
1090
|
if (other !== void 0) {
|
|
517
|
-
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${
|
|
1091
|
+
throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path12} are both named "${name}".`);
|
|
518
1092
|
}
|
|
519
|
-
pathByName.set(name, `${method.toUpperCase()} ${
|
|
1093
|
+
pathByName.set(name, `${method.toUpperCase()} ${path12}`);
|
|
520
1094
|
const placeholder = `dddEndpoint${endpointNamesByPlaceholder.size}`;
|
|
521
1095
|
endpointNamesByPlaceholder.set(placeholder, name);
|
|
522
1096
|
operation.operationId = placeholder;
|
|
@@ -538,10 +1112,10 @@ function restoreEndpointNames(code, locations, endpointNamesByPlaceholder) {
|
|
|
538
1112
|
return { code: restore(code), locations: restoredLocations };
|
|
539
1113
|
}
|
|
540
1114
|
var isCookieParameter = (parameter, doc) => {
|
|
541
|
-
const resolved =
|
|
1115
|
+
const resolved = resolveParameter2(parameter, doc);
|
|
542
1116
|
return typeof resolved === "object" && resolved !== null && resolved.in === "cookie";
|
|
543
1117
|
};
|
|
544
|
-
function
|
|
1118
|
+
function resolveParameter2(parameter, doc) {
|
|
545
1119
|
const ref = parameter?.$ref;
|
|
546
1120
|
if (typeof ref !== "string" || !ref.startsWith("#/components/parameters/")) return parameter;
|
|
547
1121
|
return doc.components?.parameters?.[ref.slice("#/components/parameters/".length)];
|
|
@@ -555,91 +1129,39 @@ function hasCookieParameters(doc) {
|
|
|
555
1129
|
return false;
|
|
556
1130
|
}
|
|
557
1131
|
function dropCookieParameters(doc) {
|
|
558
|
-
for (const item of Object.values(doc.paths ?? {})) {
|
|
559
|
-
if (!item) continue;
|
|
560
|
-
if (Array.isArray(item.parameters)) item.parameters = item.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
561
|
-
for (const method of HTTP_METHODS) {
|
|
562
|
-
const operation = item[method];
|
|
563
|
-
if (operation && Array.isArray(operation.parameters)) {
|
|
564
|
-
operation.parameters = operation.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
function titleRequestBody(operation) {
|
|
570
|
-
const content = operation.requestBody?.content;
|
|
571
|
-
for (const media of Object.values(content ?? {})) {
|
|
572
|
-
const schema = media?.schema;
|
|
573
|
-
if (!schema) continue;
|
|
574
|
-
media.schema = typeof schema.$ref === "string" ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
// src/codegen/spec.ts
|
|
579
|
-
import * as fs2 from "fs";
|
|
580
|
-
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
581
|
-
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
582
|
-
async function loadSpec(source, timeoutMs = 6e4) {
|
|
583
|
-
let text;
|
|
584
|
-
if (isUrl(source)) {
|
|
585
|
-
let response;
|
|
586
|
-
try {
|
|
587
|
-
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
588
|
-
} catch (error) {
|
|
589
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
590
|
-
}
|
|
591
|
-
if (!response.ok) {
|
|
592
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
593
|
-
}
|
|
594
|
-
text = await response.text();
|
|
595
|
-
} else {
|
|
596
|
-
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
597
|
-
text = fs2.readFileSync(source, "utf-8");
|
|
598
|
-
}
|
|
599
|
-
let parsed;
|
|
600
|
-
try {
|
|
601
|
-
parsed = JSON.parse(text);
|
|
602
|
-
} catch (error) {
|
|
603
|
-
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
604
|
-
}
|
|
605
|
-
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
606
|
-
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
607
|
-
}
|
|
608
|
-
return parsed;
|
|
609
|
-
}
|
|
610
|
-
function validateSpec(doc, source, logger) {
|
|
611
|
-
const contract = doc.info?.["x-ddd-contract"];
|
|
612
|
-
if (contract === void 0) {
|
|
613
|
-
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
614
|
-
} else {
|
|
615
|
-
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
616
|
-
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
617
|
-
throw new SdkGenerationError(
|
|
618
|
-
`${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.`
|
|
619
|
-
);
|
|
1132
|
+
for (const item of Object.values(doc.paths ?? {})) {
|
|
1133
|
+
if (!item) continue;
|
|
1134
|
+
if (Array.isArray(item.parameters)) item.parameters = item.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
1135
|
+
for (const method of HTTP_METHODS) {
|
|
1136
|
+
const operation = item[method];
|
|
1137
|
+
if (operation && Array.isArray(operation.parameters)) {
|
|
1138
|
+
operation.parameters = operation.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
|
|
1139
|
+
}
|
|
620
1140
|
}
|
|
621
1141
|
}
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
1142
|
+
}
|
|
1143
|
+
function titleRequestBody(operation) {
|
|
1144
|
+
const content = operation.requestBody?.content;
|
|
1145
|
+
for (const media of Object.values(content ?? {})) {
|
|
1146
|
+
const schema = media?.schema;
|
|
1147
|
+
if (!schema) continue;
|
|
1148
|
+
media.schema = typeof schema.$ref === "string" ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };
|
|
627
1149
|
}
|
|
628
1150
|
}
|
|
629
1151
|
|
|
630
1152
|
// src/codegen/generate.ts
|
|
631
|
-
import * as
|
|
632
|
-
import * as
|
|
633
|
-
import * as
|
|
1153
|
+
import * as fs9 from "fs";
|
|
1154
|
+
import * as os2 from "os";
|
|
1155
|
+
import * as path10 from "path";
|
|
634
1156
|
|
|
635
1157
|
// src/codegen/typescript.ts
|
|
636
|
-
import { createRequire } from "module";
|
|
1158
|
+
import { createRequire as createRequire3 } from "module";
|
|
637
1159
|
var cached;
|
|
638
1160
|
function loadTypeScript() {
|
|
639
1161
|
if (cached) return cached;
|
|
640
|
-
const require2 =
|
|
1162
|
+
const require2 = createRequire3(import.meta.url);
|
|
641
1163
|
const codegenEntry = require2.resolve("@rtk-query/codegen-openapi");
|
|
642
|
-
cached =
|
|
1164
|
+
cached = createRequire3(codegenEntry)("typescript");
|
|
643
1165
|
return cached;
|
|
644
1166
|
}
|
|
645
1167
|
|
|
@@ -859,305 +1381,109 @@ function toOpenApiPath(url) {
|
|
|
859
1381
|
}
|
|
860
1382
|
function objectReturnedBy(ts, fn) {
|
|
861
1383
|
const body = fn.body;
|
|
862
|
-
if (ts.isParenthesizedExpression(body) && ts.isObjectLiteralExpression(body.expression)) return body.expression;
|
|
863
|
-
if (ts.isObjectLiteralExpression(body)) return body;
|
|
864
|
-
if (ts.isBlock(body)) {
|
|
865
|
-
for (const statement of body.statements) {
|
|
866
|
-
if (ts.isReturnStatement(statement) && statement.expression) {
|
|
867
|
-
let expression = statement.expression;
|
|
868
|
-
if (ts.isParenthesizedExpression(expression)) expression = expression.expression;
|
|
869
|
-
if (ts.isObjectLiteralExpression(expression)) return expression;
|
|
870
|
-
}
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
return null;
|
|
874
|
-
}
|
|
875
|
-
function unwrapEncoding(ts, expression) {
|
|
876
|
-
let current = expression;
|
|
877
|
-
while (ts.isCallExpression(current) && ts.isIdentifier(current.expression) && (current.expression.text === "encodeURIComponent" || current.expression.text === "String") && current.arguments.length === 1) {
|
|
878
|
-
current = current.arguments[0];
|
|
879
|
-
}
|
|
880
|
-
return current;
|
|
881
|
-
}
|
|
882
|
-
function templateAccessors(ts, init, sourceFile) {
|
|
883
|
-
return init.templateSpans.map((span) => unwrapEncoding(ts, span.expression).getText(sourceFile).replace(/^queryArg\b/, "arg"));
|
|
884
|
-
}
|
|
885
|
-
function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
886
|
-
const definition = call.arguments[0];
|
|
887
|
-
if (!definition || !ts.isObjectLiteralExpression(definition)) return null;
|
|
888
|
-
const responseTypeNode = call.typeArguments?.[0];
|
|
889
|
-
const responseType = responseTypeNode && ts.isTypeReferenceNode(responseTypeNode) && ts.isIdentifier(responseTypeNode.typeName) ? responseTypeNode.typeName.text : void 0;
|
|
890
|
-
for (const property of definition.properties) {
|
|
891
|
-
if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) || property.name.text !== "query") continue;
|
|
892
|
-
if (!ts.isArrowFunction(property.initializer)) continue;
|
|
893
|
-
const returned = objectReturnedBy(ts, property.initializer);
|
|
894
|
-
if (!returned) continue;
|
|
895
|
-
let url;
|
|
896
|
-
let method;
|
|
897
|
-
let accessors = [];
|
|
898
|
-
let bodyArg;
|
|
899
|
-
for (const member of returned.properties) {
|
|
900
|
-
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
901
|
-
const init = member.initializer;
|
|
902
|
-
if (member.name.text === "url") {
|
|
903
|
-
if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;
|
|
904
|
-
else if (ts.isTemplateExpression(init)) {
|
|
905
|
-
url = init.getText(sourceFile).slice(1, -1);
|
|
906
|
-
accessors = templateAccessors(ts, init, sourceFile);
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
910
|
-
if (member.name.text === "body" && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {
|
|
911
|
-
const text = init.getText(sourceFile);
|
|
912
|
-
if (/^queryArg(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\b/, "arg");
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
if (url === void 0) {
|
|
916
|
-
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
917
|
-
return null;
|
|
918
|
-
}
|
|
919
|
-
const path11 = location?.path ?? toOpenApiPath(url);
|
|
920
|
-
const placeholders = [...path11.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
921
|
-
const pathArgs = {};
|
|
922
|
-
placeholders.forEach((name, index) => {
|
|
923
|
-
const accessor = accessors[index];
|
|
924
|
-
if (accessor !== void 0) pathArgs[name] = accessor;
|
|
925
|
-
});
|
|
926
|
-
return {
|
|
927
|
-
key,
|
|
928
|
-
buildType,
|
|
929
|
-
url,
|
|
930
|
-
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
931
|
-
path: path11,
|
|
932
|
-
pathArgs,
|
|
933
|
-
...bodyArg ? { bodyArg } : {},
|
|
934
|
-
...responseType ? { responseType } : {}
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
return null;
|
|
938
|
-
}
|
|
939
|
-
function parseApiEndpoints(source, logger, locations = /* @__PURE__ */ new Map()) {
|
|
940
|
-
const ts = loadTypeScript();
|
|
941
|
-
const sourceFile = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true);
|
|
942
|
-
const results = [];
|
|
943
|
-
const visit = (node) => {
|
|
944
|
-
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {
|
|
945
|
-
const callee = node.initializer.expression;
|
|
946
|
-
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === "build") {
|
|
947
|
-
const buildType = callee.name.text;
|
|
948
|
-
if (buildType === "query" || buildType === "mutation") {
|
|
949
|
-
const key = node.name.text;
|
|
950
|
-
const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);
|
|
951
|
-
if (info) results.push(info);
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
ts.forEachChild(node, visit);
|
|
957
|
-
};
|
|
958
|
-
ts.forEachChild(sourceFile, visit);
|
|
959
|
-
return results;
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
// src/codegen/files.ts
|
|
963
|
-
import * as fs3 from "fs";
|
|
964
|
-
import * as path2 from "path";
|
|
965
|
-
var OutputFiles = class {
|
|
966
|
-
files = /* @__PURE__ */ new Map();
|
|
967
|
-
lowerCaseIndex = /* @__PURE__ */ new Map();
|
|
968
|
-
set(filePath, content) {
|
|
969
|
-
const absolute = path2.resolve(filePath);
|
|
970
|
-
this.files.set(absolute, { content, generatedThisRun: true });
|
|
971
|
-
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
972
|
-
}
|
|
973
|
-
get(filePath) {
|
|
974
|
-
return this.files.get(path2.resolve(filePath))?.content;
|
|
975
|
-
}
|
|
976
|
-
isGeneratedThisRun(filePath) {
|
|
977
|
-
return this.files.get(path2.resolve(filePath))?.generatedThisRun ?? false;
|
|
978
|
-
}
|
|
979
|
-
/** Case-insensitive lookup; returns the stored path spelling. */
|
|
980
|
-
findPath(filePath) {
|
|
981
|
-
return this.lowerCaseIndex.get(path2.resolve(filePath).toLowerCase());
|
|
982
|
-
}
|
|
983
|
-
paths() {
|
|
984
|
-
return [...this.files.keys()];
|
|
985
|
-
}
|
|
986
|
-
/** Seeds the store with existing `.ts` files below `dir` (for runs that regenerate only some apis). */
|
|
987
|
-
seedFromDisk(dir) {
|
|
988
|
-
for (const absolute of listTsFiles(dir)) {
|
|
989
|
-
this.files.set(absolute, { content: fs3.readFileSync(absolute, "utf-8"), generatedThisRun: false });
|
|
990
|
-
this.lowerCaseIndex.set(absolute.toLowerCase(), absolute);
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
};
|
|
994
|
-
function listTsFiles(dir) {
|
|
995
|
-
if (!fs3.existsSync(dir)) return [];
|
|
996
|
-
const result = [];
|
|
997
|
-
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
998
|
-
const absolute = path2.join(dir, entry.name);
|
|
999
|
-
if (entry.isDirectory()) result.push(...listTsFiles(absolute));
|
|
1000
|
-
else if (entry.isFile() && entry.name.endsWith(".ts")) result.push(absolute);
|
|
1001
|
-
}
|
|
1002
|
-
return result;
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
// src/codegen/format.ts
|
|
1006
|
-
import { execFileSync } from "child_process";
|
|
1007
|
-
import * as fs4 from "fs";
|
|
1008
|
-
import { createRequire as createRequire2 } from "module";
|
|
1009
|
-
import * as path3 from "path";
|
|
1010
|
-
import prettier from "prettier";
|
|
1011
|
-
async function formatFiles(files) {
|
|
1012
|
-
for (const filePath of files.paths()) {
|
|
1013
|
-
const options = await prettier.resolveConfig(filePath, { editorconfig: true }) ?? {};
|
|
1014
|
-
files.set(filePath, await prettier.format(files.get(filePath), { ...options, filepath: filePath }));
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
function resolveTscOfInstallation(base) {
|
|
1018
|
-
let packageJsonPath;
|
|
1019
|
-
try {
|
|
1020
|
-
packageJsonPath = createRequire2(base).resolve("typescript/package.json");
|
|
1021
|
-
} catch {
|
|
1022
|
-
return null;
|
|
1023
|
-
}
|
|
1024
|
-
const packageJson = JSON.parse(fs4.readFileSync(packageJsonPath, "utf-8"));
|
|
1025
|
-
const binEntry = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.tsc;
|
|
1026
|
-
if (!binEntry) return null;
|
|
1027
|
-
const executable = path3.resolve(path3.dirname(packageJsonPath), binEntry);
|
|
1028
|
-
return fs4.existsSync(executable) ? { executable, version: packageJson.version ?? "unknown" } : null;
|
|
1029
|
-
}
|
|
1030
|
-
function resolveTypeScriptCompiler(rootDir) {
|
|
1031
|
-
const projectCompiler = resolveTscOfInstallation(path3.join(rootDir, "package.json"));
|
|
1032
|
-
if (projectCompiler) return { ...projectCompiler, origin: "project" };
|
|
1033
|
-
const ownRequire = createRequire2(import.meta.url);
|
|
1034
|
-
for (const base of [import.meta.url, ownRequire.resolve("@rtk-query/codegen-openapi")]) {
|
|
1035
|
-
const generatorCompiler = resolveTscOfInstallation(base);
|
|
1036
|
-
if (generatorCompiler) return { ...generatorCompiler, origin: "generator" };
|
|
1037
|
-
}
|
|
1038
|
-
throw new SdkGenerationError("No TypeScript compiler found for the type check (install typescript in the project, or pass --skip-tsc).");
|
|
1039
|
-
}
|
|
1040
|
-
function buildCompilerCommand(executable, args) {
|
|
1041
|
-
if (/\.(c|m)?js$/.test(executable)) return [process.execPath, [executable, ...args]];
|
|
1042
|
-
const head = fs4.readFileSync(executable).subarray(0, 100).toString("latin1");
|
|
1043
|
-
return head.startsWith("#!") && head.split("\n", 1)[0].includes("node") ? [process.execPath, [executable, ...args]] : [executable, args];
|
|
1044
|
-
}
|
|
1045
|
-
function typecheck(rootDir, tsconfig, logger) {
|
|
1046
|
-
if (!fs4.existsSync(tsconfig)) {
|
|
1047
|
-
logger.warn(`No ${path3.relative(rootDir, tsconfig) || tsconfig} \u2014 skipping the type check.`);
|
|
1048
|
-
return false;
|
|
1049
|
-
}
|
|
1050
|
-
const compiler = resolveTypeScriptCompiler(rootDir);
|
|
1051
|
-
logger.info(
|
|
1052
|
-
`Type check with TypeScript ${compiler.version} (${compiler.origin === "project" ? "the project's compiler" : "the generator's own compiler \u2014 the project has no typescript"}).`
|
|
1053
|
-
);
|
|
1054
|
-
const [command, args] = buildCompilerCommand(compiler.executable, ["--noEmit", "-p", tsconfig]);
|
|
1055
|
-
try {
|
|
1056
|
-
execFileSync(command, args, {
|
|
1057
|
-
cwd: rootDir,
|
|
1058
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1059
|
-
encoding: "utf-8"
|
|
1060
|
-
});
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
const output = error.stdout ?? "";
|
|
1063
|
-
throw new SdkGenerationError(`Type check failed:
|
|
1064
|
-
${output.split("\n").slice(0, 40).join("\n")}`);
|
|
1065
|
-
}
|
|
1066
|
-
return true;
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
// src/codegen/models.ts
|
|
1070
|
-
import * as path4 from "path";
|
|
1071
|
-
|
|
1072
|
-
// src/contract/extensions.ts
|
|
1073
|
-
function hasSideEffects(method, operation) {
|
|
1074
|
-
const explicit = operation?.["x-ddd-side-effects"];
|
|
1075
|
-
if (typeof explicit === "boolean") {
|
|
1076
|
-
return explicit;
|
|
1077
|
-
}
|
|
1078
|
-
return !["get", "head", "options", "trace"].includes(method.toLowerCase());
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
// src/codegen/operations.ts
|
|
1082
|
-
function testPattern(pattern, value) {
|
|
1083
|
-
pattern.lastIndex = 0;
|
|
1084
|
-
const result = pattern.test(value);
|
|
1085
|
-
pattern.lastIndex = 0;
|
|
1086
|
-
return result;
|
|
1087
|
-
}
|
|
1088
|
-
function matchesOperation(override, method, path11) {
|
|
1089
|
-
if (override.method && override.method.toLowerCase() !== method) return false;
|
|
1090
|
-
return typeof override.path === "string" ? override.path === path11 : testPattern(override.path, path11);
|
|
1091
|
-
}
|
|
1092
|
-
function canonical(value) {
|
|
1093
|
-
return JSON.stringify(
|
|
1094
|
-
value,
|
|
1095
|
-
(_key, inner) => inner && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner
|
|
1096
|
-
) ?? "undefined";
|
|
1384
|
+
if (ts.isParenthesizedExpression(body) && ts.isObjectLiteralExpression(body.expression)) return body.expression;
|
|
1385
|
+
if (ts.isObjectLiteralExpression(body)) return body;
|
|
1386
|
+
if (ts.isBlock(body)) {
|
|
1387
|
+
for (const statement of body.statements) {
|
|
1388
|
+
if (ts.isReturnStatement(statement) && statement.expression) {
|
|
1389
|
+
let expression = statement.expression;
|
|
1390
|
+
if (ts.isParenthesizedExpression(expression)) expression = expression.expression;
|
|
1391
|
+
if (ts.isObjectLiteralExpression(expression)) return expression;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
return null;
|
|
1097
1396
|
}
|
|
1098
|
-
function
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
if (postEntity && patchEntity) {
|
|
1103
|
-
return postEntity.action === "upsert" && patchEntity.action === "upsert" && postEntity.schema === patchEntity.schema;
|
|
1397
|
+
function unwrapEncoding(ts, expression) {
|
|
1398
|
+
let current = expression;
|
|
1399
|
+
while (ts.isCallExpression(current) && ts.isIdentifier(current.expression) && (current.expression.text === "encodeURIComponent" || current.expression.text === "String") && current.arguments.length === 1) {
|
|
1400
|
+
current = current.arguments[0];
|
|
1104
1401
|
}
|
|
1105
|
-
|
|
1106
|
-
if (post.summary === void 0 || post.summary !== patch.summary) return false;
|
|
1107
|
-
return ["parameters", "requestBody", "responses"].every((key) => canonical(post[key]) === canonical(patch[key]));
|
|
1402
|
+
return current;
|
|
1108
1403
|
}
|
|
1109
|
-
function
|
|
1110
|
-
return
|
|
1404
|
+
function templateAccessors(ts, init, sourceFile) {
|
|
1405
|
+
return init.templateSpans.map((span) => unwrapEncoding(ts, span.expression).getText(sourceFile).replace(/^queryArg\b/, "arg"));
|
|
1111
1406
|
}
|
|
1112
|
-
function
|
|
1113
|
-
const
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
if (
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1407
|
+
function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
1408
|
+
const definition = call.arguments[0];
|
|
1409
|
+
if (!definition || !ts.isObjectLiteralExpression(definition)) return null;
|
|
1410
|
+
const responseTypeNode = call.typeArguments?.[0];
|
|
1411
|
+
const responseType = responseTypeNode && ts.isTypeReferenceNode(responseTypeNode) && ts.isIdentifier(responseTypeNode.typeName) ? responseTypeNode.typeName.text : void 0;
|
|
1412
|
+
for (const property of definition.properties) {
|
|
1413
|
+
if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) || property.name.text !== "query") continue;
|
|
1414
|
+
if (!ts.isArrowFunction(property.initializer)) continue;
|
|
1415
|
+
const returned = objectReturnedBy(ts, property.initializer);
|
|
1416
|
+
if (!returned) continue;
|
|
1417
|
+
let url;
|
|
1418
|
+
let method;
|
|
1419
|
+
let accessors = [];
|
|
1420
|
+
let bodyArg;
|
|
1421
|
+
for (const member of returned.properties) {
|
|
1422
|
+
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
1423
|
+
const init = member.initializer;
|
|
1424
|
+
if (member.name.text === "url") {
|
|
1425
|
+
if (ts.isNoSubstitutionTemplateLiteral(init) || ts.isStringLiteral(init)) url = init.text;
|
|
1426
|
+
else if (ts.isTemplateExpression(init)) {
|
|
1427
|
+
url = init.getText(sourceFile).slice(1, -1);
|
|
1428
|
+
accessors = templateAccessors(ts, init, sourceFile);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
1432
|
+
if (member.name.text === "body" && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {
|
|
1433
|
+
const text = init.getText(sourceFile);
|
|
1434
|
+
if (/^queryArg(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\b/, "arg");
|
|
1435
|
+
}
|
|
1125
1436
|
}
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
endpointType,
|
|
1137
|
-
...entity ? { entity } : {}
|
|
1437
|
+
if (url === void 0) {
|
|
1438
|
+
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
1439
|
+
return null;
|
|
1440
|
+
}
|
|
1441
|
+
const path12 = location?.path ?? toOpenApiPath(url);
|
|
1442
|
+
const placeholders = [...path12.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1443
|
+
const pathArgs = {};
|
|
1444
|
+
placeholders.forEach((name, index) => {
|
|
1445
|
+
const accessor = accessors[index];
|
|
1446
|
+
if (accessor !== void 0) pathArgs[name] = accessor;
|
|
1138
1447
|
});
|
|
1448
|
+
return {
|
|
1449
|
+
key,
|
|
1450
|
+
buildType,
|
|
1451
|
+
url,
|
|
1452
|
+
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
1453
|
+
path: path12,
|
|
1454
|
+
pathArgs,
|
|
1455
|
+
...bodyArg ? { bodyArg } : {},
|
|
1456
|
+
...responseType ? { responseType } : {}
|
|
1457
|
+
};
|
|
1139
1458
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1459
|
+
return null;
|
|
1460
|
+
}
|
|
1461
|
+
function parseApiEndpoints(source, logger, locations = /* @__PURE__ */ new Map()) {
|
|
1462
|
+
const ts = loadTypeScript();
|
|
1463
|
+
const sourceFile = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true);
|
|
1464
|
+
const results = [];
|
|
1465
|
+
const visit = (node) => {
|
|
1466
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && ts.isCallExpression(node.initializer)) {
|
|
1467
|
+
const callee = node.initializer.expression;
|
|
1468
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && callee.expression.text === "build") {
|
|
1469
|
+
const buildType = callee.name.text;
|
|
1470
|
+
if (buildType === "query" || buildType === "mutation") {
|
|
1471
|
+
const key = node.name.text;
|
|
1472
|
+
const info = readEndpoint(ts, key, buildType, node.initializer, sourceFile, locations.get(key), logger);
|
|
1473
|
+
if (info) results.push(info);
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1147
1476
|
}
|
|
1148
1477
|
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
const result = [];
|
|
1154
|
-
for (const info of index.byKey.values()) {
|
|
1155
|
-
const rtkDefault = info.method === "get" ? "query" : "mutation";
|
|
1156
|
-
if (info.endpointType !== rtkDefault) result.push({ method: info.method, path: info.path, type: info.endpointType });
|
|
1157
|
-
}
|
|
1158
|
-
return result;
|
|
1478
|
+
ts.forEachChild(node, visit);
|
|
1479
|
+
};
|
|
1480
|
+
ts.forEachChild(sourceFile, visit);
|
|
1481
|
+
return results;
|
|
1159
1482
|
}
|
|
1160
1483
|
|
|
1484
|
+
// src/codegen/models.ts
|
|
1485
|
+
import * as path6 from "path";
|
|
1486
|
+
|
|
1161
1487
|
// src/codegen/response-handlers.ts
|
|
1162
1488
|
var DDD_WEB_API_IMPORT = "@mgamadeus/ddd-web/api";
|
|
1163
1489
|
var TEXT_CONTENT_TYPES = ["text/html", "text/plain", "text/xml"];
|
|
@@ -1197,10 +1523,10 @@ function detectResponseKind(responses) {
|
|
|
1197
1523
|
}
|
|
1198
1524
|
function detectResponseHandlerEndpoints(doc, endpoints, overrides = []) {
|
|
1199
1525
|
const kinds = /* @__PURE__ */ new Map();
|
|
1200
|
-
for (const { method, path:
|
|
1201
|
-
const override = overrides.find((candidate) => matchesOperation(candidate, method,
|
|
1526
|
+
for (const { method, path: path12, operation } of listOperations(doc)) {
|
|
1527
|
+
const override = overrides.find((candidate) => matchesOperation(candidate, method, path12));
|
|
1202
1528
|
const kind = override ? override.handler : detectResponseKind(operation.responses);
|
|
1203
|
-
if (kind !== "json") kinds.set(operationKey(method,
|
|
1529
|
+
if (kind !== "json") kinds.set(operationKey(method, path12), kind);
|
|
1204
1530
|
}
|
|
1205
1531
|
const keys = /* @__PURE__ */ new Map();
|
|
1206
1532
|
if (kinds.size === 0) return keys;
|
|
@@ -1425,22 +1751,22 @@ function registryMatch(name, registry) {
|
|
|
1425
1751
|
return null;
|
|
1426
1752
|
}
|
|
1427
1753
|
function importSpecifier(fromFile, toFile, esm) {
|
|
1428
|
-
let
|
|
1429
|
-
if (!
|
|
1430
|
-
return esm ? `${
|
|
1754
|
+
let relative6 = path6.relative(path6.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
|
|
1755
|
+
if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
|
|
1756
|
+
return esm ? `${relative6}.js` : relative6;
|
|
1431
1757
|
}
|
|
1432
1758
|
var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
|
|
1433
1759
|
function extractModels(input) {
|
|
1434
1760
|
const { modelsDir, registry, files, logger } = input;
|
|
1435
1761
|
const esm = input.esm === true;
|
|
1436
1762
|
const responseKinds = input.responseKinds ?? /* @__PURE__ */ new Map();
|
|
1437
|
-
const indexPath =
|
|
1763
|
+
const indexPath = path6.join(modelsDir, "index.ts");
|
|
1438
1764
|
const nameOwners = /* @__PURE__ */ new Map();
|
|
1439
1765
|
for (const filePath of files.paths()) {
|
|
1440
|
-
const
|
|
1441
|
-
if (
|
|
1766
|
+
const relative6 = path6.relative(modelsDir, filePath);
|
|
1767
|
+
if (relative6.startsWith("..") || path6.isAbsolute(relative6) || path6.resolve(filePath) === path6.resolve(indexPath)) continue;
|
|
1442
1768
|
const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
|
|
1443
|
-
if (name && !nameOwners.has(name)) nameOwners.set(name,
|
|
1769
|
+
if (name && !nameOwners.has(name)) nameOwners.set(name, path6.resolve(filePath).toLowerCase());
|
|
1444
1770
|
}
|
|
1445
1771
|
const documentModels = input.documentModels ?? /* @__PURE__ */ new Map();
|
|
1446
1772
|
const constsByFile = input.constsByFile ?? /* @__PURE__ */ new Map();
|
|
@@ -1448,16 +1774,16 @@ function extractModels(input) {
|
|
|
1448
1774
|
const documentModel = findDocumentModel(oldName, documentModels);
|
|
1449
1775
|
if (documentModel) {
|
|
1450
1776
|
const { segments, leafName } = placeDocumentModel(documentModel.model);
|
|
1451
|
-
const planned =
|
|
1777
|
+
const planned = path6.join(modelsDir, ...segments, `${leafName}${documentModel.suffix}.ts`);
|
|
1452
1778
|
return { filePath: files.findPath(planned) ?? planned, leafName: `${leafName}${documentModel.suffix}`, segments };
|
|
1453
1779
|
}
|
|
1454
1780
|
const match = registryMatch(oldName, registry);
|
|
1455
1781
|
if (match) {
|
|
1456
|
-
const planned =
|
|
1782
|
+
const planned = path6.join(modelsDir, ...match.segments, `${match.leafName}.ts`);
|
|
1457
1783
|
return { filePath: files.findPath(planned) ?? planned, leafName: match.leafName, segments: match.segments };
|
|
1458
1784
|
}
|
|
1459
1785
|
const folder = /^(Get|Post|Put|Patch|Delete)/.test(oldName) ? "_endpoints" : "_others";
|
|
1460
|
-
return { filePath:
|
|
1786
|
+
return { filePath: path6.join(modelsDir, folder, `${oldName}.ts`), leafName: oldName, segments: [] };
|
|
1461
1787
|
};
|
|
1462
1788
|
const originalNames = exportedTypeDeclarations(input.apiSource).map((declaration) => declaration.name);
|
|
1463
1789
|
const renameMap = /* @__PURE__ */ new Map();
|
|
@@ -1468,7 +1794,7 @@ function extractModels(input) {
|
|
|
1468
1794
|
const uniqueNameByPath = input.uniqueNameByPath ?? /* @__PURE__ */ new Map();
|
|
1469
1795
|
for (const oldName of originalNames) {
|
|
1470
1796
|
const { filePath, leafName, segments } = placement(oldName);
|
|
1471
|
-
const pathKey =
|
|
1797
|
+
const pathKey = path6.resolve(filePath).toLowerCase();
|
|
1472
1798
|
const isDocumentModel = findDocumentModel(oldName, documentModels) !== null;
|
|
1473
1799
|
let name = nameByPath.get(pathKey) ?? uniqueNameByPath.get(pathKey) ?? (isDocumentModel ? void 0 : files.get(filePath)?.match(EXPORTED_NAME)?.[1]);
|
|
1474
1800
|
if (!name) {
|
|
@@ -1500,7 +1826,7 @@ function extractModels(input) {
|
|
|
1500
1826
|
logger.warn(`Re-extracted type "${name}" not in rename map \u2014 skipping.`);
|
|
1501
1827
|
continue;
|
|
1502
1828
|
}
|
|
1503
|
-
if (input.modelsOnly &&
|
|
1829
|
+
if (input.modelsOnly && path6.relative(modelsDir, filePath).split(path6.sep)[0] === "_endpoints") continue;
|
|
1504
1830
|
entries.push({ name, body: text, filePath });
|
|
1505
1831
|
}
|
|
1506
1832
|
const pathByName = new Map(entries.map((entry) => [entry.name, entry.filePath]));
|
|
@@ -1509,7 +1835,7 @@ function extractModels(input) {
|
|
|
1509
1835
|
const usedInApi = [...new Set(entries.map((entry) => entry.name))].filter(
|
|
1510
1836
|
(name) => new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(name)}(?![A-Za-z0-9_$])`).test(strippedSource)
|
|
1511
1837
|
);
|
|
1512
|
-
const isPresentation = (filePath) => filePath.split(
|
|
1838
|
+
const isPresentation = (filePath) => filePath.split(path6.sep).includes("Presentation");
|
|
1513
1839
|
const barrelEntries = [];
|
|
1514
1840
|
const exportNameOf = (uniqueName) => exportNameByUniqueName.get(uniqueName) ?? uniqueName;
|
|
1515
1841
|
const writeIndex = input.writeIndex !== false;
|
|
@@ -1532,7 +1858,7 @@ function extractModels(input) {
|
|
|
1532
1858
|
if (input.enumConsts && documentModel) {
|
|
1533
1859
|
const applied = applyEnumConsts(body, name, documentModel, input.modelOptions);
|
|
1534
1860
|
typedBody = applied.body;
|
|
1535
|
-
const fileKey =
|
|
1861
|
+
const fileKey = path6.resolve(filePath).toLowerCase();
|
|
1536
1862
|
const fileConsts2 = constsByFile.get(fileKey) ?? /* @__PURE__ */ new Map();
|
|
1537
1863
|
for (const [constName, text] of applied.consts) if (!fileConsts2.has(constName)) fileConsts2.set(constName, text);
|
|
1538
1864
|
if (fileConsts2.size > 0) constsByFile.set(fileKey, fileConsts2);
|
|
@@ -1560,14 +1886,14 @@ function extractModels(input) {
|
|
|
1560
1886
|
|
|
1561
1887
|
export default ${name};
|
|
1562
1888
|
`;
|
|
1563
|
-
const fileConsts = constsByFile.get(
|
|
1889
|
+
const fileConsts = constsByFile.get(path6.resolve(filePath).toLowerCase());
|
|
1564
1890
|
files.set(filePath, fileConsts ? withEnumConsts(content, name, [...fileConsts.values()]) : content);
|
|
1565
|
-
if (isPresentation(
|
|
1891
|
+
if (isPresentation(path6.relative(modelsDir, filePath))) continue;
|
|
1566
1892
|
if (name !== uniqueName) continue;
|
|
1567
1893
|
barrelEntries.push(`export * from '${importSpecifier(indexPath, filePath, esm)}';`);
|
|
1568
1894
|
}
|
|
1569
1895
|
if (writeIndex) writeBarrel(files, indexPath, barrelEntries);
|
|
1570
|
-
const others = entries.filter((entry) =>
|
|
1896
|
+
const others = entries.filter((entry) => path6.relative(modelsDir, entry.filePath).split(path6.sep)[0] === "_others");
|
|
1571
1897
|
if (others.length > 0) {
|
|
1572
1898
|
logger.warn(`${others.length} type(s) without a namespace match placed in _others/: ${others.map((e) => e.name).join(", ")}`);
|
|
1573
1899
|
}
|
|
@@ -1595,7 +1921,7 @@ function writeBarrel(files, indexPath, newEntries) {
|
|
|
1595
1921
|
for (const entry of [...existing, ...newEntries]) {
|
|
1596
1922
|
const specifier = entry.match(/from ['"](.+)['"];?\s*$/)?.[1];
|
|
1597
1923
|
if (!specifier) continue;
|
|
1598
|
-
const target =
|
|
1924
|
+
const target = path6.resolve(path6.dirname(indexPath), specifier.replace(/\.js$/, "")) + ".ts";
|
|
1599
1925
|
const key = target.toLowerCase();
|
|
1600
1926
|
if (seen.has(key) || !files.findPath(target)) continue;
|
|
1601
1927
|
seen.add(key);
|
|
@@ -1651,9 +1977,9 @@ function readMultipartOperation(doc, requestBody) {
|
|
|
1651
1977
|
}
|
|
1652
1978
|
function detectMultipartEndpoints(doc, endpoints) {
|
|
1653
1979
|
const byOperation = /* @__PURE__ */ new Map();
|
|
1654
|
-
for (const { method, path:
|
|
1980
|
+
for (const { method, path: path12, operation } of listOperations(doc)) {
|
|
1655
1981
|
const multipart = readMultipartOperation(doc, operation.requestBody);
|
|
1656
|
-
if (multipart) byOperation.set(operationKey(method,
|
|
1982
|
+
if (multipart) byOperation.set(operationKey(method, path12), multipart);
|
|
1657
1983
|
}
|
|
1658
1984
|
const keys = /* @__PURE__ */ new Map();
|
|
1659
1985
|
if (byOperation.size === 0) return keys;
|
|
@@ -1747,92 +2073,6 @@ function injectMultipartBodies(source, endpoints, logger) {
|
|
|
1747
2073
|
}
|
|
1748
2074
|
var MULTIPART_IMPORT = `import { buildDddMultipartBody } from '${DDD_WEB_API_IMPORT}';`;
|
|
1749
2075
|
|
|
1750
|
-
// src/codegen/output.ts
|
|
1751
|
-
import * as fs5 from "fs";
|
|
1752
|
-
import * as path5 from "path";
|
|
1753
|
-
function defaultMove(from, to) {
|
|
1754
|
-
fs5.mkdirSync(path5.dirname(to), { recursive: true });
|
|
1755
|
-
try {
|
|
1756
|
-
fs5.renameSync(from, to);
|
|
1757
|
-
} catch (error) {
|
|
1758
|
-
if (error.code !== "EXDEV") throw error;
|
|
1759
|
-
fs5.cpSync(from, to, { recursive: true });
|
|
1760
|
-
fs5.rmSync(from, { recursive: true, force: true });
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
function commitOutput(files, modelsDir, stagingParent, options = {}) {
|
|
1764
|
-
const move = options.move ?? defaultMove;
|
|
1765
|
-
fs5.mkdirSync(stagingParent, { recursive: true });
|
|
1766
|
-
const staging = fs5.mkdtempSync(path5.join(stagingParent, ".ddd-web-sdk-"));
|
|
1767
|
-
const stagedModels = path5.join(staging, "models");
|
|
1768
|
-
const backupModels = path5.join(staging, "models.previous");
|
|
1769
|
-
const singles = [];
|
|
1770
|
-
try {
|
|
1771
|
-
fs5.mkdirSync(stagedModels, { recursive: true });
|
|
1772
|
-
for (const filePath of files.paths()) {
|
|
1773
|
-
const content = files.get(filePath);
|
|
1774
|
-
const relative5 = path5.relative(modelsDir, filePath);
|
|
1775
|
-
if (!relative5.startsWith("..") && !path5.isAbsolute(relative5)) {
|
|
1776
|
-
const staged = path5.join(stagedModels, relative5);
|
|
1777
|
-
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1778
|
-
fs5.writeFileSync(staged, content);
|
|
1779
|
-
} else {
|
|
1780
|
-
const staged = path5.join(staging, "files", String(singles.length));
|
|
1781
|
-
fs5.mkdirSync(path5.dirname(staged), { recursive: true });
|
|
1782
|
-
fs5.writeFileSync(staged, content);
|
|
1783
|
-
singles.push({ target: filePath, staged, backup: path5.join(staging, "files.previous", String(singles.length)) });
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
} catch (error) {
|
|
1787
|
-
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1788
|
-
throw error;
|
|
1789
|
-
}
|
|
1790
|
-
const undo = [];
|
|
1791
|
-
const rollback = () => {
|
|
1792
|
-
const failures = [];
|
|
1793
|
-
for (const step of undo.reverse()) {
|
|
1794
|
-
try {
|
|
1795
|
-
step();
|
|
1796
|
-
} catch (error) {
|
|
1797
|
-
failures.push(error);
|
|
1798
|
-
}
|
|
1799
|
-
}
|
|
1800
|
-
undo.length = 0;
|
|
1801
|
-
if (failures.length > 0) {
|
|
1802
|
-
throw new SdkGenerationError(
|
|
1803
|
-
`Could not restore the previous output; the previous output is kept in ${staging} (models.previous/, files.previous/): ${failures.map((failure) => failure.message).join("; ")}`
|
|
1804
|
-
);
|
|
1805
|
-
}
|
|
1806
|
-
fs5.rmSync(staging, { recursive: true, force: true });
|
|
1807
|
-
};
|
|
1808
|
-
const swap = (target, staged, backup, removeTarget) => {
|
|
1809
|
-
const state = { backedUp: false, movedIn: false };
|
|
1810
|
-
undo.push(() => {
|
|
1811
|
-
if (state.movedIn) removeTarget();
|
|
1812
|
-
if (state.backedUp) move(backup, target);
|
|
1813
|
-
});
|
|
1814
|
-
if (fs5.existsSync(target)) {
|
|
1815
|
-
move(target, backup);
|
|
1816
|
-
state.backedUp = true;
|
|
1817
|
-
}
|
|
1818
|
-
move(staged, target);
|
|
1819
|
-
state.movedIn = true;
|
|
1820
|
-
};
|
|
1821
|
-
try {
|
|
1822
|
-
swap(modelsDir, stagedModels, backupModels, () => fs5.rmSync(modelsDir, { recursive: true, force: true }));
|
|
1823
|
-
for (const single of singles) {
|
|
1824
|
-
swap(single.target, single.staged, single.backup, () => fs5.rmSync(single.target, { force: true }));
|
|
1825
|
-
}
|
|
1826
|
-
} catch (error) {
|
|
1827
|
-
rollback();
|
|
1828
|
-
throw error;
|
|
1829
|
-
}
|
|
1830
|
-
return {
|
|
1831
|
-
rollback,
|
|
1832
|
-
finalize: () => fs5.rmSync(staging, { recursive: true, force: true })
|
|
1833
|
-
};
|
|
1834
|
-
}
|
|
1835
|
-
|
|
1836
2076
|
// src/codegen/registry.ts
|
|
1837
2077
|
function normalizeSegment(segment) {
|
|
1838
2078
|
return segment.replace(/([A-Z])([A-Z]+)/g, (_, first, rest) => first + rest.toLowerCase());
|
|
@@ -1868,63 +2108,27 @@ function buildRegistry(docs, logger) {
|
|
|
1868
2108
|
return [...registry.entries()].sort((a, b) => b[0].length - a[0].length);
|
|
1869
2109
|
}
|
|
1870
2110
|
|
|
1871
|
-
// src/codegen/repair.ts
|
|
1872
|
-
function resolveParameter2(doc, parameter) {
|
|
1873
|
-
let current = parameter;
|
|
1874
|
-
for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
|
|
1875
|
-
const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
|
|
1876
|
-
if (!match) return null;
|
|
1877
|
-
const name = match[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1878
|
-
current = doc.components?.parameters?.[name];
|
|
1879
|
-
}
|
|
1880
|
-
return current && current.$ref === void 0 ? current : null;
|
|
1881
|
-
}
|
|
1882
|
-
function repairMissingPathParameters(doc, logger) {
|
|
1883
|
-
const repairs = [];
|
|
1884
|
-
for (const { method, path: path11, operation } of listOperations(doc)) {
|
|
1885
|
-
const placeholders = [...path11.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
|
|
1886
|
-
if (placeholders.length === 0) continue;
|
|
1887
|
-
const pathLevel = doc.paths?.[path11]?.parameters ?? [];
|
|
1888
|
-
const declared = new Set(
|
|
1889
|
-
[...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter2(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
|
|
1890
|
-
);
|
|
1891
|
-
const missing = placeholders.filter((name) => !declared.has(name));
|
|
1892
|
-
if (missing.length > 0) repairs.push({ path: path11, method, names: missing });
|
|
1893
|
-
}
|
|
1894
|
-
if (repairs.length === 0) return doc;
|
|
1895
|
-
const copy = structuredClone(doc);
|
|
1896
|
-
for (const { path: path11, method, names } of repairs) {
|
|
1897
|
-
const operation = copy.paths[path11][method];
|
|
1898
|
-
operation.parameters = [
|
|
1899
|
-
...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
|
|
1900
|
-
...operation.parameters ?? []
|
|
1901
|
-
];
|
|
1902
|
-
logger.warn(`${method.toUpperCase()} ${path11}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
|
|
1903
|
-
}
|
|
1904
|
-
return copy;
|
|
1905
|
-
}
|
|
1906
|
-
|
|
1907
2111
|
// src/codegen/rtk.ts
|
|
1908
|
-
import * as
|
|
1909
|
-
import * as
|
|
2112
|
+
import * as fs7 from "fs";
|
|
2113
|
+
import * as path8 from "path";
|
|
1910
2114
|
import prettier2 from "prettier";
|
|
1911
2115
|
|
|
1912
2116
|
// src/codegen/module-resolution.ts
|
|
1913
|
-
import Module, { createRequire as
|
|
1914
|
-
import * as
|
|
2117
|
+
import Module, { createRequire as createRequire4 } from "module";
|
|
2118
|
+
import * as path7 from "path";
|
|
1915
2119
|
var installed = false;
|
|
1916
2120
|
function installParserModuleResolution() {
|
|
1917
2121
|
if (installed) return;
|
|
1918
2122
|
installed = true;
|
|
1919
|
-
const require2 =
|
|
2123
|
+
const require2 = createRequire4(import.meta.url);
|
|
1920
2124
|
let parserRequire;
|
|
1921
2125
|
try {
|
|
1922
|
-
const codegenRequire =
|
|
1923
|
-
parserRequire =
|
|
2126
|
+
const codegenRequire = createRequire4(require2.resolve("@rtk-query/codegen-openapi"));
|
|
2127
|
+
parserRequire = createRequire4(codegenRequire.resolve("@apidevtools/swagger-parser"));
|
|
1924
2128
|
} catch {
|
|
1925
2129
|
return;
|
|
1926
2130
|
}
|
|
1927
|
-
const ajvDraft04Folder = `${
|
|
2131
|
+
const ajvDraft04Folder = `${path7.sep}ajv-draft-04${path7.sep}`;
|
|
1928
2132
|
const moduleWithResolver = Module;
|
|
1929
2133
|
const defaultResolveFilename = moduleWithResolver._resolveFilename;
|
|
1930
2134
|
moduleWithResolver._resolveFilename = function resolveAjvOfTheParser(request, parent, ...rest) {
|
|
@@ -1968,12 +2172,12 @@ function mergeEndpointOverrides(userOverrides, typeOverrides) {
|
|
|
1968
2172
|
}
|
|
1969
2173
|
function relativeImport(fromDir, target) {
|
|
1970
2174
|
if (!isPathLike(target)) return target;
|
|
1971
|
-
let
|
|
1972
|
-
if (!
|
|
1973
|
-
return
|
|
2175
|
+
let relative6 = path8.relative(fromDir, target).replace(/\\/g, "/");
|
|
2176
|
+
if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
|
|
2177
|
+
return relative6;
|
|
1974
2178
|
}
|
|
1975
2179
|
async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endpointNameOf = (rtkName) => rtkName) {
|
|
1976
|
-
|
|
2180
|
+
fs7.writeFileSync(specFile, JSON.stringify(doc));
|
|
1977
2181
|
const passthrough = {};
|
|
1978
2182
|
for (const [key, value] of Object.entries(api.config)) if (!OWN_KEYS.has(key)) passthrough[key] = value;
|
|
1979
2183
|
const userOverrides = (passthrough.endpointOverrides ?? []).map(
|
|
@@ -2009,19 +2213,19 @@ async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endp
|
|
|
2009
2213
|
return { code, locations };
|
|
2010
2214
|
}
|
|
2011
2215
|
async function findPrettierConfigFile(rootDir) {
|
|
2012
|
-
return await prettier2.resolveConfigFile(
|
|
2216
|
+
return await prettier2.resolveConfigFile(path8.join(rootDir, "openapi-config.ts")) ?? void 0;
|
|
2013
2217
|
}
|
|
2014
2218
|
|
|
2015
2219
|
// src/codegen/workspace.ts
|
|
2016
|
-
import * as
|
|
2017
|
-
import * as
|
|
2220
|
+
import * as fs8 from "fs";
|
|
2221
|
+
import * as path9 from "path";
|
|
2018
2222
|
import * as readline from "readline";
|
|
2019
2223
|
var DEFAULT_ENV_FILES = [".env", ".env.local"];
|
|
2020
2224
|
var DEFAULT_URL_KEYS = ["NEXT_PUBLIC_API_URL", "EXPO_PUBLIC_API_URL", "VITE_API_URL", "VITE_API_ENDPOINT", "API_URL"];
|
|
2021
2225
|
function parseEnvFile(filePath) {
|
|
2022
|
-
if (!
|
|
2226
|
+
if (!fs8.existsSync(filePath)) return {};
|
|
2023
2227
|
const vars = {};
|
|
2024
|
-
for (const line of
|
|
2228
|
+
for (const line of fs8.readFileSync(filePath, "utf-8").split("\n")) {
|
|
2025
2229
|
const trimmed = line.trim();
|
|
2026
2230
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2027
2231
|
const eq = trimmed.indexOf("=");
|
|
@@ -2039,7 +2243,7 @@ function firstHostLabel(url) {
|
|
|
2039
2243
|
}
|
|
2040
2244
|
function sniffWorkspace(rootDir, options) {
|
|
2041
2245
|
for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {
|
|
2042
|
-
const vars = parseEnvFile(
|
|
2246
|
+
const vars = parseEnvFile(path9.join(rootDir, file));
|
|
2043
2247
|
for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
|
|
2044
2248
|
const value = vars[key];
|
|
2045
2249
|
const label2 = value ? firstHostLabel(value) : null;
|
|
@@ -2049,11 +2253,11 @@ function sniffWorkspace(rootDir, options) {
|
|
|
2049
2253
|
return null;
|
|
2050
2254
|
}
|
|
2051
2255
|
function ask(question) {
|
|
2052
|
-
return new Promise((
|
|
2256
|
+
return new Promise((resolve8) => {
|
|
2053
2257
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
2054
|
-
rl.on("close", () =>
|
|
2258
|
+
rl.on("close", () => resolve8(""));
|
|
2055
2259
|
rl.question(question, (answer) => {
|
|
2056
|
-
|
|
2260
|
+
resolve8(answer.trim());
|
|
2057
2261
|
rl.close();
|
|
2058
2262
|
});
|
|
2059
2263
|
});
|
|
@@ -2079,9 +2283,9 @@ async function resolveWorkspace(rootDir, options, explicit, logger) {
|
|
|
2079
2283
|
// src/codegen/generate.ts
|
|
2080
2284
|
async function load(options, cwd) {
|
|
2081
2285
|
if (options.config && typeof options.config === "object") {
|
|
2082
|
-
return { config: options.config, configPath:
|
|
2286
|
+
return { config: options.config, configPath: path10.join(cwd, "<inline config>"), rootDir: cwd };
|
|
2083
2287
|
}
|
|
2084
|
-
return loadConfig(
|
|
2288
|
+
return loadConfig(path10.resolve(cwd, options.config ?? "openapi-config.ts"));
|
|
2085
2289
|
}
|
|
2086
2290
|
function selectApis(all, options) {
|
|
2087
2291
|
let selected = all;
|
|
@@ -2093,14 +2297,14 @@ function selectApis(all, options) {
|
|
|
2093
2297
|
}
|
|
2094
2298
|
if (options.schema) {
|
|
2095
2299
|
if (selected.length !== 1) throw new SdkGenerationError("--schema needs exactly one api (use --api).");
|
|
2096
|
-
const schemaSource = isUrl(options.schema) ? options.schema :
|
|
2300
|
+
const schemaSource = isUrl(options.schema) ? options.schema : path10.resolve(options.cwd ?? process.cwd(), options.schema);
|
|
2097
2301
|
selected = [{ ...selected[0], schemaSource }];
|
|
2098
2302
|
}
|
|
2099
2303
|
return selected;
|
|
2100
2304
|
}
|
|
2101
2305
|
async function generateSdk(options = {}) {
|
|
2102
2306
|
const logger = options.logger ?? consoleLogger;
|
|
2103
|
-
const cwd =
|
|
2307
|
+
const cwd = path10.resolve(options.cwd ?? process.cwd());
|
|
2104
2308
|
let loaded = await load(options, cwd);
|
|
2105
2309
|
if (loaded.config.workspace) {
|
|
2106
2310
|
const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);
|
|
@@ -2108,6 +2312,11 @@ async function generateSdk(options = {}) {
|
|
|
2108
2312
|
}
|
|
2109
2313
|
const allApis = resolveApis(loaded);
|
|
2110
2314
|
const apis = selectApis(allApis, options);
|
|
2315
|
+
const mode = options.mode ?? loaded.config.generator?.mode ?? "default";
|
|
2316
|
+
if (mode === "future" || mode === "legacy") {
|
|
2317
|
+
return generateDelegatedSdk(mode, loaded, allApis, apis, options, logger);
|
|
2318
|
+
}
|
|
2319
|
+
if (mode !== "default") throw new SdkGenerationError("SDK generator mode must be default, future, or legacy.");
|
|
2111
2320
|
const modelsDir = resolveModelsDir(loaded, allApis);
|
|
2112
2321
|
const partial = apis.length < allApis.length;
|
|
2113
2322
|
logger.info(`${apis.length} api(s): ${apis.map((api) => api.exportName).join(", ")}${partial ? " (partial run)" : ""}`);
|
|
@@ -2149,7 +2358,7 @@ async function generateSdk(options = {}) {
|
|
|
2149
2358
|
const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);
|
|
2150
2359
|
const constsByFile = /* @__PURE__ */ new Map();
|
|
2151
2360
|
const uniqueNameByPath = /* @__PURE__ */ new Map();
|
|
2152
|
-
const specDir =
|
|
2361
|
+
const specDir = fs9.mkdtempSync(path10.join(os2.tmpdir(), "ddd-web-spec-"));
|
|
2153
2362
|
try {
|
|
2154
2363
|
for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {
|
|
2155
2364
|
const doc = repairMissingPathParameters(rawDoc, logger);
|
|
@@ -2177,7 +2386,7 @@ async function generateSdk(options = {}) {
|
|
|
2177
2386
|
};
|
|
2178
2387
|
const endpointNameOf = (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName;
|
|
2179
2388
|
const runPass = async (passApi, specName, modelsOnly) => {
|
|
2180
|
-
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index,
|
|
2389
|
+
const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path10.join(specDir, specName), prettierConfigFile, endpointNameOf);
|
|
2181
2390
|
const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
|
|
2182
2391
|
const endpoints2 = parseApiEndpoints(rtk.code, logger, rtk.locations);
|
|
2183
2392
|
const handlerEndpoints2 = detectResponseHandlerEndpoints(doc, endpoints2, api.responseHandlers);
|
|
@@ -2213,7 +2422,7 @@ ${withHandlers}` : withHandlers;
|
|
|
2213
2422
|
const requestsStem = `${api.stem}Requests`;
|
|
2214
2423
|
const split = splitRequestBuilders(finalApiSource, requestsStem, esm ? `./${requestsStem}.js` : `./${requestsStem}`);
|
|
2215
2424
|
files.set(api.outputFile, split.apiSource);
|
|
2216
|
-
files.set(
|
|
2425
|
+
files.set(path10.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
|
|
2217
2426
|
logger.info(` ${split.count} request builder(s) used by ${api.stem}.ts`);
|
|
2218
2427
|
} else {
|
|
2219
2428
|
files.set(api.outputFile, finalApiSource);
|
|
@@ -2233,11 +2442,11 @@ ${withHandlers}` : withHandlers;
|
|
|
2233
2442
|
invalidation: api.invalidation,
|
|
2234
2443
|
logger
|
|
2235
2444
|
});
|
|
2236
|
-
files.set(
|
|
2237
|
-
files.set(
|
|
2445
|
+
files.set(path10.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);
|
|
2446
|
+
files.set(path10.join(api.outputDir, `${api.stem}Tags.ts`), renderTagsFile(api.stem, enhanced.tagTypes));
|
|
2238
2447
|
}
|
|
2239
2448
|
} finally {
|
|
2240
|
-
|
|
2449
|
+
fs9.rmSync(specDir, { recursive: true, force: true });
|
|
2241
2450
|
}
|
|
2242
2451
|
if (!options.skipPrettier) {
|
|
2243
2452
|
logger.info("formatting with prettier");
|
|
@@ -2248,7 +2457,7 @@ ${withHandlers}` : withHandlers;
|
|
|
2248
2457
|
if (!options.skipTsc) {
|
|
2249
2458
|
logger.info("type check (tsc --noEmit)");
|
|
2250
2459
|
try {
|
|
2251
|
-
typechecked = typecheck(loaded.rootDir,
|
|
2460
|
+
typechecked = typecheck(loaded.rootDir, path10.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
|
|
2252
2461
|
} catch (error) {
|
|
2253
2462
|
committed.rollback();
|
|
2254
2463
|
logger.error("type check failed \u2014 previous output restored");
|
|
@@ -2263,9 +2472,9 @@ ${withHandlers}` : withHandlers;
|
|
|
2263
2472
|
// src/codegen/link-skills.ts
|
|
2264
2473
|
import { spawnSync } from "child_process";
|
|
2265
2474
|
import { createHash } from "crypto";
|
|
2266
|
-
import * as
|
|
2267
|
-
import * as
|
|
2268
|
-
import * as
|
|
2475
|
+
import * as fs10 from "fs";
|
|
2476
|
+
import * as os3 from "os";
|
|
2477
|
+
import * as path11 from "path";
|
|
2269
2478
|
var PRIMARY_SKILLS_DIRECTORY = ".claude/skills";
|
|
2270
2479
|
var MIRROR_SKILLS_DIRECTORIES = [".agents/skills", ".codex/skills"];
|
|
2271
2480
|
var SKILLS_MANIFEST_FILE_NAME = ".ddd-skills.json";
|
|
@@ -2289,14 +2498,14 @@ var prefixedConsoleLogger = {
|
|
|
2289
2498
|
};
|
|
2290
2499
|
var label = (text) => text.padEnd(13);
|
|
2291
2500
|
function findSkillsRepositoryRoot(startDirectory) {
|
|
2292
|
-
const start = realpathOr(
|
|
2293
|
-
const home = realpathOr(
|
|
2501
|
+
const start = realpathOr(path11.resolve(startDirectory));
|
|
2502
|
+
const home = realpathOr(os3.homedir());
|
|
2294
2503
|
for (const marker of [".git", ".claude"]) {
|
|
2295
2504
|
let directory = start;
|
|
2296
2505
|
for (; ; ) {
|
|
2297
2506
|
const isHomeClaude = marker === ".claude" && directory === home;
|
|
2298
|
-
if (!isHomeClaude && lstatOrNull(
|
|
2299
|
-
const parent =
|
|
2507
|
+
if (!isHomeClaude && lstatOrNull(path11.join(directory, marker))) return directory;
|
|
2508
|
+
const parent = path11.dirname(directory);
|
|
2300
2509
|
if (parent === directory) break;
|
|
2301
2510
|
directory = parent;
|
|
2302
2511
|
}
|
|
@@ -2305,9 +2514,9 @@ function findSkillsRepositoryRoot(startDirectory) {
|
|
|
2305
2514
|
}
|
|
2306
2515
|
function runSkillLinks(options = {}) {
|
|
2307
2516
|
const logger = options.logger ?? prefixedConsoleLogger;
|
|
2308
|
-
const cwd =
|
|
2517
|
+
const cwd = path11.resolve(options.cwd ?? process.cwd());
|
|
2309
2518
|
const envRoot = process.env[SKILLS_ROOT_ENV];
|
|
2310
|
-
const requestedRoot = options.root ?
|
|
2519
|
+
const requestedRoot = options.root ? path11.resolve(cwd, options.root) : envRoot ? path11.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
|
|
2311
2520
|
const linker = new SkillLinker(requestedRoot, options, logger);
|
|
2312
2521
|
return linker.run();
|
|
2313
2522
|
}
|
|
@@ -2412,7 +2621,7 @@ var SkillLinker = class {
|
|
|
2412
2621
|
operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
|
|
2413
2622
|
action = "linked";
|
|
2414
2623
|
} else if (entryType === "link") {
|
|
2415
|
-
const currentTarget =
|
|
2624
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2416
2625
|
if (currentTarget !== desiredTarget) {
|
|
2417
2626
|
if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
|
|
2418
2627
|
warnings.push(`${label("clash")}${display}: a symlink of the app to ${currentTarget} exists; the skill of ${skill.package} is not linked`);
|
|
@@ -2428,7 +2637,7 @@ var SkillLinker = class {
|
|
|
2428
2637
|
continue;
|
|
2429
2638
|
}
|
|
2430
2639
|
this.results.push({ skill: skillName, action, target: desiredTarget, package: skill.package });
|
|
2431
|
-
let skillFileHash = createHash("sha256").update(
|
|
2640
|
+
let skillFileHash = createHash("sha256").update(fs10.readFileSync(`${skill.directory}/SKILL.md`)).digest("hex");
|
|
2432
2641
|
const previous = previousEntries[skillName];
|
|
2433
2642
|
if (previous && previous.package === skill.package && skill.version !== null && previous.version === skill.version && typeof previous.sha256 === "string" && previous.sha256 !== skillFileHash) {
|
|
2434
2643
|
warnings.push(
|
|
@@ -2449,9 +2658,9 @@ var SkillLinker = class {
|
|
|
2449
2658
|
if (managed.has(skillName) || winners.has(skillName) || !previous || typeof previous !== "object") continue;
|
|
2450
2659
|
const linkPath = `${primary}/${skillName}`;
|
|
2451
2660
|
if (getEntryType(linkPath) !== "link") continue;
|
|
2452
|
-
const currentTarget =
|
|
2661
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2453
2662
|
if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) continue;
|
|
2454
|
-
if (
|
|
2663
|
+
if (fs10.existsSync(linkPath)) {
|
|
2455
2664
|
managed.set(skillName, {
|
|
2456
2665
|
package: previous.package ?? null,
|
|
2457
2666
|
version: previous.version ?? null,
|
|
@@ -2465,8 +2674,8 @@ var SkillLinker = class {
|
|
|
2465
2674
|
const removedNames = /* @__PURE__ */ new Set();
|
|
2466
2675
|
for (const entryName of listDirectoryNames(primary)) {
|
|
2467
2676
|
const linkPath = `${primary}/${entryName}`;
|
|
2468
|
-
if (managed.has(entryName) || getEntryType(linkPath) !== "link" ||
|
|
2469
|
-
const currentTarget =
|
|
2677
|
+
if (managed.has(entryName) || getEntryType(linkPath) !== "link" || fs10.existsSync(linkPath)) continue;
|
|
2678
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2470
2679
|
if (isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
|
|
2471
2680
|
removedNames.add(entryName);
|
|
2472
2681
|
operations.push({ kind: "remove", path: linkPath, display: `${PRIMARY_SKILLS_DIRECTORY}/${entryName} (broken link to ${currentTarget})` });
|
|
@@ -2479,7 +2688,7 @@ var SkillLinker = class {
|
|
|
2479
2688
|
const mirrorLogical = `${this.root}/${mirrorName}`;
|
|
2480
2689
|
if (getEntryType(mirrorLogical) === "missing" || !isDirectory(mirrorLogical)) continue;
|
|
2481
2690
|
const mirror = realpathOr(mirrorLogical);
|
|
2482
|
-
const mirrorParent = realpathOr(
|
|
2691
|
+
const mirrorParent = realpathOr(path11.dirname(mirrorLogical));
|
|
2483
2692
|
if (mirror === primary || mirrorParent === primary) continue;
|
|
2484
2693
|
mirrorGitignoreNames.set(mirror, []);
|
|
2485
2694
|
for (const skillName of managedNames) {
|
|
@@ -2491,7 +2700,7 @@ var SkillLinker = class {
|
|
|
2491
2700
|
if (entryType === "missing") {
|
|
2492
2701
|
operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
|
|
2493
2702
|
} else if (entryType === "link") {
|
|
2494
|
-
const currentTarget =
|
|
2703
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2495
2704
|
if (currentTarget !== desiredTarget) {
|
|
2496
2705
|
const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
|
|
2497
2706
|
const pointsToPrimary = resolvedTarget === primaryEntryPath || resolvedTarget === `${primary}/${skillName}`;
|
|
@@ -2512,11 +2721,11 @@ var SkillLinker = class {
|
|
|
2512
2721
|
for (const entryName of listDirectoryNames(mirror)) {
|
|
2513
2722
|
const linkPath = `${mirror}/${entryName}`;
|
|
2514
2723
|
if (managed.has(entryName) || getEntryType(linkPath) !== "link") continue;
|
|
2515
|
-
const currentTarget =
|
|
2724
|
+
const currentTarget = fs10.readlinkSync(linkPath);
|
|
2516
2725
|
const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
|
|
2517
2726
|
const pointsToPrimary = resolvedTarget === `${primaryLogical}/${entryName}` || resolvedTarget === `${primary}/${entryName}`;
|
|
2518
|
-
const isBrokenDddLink = !
|
|
2519
|
-
const isFormerMirror = pointsToPrimary && (removedNames.has(entryName) || entryName in previousEntries) && (!
|
|
2727
|
+
const isBrokenDddLink = !fs10.existsSync(linkPath) && isDddVendorPath(resolvedTarget);
|
|
2728
|
+
const isFormerMirror = pointsToPrimary && (removedNames.has(entryName) || entryName in previousEntries) && (!fs10.existsSync(`${primary}/${entryName}`) || removedNames.has(entryName));
|
|
2520
2729
|
if (isBrokenDddLink || isFormerMirror) {
|
|
2521
2730
|
operations.push({ kind: "remove", path: linkPath, display: `${mirrorName}/${entryName} (link to removed ${currentTarget})` });
|
|
2522
2731
|
}
|
|
@@ -2524,7 +2733,7 @@ var SkillLinker = class {
|
|
|
2524
2733
|
}
|
|
2525
2734
|
const manifestPath = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
|
|
2526
2735
|
const manifestContent = encodeManifest(managedNames, managed);
|
|
2527
|
-
if ((isFile(manifestPath) ?
|
|
2736
|
+
if ((isFile(manifestPath) ? fs10.readFileSync(manifestPath, "utf-8") : null) !== manifestContent) {
|
|
2528
2737
|
operations.push({ kind: "write", path: manifestPath, content: manifestContent, display: `${PRIMARY_SKILLS_DIRECTORY}/${SKILLS_MANIFEST_FILE_NAME}` });
|
|
2529
2738
|
}
|
|
2530
2739
|
const primaryGitignoreEntries = [`/${SKILLS_MANIFEST_FILE_NAME}`];
|
|
@@ -2539,7 +2748,7 @@ var SkillLinker = class {
|
|
|
2539
2748
|
}
|
|
2540
2749
|
for (const [directory, entries] of gitignoreTargets) {
|
|
2541
2750
|
const gitignorePath = `${directory}/.gitignore`;
|
|
2542
|
-
const currentContent = isFile(gitignorePath) ?
|
|
2751
|
+
const currentContent = isFile(gitignorePath) ? fs10.readFileSync(gitignorePath, "utf-8") : null;
|
|
2543
2752
|
const newContent = createGitignoreContent(currentContent, entries);
|
|
2544
2753
|
if (newContent === null) {
|
|
2545
2754
|
warnings.push(
|
|
@@ -2591,8 +2800,8 @@ var SkillLinker = class {
|
|
|
2591
2800
|
return { winners, warnings };
|
|
2592
2801
|
}
|
|
2593
2802
|
legacySourcePackage(sourceDir) {
|
|
2594
|
-
const skillsDirectory =
|
|
2595
|
-
const packageJson = readJson(
|
|
2803
|
+
const skillsDirectory = path11.resolve(path11.resolve(this.options.cwd ?? process.cwd()), sourceDir);
|
|
2804
|
+
const packageJson = readJson(path11.join(skillsDirectory, "..", "..", "package.json"));
|
|
2596
2805
|
return {
|
|
2597
2806
|
package: typeof packageJson?.name === "string" ? packageJson.name : "@mgamadeus/ddd-web",
|
|
2598
2807
|
version: typeof packageJson?.version === "string" ? packageJson.version : null,
|
|
@@ -2607,10 +2816,10 @@ var SkillLinker = class {
|
|
|
2607
2816
|
for (const folderName of listDirectoryNames(composerScope)) {
|
|
2608
2817
|
const packageDirectory = `${composerScope}/${folderName}`;
|
|
2609
2818
|
if (!isDirectory(packageDirectory)) continue;
|
|
2610
|
-
const
|
|
2819
|
+
const packageName2 = `mgamadeus/${folderName}`;
|
|
2611
2820
|
packages.push({
|
|
2612
|
-
package:
|
|
2613
|
-
version: installedVersions.get(
|
|
2821
|
+
package: packageName2,
|
|
2822
|
+
version: installedVersions.get(packageName2) ?? readJsonVersion(`${packageDirectory}/composer.json`),
|
|
2614
2823
|
skillsDirectory: `${packageDirectory}/.claude/skills`
|
|
2615
2824
|
});
|
|
2616
2825
|
}
|
|
@@ -2656,13 +2865,13 @@ var SkillLinker = class {
|
|
|
2656
2865
|
}
|
|
2657
2866
|
applyOperations(operations) {
|
|
2658
2867
|
const primary = this.resolvePrimaryDirectory();
|
|
2659
|
-
|
|
2868
|
+
fs10.mkdirSync(primary, { recursive: true });
|
|
2660
2869
|
for (const kind of ["remove", "relink", "link", "write"]) {
|
|
2661
2870
|
for (const operation of operations) {
|
|
2662
2871
|
if (operation.kind !== kind) continue;
|
|
2663
|
-
if (kind === "remove" || kind === "relink")
|
|
2664
|
-
if (kind === "relink" || kind === "link")
|
|
2665
|
-
if (kind === "write")
|
|
2872
|
+
if (kind === "remove" || kind === "relink") fs10.unlinkSync(operation.path);
|
|
2873
|
+
if (kind === "relink" || kind === "link") fs10.symlinkSync(operation.target, operation.path, "dir");
|
|
2874
|
+
if (kind === "write") fs10.writeFileSync(operation.path, operation.content);
|
|
2666
2875
|
}
|
|
2667
2876
|
}
|
|
2668
2877
|
}
|
|
@@ -2738,7 +2947,7 @@ function readJsonVersion(jsonPath) {
|
|
|
2738
2947
|
}
|
|
2739
2948
|
function readJson(jsonPath) {
|
|
2740
2949
|
try {
|
|
2741
|
-
return JSON.parse(
|
|
2950
|
+
return JSON.parse(fs10.readFileSync(jsonPath, "utf-8"));
|
|
2742
2951
|
} catch {
|
|
2743
2952
|
return null;
|
|
2744
2953
|
}
|
|
@@ -2751,35 +2960,35 @@ function getEntryType(entryPath) {
|
|
|
2751
2960
|
}
|
|
2752
2961
|
function lstatOrNull(entryPath) {
|
|
2753
2962
|
try {
|
|
2754
|
-
return
|
|
2963
|
+
return fs10.lstatSync(entryPath);
|
|
2755
2964
|
} catch {
|
|
2756
2965
|
return null;
|
|
2757
2966
|
}
|
|
2758
2967
|
}
|
|
2759
2968
|
function isDirectory(entryPath) {
|
|
2760
2969
|
try {
|
|
2761
|
-
return
|
|
2970
|
+
return fs10.statSync(entryPath).isDirectory();
|
|
2762
2971
|
} catch {
|
|
2763
2972
|
return false;
|
|
2764
2973
|
}
|
|
2765
2974
|
}
|
|
2766
2975
|
function isFile(entryPath) {
|
|
2767
2976
|
try {
|
|
2768
|
-
return
|
|
2977
|
+
return fs10.statSync(entryPath).isFile();
|
|
2769
2978
|
} catch {
|
|
2770
2979
|
return false;
|
|
2771
2980
|
}
|
|
2772
2981
|
}
|
|
2773
2982
|
function realpathOr(entryPath) {
|
|
2774
2983
|
try {
|
|
2775
|
-
return
|
|
2984
|
+
return fs10.realpathSync(entryPath);
|
|
2776
2985
|
} catch {
|
|
2777
2986
|
return entryPath;
|
|
2778
2987
|
}
|
|
2779
2988
|
}
|
|
2780
2989
|
function listDirectoryNames(directory) {
|
|
2781
2990
|
try {
|
|
2782
|
-
return
|
|
2991
|
+
return fs10.readdirSync(directory).sort(compareBytes);
|
|
2783
2992
|
} catch {
|
|
2784
2993
|
return [];
|
|
2785
2994
|
}
|
|
@@ -2792,10 +3001,10 @@ function isDddVendorPath(candidate) {
|
|
|
2792
3001
|
return withSlash.includes("/vendor/mgamadeus/") || withSlash.includes("/node_modules/@mgamadeus/");
|
|
2793
3002
|
}
|
|
2794
3003
|
function resolveLinkTarget(linkDirectory, target) {
|
|
2795
|
-
return
|
|
3004
|
+
return path11.posix.resolve(linkDirectory, target);
|
|
2796
3005
|
}
|
|
2797
3006
|
function relativePath(fromDirectory, toPath) {
|
|
2798
|
-
return
|
|
3007
|
+
return path11.posix.relative(fromDirectory, toPath) || ".";
|
|
2799
3008
|
}
|
|
2800
3009
|
function quoteShellArgument(argument) {
|
|
2801
3010
|
return /^[A-Za-z0-9._/@+=:-]+$/.test(argument) ? argument : `'${argument.replace(/'/g, "'\\''")}'`;
|
|
@@ -2808,13 +3017,14 @@ export {
|
|
|
2808
3017
|
silentLogger,
|
|
2809
3018
|
SdkGenerationError,
|
|
2810
3019
|
broadInvalidation,
|
|
2811
|
-
buildEndpointNameFromPath,
|
|
2812
3020
|
SUPPORTED_CONTRACT,
|
|
2813
3021
|
loadSpec,
|
|
2814
3022
|
validateSpec,
|
|
3023
|
+
generateLegacySdk,
|
|
3024
|
+
buildEndpointNameFromPath,
|
|
2815
3025
|
generateSdk,
|
|
2816
3026
|
findSkillsRepositoryRoot,
|
|
2817
3027
|
runSkillLinks,
|
|
2818
3028
|
linkSkills
|
|
2819
3029
|
};
|
|
2820
|
-
//# sourceMappingURL=chunk-
|
|
3030
|
+
//# sourceMappingURL=chunk-AGECBV52.js.map
|