@mgamadeus/ddd-web 0.18.0 → 0.19.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.
@@ -1,9 +1,9 @@
1
1
  ---
2
2
  name: ddd-web-specialist
3
- description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd: openapi-config.ts defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), ddd-web-sdk modes default, future and legacy (cache tags by entity identity, mergeDddTagTypes, blob downloads, multipartFiles uploads, progress via baseQuery.upload), QueryOptions builders, createDddBaseQuery (Bearer, shared refresh + retry, relogin, session-bound requests, normalizeDddError), token storage, JWT helpers, MooTools Request (dddFetchApiRequestPlugin), /issues reporting (browser, Node, React Native), link-skills (--check), release. Use when wiring a frontend to a DDD API, regenerating or switching SDK modes, building filters, uploading files, FormData, upload or download progress, fixing token refresh, guest login, a request sent under the wrong account after a switch, stale cache tags, downloading an export, requests failing in a legacy page, reporting errors to the issues log, linking skills, or releasing ddd-web."
3
+ description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd: openapi-config.ts defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), ddd-web-sdk modes default, future and legacy (MSW handlers, legacy prune, cache tags by entity identity, mergeDddTagTypes, blob downloads, multipartFiles uploads, progress via baseQuery.upload), QueryOptions, createDddBaseQuery (Bearer, shared refresh + retry, relogin, session-bound requests, normalizeDddError), token storage, JWT, MooTools Request, /issues reporting (browser, Node), link-skills (--check), release. Use when wiring a frontend to a DDD API, regenerating or switching SDK modes, MSW mocks for stories, pruning stale generated files, building filters, uploading files, FormData, upload or download progress, fixing token refresh, guest login, a request sent under the wrong account after a switch, stale cache tags, downloading an export, requests failing in a legacy page, reporting errors to the issues log, linking skills, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.7.0"
6
+ version: "1.8.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -92,6 +92,10 @@ for models and a promise client. Use `--mode legacy` with `swagger-sdk-generator
92
92
  models, stores, thunks, and mocks. Use `generator.mode` to select a mode in config.
93
93
  Opt-in output goes to `src/generated-sdk/<mode>/<api-stem>/` by default. See [references/consumer.md](references/consumer.md).
94
94
 
95
+ `mswHandlers: { modelMocks: { importPrefix } }` (default mode, off when absent) adds `<stem>Mocks.ts`: an MSW handler
96
+ factory per operation answering the response model's mock. `generateLegacySdk({ prune: true })` deletes files an
97
+ earlier legacy run wrote and this one no longer plans (manifest `.ddd-web-legacy-sdk.json`, never unlisted files).
98
+
95
99
  ## Rules
96
100
 
97
101
  - **Never edit generated files** (`<stem>.ts`, `<stem>Enhanced.ts`, `<stem>Tags.ts`, the models directory). Change the
@@ -36,6 +36,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
36
36
  | `sideEffects` | Overrides checked before the global ones (first match wins). |
37
37
  | `responseHandlers` | Overrides checked before the global ones (first match wins). |
38
38
  | `invalidation` | Resolver checked before the global one (see section 3). |
39
+ | `mswHandlers` | `false`: no MSW handlers for this api; an object turns them on for it and overrides the global fields: `outputFile` (default `<stem>Mocks.ts` next to the api file), `exportName` (default `<stem>Mocks`), `modelMocks`. |
39
40
  | `esmExtensions` | `true` for `moduleResolution: nodenext`: generated relative imports end in `.js`. |
40
41
  | `encodePathParams` | Default `true`: a path parameter is passed through `encodeURIComponent` in the generated URL — callers pass the raw value and never encode it themselves (it would be encoded twice). `false` restores the plain interpolation. |
41
42
  | any other key | Passed to RTK codegen (`argSuffix`, `flattenArg`, `endpointOverrides`, `filterEndpoints`, …). |
@@ -52,6 +53,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
52
53
  | `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. |
53
54
  | `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. |
54
55
  | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
56
+ | `mswHandlers` | `{ modelMocks?: { importPrefix, fileSuffix?, exportName? } }`: writes `<stem>Mocks.ts` (MSW v2 handler factories, one per operation that has a request builder) for every api. Off when absent — output unchanged. `msw` is the app's dependency. See "MSW handlers" in section 3. |
55
57
  | `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`. The built name is used verbatim (no second camel-casing); your `filterEndpoints` / `endpointOverrides` match it. Two operations with one name stop the run. `bodyArg: 'requestBody'`: the body is the argument's `requestBody`, whatever its DTO is called. `requestBuilders: true`: every endpoint's request builder goes into `<stem>Requests.ts` (`export const <stem>Requests = { <endpoint>: (queryArg: <Arg>): string \| FetchArgs => ({ url, params, body, … }) }`) and the endpoint uses it — a bundle that only builds requests imports that module without the endpoint injection. `requestBuilders: 'all'`: the module holds the builder of every operation (their argument types are written) while `filterEndpoints` still decides what the api file injects. `cookieParameters: 'drop'` (default): parameters `in: cookie` leave the endpoints (a browser sends cookies itself; `FetchArgs` has no field for them); `'keep'` restores RTK's output. Query and path parameters stay flat in the argument. |
