@mgamadeus/ddd-web 0.17.1 → 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), the RTK Query SDK from ddd-web-sdk (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, foreign global Request (MooTools: dddFetchApiRequestPlugin), the client-errors reporter /issues (browser, Node, React Native), link-skills (all DDD skills, --check), release. Use when wiring a frontend to a DDD API, regenerating the SDK, 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.6.0"
6
+ version: "1.8.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -85,6 +85,17 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
85
85
  });
86
86
  ```
87
87
 
88
+ ## SDK modes
89
+
90
+ DDD RTK Query is the default. Use `ddd-web-sdk --mode future` with the consumer’s `swagger-sdk-generator@^3`
91
+ for models and a promise client. Use `--mode legacy` with `swagger-sdk-generator@^3.1` for legacy-dialect
92
+ models, stores, thunks, and mocks. Use `generator.mode` to select a mode in config.
93
+ Opt-in output goes to `src/generated-sdk/<mode>/<api-stem>/` by default. See [references/consumer.md](references/consumer.md).
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
+
88
99
  ## Rules
89
100
 
90
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`, …). |
@@ -44,6 +45,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
44
45
 
45
46
  | Option | Meaning |
46
47
  |---|---|
48
+ | `generator` | Select `{ mode: "future" }` or `{ mode: "legacy" }` for the consumer-installed SDK generator. The existing DDD RTK Query engine is the default. |
47
49
  | `modelsDir` | Model output directory. Default `<dir of the first outputFile>/../models`; without it every api must share one output directory. |
48
50
  | `skipUpdatePostTwins` | DDD `#[Update]` serves the same route as PATCH and POST; `true` generates only the PATCH hook. With `x-ddd-entity` both must be `upsert` of the same entity; without it summary, parameters, body and responses must be identical. Conflicting annotations never skip. Default `false` (keep it `false` when app code already calls the POST hooks). |
49
51
  | `sideEffects` | `SideEffectsOverride[]` for specs without `x-ddd-side-effects`: `{ method?, path: string \| RegExp, sideEffects, endpointType? }`. A writing GET becomes a mutation, a reading POST a query; `endpointType: 'mutation'` keeps a reading POST a mutation that invalidates nothing. |
@@ -51,6 +53,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
51
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. |
52
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. |
53
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. |
54
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. |
55
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. |
56
59
 
