@mgamadeus/ddd-web 0.2.2 → 0.3.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 +8 -5
- package/.claude/skills/ddd-web-specialist/references/consumer.md +39 -4
- package/CHANGELOG.md +35 -0
- package/README.md +23 -1
- package/dist/{chunk-OL742YG5.js → chunk-VJ2CHVSL.js} +295 -87
- package/dist/chunk-VJ2CHVSL.js.map +1 -0
- package/dist/codegen/cli.js +1 -1
- package/dist/codegen/index.d.ts +66 -3
- package/dist/codegen/index.js +3 -1
- package/dist/contract/index.d.ts +1 -1
- package/dist/contract/index.js.map +1 -1
- package/dist/{extensions-DToc6G5E.d.ts → extensions-CmINl0EY.d.ts} +4 -1
- package/dist/query/index.d.ts +2 -2
- package/package.json +1 -1
- package/dist/chunk-OL742YG5.js.map +0 -1
|
@@ -50,7 +50,10 @@ function resolveApis(loaded) {
|
|
|
50
50
|
outputDir: path.dirname(outputFile),
|
|
51
51
|
skipUpdatePostTwins: entry.skipUpdatePostTwins ?? config.skipUpdatePostTwins ?? false,
|
|
52
52
|
sideEffects: [...entry.sideEffects ?? [], ...config.sideEffects ?? []],
|
|
53
|
-
responseHandlers: [...entry.responseHandlers ?? [], ...config.responseHandlers ?? []]
|
|
53
|
+
responseHandlers: [...entry.responseHandlers ?? [], ...config.responseHandlers ?? []],
|
|
54
|
+
invalidation: [entry.invalidation, config.invalidation].filter(
|
|
55
|
+
(resolver) => typeof resolver === "function"
|
|
56
|
+
)
|
|
54
57
|
};
|
|
55
58
|
});
|
|
56
59
|
}
|
|
@@ -89,63 +92,6 @@ var SdkGenerationError = class extends Error {
|
|
|
89
92
|
name = "SdkGenerationError";
|
|
90
93
|
};
|
|
91
94
|
|
|
92
|
-
// src/codegen/spec.ts
|
|
93
|
-
import * as fs2 from "fs";
|
|
94
|
-
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
95
|
-
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
96
|
-
async function loadSpec(source, timeoutMs = 6e4) {
|
|
97
|
-
let text;
|
|
98
|
-
if (isUrl(source)) {
|
|
99
|
-
let response;
|
|
100
|
-
try {
|
|
101
|
-
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
102
|
-
} catch (error) {
|
|
103
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
104
|
-
}
|
|
105
|
-
if (!response.ok) {
|
|
106
|
-
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
107
|
-
}
|
|
108
|
-
text = await response.text();
|
|
109
|
-
} else {
|
|
110
|
-
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
111
|
-
text = fs2.readFileSync(source, "utf-8");
|
|
112
|
-
}
|
|
113
|
-
let parsed;
|
|
114
|
-
try {
|
|
115
|
-
parsed = JSON.parse(text);
|
|
116
|
-
} catch (error) {
|
|
117
|
-
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
118
|
-
}
|
|
119
|
-
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
120
|
-
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
121
|
-
}
|
|
122
|
-
return parsed;
|
|
123
|
-
}
|
|
124
|
-
function validateSpec(doc, source, logger) {
|
|
125
|
-
const contract = doc.info?.["x-ddd-contract"];
|
|
126
|
-
if (contract === void 0) {
|
|
127
|
-
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
128
|
-
} else {
|
|
129
|
-
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
130
|
-
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
131
|
-
throw new SdkGenerationError(
|
|
132
|
-
`${source}: DDD contract ${JSON.stringify(number ?? contract)} is not supported by this @mgamadeus/ddd-web (supported: ${SUPPORTED_CONTRACT.min}\u2013${SUPPORTED_CONTRACT.max}). Update @mgamadeus/ddd-web or the backend.`
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));
|
|
137
|
-
if (!hasSchemaTags) {
|
|
138
|
-
throw new SdkGenerationError(
|
|
139
|
-
`${source}: no <SchemaDefinition schemaRef="\u2026"/> markup in tags[].description. The codegen needs it to place models into namespace folders \u2014 fetch the spec without removeSchemaTags=1.`
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// src/codegen/generate.ts
|
|
145
|
-
import * as fs8 from "fs";
|
|
146
|
-
import * as os from "os";
|
|
147
|
-
import * as path8 from "path";
|
|
148
|
-
|
|
149
95
|
// src/codegen/openapi.ts
|
|
150
96
|
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
151
97
|
function listOperations(doc) {
|
|
@@ -240,39 +186,195 @@ function isPrimaryEntityPath(path10, tag) {
|
|
|
240
186
|
return last !== void 0 && segmentToPascal(last).toLowerCase() === tag.toLowerCase();
|
|
241
187
|
}
|
|
242
188
|
var list = (tag) => `{ type: '${tag}' as const, id: 'LIST' }`;
|
|
243
|
-
var broad = (tag) => `{ type: '${tag}' as const }`;
|
|
244
189
|
var byArg = (tag, accessor) => `{ type: '${tag}' as const, id: ${accessor} }`;
|
|
245
190
|
var withArg = (items) => `(_result: unknown, _error: unknown, arg: any) => [${items}]`;
|
|
246
|
-
function
|
|
191
|
+
function entityProvidesExpression(endpoint, info, tag) {
|
|
247
192
|
const identity = info.entity?.identity?.startsWith("path:") ? info.entity.identity.slice("path:".length) : null;
|
|
248
193
|
const pathIdentity = identity ? endpoint.pathArgs[identity] ?? null : null;
|
|
249
|
-
if (
|
|
250
|
-
|
|
251
|
-
return { key: "providesTags", line: withArg(byArg(tag, pathIdentity)) };
|
|
252
|
-
}
|
|
253
|
-
return { key: "providesTags", line: `[${list(tag)}]` };
|
|
254
|
-
}
|
|
255
|
-
if (pathIdentity && (info.entity?.action === "upsert" || info.entity?.action === "delete")) {
|
|
256
|
-
return { key: "invalidatesTags", line: withArg(`${byArg(tag, pathIdentity)}, ${list(tag)}`) };
|
|
194
|
+
if (pathIdentity && info.entity?.action !== "list") {
|
|
195
|
+
return { key: "providesTags", line: withArg(byArg(tag, pathIdentity)) };
|
|
257
196
|
}
|
|
258
|
-
return { key: "
|
|
197
|
+
return { key: "providesTags", line: `[${list(tag)}]` };
|
|
259
198
|
}
|
|
260
|
-
function
|
|
199
|
+
function heuristicProvidesExpression(endpoint, tag) {
|
|
261
200
|
const trailing = trailingPlaceholder(endpoint.path);
|
|
262
201
|
const single = trailing !== null && isPrimaryEntityPath(endpoint.path, tag) ? endpoint.pathArgs[trailing] ?? null : null;
|
|
263
|
-
|
|
264
|
-
|
|
202
|
+
return single ? { key: "providesTags", line: withArg(byArg(tag, single)) } : { key: "providesTags", line: `[${list(tag)}]` };
|
|
203
|
+
}
|
|
204
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
205
|
+
var DOTTED_PATH = /^([A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*)?$/;
|
|
206
|
+
function relativeAccessor(accessor) {
|
|
207
|
+
if (accessor === "arg") return "";
|
|
208
|
+
return accessor.startsWith("arg.") && DOTTED_PATH.test(accessor.slice(4)) ? accessor.slice(4) : null;
|
|
209
|
+
}
|
|
210
|
+
function joinPath(base, rest) {
|
|
211
|
+
return [base, rest].filter(Boolean).join(".");
|
|
212
|
+
}
|
|
213
|
+
var listTag = (type) => ({ type, id: "LIST" });
|
|
214
|
+
var argTag = (type, arg) => ({ type, arg });
|
|
215
|
+
function singularForms(tag) {
|
|
216
|
+
const lower = tag.toLowerCase();
|
|
217
|
+
const forms = /* @__PURE__ */ new Set([lower]);
|
|
218
|
+
if (lower.endsWith("ies")) forms.add(`${lower.slice(0, -3)}y`);
|
|
219
|
+
if (lower.endsWith("es")) forms.add(lower.slice(0, -2));
|
|
220
|
+
if (lower.endsWith("s")) forms.add(lower.slice(0, -1));
|
|
221
|
+
return [...forms];
|
|
222
|
+
}
|
|
223
|
+
function identityPathParameter(path10, tag) {
|
|
224
|
+
const singulars = singularForms(tag);
|
|
225
|
+
const segments = path10.split("/").filter(Boolean);
|
|
226
|
+
let found = null;
|
|
227
|
+
segments.forEach((segment, index) => {
|
|
228
|
+
const name = segment.match(/^\{([^}]+)\}$/)?.[1];
|
|
229
|
+
if (!name) return;
|
|
230
|
+
const idMatch = name.match(/^(.+?)(Id|ID|_id)$/);
|
|
231
|
+
if (idMatch && singulars.includes(idMatch[1].toLowerCase())) {
|
|
232
|
+
found = name;
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const previous = segments[index - 1];
|
|
236
|
+
const namesOtherEntity = idMatch !== null;
|
|
237
|
+
if (!namesOtherEntity && previous && !previous.startsWith("{") && segmentToPascal(previous).toLowerCase() === tag.toLowerCase()) {
|
|
238
|
+
found = name;
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
return found;
|
|
242
|
+
}
|
|
243
|
+
var SCHEMA_PREFIX = "#/components/schemas/";
|
|
244
|
+
function referencedName(schema) {
|
|
245
|
+
if (!schema) return null;
|
|
246
|
+
if (typeof schema.$ref === "string" && schema.$ref.startsWith(SCHEMA_PREFIX)) return schema.$ref.slice(SCHEMA_PREFIX.length);
|
|
247
|
+
for (const key of ["allOf", "oneOf", "anyOf"]) {
|
|
248
|
+
const members = (schema[key] ?? []).filter((member) => member && !member.type?.includes("null"));
|
|
249
|
+
if (members.length === 1) return referencedName(members[0]);
|
|
265
250
|
}
|
|
266
|
-
return
|
|
251
|
+
return null;
|
|
267
252
|
}
|
|
253
|
+
function schemaByName(doc, name) {
|
|
254
|
+
return doc.components?.schemas?.[name];
|
|
255
|
+
}
|
|
256
|
+
function requestBodySchema(doc, operation) {
|
|
257
|
+
let body = operation.requestBody;
|
|
258
|
+
if (body?.$ref?.startsWith("#/components/requestBodies/")) {
|
|
259
|
+
body = doc.components?.requestBodies?.[body.$ref.slice("#/components/requestBodies/".length)];
|
|
260
|
+
}
|
|
261
|
+
for (const media of Object.values(body?.content ?? {})) {
|
|
262
|
+
if (media?.schema) return media.schema;
|
|
263
|
+
}
|
|
264
|
+
return void 0;
|
|
265
|
+
}
|
|
266
|
+
function identityBodyPath(doc, operation, tag, lookup) {
|
|
267
|
+
const schema = requestBodySchema(doc, operation);
|
|
268
|
+
if (!schema) return null;
|
|
269
|
+
const isTag = (name) => entityTag(name, lookup).toLowerCase() === tag.toLowerCase();
|
|
270
|
+
const hasId = (name) => !!schemaByName(doc, name)?.properties?.id;
|
|
271
|
+
const bodyName = referencedName(schema);
|
|
272
|
+
if (bodyName && isTag(bodyName) && hasId(bodyName)) return "id";
|
|
273
|
+
const resolved = bodyName ? schemaByName(doc, bodyName) : schema;
|
|
274
|
+
let references = 0;
|
|
275
|
+
let candidate = null;
|
|
276
|
+
for (const [property, propertySchema] of Object.entries(resolved?.properties ?? {})) {
|
|
277
|
+
const single = referencedName(propertySchema);
|
|
278
|
+
const element = single ? null : referencedName(propertySchema?.items);
|
|
279
|
+
const name = single ?? element;
|
|
280
|
+
if (!name || !isTag(name)) continue;
|
|
281
|
+
references++;
|
|
282
|
+
if (single && hasId(single) && IDENTIFIER.test(property)) candidate = property;
|
|
283
|
+
}
|
|
284
|
+
return references === 1 && candidate ? `${candidate}.id` : null;
|
|
285
|
+
}
|
|
286
|
+
function entityInvalidation(endpoint, info, tag) {
|
|
287
|
+
const action = info.entity?.action;
|
|
288
|
+
const identity = info.entity?.identity ?? "";
|
|
289
|
+
if (action === "upsert" || action === "delete") {
|
|
290
|
+
if (identity.startsWith("path:")) {
|
|
291
|
+
const accessor = endpoint.pathArgs[identity.slice("path:".length)];
|
|
292
|
+
const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
293
|
+
if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
|
|
294
|
+
}
|
|
295
|
+
if (identity.startsWith("body:") && endpoint.bodyArg !== void 0) {
|
|
296
|
+
const body = relativeAccessor(endpoint.bodyArg);
|
|
297
|
+
const inner = identity.slice("body:".length);
|
|
298
|
+
if (body !== null && DOTTED_PATH.test(inner)) return [listTag(tag), argTag(tag, joinPath(body, inner))];
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return [listTag(tag), tag];
|
|
302
|
+
}
|
|
303
|
+
function heuristicInvalidation(endpoint, info, tag, doc, lookup) {
|
|
304
|
+
const parameter = identityPathParameter(endpoint.path, tag);
|
|
305
|
+
const accessor = parameter ? endpoint.pathArgs[parameter] : void 0;
|
|
306
|
+
const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
|
|
307
|
+
if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
|
|
308
|
+
if (info && endpoint.bodyArg !== void 0) {
|
|
309
|
+
const body = relativeAccessor(endpoint.bodyArg);
|
|
310
|
+
const inner = identityBodyPath(doc, info.operation, tag, lookup);
|
|
311
|
+
if (body !== null && inner) return [listTag(tag), argTag(tag, joinPath(body, inner))];
|
|
312
|
+
}
|
|
313
|
+
return [listTag(tag), tag];
|
|
314
|
+
}
|
|
315
|
+
function quote(value) {
|
|
316
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
317
|
+
}
|
|
318
|
+
function checkTags(tags, key) {
|
|
319
|
+
if (!Array.isArray(tags)) throw new SdkGenerationError(`invalidation for ${key} must return an array or undefined.`);
|
|
320
|
+
for (const tag of tags) {
|
|
321
|
+
const type = typeof tag === "string" ? tag : tag?.type;
|
|
322
|
+
if (typeof type !== "string" || type === "") {
|
|
323
|
+
throw new SdkGenerationError(`invalidation for ${key}: every tag needs a non-empty type (got ${JSON.stringify(tag)}).`);
|
|
324
|
+
}
|
|
325
|
+
if (typeof tag === "object") {
|
|
326
|
+
const candidate = tag;
|
|
327
|
+
const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
|
|
328
|
+
const hasArg = typeof candidate.arg === "string" && DOTTED_PATH.test(candidate.arg);
|
|
329
|
+
if (hasId === hasArg) {
|
|
330
|
+
throw new SdkGenerationError(
|
|
331
|
+
`invalidation for ${key}: tag ${JSON.stringify(tag)} needs either an id (string / number) or an arg (dotted path).`
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return tags;
|
|
337
|
+
}
|
|
338
|
+
var ID_HELPER = "tagWithId";
|
|
339
|
+
var ID_HELPER_SOURCE = [
|
|
340
|
+
"// `{ type, id }` only when the id is known: a tag with `id: undefined` would invalidate every entry of the type.",
|
|
341
|
+
`const ${ID_HELPER} = <T extends string>(type: T, id: unknown): Array<{ type: T; id: string | number }> =>`,
|
|
342
|
+
" typeof id === 'string' || typeof id === 'number' ? [{ type, id }] : [];"
|
|
343
|
+
];
|
|
344
|
+
function renderInvalidation(tags, endpoint) {
|
|
345
|
+
const pathArgs = new Set(Object.values(endpoint.pathArgs).map(relativeAccessor));
|
|
346
|
+
let readsArg = false;
|
|
347
|
+
const items = tags.map((tag) => {
|
|
348
|
+
if (typeof tag === "string") return `{ type: ${quote(tag)} as const }`;
|
|
349
|
+
if ("id" in tag) return `{ type: ${quote(tag.type)} as const, id: ${typeof tag.id === "number" ? tag.id : quote(tag.id)} }`;
|
|
350
|
+
readsArg = true;
|
|
351
|
+
if (pathArgs.has(tag.arg)) return `{ type: ${quote(tag.type)} as const, id: ${tag.arg === "" ? "arg" : `arg.${tag.arg}`} }`;
|
|
352
|
+
const optional = tag.arg === "" ? "arg" : `arg?.${tag.arg.split(".").join("?.")}`;
|
|
353
|
+
return `...${ID_HELPER}(${quote(tag.type)} as const, ${optional})`;
|
|
354
|
+
});
|
|
355
|
+
return readsArg ? withArg(items.join(", ")) : `[${items.join(", ")}]`;
|
|
356
|
+
}
|
|
357
|
+
function tagTypes(tags) {
|
|
358
|
+
return tags.map((tag) => typeof tag === "string" ? tag : tag.type);
|
|
359
|
+
}
|
|
360
|
+
var broadInvalidation = (operation) => {
|
|
361
|
+
if (!operation.tag || !operation.sideEffects) return void 0;
|
|
362
|
+
const entity = operation.entity;
|
|
363
|
+
if (entity?.identity?.startsWith("path:") && (entity.action === "upsert" || entity.action === "delete")) return void 0;
|
|
364
|
+
return [{ type: operation.tag, id: "LIST" }, operation.tag];
|
|
365
|
+
};
|
|
268
366
|
function buildEnhancedEndpoints(input) {
|
|
269
367
|
const { endpoints, index, audience, logger } = input;
|
|
368
|
+
const doc = input.doc ?? {};
|
|
369
|
+
const resolvers = input.invalidation ?? [];
|
|
270
370
|
const lookup = new Map(input.operationTags.map((tag) => [tag.toLowerCase(), tag]));
|
|
271
371
|
const allTags = new Set(input.operationTags);
|
|
272
372
|
const used = /* @__PURE__ */ new Set();
|
|
273
373
|
const lines = [];
|
|
274
374
|
let skipped = 0;
|
|
275
375
|
let urlFallbacks = 0;
|
|
376
|
+
let identities = 0;
|
|
377
|
+
let wholeType = 0;
|
|
276
378
|
for (const endpoint of endpoints) {
|
|
277
379
|
const info = index.byKey.get(operationKey(endpoint.method, endpoint.path));
|
|
278
380
|
let tag;
|
|
@@ -287,21 +389,59 @@ function buildEnhancedEndpoints(input) {
|
|
|
287
389
|
if (tag) urlFallbacks++;
|
|
288
390
|
}
|
|
289
391
|
}
|
|
290
|
-
|
|
392
|
+
let expression = null;
|
|
393
|
+
if (endpoint.buildType === "query") {
|
|
394
|
+
if (tag) expression = info?.entity ? entityProvidesExpression(endpoint, info, tag) : heuristicProvidesExpression(endpoint, tag);
|
|
395
|
+
} else {
|
|
396
|
+
let defaultTags = [];
|
|
397
|
+
if (tag && (!info || info.sideEffects)) {
|
|
398
|
+
defaultTags = info?.entity ? entityInvalidation(endpoint, info, tag) : heuristicInvalidation(endpoint, info, tag, doc, lookup);
|
|
399
|
+
}
|
|
400
|
+
let tags = defaultTags;
|
|
401
|
+
if (resolvers.length > 0) {
|
|
402
|
+
const operation = {
|
|
403
|
+
key: endpoint.key,
|
|
404
|
+
api: input.apiName ?? input.stem,
|
|
405
|
+
method: endpoint.method.toUpperCase(),
|
|
406
|
+
path: endpoint.path,
|
|
407
|
+
tag,
|
|
408
|
+
...info ? { operation: info.operation } : {},
|
|
409
|
+
...info?.entity ? { entity: info.entity } : {},
|
|
410
|
+
sideEffects: info?.sideEffects ?? true,
|
|
411
|
+
pathArgs: Object.fromEntries(
|
|
412
|
+
Object.entries(endpoint.pathArgs).flatMap(([name, accessor]) => {
|
|
413
|
+
const relative6 = relativeAccessor(accessor);
|
|
414
|
+
return relative6 === null ? [] : [[name, relative6]];
|
|
415
|
+
})
|
|
416
|
+
),
|
|
417
|
+
...endpoint.bodyArg !== void 0 && relativeAccessor(endpoint.bodyArg) !== null ? { bodyArg: relativeAccessor(endpoint.bodyArg) } : {},
|
|
418
|
+
defaultTags: defaultTags.map((entry) => typeof entry === "string" ? entry : { ...entry })
|
|
419
|
+
};
|
|
420
|
+
for (const resolver of resolvers) {
|
|
421
|
+
const result = resolver(operation);
|
|
422
|
+
if (result !== void 0) {
|
|
423
|
+
tags = checkTags(result, endpoint.key);
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (tag || tags.length > 0) {
|
|
429
|
+
expression = { key: "invalidatesTags", line: renderInvalidation(tags, endpoint) };
|
|
430
|
+
for (const type of tagTypes(tags)) {
|
|
431
|
+
used.add(type);
|
|
432
|
+
allTags.add(type);
|
|
433
|
+
}
|
|
434
|
+
if (tags.some((entry) => typeof entry !== "string" && "arg" in entry)) identities++;
|
|
435
|
+
else if (tags.some((entry) => typeof entry === "string")) wholeType++;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (!expression) {
|
|
291
439
|
logger.warn(`No tag for ${endpoint.key} (${endpoint.url}) \u2014 no cache tags generated.`);
|
|
292
440
|
skipped++;
|
|
293
441
|
continue;
|
|
294
442
|
}
|
|
295
|
-
let expression;
|
|
296
|
-
if (endpoint.buildType === "mutation" && info && !info.sideEffects) {
|
|
297
|
-
expression = { key: "invalidatesTags", line: "[]" };
|
|
298
|
-
} else if (info?.entity) {
|
|
299
|
-
expression = entityTagExpression(endpoint, info, tag);
|
|
300
|
-
} else {
|
|
301
|
-
expression = heuristicTagExpression(endpoint, tag);
|
|
302
|
-
}
|
|
303
443
|
lines.push(` ${endpoint.key}: {`, ` ${expression.key}: ${expression.line},`, " },");
|
|
304
|
-
used.add(tag);
|
|
444
|
+
if (tag) used.add(tag);
|
|
305
445
|
}
|
|
306
446
|
const varName = `${input.stem}Enhanced`;
|
|
307
447
|
const source = [
|
|
@@ -311,10 +451,11 @@ function buildEnhancedEndpoints(input) {
|
|
|
311
451
|
`import '${input.apiModuleImport}';`,
|
|
312
452
|
`import { ${input.baseApiName} } from '${input.baseApiImport}';`,
|
|
313
453
|
"",
|
|
454
|
+
...lines.some((line) => line.includes(`...${ID_HELPER}(`)) ? [...ID_HELPER_SOURCE, ""] : [],
|
|
314
455
|
"// enhanceEndpoints mutates the endpoint definitions in place: import this file once (e.g. in the store)",
|
|
315
456
|
`// and keep using the hooks from ${input.stem} \u2014 they pick up the tags.`,
|
|
316
457
|
`export const ${varName} = ${input.baseApiName}.enhanceEndpoints({`,
|
|
317
|
-
` addTagTypes: [${[...used].sort().map((tag) =>
|
|
458
|
+
` addTagTypes: [${[...used].sort().map((tag) => quote(tag)).join(", ")}],`,
|
|
318
459
|
" endpoints: {",
|
|
319
460
|
...lines,
|
|
320
461
|
" },",
|
|
@@ -322,11 +463,68 @@ function buildEnhancedEndpoints(input) {
|
|
|
322
463
|
""
|
|
323
464
|
].join("\n");
|
|
324
465
|
logger.info(
|
|
325
|
-
` enhanced ${endpoints.length - skipped} endpoints (${skipped} without tag, ${urlFallbacks} via URL fallback, ${used.size} tag types)`
|
|
466
|
+
` enhanced ${endpoints.length - skipped} endpoints (${skipped} without tag, ${urlFallbacks} via URL fallback, ${used.size} tag types; ${identities} writes by identity, ${wholeType} invalidate a whole tag type)`
|
|
326
467
|
);
|
|
327
468
|
return { source, tagTypes: [...allTags].sort() };
|
|
328
469
|
}
|
|
329
470
|
|
|
471
|
+
// src/codegen/spec.ts
|
|
472
|
+
import * as fs2 from "fs";
|
|
473
|
+
var SUPPORTED_CONTRACT = { min: 1, max: 1 };
|
|
474
|
+
var SCHEMA_DEFINITION_MARKUP = "<SchemaDefinition schemaRef=";
|
|
475
|
+
async function loadSpec(source, timeoutMs = 6e4) {
|
|
476
|
+
let text;
|
|
477
|
+
if (isUrl(source)) {
|
|
478
|
+
let response;
|
|
479
|
+
try {
|
|
480
|
+
response = await fetch(source, { signal: AbortSignal.timeout(timeoutMs) });
|
|
481
|
+
} catch (error) {
|
|
482
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: ${error.message}`);
|
|
483
|
+
}
|
|
484
|
+
if (!response.ok) {
|
|
485
|
+
throw new SdkGenerationError(`Could not fetch spec ${source}: HTTP ${response.status} ${response.statusText}`);
|
|
486
|
+
}
|
|
487
|
+
text = await response.text();
|
|
488
|
+
} else {
|
|
489
|
+
if (!fs2.existsSync(source)) throw new SdkGenerationError(`Spec file not found: ${source}`);
|
|
490
|
+
text = fs2.readFileSync(source, "utf-8");
|
|
491
|
+
}
|
|
492
|
+
let parsed;
|
|
493
|
+
try {
|
|
494
|
+
parsed = JSON.parse(text);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
throw new SdkGenerationError(`Spec ${source} is not valid JSON: ${error.message}`);
|
|
497
|
+
}
|
|
498
|
+
if (!parsed || typeof parsed !== "object" || !("paths" in parsed)) {
|
|
499
|
+
throw new SdkGenerationError(`Spec ${source} is not an OpenAPI document (no "paths").`);
|
|
500
|
+
}
|
|
501
|
+
return parsed;
|
|
502
|
+
}
|
|
503
|
+
function validateSpec(doc, source, logger) {
|
|
504
|
+
const contract = doc.info?.["x-ddd-contract"];
|
|
505
|
+
if (contract === void 0) {
|
|
506
|
+
logger.warn(`${source}: no info.x-ddd-contract \u2014 assuming a pre-contract DDD spec.`);
|
|
507
|
+
} else {
|
|
508
|
+
const number = typeof contract === "object" && contract ? contract.contract : void 0;
|
|
509
|
+
if (typeof number !== "number" || number < SUPPORTED_CONTRACT.min || number > SUPPORTED_CONTRACT.max) {
|
|
510
|
+
throw new SdkGenerationError(
|
|
511
|
+
`${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.`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
const hasSchemaTags = (doc.tags ?? []).some((tag) => tag.description?.includes(SCHEMA_DEFINITION_MARKUP));
|
|
516
|
+
if (!hasSchemaTags) {
|
|
517
|
+
throw new SdkGenerationError(
|
|
518
|
+
`${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.`
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// src/codegen/generate.ts
|
|
524
|
+
import * as fs8 from "fs";
|
|
525
|
+
import * as os from "os";
|
|
526
|
+
import * as path8 from "path";
|
|
527
|
+
|
|
330
528
|
// src/codegen/typescript.ts
|
|
331
529
|
import { createRequire } from "module";
|
|
332
530
|
var cached;
|
|
@@ -380,6 +578,7 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
380
578
|
let url;
|
|
381
579
|
let method;
|
|
382
580
|
let accessors = [];
|
|
581
|
+
let bodyArg;
|
|
383
582
|
for (const member of returned.properties) {
|
|
384
583
|
if (!ts.isPropertyAssignment(member) || !ts.isIdentifier(member.name)) continue;
|
|
385
584
|
const init = member.initializer;
|
|
@@ -391,6 +590,10 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
391
590
|
}
|
|
392
591
|
}
|
|
393
592
|
if (member.name.text === "method" && ts.isStringLiteral(init)) method = init.text;
|
|
593
|
+
if (member.name.text === "body" && (ts.isIdentifier(init) || ts.isPropertyAccessExpression(init))) {
|
|
594
|
+
const text = init.getText(sourceFile);
|
|
595
|
+
if (/^queryArg(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(text)) bodyArg = text.replace(/^queryArg\b/, "arg");
|
|
596
|
+
}
|
|
394
597
|
}
|
|
395
598
|
if (url === void 0) {
|
|
396
599
|
logger.warn(`No extractable URL for endpoint "${key}" \u2014 skipping.`);
|
|
@@ -410,6 +613,7 @@ function readEndpoint(ts, key, buildType, call, sourceFile, location, logger) {
|
|
|
410
613
|
method: (location?.method ?? method ?? "GET").toUpperCase(),
|
|
411
614
|
path: path10,
|
|
412
615
|
pathArgs,
|
|
616
|
+
...bodyArg ? { bodyArg } : {},
|
|
413
617
|
...responseType ? { responseType } : {}
|
|
414
618
|
};
|
|
415
619
|
}
|
|
@@ -1177,7 +1381,7 @@ import * as fs6 from "fs";
|
|
|
1177
1381
|
import * as path6 from "path";
|
|
1178
1382
|
import { generateEndpoints } from "@rtk-query/codegen-openapi";
|
|
1179
1383
|
import prettier2 from "prettier";
|
|
1180
|
-
var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers"]);
|
|
1384
|
+
var OWN_KEYS = /* @__PURE__ */ new Set(["schemaFile", "apiFile", "outputFile", "audience", "baseApiImport", "skipUpdatePostTwins", "sideEffects", "responseHandlers", "invalidation"]);
|
|
1181
1385
|
function matches(matcher, name, definition) {
|
|
1182
1386
|
if (matcher === void 0) return true;
|
|
1183
1387
|
if (typeof matcher === "function") return matcher(name, definition);
|
|
@@ -1408,13 +1612,16 @@ async function generateSdk(options = {}) {
|
|
|
1408
1612
|
const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
|
|
1409
1613
|
const enhanced = buildEnhancedEndpoints({
|
|
1410
1614
|
stem: api.stem,
|
|
1615
|
+
apiName: api.exportName,
|
|
1411
1616
|
apiModuleImport: withExtension(`./${api.stem}`),
|
|
1412
1617
|
baseApiImport: api.config.baseApiImport ?? withExtension(relativeImport(api.outputDir, api.apiFile).replace(/\.[cm]?[jt]sx?$/, "")),
|
|
1413
1618
|
baseApiName: api.config.apiImport ?? "api",
|
|
1414
1619
|
audience: api.audience,
|
|
1415
1620
|
endpoints,
|
|
1416
1621
|
index,
|
|
1622
|
+
doc,
|
|
1417
1623
|
operationTags: collectOperationTags(doc, api.audience),
|
|
1624
|
+
invalidation: api.invalidation,
|
|
1418
1625
|
logger
|
|
1419
1626
|
});
|
|
1420
1627
|
files.set(path8.join(api.outputDir, `${api.stem}Enhanced.ts`), enhanced.source);
|
|
@@ -1505,10 +1712,11 @@ export {
|
|
|
1505
1712
|
consoleLogger,
|
|
1506
1713
|
silentLogger,
|
|
1507
1714
|
SdkGenerationError,
|
|
1715
|
+
broadInvalidation,
|
|
1508
1716
|
SUPPORTED_CONTRACT,
|
|
1509
1717
|
loadSpec,
|
|
1510
1718
|
validateSpec,
|
|
1511
1719
|
generateSdk,
|
|
1512
1720
|
linkSkills
|
|
1513
1721
|
};
|
|
1514
|
-
//# sourceMappingURL=chunk-
|
|
1722
|
+
//# sourceMappingURL=chunk-VJ2CHVSL.js.map
|