@mgamadeus/ddd-web 0.9.0 → 0.10.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.
@@ -50,6 +50,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
50
50
  | `invalidation` | `(operation: InvalidationOperation) => InvalidationTag[] \| undefined`: overrides the tags a mutation invalidates; `undefined` keeps the default. `broadInvalidation` (exported) restores the 0.2 behaviour. See section 3. |
51
51
  | `workspace` | `{ envVar, envFiles?, urlKeys?, prompt? }`: resolves a workspace / subdomain value (CLI `--workspace` → env → URL sniffed from `.env` / `.env.local` → TTY prompt) into `process.env[envVar]` before the config is evaluated again. |
52
52
  | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
53
+ | `endpoints` | How endpoints and their body argument are named; off by default. `naming: 'path'`: a pure function of verb and path — `stripPathPrefix` (default `/api` or `/app/api`) cut, every `{param}/` cut out and only the LAST one kept, the rest split on `/ _ - .` and capitalised behind the verb, `By<LastInner>` appended, a trailing `{param}` becomes `By<Param>` where it stands (`POST /api/client/ai/conversations/{locationId}/purposed/{purposeName}` → `postClientAiConversationsPurposedByPurposeNameByLocationId`; `buildEndpointNameFromPath` is exported). `naming` may be a function `({ method, path, operation }) => name`. Two operations with one name stop the run. `bodyArg: 'requestBody'`: the body is the argument's `requestBody`, whatever its DTO is called. Query and path parameters stay flat in the argument. |
53
54
  | `models` | How the models of the component schemas are written; every option off by default. `naming: 'document'`: the model is named by the schema name's last dot segment exactly (`AIConversationMessage`, not `AiConversationMessage`), the segments before it are its folders — a neighbour namespace that prefixes the name never splits it. `enums: 'const'` (needs `naming: 'document'`): an enum property becomes `export const <Model><Property> = {…}` and `<Model><Property>Strict = {…} as const` in the model's file, the property typed `(typeof XStrict)[keyof typeof XStrict]` (`\| null` when nullable; `Array<…>` for an enum of array items); keys are the values with spaces, `/`, `\` as `_`, `""` as `EMPTY`. `nullableRefs: true`: `\| null` beside a nullable `$ref`. `idType: 'number' \| 'string'`: an `id` declared `string \| integer` gets that type. |
54
55
 
55
56
  ```ts
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Added
6
+ - Codegen option `endpoints` (off by default, output unchanged without it):
7
+ - `naming: 'path'`: endpoint (and hook) names as a pure function of verb and path — the prefix
8
+ (`stripPathPrefix`, default `/api` or `/app/api`) cut, every `{param}/` cut out and only the last one kept, the
9
+ rest capitalised behind the verb, `By<LastInner>` appended, a trailing `{param}` as `By<Param>` where it stands;
10
+ `naming` may also be a function. Two operations with the same name stop the run. `buildEndpointNameFromPath` is
11
+ exported.
12
+ - `bodyArg: 'requestBody'`: the request body is the argument's `requestBody`, independent of the DTO's schema
13
+ name.
14
+
3
15
  ## 0.9.0
4
16
 
5
17
  ### Added
@@ -476,6 +476,58 @@ function buildEnhancedEndpoints(input) {
476
476
  return { source, tagTypes: [...allTags].sort() };
477
477
  }
478
478
 