56
58
  | `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. With `naming: 'document'` every file exports its own schema's name, also when another folder holds it too; importers alias it, the barrel leaves such a name out, and the api file imports each model by its path. `index: false`: no barrel. `enumPropertyType: 'wide'`: the property typed from the plain object (`string` in effect) instead of the Strict one. `objectType: 'const'`: a string `objectType` gets the one-value const of its schema name (`.` → `\\`, key `.` → `_`) and is required. Enum keys camel-case a dash (`gpt-realtime` → `gptRealtime`); a value that still gives no identifier is its own quoted key; an enum on an array schema stays an array. `scope: 'all'`: the models of every operation are written also when `filterEndpoints` keeps them out of the api file (their argument types are not). With several documents a shared model and its enum consts come from the first-listed one. |
57
59
 
@@ -109,6 +111,13 @@ mode generates a promise client and models. Set `outputs.mocks: {}` to add seede
109
111
  The opt-in modes use bundler-style TypeScript module resolution. They retain DDD document validation,
110
112
  path-parameter repair, `skipUpdatePostTwins` and type-check rollback. DDD RTK-specific options apply in default mode.
111
113
 
114
+ `generateLegacySdk({ sources, prune: true })` (an app that keeps its own legacy sources and directories) also deletes
115
+ the files an earlier run wrote and this run no longer plans. The manifest `.ddd-web-legacy-sdk.json` (`manifestFile`)
116
+ records per source and output the files written; only listed files are deleted, only for outputs that ran, and never
117
+ one that an output which did not run (left out, skipped, not configured) still lists — hand-written files in a shared
118
+ mocks root and the mocks of a document left out of a partial run stay. First run: manifest only. `dryRun`: report in
119
+ `result.pruned`, delete nothing, keep the manifest. Empty folders below an output directory go.
120
+
112
121
  ## 3. Generated files and cache tags
113
122
 
114
123
  | File | Content |
@@ -117,6 +126,23 @@ path-parameter repair, `skipUpdatePostTwins` and type-check rollback. DDD RTK-sp
117
126
  | `<stem>Enhanced.ts` | `baseApi.enhanceEndpoints({ addTagTypes, endpoints })` — `providesTags` / `invalidatesTags`; import once |
118
127
  | `<stem>Tags.ts` | `<stem>TagTypes` (const list) and `<Stem>TagType` (union): the tags of the generated endpoints. A tag whose operations are all left out by `filterEndpoints` is not listed; hand-written endpoints name it as an own tag |
119
128
  | `models/…` | one file per schema in its namespace folder (`App/Domain/…`), barrel `index.ts`; same leaf names in different namespaces get unique exported names |
129
+ | `<stem>Mocks.ts` | only with `mswHandlers`: `export const <stem>Mocks = { <operation>: (custom?: Partial<StoryMock<Response, Arg>>) => http.<verb>(…) }` and the `StoryMock` type |
130
+
131
+ ### MSW handlers (`mswHandlers`)
132
+
133
+ ```ts
134
+ mswHandlers: { modelMocks: { importPrefix: '@mocks/models/' } } // fileSuffix '.mock', exportName get<Model>Mock
135
+ ```
136
+
137
+ - One factory per operation with a request builder (all operations with `requestBuilders: 'all'`, else the api's
138
+ endpoints). URL `*<path>` with `*` per `{param}` (any origin; MSW ignores the query). `*` spans segments: use a
139
+ static path before a parameterised one it also matches, or pass `url`.
140
+ - Default answer: one model → `get<Model>Mock()` from `importPrefix + <model path below modelsDir> + fileSuffix`;
141
+ array of a model → `[mock]`; no content / other shapes / no `modelMocks` → `null`; file download → `null`, 200;
142
+ status = first declared 2xx.
143
+ - `custom`: `url`, `status`, `delay`, `response` (value or `(params, defaultMock, info) => value | Promise`;
144
+ `params` = path + query values as strings). `null` → empty body; a download takes a `Blob` / string body.
145
+ - Typed by the generated `<Op>ApiResponse` / `<Op>ApiArg`; a mock of another shape fails the type check.
120
146
 
121
147
  Tag per endpoint: the entity of `x-ddd-entity` when present, else the operation tag, else the last path segment that
122
148
  names a known tag (warning when none is found — the endpoint gets no tags).
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Added
6
+ - `generateLegacySdk({ prune: true })`: deletes the files an earlier run wrote and this run no longer plans. A
7
+ manifest (`manifestFile`, default `.ddd-web-legacy-sdk.json`) records each source's and output's files; only listed
8
+ files are deleted (hand-written files in a shared output directory stay), only for outputs that ran, and never a
9
+ file an output that did not run (left out, skipped, not configured this time) still lists. The first run deletes
10
+ nothing; `dryRun` reports and deletes nothing; folders left empty below an output directory are removed. Each
11
+ result carries `pruned` (the deleted paths). Off by default: without `prune` nothing changes.
12
+ - `mswHandlers` (default mode): `<stem>Mocks.ts` next to each api file with one MSW handler factory per operation that
13
+ has a request builder — URL `*` + path with `*` per path parameter, default answer from the application's model
14
+ mocks (`modelMocks.importPrefix` + model path + `fileSuffix`, `get<Model>Mock`), an array of the item mock, `null`
15
+ for no content and file downloads; overrides `url`, `status`, `delay`, `response` (value or function of params,
16
+ default mock, info); `StoryMock` type exported. Per api: `outputFile`, `exportName`, `false`. `msw` is the
17
+ consumer's dependency (generated code imports it); none is added to DDD Web. Off when absent: the generated
18
+ output is byte-identical to 0.18.0 (compared on the sample spec and on three large application documents).
19
+ - Types `LegacySdkResult`, `MswHandlersOptions`, `ApiMswHandlersOptions`, `ModelMocksOptions` from `/codegen`.
20
+
21
+ ### Tests
22
+ - `test/codegen/legacy-prune.test.ts` (first run, removed files, shared directory with hand-written files, partial
23
+ and skipped runs, dry run, manifest bounds) and `test/codegen/msw-handlers.test.ts` (snapshot, path parameters,
24
+ arrays, no content, text and binary, filtered endpoints, type check against generated models, MSW at runtime).
25
+ `msw` is a dev dependency for these tests only.
26
+
3
27
  ## 0.18.0
4
28
 
5
29
  ### Added
package/README.md CHANGED
@@ -66,6 +66,35 @@ The default command generates the DDD RTK Query SDK. Install `swagger-sdk-genera
66
66
  generates legacy-dialect models, stores, thunks and mocks and needs `swagger-sdk-generator@^3.1`. Each opt-in mode writes to a separate
