@mgamadeus/ddd-web 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 [path12, item] of Object.entries(doc.paths ?? {})) {
102
+ for (const [path13, 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: path12, operation });
106
+ if (operation) result.push({ method, path: path13, operation });
107
107
  }
108
108
  }
109
109
  return result;
110
110
  }
111
- function operationKey(method, path12) {
112
- return `${method.toUpperCase()} ${path12}`;
111
+ function operationKey(method, path13) {
112
+ return `${method.toUpperCase()} ${path13}`;
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(path12, lookup) {
169
+ function tagFromPath(path13, lookup) {
170
170
  let matched = null;
171
- for (const segment of path12.replace(/\{[^}]+\}/g, "").split("/").filter(Boolean)) {
171
+ for (const segment of path13.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(path12) {
184
- return path12.match(/\{([^}]+)\}\/?$/)?.[1] ?? null;
183
+ function trailingPlaceholder(path13) {
184
+ return path13.match(/\{([^}]+)\}\/?$/)?.[1] ?? null;
185
185
  }
186
- function isPrimaryEntityPath(path12, tag) {
187
- const segments = path12.replace(/\{[^}]+\}\/?$/, "").split("/").filter(Boolean);
186
+ function isPrimaryEntityPath(path13, tag) {
187
+ const segments = path13.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(path12, tag) {
226
+ function identityPathParameter(path13, tag) {
227
227
  const singulars = singularForms(tag);
228
- const segments = path12.split("/").filter(Boolean);
228
+ const segments = path13.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 relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
296
- if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
295
+ const relative7 = accessor !== void 0 ? relativeAccessor(accessor) : null;
296
+ if (relative7 !== null) return [argTag(tag, relative7), 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 relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
310
- if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
309
+ const relative7 = accessor !== void 0 ? relativeAccessor(accessor) : null;
310
+ if (relative7 !== null) return [argTag(tag, relative7), 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 relative6 = relativeAccessor(accessor);
422
- return relative6 === null ? [] : [[name, relative6]];
421
+ const relative7 = relativeAccessor(accessor);
422
+ return relative7 === null ? [] : [[name, relative7]];
423
423
  })
424
424
  ),
425
425
  ...endpoint.bodyArg !== void 0 && relativeAccessor(endpoint.bodyArg) !== null ? { bodyArg: relativeAccessor(endpoint.bodyArg) } : {},
@@ -657,9 +657,9 @@ function testPattern(pattern, value) {
657
657
  pattern.lastIndex = 0;
658
658
  return result;
659
659
  }
660
- function matchesOperation(override, method, path12) {
660
+ function matchesOperation(override, method, path13) {
661
661
  if (override.method && override.method.toLowerCase() !== method) return false;
662
- return typeof override.path === "string" ? override.path === path12 : testPattern(override.path, path12);
662
+ return typeof override.path === "string" ? override.path === path13 : testPattern(override.path, path13);
663
663
  }
664
664
  function canonical(value) {
665
665
  return JSON.stringify(
@@ -683,9 +683,9 @@ function isEntityExtension(value) {
683
683
  }
684
684
  function indexOperations(doc, overrides, skipUpdatePostTwins) {
685
685
  const byKey = /* @__PURE__ */ new Map();
686
- for (const { method, path: path12, operation } of listOperations(doc)) {
686
+ for (const { method, path: path13, operation } of listOperations(doc)) {
687
687
  const extension = operation["x-ddd-side-effects"];
688
- const override = overrides.find((candidate) => matchesOperation(candidate, method, path12));
688
+ const override = overrides.find((candidate) => matchesOperation(candidate, method, path13));
689
689
  let sideEffects = hasSideEffects(method, operation);
690
690
  let explicit = false;
691
691
  if (typeof extension === "boolean") {
@@ -699,9 +699,9 @@ function indexOperations(doc, overrides, skipUpdatePostTwins) {
699
699
  const classifiedType = explicit ? sideEffects ? "mutation" : "query" : naturalType;
700
700
  const endpointType = typeof extension !== "boolean" && override?.endpointType || classifiedType;
701
701
  const entity = isEntityExtension(operation["x-ddd-entity"]) ? operation["x-ddd-entity"] : void 0;
702
- byKey.set(operationKey(method, path12), {
702
+ byKey.set(operationKey(method, path13), {
703
703
  method,
704
- path: path12,
704
+ path: path13,
705
705
  operation,
706
706
  sideEffects,
707
707
  sideEffectsExplicit: explicit,
@@ -711,11 +711,11 @@ function indexOperations(doc, overrides, skipUpdatePostTwins) {
711
711
  }
712
712
  const skippedTwins = /* @__PURE__ */ new Set();
713
713
  if (skipUpdatePostTwins) {
714
- for (const [path12, item] of Object.entries(doc.paths ?? {})) {
714
+ for (const [path13, item] of Object.entries(doc.paths ?? {})) {
715
715
  const post = item?.post;
716
716
  const patch = item?.patch;
717
717
  if (post && patch && isUpsertTwin(post, patch)) {
718
- skippedTwins.add(operationKey("post", path12));
718
+ skippedTwins.add(operationKey("post", path13));
719
719
  }
720
720
  }
721
721
  }
@@ -754,9 +754,9 @@ function commitOutput(files, modelsDir, stagingParent, options = {}) {
754
754
  fs5.mkdirSync(stagedModels, { recursive: true });
755
755
  for (const filePath of files.paths()) {
756
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);
757
+ const relative7 = modelsDir === void 0 ? void 0 : path4.relative(modelsDir, filePath);
758
+ if (relative7 !== void 0 && !relative7.startsWith("..") && !path4.isAbsolute(relative7)) {
759
+ const staged = path4.join(stagedModels, relative7);
760
760
  fs5.mkdirSync(path4.dirname(staged), { recursive: true });
761
761
  fs5.writeFileSync(staged, content);
762
762
  } else {
@@ -831,25 +831,25 @@ function resolveParameter(doc, parameter) {
831
831
  }
832
832
  function repairMissingPathParameters(doc, logger) {
833
833
  const repairs = [];
834
- for (const { method, path: path12, operation } of listOperations(doc)) {
835
- const placeholders = [...path12.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
834
+ for (const { method, path: path13, operation } of listOperations(doc)) {
835
+ const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
836
836
  if (placeholders.length === 0) continue;
837
- const pathLevel = doc.paths?.[path12]?.parameters ?? [];
837
+ const pathLevel = doc.paths?.[path13]?.parameters ?? [];
838
838
  const declared = new Set(
839
839
  [...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
840
840
  );
841
841
  const missing = placeholders.filter((name) => !declared.has(name));
842
- if (missing.length > 0) repairs.push({ path: path12, method, names: missing });
842
+ if (missing.length > 0) repairs.push({ path: path13, method, names: missing });
843
843
  }
844
844
  if (repairs.length === 0) return doc;
845
845
  const copy = structuredClone(doc);
846
- for (const { path: path12, method, names } of repairs) {
847
- const operation = copy.paths[path12][method];
846
+ for (const { path: path13, method, names } of repairs) {
847
+ const operation = copy.paths[path13][method];
848
848
  operation.parameters = [
849
849
  ...names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })),
850
850
  ...operation.parameters ?? []
851
851
  ];
852
- logger.warn(`${method.toUpperCase()} ${path12}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
852
+ logger.warn(`${method.toUpperCase()} ${path13}: path parameter(s) ${names.join(", ")} not declared in the spec \u2014 added as string.`);
853
853
  }
854
854
  return copy;
855
855
  }
@@ -908,12 +908,100 @@ async function generateLegacySdk(options) {
908
908
  }
909
909
  }
910
910
  }
911
+ const prune = options.prune ? planLegacyPrune(options.sources, results, cwd, options.manifestFile) : void 0;
911
912
  if (!options.dryRun && files.paths().length) commitOutput(files, void 0, cwd).finalize();
913
+ if (prune) {
914
+ const count = prune.deletions.reduce((total, { files: deleted }) => total + deleted.length, 0);
915
+ for (const { result, files: deleted } of prune.deletions) result.pruned.push(...deleted);
916
+ if (options.dryRun) {
917
+ logger.info("prune: would delete " + count + " file(s) no longer generated");
918
+ } else {
919
+ for (const { root, files: deleted } of prune.deletions) {
920
+ for (const file of deleted) {
921
+ fs6.rmSync(file, { force: true });
922
+ removeEmptyParents(path5.dirname(file), root);
923
+ }
924
+ }
925
+ fs6.mkdirSync(path5.dirname(prune.manifestPath), { recursive: true });
926
+ fs6.writeFileSync(prune.manifestPath, JSON.stringify(prune.manifest, null, 2) + "\n");
927
+ logger.info("prune: deleted " + count + " file(s) no longer generated");
928
+ }
929
+ }
912
930
  return results;
913
931
  }
932
+ function readLegacyManifest(file) {
933
+ if (!fs6.existsSync(file)) return { version: 1, sources: {} };
934
+ let parsed;
935
+ try {
936
+ parsed = JSON.parse(fs6.readFileSync(file, "utf8"));
937
+ } catch (error) {
938
+ throw new SdkGenerationError("Cannot read the legacy SDK manifest " + file + ": " + error.message);
939
+ }
940
+ const sources = parsed?.sources;
941
+ if (parsed?.version !== 1 || !sources || typeof sources !== "object") {
942
+ throw new SdkGenerationError("Unsupported legacy SDK manifest " + file + ". Delete it to start a new one.");
943
+ }
944
+ return parsed;
945
+ }
946
+ function manifestPath(cwd, file) {
947
+ return contains(cwd, file) ? path5.relative(cwd, file).split(path5.sep).join("/") : file;
948
+ }
949
+ function planLegacyPrune(sources, results, cwd, manifestFile) {
950
+ const file = path5.resolve(cwd, manifestFile ?? ".ddd-web-legacy-sdk.json");
951
+ const previous = readLegacyManifest(file);
952
+ const planned = /* @__PURE__ */ new Set();
953
+ const next = { version: 1, sources: {} };
954
+ const ran = /* @__PURE__ */ new Map();
955
+ for (const source of sources) {
956
+ const result = results.find((candidate) => candidate.source === source.name);
957
+ if (!result?.ok || result.skipped) continue;
958
+ ran.set(source.name, { source, result });
959
+ const entries = {};
960
+ for (const [name, options] of Object.entries(source.outputs)) {
961
+ const dir = path5.resolve(cwd, String(options.dir));
962
+ const written = (result.planned ?? []).filter((output) => output.dir === dir).flatMap((output) => output.files.map((planFile) => path5.resolve(output.dir, planFile.path)));
963
+ written.forEach((target) => planned.add(target));
964
+ entries[name] = { dir: manifestPath(cwd, dir), files: [...new Set(written.map((target) => manifestPath(cwd, target)))].sort() };
965
+ }
966
+ next.sources[source.name] = entries;
967
+ }
968
+ const ranOutputs = new Set(Object.entries(next.sources).flatMap(([sourceName, outputs]) => Object.keys(outputs).map((output) => sourceName + "\0" + output)));
969
+ const ranOutput = (sourceName, output) => ranOutputs.has(sourceName + "\0" + output);
970
+ const kept = /* @__PURE__ */ new Set();
971
+ for (const [sourceName, outputs] of Object.entries(previous.sources)) {
972
+ for (const [output, entry] of Object.entries(outputs ?? {})) {
973
+ if (ranOutput(sourceName, output)) continue;
974
+ (entry?.files ?? []).forEach((listed) => kept.add(path5.resolve(cwd, listed)));
975
+ (next.sources[sourceName] ??= {})[output] = entry;
976
+ }
977
+ }
978
+ const claimed = /* @__PURE__ */ new Set();
979
+ const deletions = [];
980
+ for (const [sourceName, outputs] of Object.entries(previous.sources)) {
981
+ const current = ran.get(sourceName);
982
+ if (!current) continue;
983
+ for (const [output, entry] of Object.entries(outputs ?? {})) {
984
+ if (!ranOutput(sourceName, output) || !entry || typeof entry.dir !== "string" || !Array.isArray(entry.files)) continue;
985
+ const root = path5.resolve(cwd, entry.dir);
986
+ const stale = entry.files.map((listed) => path5.resolve(cwd, listed)).filter((target) => contains(root, target) && target !== root && !planned.has(target) && !kept.has(target) && !claimed.has(target) && fs6.lstatSync(target, { throwIfNoEntry: false })?.isFile() === true);
987
+ stale.forEach((target) => claimed.add(target));
988
+ if (stale.length) deletions.push({ result: current.result, root, files: stale.sort() });
989
+ }
990
+ }
991
+ for (const { result } of ran.values()) result.pruned = [];
992
+ return { manifestPath: file, manifest: next, deletions };
993
+ }
994
+ function removeEmptyParents(directory, root) {
995
+ let current = directory;
996
+ while (current !== root && contains(root, current)) {
997
+ if (!fs6.existsSync(current) || fs6.readdirSync(current).length > 0) return;
998
+ fs6.rmdirSync(current);
999
+ current = path5.dirname(current);
1000
+ }
1001
+ }
914
1002
  function contains(parent, child) {
915
- const relative6 = path5.relative(parent, child);
916
- return relative6 !== ".." && !relative6.startsWith(".." + path5.sep) && !path5.isAbsolute(relative6);
1003
+ const relative7 = path5.relative(parent, child);
1004
+ return relative7 !== ".." && !relative7.startsWith(".." + path5.sep) && !path5.isAbsolute(relative7);
917
1005
  }
918
1006
  function assertGeneratedDirectory(directory) {
919
1007
  const entry = fs6.lstatSync(directory, { throwIfNoEntry: false });
@@ -1054,8 +1142,8 @@ async function generateDelegatedSdk(mode, loaded, allApis, apis, options, logger
1054
1142
  var REQUEST_BODY_ARG = "requestBody";
1055
1143
  var DEFAULT_STRIP_PATH_PREFIX = /^\/(?:app\/)?api(?=\/)/;
1056
1144
  var upperFirst = (value) => value.charAt(0).toUpperCase() + value.slice(1);
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, "");
1145
+ function buildEndpointNameFromPath(method, path13, stripPathPrefix = DEFAULT_STRIP_PATH_PREFIX) {
1146
+ const stripped = typeof stripPathPrefix === "string" ? path13.startsWith(stripPathPrefix) ? path13.slice(stripPathPrefix.length) : path13 : path13.replace(stripPathPrefix, "");
1059
1147
  let lastInnerParameter = null;
1060
1148
  const withoutInnerParameters = stripped.replace(/\{([^}]+)\}\//g, (_, parameter) => {
1061
1149
  lastInnerParameter = parameter;
@@ -1076,21 +1164,21 @@ function prepareDocumentForEndpoints(doc, options) {
1076
1164
  const prepared = structuredClone(doc);
1077
1165
  if (dropsCookieParameters) dropCookieParameters(prepared);
1078
1166
  const pathByName = /* @__PURE__ */ new Map();
1079
- for (const [path12, item] of Object.entries(prepared.paths ?? {})) {
1167
+ for (const [path13, item] of Object.entries(prepared.paths ?? {})) {
1080
1168
  if (!item) continue;
1081
1169
  for (const method of HTTP_METHODS) {
1082
1170
  const operation = item[method];
1083
1171
  if (!operation) continue;
1084
1172
  if (naming !== "rtk") {
1085
- const name = naming === "path" ? buildEndpointNameFromPath(method, path12, options.stripPathPrefix) : naming({ method, path: path12, operation });
1173
+ const name = naming === "path" ? buildEndpointNameFromPath(method, path13, options.stripPathPrefix) : naming({ method, path: path13, operation });
1086
1174
  if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
1087
- throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path12}) is no identifier.`);
1175
+ throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path13}) is no identifier.`);
1088
1176
  }
1089
1177
  const other = pathByName.get(name);
1090
1178
  if (other !== void 0) {
1091
- throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path12} are both named "${name}".`);
1179
+ throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path13} are both named "${name}".`);
1092
1180
  }
1093
- pathByName.set(name, `${method.toUpperCase()} ${path12}`);
1181
+ pathByName.set(name, `${method.toUpperCase()} ${path13}`);
1094
1182
  const placeholder = `dddEndpoint${endpointNamesByPlaceholder.size}`;
1095
1183
  endpointNamesByPlaceholder.set(placeholder, name);
1096
1184
  operation.operationId = placeholder;
@@ -1152,7 +1240,7 @@ function titleRequestBody(operation) {
1152
1240
  // src/codegen/generate.ts
1153
1241
  import * as fs9 from "fs";
1154
1242
  import * as os2 from "os";
1155
- import * as path10 from "path";
1243
+ import * as path11 from "path";
1156
1244
 
1157
1245
  // src/codegen/typescript.ts
1158
1246
  import { createRequire as createRequire3 } from "module";
@@ -1238,7 +1326,8 @@ function applyEnumConsts(body, modelName, model, options = {}) {
1238
1326
  if (!values || values.length === 0) continue;
1239
1327
  const constName = `${modelName}${propertyName2.charAt(0).toUpperCase()}${propertyName2.slice(1)}`;
1240
1328
  if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(constName)) continue;
1241
- const members = [...new Set(values.map(String))].map((value) => ` ${enumKeyOf(value)}: ${JSON.stringify(value)},`).join("\n");
1329
+ const unique = [...new Map(values.map((value) => [String(value), value])).values()];
1330
+ const members = unique.map((value) => ` ${enumKeyOf(String(value))}: ${JSON.stringify(value)},`).join("\n");
1242
1331
  consts.set(constName, `export const ${constName} = {
1243
1332
  ${members}
1244
1333
  };
@@ -1438,8 +1527,8 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
1438
1527
  logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
1439
1528
  return null;
1440
1529
  }
1441
- const path12 = location?.path ?? toOpenApiPath(url);
1442
- const placeholders = [...path12.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
1530
+ const path13 = location?.path ?? toOpenApiPath(url);
1531
+ const placeholders = [...path13.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
1443
1532
  const pathArgs = {};
1444
1533
  placeholders.forEach((name, index) => {
1445
1534
  const accessor = accessors[index];
@@ -1450,7 +1539,7 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
1450
1539
  buildType,
1451
1540
  url,
1452
1541
  method: (location?.method ?? method ?? "GET").toUpperCase(),
1453
- path: path12,
1542
+ path: path13,
1454
1543
  pathArgs,
1455
1544
  ...bodyArg ? { bodyArg } : {},
1456
1545
  ...responseType ? { responseType } : {}
@@ -1523,10 +1612,10 @@ function detectResponseKind(responses) {
1523
1612
  }
1524
1613
  function detectResponseHandlerEndpoints(doc, endpoints, overrides = []) {
1525
1614
  const kinds = /* @__PURE__ */ new Map();
1526
- for (const { method, path: path12, operation } of listOperations(doc)) {
1527
- const override = overrides.find((candidate) => matchesOperation(candidate, method, path12));
1615
+ for (const { method, path: path13, operation } of listOperations(doc)) {
1616
+ const override = overrides.find((candidate) => matchesOperation(candidate, method, path13));
1528
1617
  const kind = override ? override.handler : detectResponseKind(operation.responses);
1529
- if (kind !== "json") kinds.set(operationKey(method, path12), kind);
1618
+ if (kind !== "json") kinds.set(operationKey(method, path13), kind);
1530
1619
  }
1531
1620
  const keys = /* @__PURE__ */ new Map();
1532
1621
  if (kinds.size === 0) return keys;
@@ -1751,9 +1840,9 @@ function registryMatch(name, registry) {
1751
1840
  return null;
1752
1841
  }
1753
1842
  function importSpecifier(fromFile, toFile, 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;
1843
+ let relative7 = path6.relative(path6.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
1844
+ if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
1845
+ return esm ? `${relative7}.js` : relative7;
1757
1846
  }
1758
1847
  var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
1759
1848
  function extractModels(input) {
@@ -1763,8 +1852,8 @@ function extractModels(input) {
1763
1852
  const indexPath = path6.join(modelsDir, "index.ts");
1764
1853
  const nameOwners = /* @__PURE__ */ new Map();
1765
1854
  for (const filePath of files.paths()) {
1766
- const relative6 = path6.relative(modelsDir, filePath);
1767
- if (relative6.startsWith("..") || path6.isAbsolute(relative6) || path6.resolve(filePath) === path6.resolve(indexPath)) continue;
1855
+ const relative7 = path6.relative(modelsDir, filePath);
1856
+ if (relative7.startsWith("..") || path6.isAbsolute(relative7) || path6.resolve(filePath) === path6.resolve(indexPath)) continue;
1768
1857
  const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
1769
1858
  if (name && !nameOwners.has(name)) nameOwners.set(name, path6.resolve(filePath).toLowerCase());
1770
1859
  }
@@ -1943,6 +2032,252 @@ ${defaultExport}
1943
2032
  `;
1944
2033
  }
1945
2034
 
2035
+ // src/codegen/msw-handlers.ts
2036
+ import * as path7 from "path";
2037
+ var IDENTIFIER2 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2038
+ function renderMswHandlers(input) {
2039
+ const ts = loadTypeScript();
2040
+ const apiFile = ts.createSourceFile("api.ts", input.apiSource, ts.ScriptTarget.Latest, true);
2041
+ const apiImports = readImports(ts, apiFile, input.apiFilePath, input.files);
2042
+ const typeArguments = readTypeArguments(ts, apiFile);
2043
+ const typeImports = /* @__PURE__ */ new Map();
2044
+ const mockImports = /* @__PURE__ */ new Map();
2045
+ const mockLocalBySpecifier = /* @__PURE__ */ new Map();
2046
+ const mockOf = (model) => {
2047
+ const options = input.modelMocks;
2048
+ if (!options) return null;
2049
+ const relative7 = path7.relative(input.modelsDir, model.file).replace(/\.ts$/, "").split(path7.sep).join("/");
2050
+ if (relative7.startsWith("..") || path7.isAbsolute(relative7)) return null;
2051
+ const modelName = path7.basename(relative7);
2052
+ const prefix = options.importPrefix.endsWith("/") || options.importPrefix === "" ? options.importPrefix : `${options.importPrefix}/`;
2053
+ const specifier = `${prefix}${relative7}${options.fileSuffix ?? ".mock"}`;
2054
+ const exported = options.exportName?.(modelName, relative7) ?? `get${modelName}Mock`;
2055
+ const key = `${specifier}\0${exported}`;
2056
+ const known = mockLocalBySpecifier.get(key);
2057
+ if (known) return known;
2058
+ let local = exported;
2059
+ for (let index = 2; mockImports.has(local) || typeImports.has(local); index++) local = `${exported}${index}`;
2060
+ mockImports.set(local, { exported, specifier });
2061
+ mockLocalBySpecifier.set(key, local);
2062
+ return local;
2063
+ };
2064
+ const useType = (text) => {
2065
+ for (const match of text.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)) {
2066
+ const imported = apiImports.get(match[0]);
2067
+ if (imported) typeImports.set(match[0], imported);
2068
+ }
2069
+ return text;
2070
+ };
2071
+ const entries = [];
2072
+ for (const endpoint of input.endpoints) {
2073
+ const types = typeArguments.get(endpoint.key);
2074
+ if (!types) continue;
2075
+ const method = endpoint.method.toLowerCase();
2076
+ const kind = input.responseKinds.get(endpoint.key) ?? "json";
2077
+ const operation = input.doc.paths?.[endpoint.path]?.[method];
2078
+ const status = kind === "blob" ? 200 : successStatus(operation?.responses);
2079
+ const argType = useType(types.arg ?? "void");
2080
+ let responseType = kind === "blob" ? "Blob | string | null" : useType(types.response ?? "unknown");
2081
+ let defaultMock = "null";
2082
+ if (kind === "json" && types.response && IDENTIFIER2.test(types.response)) {
2083
+ const shape = responseShape(ts, types.response, apiImports, input.files);
2084
+ const local = shape ? mockOf(shape.model) : null;
2085
+ if (shape && local) defaultMock = shape.array ? `[${local}()]` : `${local}()`;
2086
+ }
2087
+ if (kind === "text" && responseType === "unknown") responseType = "string";
2088
+ const pattern = `*${endpoint.path.replace(/\{[^}]+\}/g, "*")}`;
2089
+ const key = IDENTIFIER2.test(endpoint.key) ? endpoint.key : JSON.stringify(endpoint.key);
2090
+ entries.push(
2091
+ ` ${key}: (custom?: Partial<StoryMock<${responseType}, ${argType}>>) =>
2092
+ mockOperation<${responseType}, ${argType}>(${JSON.stringify(method)}, ${JSON.stringify(pattern)}, ${JSON.stringify(endpoint.path)}, ${JSON.stringify(kind)}, ${status}, () => ${defaultMock}, custom),`
2093
+ );
2094
+ }
2095
+ const specifierOf = (file) => {
2096
+ let relative7 = path7.relative(path7.dirname(input.outputFile), file.replace(/\.ts$/, "")).split(path7.sep).join("/");
2097
+ if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
2098
+ if (input.esm) return `${relative7}.js`;
2099
+ return relative7.endsWith("/index") ? relative7.slice(0, -"/index".length) : relative7;
2100
+ };
2101
+ const typeLines = groupImports([...typeImports].map(([local, { exported, file }]) => ({ local, exported, specifier: specifierOf(file) })), true);
2102
+ const mockLines = groupImports([...mockImports].map(([local, { exported, specifier }]) => ({ local, exported, specifier })), false);
2103
+ return [
2104
+ "// Generated by @mgamadeus/ddd-web (mswHandlers). Do not edit.",
2105
+ "import { delay, http, HttpResponse, type DefaultBodyType, type HttpResponseResolver, type PathParams } from 'msw';",
2106
+ ...typeLines,
2107
+ ...mockLines,
2108
+ "",
2109
+ RUNTIME,
2110
+ `/** MSW handler factories of ${input.exportName.replace(/Mocks$/, "")}: one per operation, answering its default mock. */`,
2111
+ `export const ${input.exportName} = {`,
2112
+ ...entries,
2113
+ "};",
2114
+ ""
2115
+ ].join("\n");
2116
+ }
2117
+ function groupImports(names, typeOnly) {
2118
+ const bySpecifier = /* @__PURE__ */ new Map();
2119
+ for (const { local, exported, specifier } of names) {
2120
+ const list2 = bySpecifier.get(specifier) ?? [];
2121
+ list2.push(exported === local ? local : `${exported} as ${local}`);
2122
+ bySpecifier.set(specifier, list2);
2123
+ }
2124
+ return [...bySpecifier].map(([specifier, list2]) => `import ${typeOnly ? "type " : ""}{ ${list2.join(", ")} } from '${specifier}';`);
2125
+ }
2126
+ var RUNTIME = `type ResolverInfo = Parameters<HttpResponseResolver<PathParams, DefaultBodyType>>[0];
2127
+
2128
+ /** The path parameters and query string values of the request, by name, as the strings that arrived. */
2129
+ export type StoryMockParams<Arg> = { [Name in Arg extends object ? Extract<keyof Arg, string> : never]?: string } & {
2130
+ [name: string]: string | undefined;
2131
+ };
2132
+
2133
+ /** How a generated handler answers; the factories take \`Partial<StoryMock<\u2026>>\`. */
2134
+ export interface StoryMock<Response, Arg = void> {
2135
+ /** URL pattern matched instead of the generated one (any origin + the operation path, \`*\` per path parameter). */
2136
+ url: string;
2137
+ /** Default: the operation's first declared 2xx status (200 for a file download). */
2138
+ status: number;
2139
+ /** Delay before answering (MSW \`delay\`). */
2140
+ delay: number | 'real' | 'infinite';
2141
+ /** The answer, or a function computing it from the request's parameters and the default mock. */
2142
+ response:
2143
+ | Response
2144
+ | ((params: StoryMockParams<Arg>, defaultMock: Response | null, info: ResolverInfo) => Response | Promise<Response>);
2145
+ }
2146
+
2147
+ type BodyKind = 'json' | 'text' | 'blob';
2148
+
2149
+ const readParams = (template: string, info: ResolverInfo): Record<string, string> => {
2150
+ const url = new URL(info.request.url);
2151
+ const params: Record<string, string> = {};
2152
+ url.searchParams.forEach((value, name) => {
2153
+ params[name] = value;
2154
+ });
2155
+ const parts = template.split(/\\{([^}]+)\\}/);
2156
+ const names = parts.filter((_, index) => index % 2 === 1);
2157
+ const pattern = parts
2158
+ .map((part, index) => (index % 2 === 1 ? '([^/]+)' : part.replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&')))
2159
+ .join('');
2160
+ const match = new RegExp(pattern + '/?$').exec(url.pathname);
2161
+ names.forEach((name, index) => {
2162
+ const value = match?.[index + 1];
2163
+ if (value !== undefined) params[name] = decodeURIComponent(value);
2164
+ });
2165
+ return params;
2166
+ };
2167
+
2168
+ const mockOperation = <Response, Arg>(
2169
+ method: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options',
2170
+ pattern: string,
2171
+ template: string,
2172
+ kind: BodyKind,
2173
+ status: number,
2174
+ defaultMock: () => Response | null,
2175
+ custom: Partial<StoryMock<Response, Arg>> = {},
2176
+ ) =>
2177
+ http[method](custom.url ?? pattern, async (info) => {
2178
+ if (custom.delay !== undefined) await delay(custom.delay);
2179
+ const fallback = defaultMock();
2180
+ const answer = custom.response;
2181
+ const body =
2182
+ typeof answer === 'function'
2183
+ ? await (answer as (params: StoryMockParams<Arg>, defaultMock: Response | null, info: ResolverInfo) => Response | Promise<Response>)(
2184
+ readParams(template, info) as StoryMockParams<Arg>,
2185
+ fallback,
2186
+ info,
2187
+ )
2188
+ : answer !== undefined
2189
+ ? answer
2190
+ : fallback;
2191
+ const init = { status: custom.status ?? status };
2192
+ if (body === null || body === undefined) return new HttpResponse(null, init);
2193
+ if (kind === 'json') return HttpResponse.json(body as never, init);
2194
+ return new HttpResponse(body as unknown as BodyInit, init);
2195
+ });
2196
+ `;
2197
+ function successStatus(responses) {
2198
+ const codes = Object.keys(responses ?? {}).filter((code) => /^2\d\d$/.test(code)).map(Number).sort((a, b) => a - b);
2199
+ return codes[0] ?? 200;
2200
+ }
2201
+ function readTypeArguments(ts, sourceFile) {
2202
+ const result = /* @__PURE__ */ new Map();
2203
+ const visit = (node) => {
2204
+ if (ts.isPropertyAssignment(node) && ts.isCallExpression(node.initializer)) {
2205
+ const callee = node.initializer.expression;
2206
+ if (ts.isPropertyAccessExpression(callee) && ["query", "mutation"].includes(callee.name.text)) {
2207
+ const key = node.name.getText(sourceFile).replace(/^["']|["']$/g, "");
2208
+ const [response, arg] = node.initializer.typeArguments ?? [];
2209
+ result.set(key, { response: response?.getText(sourceFile), arg: arg?.getText(sourceFile) });
2210
+ return;
2211
+ }
2212
+ }
2213
+ ts.forEachChild(node, visit);
2214
+ };
2215
+ visit(sourceFile);
2216
+ return result;
2217
+ }
2218
+ function readImports(ts, sourceFile, filePath, files) {
2219
+ const result = /* @__PURE__ */ new Map();
2220
+ for (const statement of sourceFile.statements) {
2221
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
2222
+ const specifier = statement.moduleSpecifier.text;
2223
+ if (!specifier.startsWith(".")) continue;
2224
+ const base = path7.resolve(path7.dirname(filePath), specifier.replace(/\.js$/, ""));
2225
+ const file = files.findPath(`${base}.ts`) ?? files.findPath(path7.join(base, "index.ts"));
2226
+ const bindings = statement.importClause?.namedBindings;
2227
+ if (!file || !bindings || !ts.isNamedImports(bindings)) continue;
2228
+ for (const element of bindings.elements) {
2229
+ result.set(element.name.text, { exported: (element.propertyName ?? element.name).text, file });
2230
+ }
2231
+ }
2232
+ return result;
2233
+ }
2234
+ function declaringFile(name, module, files) {
2235
+ const declares = (file) => new RegExp(`^export (?:type|interface) ${name}\\b`, "m").test(files.get(file) ?? "");
2236
+ if (declares(module)) return module;
2237
+ const barrel = files.get(module) ?? "";
2238
+ for (const match of barrel.matchAll(/from ['"](.+?)['"]/g)) {
2239
+ const base = path7.resolve(path7.dirname(module), match[1].replace(/\.js$/, ""));
2240
+ const file = files.findPath(`${base}.ts`);
2241
+ if (file && declares(file)) return file;
2242
+ }
2243
+ return void 0;
2244
+ }
2245
+ function responseShape(ts, responseType, apiImports, files) {
2246
+ const imported = apiImports.get(responseType);
2247
+ if (!imported) return null;
2248
+ const file = declaringFile(imported.exported, imported.file, files);
2249
+ if (!file) return null;
2250
+ const sourceFile = ts.createSourceFile("response.ts", files.get(file), ts.ScriptTarget.Latest, true);
2251
+ const alias = sourceFile.statements.find(
2252
+ (statement) => ts.isTypeAliasDeclaration(statement) && statement.name.text === imported.exported
2253
+ );
2254
+ if (!alias) return null;
2255
+ let type = alias.type;
2256
+ while (ts.isParenthesizedTypeNode(type)) type = type.type;
2257
+ if (ts.isUnionTypeNode(type)) {
2258
+ const members = type.types.filter(
2259
+ (member) => !(ts.isLiteralTypeNode(member) && member.literal.kind === ts.SyntaxKind.NullKeyword) && member.kind !== ts.SyntaxKind.UndefinedKeyword
2260
+ );
2261
+ if (members.length !== 1) return null;
2262
+ type = members[0];
2263
+ }
2264
+ let array = false;
2265
+ if (ts.isArrayTypeNode(type)) {
2266
+ array = true;
2267
+ type = type.elementType;
2268
+ } else if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName) && type.typeName.text === "Array" && type.typeArguments?.length === 1) {
2269
+ array = true;
2270
+ type = type.typeArguments[0];
2271
+ }
2272
+ while (ts.isParenthesizedTypeNode(type)) type = type.type;
2273
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName) || type.typeArguments) return null;
2274
+ const modelImports = readImports(ts, sourceFile, file, files);
2275
+ const model = modelImports.get(type.typeName.text);
2276
+ if (!model) return null;
2277
+ const modelFile = declaringFile(model.exported, model.file, files);
2278
+ return modelFile ? { model: { file: modelFile, exported: model.exported }, array } : null;
2279
+ }
2280
+
1946
2281
  // src/codegen/multipart.ts
1947
2282
  var MULTIPART_FILES_ARG = "multipartFiles";
1948
2283
  var BODY_FIELD = "body";
@@ -1977,9 +2312,9 @@ function readMultipartOperation(doc, requestBody) {
1977
2312
  }
1978
2313
  function detectMultipartEndpoints(doc, endpoints) {
1979
2314
  const byOperation = /* @__PURE__ */ new Map();
1980
- for (const { method, path: path12, operation } of listOperations(doc)) {
2315
+ for (const { method, path: path13, operation } of listOperations(doc)) {
1981
2316
  const multipart = readMultipartOperation(doc, operation.requestBody);
1982
- if (multipart) byOperation.set(operationKey(method, path12), multipart);
2317
+ if (multipart) byOperation.set(operationKey(method, path13), multipart);
1983
2318
  }
1984
2319
  const keys = /* @__PURE__ */ new Map();
1985
2320
  if (byOperation.size === 0) return keys;
@@ -2110,12 +2445,12 @@ function buildRegistry(docs, logger) {
2110
2445
 
2111
2446
  // src/codegen/rtk.ts
2112
2447
  import * as fs7 from "fs";
2113
- import * as path8 from "path";
2448
+ import * as path9 from "path";
2114
2449
  import prettier2 from "prettier";
2115
2450
 
2116
2451
  // src/codegen/module-resolution.ts
2117
2452
  import Module, { createRequire as createRequire4 } from "module";
2118
- import * as path7 from "path";
2453
+ import * as path8 from "path";
2119
2454
  var installed = false;
2120
2455
  function installParserModuleResolution() {
2121
2456
  if (installed) return;
@@ -2128,7 +2463,7 @@ function installParserModuleResolution() {
2128
2463
  } catch {
2129
2464
  return;
2130
2465
  }
2131
- const ajvDraft04Folder = `${path7.sep}ajv-draft-04${path7.sep}`;
2466
+ const ajvDraft04Folder = `${path8.sep}ajv-draft-04${path8.sep}`;
2132
2467
  const moduleWithResolver = Module;
2133
2468
  const defaultResolveFilename = moduleWithResolver._resolveFilename;
2134
2469
  moduleWithResolver._resolveFilename = function resolveAjvOfTheParser(request, parent, ...rest) {
@@ -2147,7 +2482,7 @@ async function loadRtkCodegen() {
2147
2482
  }
2148
2483
 
2149
2484
  // src/codegen/rtk.ts
2150
- var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers", "invalidation"]);
2485
+ var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers", "invalidation", "mswHandlers"]);
2151
2486
  function matches(matcher, name, definition) {
2152
2487
  if (matcher === void 0) return true;
2153
2488
  if (typeof matcher === "function") return matcher(name, definition);
@@ -2172,9 +2507,9 @@ function mergeEndpointOverrides(userOverrides, typeOverrides) {
2172
2507
  }
2173
2508
  function relativeImport(fromDir, target) {
2174
2509
  if (!isPathLike(target)) return target;
2175
- let relative6 = path8.relative(fromDir, target).replace(/\\/g, "/");
2176
- if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
2177
- return relative6;
2510
+ let relative7 = path9.relative(fromDir, target).replace(/\\/g, "/");
2511
+ if (!relative7.startsWith(".")) relative7 = `./${relative7}`;
2512
+ return relative7;
2178
2513
  }
2179
2514
  async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endpointNameOf = (rtkName) => rtkName) {
2180
2515
  fs7.writeFileSync(specFile, JSON.stringify(doc));
@@ -2213,12 +2548,12 @@ async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endp
2213
2548
  return { code, locations };
2214
2549
  }
2215
2550
  async function findPrettierConfigFile(rootDir) {
2216
- return await prettier2.resolveConfigFile(path8.join(rootDir, "openapi-config.ts")) ?? void 0;
2551
+ return await prettier2.resolveConfigFile(path9.join(rootDir, "openapi-config.ts")) ?? void 0;
2217
2552
  }
2218
2553
 
2219
2554
  // src/codegen/workspace.ts
2220
2555
  import * as fs8 from "fs";
2221
- import * as path9 from "path";
2556
+ import * as path10 from "path";
2222
2557
  import * as readline from "readline";
2223
2558
  var DEFAULT_ENV_FILES = [".env", ".env.local"];
2224
2559
  var DEFAULT_URL_KEYS = ["NEXT_PUBLIC_API_URL", "EXPO_PUBLIC_API_URL", "VITE_API_URL", "VITE_API_ENDPOINT", "API_URL"];
@@ -2243,7 +2578,7 @@ function firstHostLabel(url) {
2243
2578
  }
2244
2579
  function sniffWorkspace(rootDir, options) {
2245
2580
  for (const file of options.envFiles ?? DEFAULT_ENV_FILES) {
2246
- const vars = parseEnvFile(path9.join(rootDir, file));
2581
+ const vars = parseEnvFile(path10.join(rootDir, file));
2247
2582
  for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
2248
2583
  const value = vars[key];
2249
2584
  const label2 = value ? firstHostLabel(value) : null;
@@ -2253,11 +2588,11 @@ function sniffWorkspace(rootDir, options) {
2253
2588
  return null;
2254
2589
  }
2255
2590
  function ask(question) {
2256
- return new Promise((resolve8) => {
2591
+ return new Promise((resolve9) => {
2257
2592
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2258
- rl.on("close", () => resolve8(""));
2593
+ rl.on("close", () => resolve9(""));
2259
2594
  rl.question(question, (answer) => {
2260
- resolve8(answer.trim());
2595
+ resolve9(answer.trim());
2261
2596
  rl.close();
2262
2597
  });
2263
2598
  });
@@ -2283,9 +2618,9 @@ async function resolveWorkspace(rootDir, options, explicit, logger) {
2283
2618
  // src/codegen/generate.ts
2284
2619
  async function load(options, cwd) {
2285
2620
  if (options.config && typeof options.config === "object") {
2286
- return { config: options.config, configPath: path10.join(cwd, "<inline config>"), rootDir: cwd };
2621
+ return { config: options.config, configPath: path11.join(cwd, "<inline config>"), rootDir: cwd };
2287
2622
  }
2288
- return loadConfig(path10.resolve(cwd, options.config ?? "openapi-config.ts"));
2623
+ return loadConfig(path11.resolve(cwd, options.config ?? "openapi-config.ts"));
2289
2624
  }
2290
2625
  function selectApis(all, options) {
2291
2626
  let selected = all;
@@ -2297,14 +2632,14 @@ function selectApis(all, options) {
2297
2632
  }
2298
2633
  if (options.schema) {
2299
2634
  if (selected.length !== 1) throw new SdkGenerationError("--schema needs exactly one api (use --api).");
2300
- const schemaSource = isUrl(options.schema) ? options.schema : path10.resolve(options.cwd ?? process.cwd(), options.schema);
2635
+ const schemaSource = isUrl(options.schema) ? options.schema : path11.resolve(options.cwd ?? process.cwd(), options.schema);
2301
2636
  selected = [{ ...selected[0], schemaSource }];
2302
2637
  }
2303
2638
  return selected;
2304
2639
  }
2305
2640
  async function generateSdk(options = {}) {
2306
2641
  const logger = options.logger ?? consoleLogger;
2307
- const cwd = path10.resolve(options.cwd ?? process.cwd());
2642
+ const cwd = path11.resolve(options.cwd ?? process.cwd());
2308
2643
  let loaded = await load(options, cwd);
2309
2644
  if (loaded.config.workspace) {
2310
2645
  const value = await resolveWorkspace(loaded.rootDir, loaded.config.workspace, options.workspace, logger);
@@ -2358,7 +2693,7 @@ async function generateSdk(options = {}) {
2358
2693
  const prettierConfigFile = await findPrettierConfigFile(loaded.rootDir);
2359
2694
  const constsByFile = /* @__PURE__ */ new Map();
2360
2695
  const uniqueNameByPath = /* @__PURE__ */ new Map();
2361
- const specDir = fs9.mkdtempSync(path10.join(os2.tmpdir(), "ddd-web-spec-"));
2696
+ const specDir = fs9.mkdtempSync(path11.join(os2.tmpdir(), "ddd-web-spec-"));
2362
2697
  try {
2363
2698
  for (const [i, { api, write, doc: rawDoc }] of steps.entries()) {
2364
2699
  const doc = repairMissingPathParameters(rawDoc, logger);
@@ -2386,7 +2721,7 @@ async function generateSdk(options = {}) {
2386
2721
  };
2387
2722
  const endpointNameOf = (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName;
2388
2723
  const runPass = async (passApi, specName, modelsOnly) => {
2389
- const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path10.join(specDir, specName), prettierConfigFile, endpointNameOf);
2724
+ const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path11.join(specDir, specName), prettierConfigFile, endpointNameOf);
2390
2725
  const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
2391
2726
  const endpoints2 = parseApiEndpoints(rtk.code, logger, rtk.locations);
2392
2727
  const handlerEndpoints2 = detectResponseHandlerEndpoints(doc, endpoints2, api.responseHandlers);
@@ -2400,20 +2735,23 @@ async function generateSdk(options = {}) {
2400
2735
  const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints2);
2401
2736
  const finalApiSource2 = multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
2402
2737
  ${withHandlers}` : withHandlers;
2403
- return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2 };
2738
+ return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2, apiSource };
2404
2739
  };
2405
2740
  const buildersOfAllOperations = endpointOptions.requestBuilders === "all" && api.config.filterEndpoints !== void 0;
2406
2741
  let requestsSourceOfAllOperations = null;
2742
+ let passOfAllOperations = null;
2407
2743
  if ((modelOptions.scope === "all" || buildersOfAllOperations) && api.config.filterEndpoints !== void 0) {
2408
2744
  const unfiltered = await runPass({ ...api, config: { ...api.config, filterEndpoints: void 0 } }, `${i}-all.json`, !buildersOfAllOperations);
2409
2745
  if (buildersOfAllOperations) {
2746
+ passOfAllOperations = unfiltered;
2410
2747
  const requestsStem = `${api.stem}Requests`;
2411
2748
  requestsSourceOfAllOperations = splitRequestBuilders(unfiltered.finalApiSource, requestsStem, `./${requestsStem}`).requestsSource;
2412
2749
  logger.info(" request builders of all operations (endpoints.requestBuilders all)");
2413
2750
  }
2414
2751
  if (modelOptions.scope === "all") logger.info(" models of all operations written (models.scope all)");
2415
2752
  }
2416
- const { endpoints, handlerEndpoints, multipartCount, finalApiSource } = await runPass(api, `${i}.json`, false);
2753
+ const mainPass = await runPass(api, `${i}.json`, false);
2754
+ const { endpoints, handlerEndpoints, multipartCount, finalApiSource } = mainPass;
2417
2755
  const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
2418
2756
  if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
2419
2757
  if (multipartCount > 0) logger.info(` ${multipartCount} multipart endpoint(s) (multipartFiles)`);
@@ -2422,11 +2760,30 @@ ${withHandlers}` : withHandlers;
2422
2760
  const requestsStem = `${api.stem}Requests`;
2423
2761
  const split = splitRequestBuilders(finalApiSource, requestsStem, esm ? `./${requestsStem}.js` : `./${requestsStem}`);
2424
2762
  files.set(api.outputFile, split.apiSource);
2425
- files.set(path10.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
2763
+ files.set(path11.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
2426
2764
  logger.info(` ${split.count} request builder(s) used by ${api.stem}.ts`);
2427
2765
  } else {
2428
2766
  files.set(api.outputFile, finalApiSource);
2429
2767
  }
2768
+ const msw = api.config.mswHandlers === false ? void 0 : api.config.mswHandlers ?? loaded.config.mswHandlers ? { ...loaded.config.mswHandlers, ...api.config.mswHandlers || {} } : void 0;
2769
+ if (msw) {
2770
+ const pass = passOfAllOperations ?? mainPass;
2771
+ const outputFile = msw.outputFile ? path11.resolve(loaded.rootDir, msw.outputFile) : path11.join(api.outputDir, `${api.stem}Mocks.ts`);
2772
+ files.set(outputFile, renderMswHandlers({
2773
+ apiSource: pass.apiSource,
2774
+ apiFilePath: api.outputFile,
2775
+ endpoints: pass.endpoints,
2776
+ responseKinds: new Map([...pass.handlerEndpoints].filter((entry) => entry[1] === "text" || entry[1] === "blob")),
2777
+ doc,
2778
+ files,
2779
+ modelsDir,
2780
+ outputFile,
2781
+ exportName: msw.exportName ?? `${api.stem}Mocks`,
2782
+ modelMocks: msw.modelMocks,
2783
+ esm
2784
+ }));
2785
+ logger.info(` MSW handlers of ${pass.endpoints.length} operation(s) (${path11.basename(outputFile)})`);
2786
+ }
2430
2787
  const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
2431
2788
  const enhanced = buildEnhancedEndpoints({
2432
2789
  stem: api.stem,
@@ -2442,8 +2799,8 @@ ${withHandlers}` : withHandlers;
2442
2799
  invalidation: api.invalidation,
2443
2800
  logger
2444
2801
  });
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));
2802
+ files.set(path11.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);
2803
+ files.set(path11.join(api.outputDir, `${api.stem}Tags.ts`), renderTagsFile(api.stem, enhanced.tagTypes));
2447
2804
  }
2448
2805
  } finally {
2449
2806
  fs9.rmSync(specDir, { recursive: true, force: true });
@@ -2457,7 +2814,7 @@ ${withHandlers}` : withHandlers;
2457
2814
  if (!options.skipTsc) {
2458
2815
  logger.info("type check (tsc --noEmit)");
2459
2816
  try {
2460
- typechecked = typecheck(loaded.rootDir, path10.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
2817
+ typechecked = typecheck(loaded.rootDir, path11.resolve(loaded.rootDir, loaded.config.tsconfig ?? "tsconfig.json"), logger);
2461
2818
  } catch (error) {
2462
2819
  committed.rollback();
2463
2820
  logger.error("type check failed \u2014 previous output restored");
@@ -2474,7 +2831,7 @@ import { spawnSync } from "child_process";
2474
2831
  import { createHash } from "crypto";
2475
2832
  import * as fs10 from "fs";
2476
2833
  import * as os3 from "os";
2477
- import * as path11 from "path";
2834
+ import * as path12 from "path";
2478
2835
  var PRIMARY_SKILLS_DIRECTORY = ".claude/skills";
2479
2836
  var MIRROR_SKILLS_DIRECTORIES = [".agents/skills", ".codex/skills"];
2480
2837
  var SKILLS_MANIFEST_FILE_NAME = ".ddd-skills.json";
@@ -2498,14 +2855,14 @@ var prefixedConsoleLogger = {
2498
2855
  };
2499
2856
  var label = (text) => text.padEnd(13);
2500
2857
  function findSkillsRepositoryRoot(startDirectory) {
2501
- const start = realpathOr(path11.resolve(startDirectory));
2858
+ const start = realpathOr(path12.resolve(startDirectory));
2502
2859
  const home = realpathOr(os3.homedir());
2503
2860
  for (const marker of [".git", ".claude"]) {
2504
2861
  let directory = start;
2505
2862
  for (; ; ) {
2506
2863
  const isHomeClaude = marker === ".claude" && directory === home;
2507
- if (!isHomeClaude && lstatOrNull(path11.join(directory, marker))) return directory;
2508
- const parent = path11.dirname(directory);
2864
+ if (!isHomeClaude && lstatOrNull(path12.join(directory, marker))) return directory;
2865
+ const parent = path12.dirname(directory);
2509
2866
  if (parent === directory) break;
2510
2867
  directory = parent;
2511
2868
  }
@@ -2514,9 +2871,9 @@ function findSkillsRepositoryRoot(startDirectory) {
2514
2871
  }
2515
2872
  function runSkillLinks(options = {}) {
2516
2873
  const logger = options.logger ?? prefixedConsoleLogger;
2517
- const cwd = path11.resolve(options.cwd ?? process.cwd());
2874
+ const cwd = path12.resolve(options.cwd ?? process.cwd());
2518
2875
  const envRoot = process.env[SKILLS_ROOT_ENV];
2519
- const requestedRoot = options.root ? path11.resolve(cwd, options.root) : envRoot ? path11.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
2876
+ const requestedRoot = options.root ? path12.resolve(cwd, options.root) : envRoot ? path12.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
2520
2877
  const linker = new SkillLinker(requestedRoot, options, logger);
2521
2878
  return linker.run();
2522
2879
  }
@@ -2688,7 +3045,7 @@ var SkillLinker = class {
2688
3045
  const mirrorLogical = `${this.root}/${mirrorName}`;
2689
3046
  if (getEntryType(mirrorLogical) === "missing" || !isDirectory(mirrorLogical)) continue;
2690
3047
  const mirror = realpathOr(mirrorLogical);
2691
- const mirrorParent = realpathOr(path11.dirname(mirrorLogical));
3048
+ const mirrorParent = realpathOr(path12.dirname(mirrorLogical));
2692
3049
  if (mirror === primary || mirrorParent === primary) continue;
2693
3050
  mirrorGitignoreNames.set(mirror, []);
2694
3051
  for (const skillName of managedNames) {
@@ -2731,17 +3088,17 @@ var SkillLinker = class {
2731
3088
  }
2732
3089
  }
2733
3090
  }
2734
- const manifestPath = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
3091
+ const manifestPath2 = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
2735
3092
  const manifestContent = encodeManifest(managedNames, managed);
2736
- if ((isFile(manifestPath) ? fs10.readFileSync(manifestPath, "utf-8") : null) !== manifestContent) {
2737
- operations.push({ kind: "write", path: manifestPath, content: manifestContent, display: `${PRIMARY_SKILLS_DIRECTORY}/${SKILLS_MANIFEST_FILE_NAME}` });
3093
+ if ((isFile(manifestPath2) ? fs10.readFileSync(manifestPath2, "utf-8") : null) !== manifestContent) {
3094
+ operations.push({ kind: "write", path: manifestPath2, content: manifestContent, display: `${PRIMARY_SKILLS_DIRECTORY}/${SKILLS_MANIFEST_FILE_NAME}` });
2738
3095
  }
2739
3096
  const primaryGitignoreEntries = [`/${SKILLS_MANIFEST_FILE_NAME}`];
2740
3097
  for (const skillName of managedNames) {
2741
3098
  primaryGitignoreEntries.push(`/${skillName}`);
2742
3099
  gitPaths.push(`${primary}/${skillName}`);
2743
3100
  }
2744
- gitPaths.push(manifestPath);
3101
+ gitPaths.push(manifestPath2);
2745
3102
  const gitignoreTargets = /* @__PURE__ */ new Map([[primary, primaryGitignoreEntries]]);
2746
3103
  for (const [mirror, names] of mirrorGitignoreNames) {
2747
3104
  gitignoreTargets.set(mirror, [...names].sort(compareBytes).map((name) => `/${name}`));
@@ -2800,8 +3157,8 @@ var SkillLinker = class {
2800
3157
  return { winners, warnings };
2801
3158
  }
2802
3159
  legacySourcePackage(sourceDir) {
2803
- const skillsDirectory = path11.resolve(path11.resolve(this.options.cwd ?? process.cwd()), sourceDir);
2804
- const packageJson = readJson(path11.join(skillsDirectory, "..", "..", "package.json"));
3160
+ const skillsDirectory = path12.resolve(path12.resolve(this.options.cwd ?? process.cwd()), sourceDir);
3161
+ const packageJson = readJson(path12.join(skillsDirectory, "..", "..", "package.json"));
2805
3162
  return {
2806
3163
  package: typeof packageJson?.name === "string" ? packageJson.name : "@mgamadeus/ddd-web",
2807
3164
  version: typeof packageJson?.version === "string" ? packageJson.version : null,
@@ -2889,9 +3246,9 @@ var SkillLinker = class {
2889
3246
  this.logger[level](line);
2890
3247
  }
2891
3248
  };
2892
- function readManifestEntries(manifestPath) {
2893
- if (!isFile(manifestPath)) return {};
2894
- const manifest = readJson(manifestPath);
3249
+ function readManifestEntries(manifestPath2) {
3250
+ if (!isFile(manifestPath2)) return {};
3251
+ const manifest = readJson(manifestPath2);
2895
3252
  if (!manifest || typeof manifest.skills !== "object" || manifest.skills === null || Array.isArray(manifest.skills)) return null;
2896
3253
  return manifest.skills;
2897
3254
  }
@@ -3001,10 +3358,10 @@ function isDddVendorPath(candidate) {
3001
3358
  return withSlash.includes("/vendor/mgamadeus/") || withSlash.includes("/node_modules/@mgamadeus/");
3002
3359
  }
3003
3360
  function resolveLinkTarget(linkDirectory, target) {
3004
- return path11.posix.resolve(linkDirectory, target);
3361
+ return path12.posix.resolve(linkDirectory, target);
3005
3362
  }
3006
3363
  function relativePath(fromDirectory, toPath) {
3007
- return path11.posix.relative(fromDirectory, toPath) || ".";
3364
+ return path12.posix.relative(fromDirectory, toPath) || ".";
3008
3365
  }
3009
3366
  function quoteShellArgument(argument) {
3010
3367
  return /^[A-Za-z0-9._/@+=:-]+$/.test(argument) ? argument : `'${argument.replace(/'/g, "'\\''")}'`;
@@ -3027,4 +3384,4 @@ export {
3027
3384
  runSkillLinks,
3028
3385
  linkSkills
3029
3386
  };
3030
- //# sourceMappingURL=chunk-AGECBV52.js.map
3387
+ //# sourceMappingURL=chunk-HSPGT4KA.js.map