479
+ // src/codegen/document-endpoints.ts
480
+ var REQUEST_BODY_ARG = "requestBody";
481
+ var DEFAULT_STRIP_PATH_PREFIX = /^\/(?:app\/)?api(?=\/)/;
482
+ var upperFirst = (value) => value.charAt(0).toUpperCase() + value.slice(1);
483
+ function buildEndpointNameFromPath(method, path11, stripPathPrefix = DEFAULT_STRIP_PATH_PREFIX) {
484
+ const stripped = typeof stripPathPrefix === "string" ? path11.startsWith(stripPathPrefix) ? path11.slice(stripPathPrefix.length) : path11 : path11.replace(stripPathPrefix, "");
485
+ let lastInnerParameter = null;
486
+ const withoutInnerParameters = stripped.replace(/\{([^}]+)\}\//g, (_, parameter) => {
487
+ lastInnerParameter = parameter;
488
+ return "";
489
+ });
490
+ const pieces = withoutInnerParameters.split(/[/_.-]/).filter((piece) => piece !== "").map(upperFirst).join("");
491
+ const name = `${method.toLowerCase()}${pieces}${lastInnerParameter ? `By${upperFirst(lastInnerParameter)}` : ""}`;
492
+ return name.replace(/\{([^}]+)\}/g, (_, parameter) => `By${upperFirst(parameter)}`);
493
+ }
494
+ function prepareDocumentForEndpoints(doc, options) {
495
+ const naming = options.naming ?? "rtk";
496
+ const bodyArg = options.bodyArg ?? "rtk";
497
+ if (naming === "rtk" && bodyArg === "rtk") return doc;
498
+ const prepared = structuredClone(doc);
499
+ const pathByName = /* @__PURE__ */ new Map();
500
+ for (const [path11, item] of Object.entries(prepared.paths ?? {})) {
501
+ if (!item) continue;
502
+ for (const method of HTTP_METHODS) {
503
+ const operation = item[method];
504
+ if (!operation) continue;
505
+ if (naming !== "rtk") {
506
+ const name = naming === "path" ? buildEndpointNameFromPath(method, path11, options.stripPathPrefix) : naming({ method, path: path11, operation });
507
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
508
+ throw new SdkGenerationError(`endpoints.naming: "${name}" (${method.toUpperCase()} ${path11}) is no identifier.`);
509
+ }
510
+ const other = pathByName.get(name);
511
+ if (other !== void 0) {
512
+ throw new SdkGenerationError(`endpoints.naming: ${other} and ${method.toUpperCase()} ${path11} are both named "${name}".`);
513
+ }
514
+ pathByName.set(name, `${method.toUpperCase()} ${path11}`);
515
+ operation.operationId = name;
516
+ }
517
+ if (bodyArg === REQUEST_BODY_ARG) titleRequestBody(operation);
518
+ }
519
+ }
520
+ return prepared;
521
+ }
522
+ function titleRequestBody(operation) {
523
+ const content = operation.requestBody?.content;
524
+ for (const media of Object.values(content ?? {})) {
525
+ const schema = media?.schema;
526
+ if (!schema) continue;
527
+ media.schema = typeof schema.$ref === "string" ? { title: REQUEST_BODY_ARG, allOf: [{ $ref: schema.$ref }] } : { ...schema, title: REQUEST_BODY_ARG };
528
+ }
529
+ }
530
+
479
531
  // src/codegen/spec.ts
480
532
  import * as fs2 from "fs";
481
533
  var SUPPORTED_CONTRACT = { min: 1, max: 1 };
@@ -1925,7 +1977,8 @@ async function generateSdk(options = {}) {
1925
1977
  if (index.skippedTwins.size > 0) logger.info(` skipping ${index.skippedTwins.size} POST twin(s) of PATCH upserts`);
1926
1978
  const modelOptions = loaded.config.models ?? {};
1927
1979
  const prepared = prepareDocumentForModels(doc, modelOptions);
1928
- const rtk = await runRtkCodegen(api, prepared.doc, index, path9.join(specDir, `${i}.json`), prettierConfigFile);
1980
+ const rtkDoc = prepareDocumentForEndpoints(prepared.doc, loaded.config.endpoints ?? {});
1981
+ const rtk = await runRtkCodegen(api, rtkDoc, index, path9.join(specDir, `${i}.json`), prettierConfigFile);
1929
1982
  const endpoints = parseApiEndpoints(rtk.code, logger, rtk.locations);
1930
1983
  const handlerEndpoints = detectResponseHandlerEndpoints(doc, endpoints, api.responseHandlers);
1931
1984
  const responseKinds = /* @__PURE__ */ new Map();
@@ -2059,10 +2112,11 @@ export {
2059
2112
  silentLogger,
2060
2113
  SdkGenerationError,
2061
2114
  broadInvalidation,
2115
+ buildEndpointNameFromPath,
2062
2116
  SUPPORTED_CONTRACT,
2063
2117
  loadSpec,
2064
2118
  validateSpec,
2065
2119
  generateSdk,
2066
2120
  linkSkills
2067
2121
  };
2068
- //# sourceMappingURL=chunk-TPFRUK5O.js.map
2122
+ //# sourceMappingURL=chunk-PZ6AAETR.js.map