67
67
  generated directory and uses the consumer’s generator installation. See [SDK generation modes](docs/sdk-generator-integration.md).
68
68
 
69
+ `generateLegacySdk({ …, prune: true })` also deletes the files an earlier run wrote and this run no longer plans,
70
+ tracked per source and output in `.ddd-web-legacy-sdk.json`; files it never wrote are never deleted.
71
+
72
+ ### MSW handlers
73
+
74
+ With `mswHandlers` in `openapi-config.ts` the default mode also writes `<stem>Mocks.ts` next to each api file: one
75
+ [MSW](https://mswjs.io) handler factory per operation that has a request builder, answering the response model's mock
76
+ from your model mocks. Off when absent (the output is unchanged); `msw` is a dependency of your project, not of DDD Web.
77
+
78
+ ```ts
79
+ export default defineConfig({
80
+ endpoints: { requestBuilders: 'all' },
81
+ mswHandlers: { modelMocks: { importPrefix: '@mocks/models/' } }, // → import { getBookMock } from '@mocks/models/App/…/Book.mock'
82
+ apis: [/* … */],
83
+ });
84
+ ```
85
+
86
+ ```ts
87
+ import { adminApiMocks } from './api/adminApiMocks';
88
+
89
+ export const handlers = [
90
+ adminApiMocks.getApiAdminLibraryBooksByBookId(), // GET */api/admin/library/books/* → getBookGetResponseDtoMock()
91
+ adminApiMocks.deleteApiAdminLibraryBooksByBookId({ status: 500, delay: 300 }),
92
+ adminApiMocks.getApiAdminLibraryBooksList({ response: (params, defaultMock) => ({ ...defaultMock!, books: { elements: [] } }) }),
93
+ ];
94
+ ```
95
+
96
+ See [SDK generation modes](docs/sdk-generator-integration.md#msw-handlers-default-mode).
97
+
69
98
  ### File downloads
70
99
 
71
100
  Endpoints whose 2xx responses are files (`application/octet-stream`, `application/zip`, `application/pdf`,