@@ -94,6 +97,27 @@ skipTsc, logger })` from `/codegen`.
94
97
 
95
98
  Add a script: `"gen:sdk": "ddd-web-sdk"`. Commit the generated files and, if you use snapshots, the snapshot.
96
99
 
100
+ ### Opt-in generation
101
+
102
+ Select `--mode future` or `--mode legacy` to override the configured mode for a run. Future mode needs
103
+ `swagger-sdk-generator@^3` as an app dependency. Legacy mode needs `swagger-sdk-generator@^3.1`. Legacy output uses Redux Toolkit, RxJS, Faker, and the configured model aliases.
104
+
105
+ Output goes to `src/generated-sdk/<mode>/<output-file-stem>/` unless `generator.outputDir` sets another base.
106
+ Use `generator.outputs` to pass model, client, store or mock options supported by the selected mode. Future
107
+ mode generates a promise client and models. Set `outputs.mocks: {}` to add seeded mocks. Set
108
+ `outputs.client.transport: 'none'` to require an injected transport. Pass a custom transport or use
109
+ `createAxiosTransport` from `swagger-sdk-generator/runtime` with the app’s own Axios instance.
110
+
111
+ The opt-in modes use bundler-style TypeScript module resolution. They retain DDD document validation,
112
+ path-parameter repair, `skipUpdatePostTwins` and type-check rollback. DDD RTK-specific options apply in default mode.
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
+
97
121
  ## 3. Generated files and cache tags
98
122
 
99
123
  | File | Content |
@@ -102,6 +126,23 @@ Add a script: `"gen:sdk": "ddd-web-sdk"`. Commit the generated files and, if you
102
126
  | `<stem>Enhanced.ts` | `baseApi.enhanceEndpoints({ addTagTypes, endpoints })` — `providesTags` / `invalidatesTags`; import once |
103
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 |
104
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.
105
146
 
106
147
  Tag per endpoint: the entity of `x-ddd-entity` when present, else the operation tag, else the last path segment that
107
148
  names a known tag (warning when none is found — the endpoint gets no tags).
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
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
+
27
+ ## 0.18.0
28
+
29
+ ### Added
30
+ - Opt-in SDK modes over the consumer's `swagger-sdk-generator` (`ddd-web-sdk --mode future|legacy`, or
31
+ `generator.mode` in `openapi-config.ts`). Without a mode the generator is unchanged: DDD RTK Query, same output.
32
+ - `future` (`swagger-sdk-generator@^3`): models and a typed promise client with a configurable transport (Fetch by
33
+ default, an injected Axios instance, or a custom one) and optional seeded mocks.
34
+ - `legacy` (`swagger-sdk-generator@^3.1`): legacy-dialect models, Redux-RxJS stores with thunks, and mocks.
35
+ - Each opt-in API writes to `src/generated-sdk/<mode>/<output-file-stem>/` (`generator.outputDir` sets the base),
36
+ is checked against the DDD contract, gets missing path parameters repaired, honours `skipUpdatePostTwins`, and is
37
+ restored with every other selected API when the type check fails; `--api` and `--schema` work as for the default.
38
+ - `generator.outputs` passes output options through, e.g. `client.transport` or `stores.runtimeModule` (one
39
+ application-owned store runtime instead of a generated one).
40
+ - `generateLegacySdk()` from `/codegen`: runs legacy mode for an application that keeps its own sources and output
41
+ directories (plain OpenAPI documents, staged before writing; files outside the plan stay).
42
+ - Docs: `docs/sdk-generator-integration.md`.
43
+
3
44
  ## 0.17.1
4
45
 
5
46
  ### Fixed
package/README.md CHANGED
@@ -59,6 +59,42 @@ The package is an ES module. A CommonJS script may `require()` the entries witho
59
59
  ≥ 20.19 or ≥ 22.12 (Node's require of an ES module; none of them uses top-level await). `/api` (RTK Query), `/vite`
60
60
  and `/codegen` are import-only.
61
61
 
62
+ ### Opt-in SDK modes
63
+
64
+ The default command generates the DDD RTK Query SDK. Install `swagger-sdk-generator@^3` and run
65
+ `pnpm exec ddd-web-sdk --mode future` to generate a typed promise client and models. `--mode legacy`
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
+ generated directory and uses the consumer’s generator installation. See [SDK generation modes](docs/sdk-generator-integration.md).
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
+
62
98
  ### File downloads
63
99
 
64
100
  Endpoints whose 2xx responses are files (`application/octet-stream`, `application/zip`, `application/pdf`,
@@ -203,6 +239,14 @@ Everything is redacted on the device (tokens in paths and queries, e-mails, bear
203
239
  known noise is dropped, repeats are folded into `count`, and caps, batching, retry and backoff keep a broken page from
204
240
  flooding the endpoint. Details: the agent skill, `references/consumer.md` › Client errors.
205
241
 
242
+ ## Untrusted content
243
+
244
+ Generated clients return what the backend sends, including text and files users, mail, third parties or a model wrote.
245
+ Treat it as foreign: never pass it to `dangerouslySetInnerHTML`, `eval`, `new Function` or an `iframe` with
246
+ `allow-same-origin`; open foreign files through their download URLs (the backend serves them with
247
+ `UntrustedContentResponseDto`: attachment, `nosniff`, `CSP: sandbox`). The backend rule and its helpers: skill
248
+ `ddd-untrusted-input-specialist` of `mgamadeus/ddd`.
249
+
206
250
  ## Agent skills (`link-skills`)
207
251
 
208
252
  The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). `ddd-web link-skills`