@mgamadeus/ddd-web 0.3.1 → 0.5.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.
@@ -1219,6 +1219,136 @@ function writeBarrel(files, indexPath, newEntries) {
1219
1219
  `);
1220
1220
  }
1221
1221
 
1222
+ // src/codegen/multipart.ts
1223
+ var MULTIPART_FILES_ARG = "multipartFiles";
1224
+ var BODY_FIELD = "body";
1225
+ var FILE_PART_TYPE = "(Blob | { uri: string; name: string; type: string })";
1226
+ var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1227
+ function resolveRef(doc, value) {
1228
+ let current = value;
1229
+ for (let depth = 0; depth < 5 && isObject(current) && typeof current.$ref === "string"; depth++) {
1230
+ const segments = current.$ref.replace(/^#\//, "").split("/");
1231
+ let target = doc;
1232
+ for (const segment of segments) target = isObject(target) ? target[segment.replace(/~1/g, "/").replace(/~0/g, "~")] : void 0;
1233
+ current = target;
1234
+ }
1235
+ return isObject(current) ? current : void 0;
1236
+ }
1237
+ var isJsonMediaType = (type) => /(^|\/|\+)json$/.test(type.split(";")[0].trim().toLowerCase());
1238
+ function readMultipartOperation(doc, requestBody) {
1239
+ const content = resolveRef(doc, requestBody)?.content;
1240
+ if (!isObject(content)) return null;
1241
+ const multipartKey = Object.keys(content).find((type) => type.split(";")[0].trim().toLowerCase() === "multipart/form-data");
1242
+ if (!multipartKey || !isObject(content[multipartKey])) return null;
1243
+ const schema = resolveRef(doc, content[multipartKey].schema);
1244
+ const properties = isObject(schema?.properties) ? schema.properties : {};
1245
+ const fields = Object.keys(properties).filter((name) => name !== BODY_FIELD);
1246
+ if (fields.length === 0) return null;
1247
+ const requiredList = Array.isArray(schema?.required) ? schema.required.filter((name) => typeof name === "string") : [];
1248
+ return {
1249
+ fields,
1250
+ required: fields.filter((name) => requiredList.includes(name)),
1251
+ multipartOnly: !Object.keys(content).some(isJsonMediaType)
1252
+ };
1253
+ }
1254
+ function detectMultipartEndpoints(doc, endpoints) {
1255
+ const byOperation = /* @__PURE__ */ new Map();
1256
+ for (const { method, path: path10, operation } of listOperations(doc)) {
1257
+ const multipart = readMultipartOperation(doc, operation.requestBody);
1258
+ if (multipart) byOperation.set(operationKey(method, path10), multipart);
1259
+ }
1260
+ const keys = /* @__PURE__ */ new Map();
1261
+ if (byOperation.size === 0) return keys;
1262
+ for (const endpoint of endpoints) {
1263
+ const multipart = byOperation.get(operationKey(endpoint.method, endpoint.path));
1264
+ if (multipart) keys.set(endpoint.key, multipart);
1265
+ }
1266
+ return keys;
1267
+ }
1268
+ var quoteKey = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
1269
+ function filesMember(multipart) {
1270
+ const members = multipart.fields.map((field) => {
1271
+ const required2 = multipart.multipartOnly && multipart.required.includes(field);
1272
+ return `${quoteKey(field)}${required2 ? "" : "?"}: readonly ${FILE_PART_TYPE}[]${required2 ? "" : " | null"}`;
1273
+ }).join("; ");
1274
+ const required = multipart.multipartOnly && multipart.required.length > 0;
1275
+ const doc = multipart.multipartOnly ? "/** File parts of the multipart request. */" : "/** File parts: with at least one file the request is sent as multipart/form-data (JSON envelope in the field `body`), else as JSON. */";
1276
+ return `${doc}
1277
+ ${MULTIPART_FILES_ARG}${required ? "" : "?"}: { ${members} };`;
1278
+ }
1279
+ function injectMultipartBodies(source, endpoints, logger) {
1280
+ if (endpoints.size === 0) return { source, injected: [] };
1281
+ const ts = loadTypeScript();
1282
+ const file = ts.createSourceFile("api.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
1283
+ const typeAliases = /* @__PURE__ */ new Map();
1284
+ for (const statement of file.statements) if (ts.isTypeAliasDeclaration(statement)) typeAliases.set(statement.name.text, statement);
1285
+ const edits = [];
1286
+ const injected = [];
1287
+ const skip = (key, reason) => logger.warn(` ${key}: multipart body not generated (${reason}) \u2014 the endpoint sends JSON only.`);
1288
+ const visit = (node) => {
1289
+ if (ts.isPropertyAssignment(node)) {
1290
+ const key = propertyName(ts, node.name);
1291
+ const multipart = key === void 0 ? void 0 : endpoints.get(key);
1292
+ if (key !== void 0 && multipart && isBuildCall(ts, node.initializer)) {
1293
+ const call = node.initializer;
1294
+ const returned = queryReturnObject(ts, call);
1295
+ if (typeof returned === "string") return skip(key, returned);
1296
+ const definition = call.arguments[0];
1297
+ const query = definition.properties.find((property) => property.name !== void 0 && propertyName(ts, property.name) === "query");
1298
+ const fn = query && ts.isPropertyAssignment(query) ? query.initializer : void 0;
1299
+ const parameter = fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ? fn.parameters[0] : void 0;
1300
+ if (!parameter || !ts.isIdentifier(parameter.name)) return skip(key, "the endpoint takes no argument");
1301
+ const argName = parameter.name.text;
1302
+ const argTypeNode = call.typeArguments?.[1];
1303
+ const alias = argTypeNode && ts.isTypeReferenceNode(argTypeNode) && ts.isIdentifier(argTypeNode.typeName) ? typeAliases.get(argTypeNode.typeName.text) : void 0;
1304
+ if (!alias || !ts.isTypeLiteralNode(alias.type)) return skip(key, "its argument type is not an object type (flattenArg?)");
1305
+ const literal = alias.type;
1306
+ const memberName = (member) => member.name ? propertyName(ts, member.name) : void 0;
1307
+ if (literal.members.some((member) => memberName(member) === MULTIPART_FILES_ARG)) {
1308
+ return skip(key, `the argument already has a member "${MULTIPART_FILES_ARG}"`);
1309
+ }
1310
+ const body = returned.properties.find((property) => property.name !== void 0 && propertyName(ts, property.name) === "body");
1311
+ let jsonBody = "undefined";
1312
+ if (body) {
1313
+ if (!ts.isPropertyAssignment(body)) return skip(key, "unexpected `body` member");
1314
+ const text = body.initializer.getText(file);
1315
+ if (text === argName) return skip(key, "the argument is the request body itself (flattenArg)");
1316
+ if (multipart.multipartOnly) {
1317
+ const accessor = new RegExp(`^${argName}\\.([A-Za-z_$][A-Za-z0-9_$]*)$`).exec(text)?.[1];
1318
+ const member = accessor ? literal.members.find((candidate) => memberName(candidate) === accessor) : void 0;
1319
+ if (member) edits.push({ start: member.getFullStart(), end: member.getEnd(), text: "" });
1320
+ } else {
1321
+ jsonBody = text;
1322
+ }
1323
+ edits.push({
1324
+ start: body.initializer.getStart(file),
1325
+ end: body.initializer.getEnd(),
1326
+ text: `buildDddMultipartBody(${jsonBody}, ${argName}.${MULTIPART_FILES_ARG})`
1327
+ });
1328
+ } else {
1329
+ const close2 = returned.end - 1;
1330
+ const separator = returned.properties.length > 0 && !returned.properties.hasTrailingComma ? ", " : " ";
1331
+ edits.push({ start: close2, end: close2, text: `${separator}body: buildDddMultipartBody(undefined, ${argName}.${MULTIPART_FILES_ARG}) ` });
1332
+ }
1333
+ const close = literal.end - 1;
1334
+ edits.push({ start: close, end: close, text: `
1335
+ ${filesMember(multipart)}
1336
+ ` });
1337
+ injected.push(key);
1338
+ return;
1339
+ }
1340
+ }
1341
+ ts.forEachChild(node, visit);
1342
+ };
1343
+ visit(file);
1344
+ let result = source;
1345
+ for (const { start, end, text } of edits.sort((a, b) => b.start - a.start || b.end - a.end)) {
1346
+ result = result.slice(0, start) + text + result.slice(end);
1347
+ }
1348
+ return { source: result, injected };
1349
+ }
1350
+ var MULTIPART_IMPORT = `import { buildDddMultipartBody } from '${DDD_WEB_API_IMPORT}';`;
1351
+
1222
1352
  // src/codegen/output.ts
1223
1353
  import * as fs5 from "fs";
1224
1354
  import * as path5 from "path";
@@ -1596,9 +1726,11 @@ async function generateSdk(options = {}) {
1596
1726
  }
1597
1727
  const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
1598
1728
  if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
1729
+ const multipart = injectMultipartBodies(rtk.code, detectMultipartEndpoints(doc, endpoints), logger);
1730
+ if (multipart.injected.length > 0) logger.info(` ${multipart.injected.length} multipart endpoint(s) (multipartFiles)`);
1599
1731
  const esm = api.config.esmExtensions === true;
1600
1732
  const apiSource = extractModels({
1601
- apiSource: rtk.code,
1733
+ apiSource: multipart.source,
1602
1734
  apiFilePath: api.outputFile,
1603
1735
  modelsDir,
1604
1736
  registry,
@@ -1608,7 +1740,9 @@ async function generateSdk(options = {}) {
1608
1740
  responseKinds
1609
1741
  });
1610
1742
  if (!write) continue;
1611
- files.set(api.outputFile, injectResponseHandlers(apiSource, handlerEndpoints));
1743
+ const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints);
1744
+ files.set(api.outputFile, multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
1745
+ ${withHandlers}` : withHandlers);
1612
1746
  const withExtension = (specifier) => esm ? `${specifier}.js` : specifier;
1613
1747
  const enhanced = buildEnhancedEndpoints({
1614
1748
  stem: api.stem,
@@ -1719,4 +1853,4 @@ export {
1719
1853
  generateSdk,
1720
1854
  linkSkills
1721
1855
  };
1722
- //# sourceMappingURL=chunk-VJ2CHVSL.js.map
1856
+ //# sourceMappingURL=chunk-6PDXSGVW.js.map