@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.
@@ -1,9 +1,9 @@
1
1
  ---
2
2
  name: ddd-web-specialist
3
- description: "Use and maintain @mgamadeus/ddd-web, the TS client for mgamadeus/ddd backends. Covers openapi-config.ts with defineConfig (schemaFile URL or snapshot, apiFile, outputFile, modelsDir, skipUpdatePostTwins, sideEffects and responseHandlers overrides, baseApiImport, esmExtensions, workspace), the RTK Query SDK from ddd-web-sdk (--config, --api, --schema, --skip-tsc; Enhanced/Tags files, cache tags from x-ddd-entity or path heuristics, file downloads via blobResponseHandler), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter, buildFulltextFilter), createDddBaseQuery (Bearer, shared refresh + retry, shouldRefresh, normalizeDddError), token storage, JWT helpers, contract types (x-ddd-*, DDD date-time, translations), link-skills, maintaining (pnpm, tsup, vitest, consumer check, trusted-publishing npm release, 0.x semver). Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, fixing token refresh or cache tags, downloading an Excel/ZIP/PDF export, or releasing ddd-web."
3
+ description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd. Covers openapi-config.ts with defineConfig (schemaFile, apiFile, outputFile, modelsDir, skipUpdatePostTwins, sideEffects and responseHandlers overrides, invalidation resolver, baseApiImport, esmExtensions, workspace), the RTK Query SDK from ddd-web-sdk (--api, --schema, --skip-tsc; Enhanced/Tags files, cache tags by entity identity, file downloads via blobResponseHandler), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter, buildFulltextFilter), createDddBaseQuery (Bearer, shared refresh + retry, shouldRefresh, normalizeDddError), token storage, JWT helpers, contract types (x-ddd-*, DDD date-time, translations), link-skills, maintaining (pnpm, vitest, consumer check, trusted-publishing release, 0.x semver). Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, fixing token refresh, cache tags or refetch storms, downloading an Excel/ZIP/PDF export, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.1.0"
6
+ version: "1.2.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -97,9 +97,12 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
97
97
  - **One refresh policy:** pass `shouldRefresh` instead of wrapping the base query; auth endpoints never refresh.
98
98
  - **The spec must keep its `<SchemaDefinition schemaRef="…"/>` tag markup** — never fetch it with
99
99
  `removeSchemaTags=1`; the codegen aborts without it.
100
- - `x-ddd-*` extensions are optional: without them the codegen falls back to HTTP-method and path heuristics and
101
- invalidates conservatively. A spec without `info.x-ddd-contract` is read as a pre-contract DDD spec (warning); an
102
- unsupported contract number aborts.
100
+ - `x-ddd-*` extensions are optional: without them the codegen falls back to HTTP-method, path and request-body
101
+ heuristics. **Cache invalidation is by identity:** a write invalidates `{ type, id }` + LIST (identity from
102
+ `x-ddd-entity`, a `{…Id}` path parameter even with an action suffix, or the request DTO's `<entity>.id`); only a write
103
+ without identity invalidates its whole tag type. Writes that change more than their own entity get an
104
+ `invalidation` resolver in the config (`broadInvalidation` = the 0.2 behaviour). A spec without
105
+ `info.x-ddd-contract` is read as a pre-contract DDD spec (warning); an unsupported contract number aborts.
103
106
 
104
107
  ## References
105
108
 
@@ -33,6 +33,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
33
33
  | `skipUpdatePostTwins` | Overrides the global setting for this api. |
34
34
  | `sideEffects` | Overrides checked before the global ones (first match wins). |
35
35
  | `responseHandlers` | Overrides checked before the global ones (first match wins). |
36
+ | `invalidation` | Resolver checked before the global one (see section 3). |
36
37
  | `esmExtensions` | `true` for `moduleResolution: nodenext`: generated relative imports end in `.js`. |
37
38
  | any other key | Passed to RTK codegen (`argSuffix`, `flattenArg`, `endpointOverrides`, `filterEndpoints`, …). |
38
39
 
@@ -44,6 +45,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
44
45
  | `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). |
45
46
  | `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. |
46
47
  | `responseHandlers` | `ResponseHandlerOverride[]`: `{ method?, path: string \| RegExp, handler: 'blob' \| 'text' \| 'json' }`, same matching as `sideEffects`. Wins over content-type detection — for specs that declare no or the wrong content type (a DDD backend often declares `application/json` for an Excel export). `json` turns a detected handler off. See section 3a. |
48
+ | `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. |
47
49
  | `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. |
48
50
  | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
49
51
 
@@ -99,14 +101,46 @@ Add a script: `"gen:sdk": "ddd-web-sdk"`. Commit the generated files and, if you
99
101
  Tag per endpoint: the entity of `x-ddd-entity` when present, else the operation tag, else the last path segment that
100
102
  names a known tag (warning when none is found — the endpoint gets no tags).
101
103
 
102
- | Endpoint | With `x-ddd-entity` | Without (path heuristic) |
104
+ | Endpoint | With `x-ddd-entity` (authoritative) | Without (identity heuristic) |
103
105
  |---|---|---|
104
106
  | query, single (`…/{id}`) | provides `{ type, id }` | provides `{ type, id }` when the path is `/<collection>/{id}` |
105
- | query, list / filter | provides `{ type, id: 'LIST' }` | same |
106
- | upsert / delete with a path identity | invalidates `{ type, id }` + LIST | — |
107
- | any other write | invalidates LIST + the whole tag | invalidates LIST + the whole tag |
107
+ | query, list / filter / action suffix | provides `{ type, id: 'LIST' }` | same |
108
+ | write with a path identity | upsert / delete with `identity: path:…`: invalidates `{ type, id }` + LIST | a path parameter naming the entity (`{bookId}` for `Books`) or right after its collection segment (`/books/{id}`): invalidates `{ type, id }` + LIST — also with an action suffix (`DELETE /books/{bookId}/cover`, `POST /books/{bookId}/publish`) |
109
+ | write with a body identity | upsert with `identity: body:book.id`: invalidates LIST + `{ type, id }` | the request DTO has exactly one property holding an entity of the tag (`{ book: Book }` → `book.id`, or the body is the entity): invalidates LIST + `{ type, id }` |
110
+ | write without identity (merge, batch, `action`, a path parameter of another entity) | invalidates LIST + the whole tag | invalidates LIST + the whole tag |
108
111
  | mutation without side effects | invalidates nothing | invalidates nothing |
109
112
 
113
+ A body identity is read with optional chaining and added only while it is set (helper `tagWithId` in the enhanced
114
+ file): a create without id invalidates LIST alone, because `{ type, id: undefined }` would hit the whole tag type.
115
+ A path parameter that names another entity (`/books/{authorId}/import` under `Books`) is not an identity.
116
+
117
+ What a write does **not** invalidate: other tag types (writing a book does not refresh authors) and, for a write by
118
+ identity, single-entity queries of other ids of the same type. Where a write changes more than its own entity, add an
119
+ `invalidation` resolver:
120
+
121
+ ```ts
122
+ import { defineConfig, type InvalidationResolver } from '@mgamadeus/ddd-web/codegen';
123
+
124
+ const invalidation: InvalidationResolver = (operation) => {
125
+ // operation: { key, api, method, path, tag, operation?, entity?, sideEffects, pathArgs, bodyArg?, defaultTags }
126
+ if (operation.key === 'postApiAdminLibraryBooksByBookIdPublish') {
127
+ return [...operation.defaultTags, { type: 'Authors', id: 'LIST' }]; // also refresh author lists
128
+ }
129
+ if (operation.path.endsWith('/merge') && operation.tag) return [{ type: operation.tag, id: 'LIST' }, operation.tag];
130
+ return undefined; // keep the default
131
+ };
132
+
133
+ export default defineConfig({ invalidation, apis: [/* … */] });
134
+ ```
135
+
136
+ `InvalidationTag`: `'Books'` = every cached entry of the type; `{ type, id }` = a literal id (`'LIST'`);
137
+ `{ type, arg }` = the id read from the endpoint argument by a dotted path (`operation.pathArgs.bookId`,
138
+ `` `${operation.bodyArg}.book.id` ``; `''` = the argument itself with `flattenArg`). Resolver tag types are registered in
139
+ `addTagTypes` and the tags file. The resolver runs for every generated mutation (also side-effect-free ones, whose
140
+ default is `[]`); api-entry resolver first, then the global one; an invalid result aborts the generation.
141
+ `invalidation: broadInvalidation` restores the 0.2 output (every write without an `x-ddd-entity` path identity
142
+ invalidates LIST + its whole tag type).
143
+
110
144
  ## 3a. File downloads and text responses
111
145
 
112
146
  The response handler of each endpoint follows its 2xx content types:
@@ -272,6 +306,7 @@ Idempotent; an existing symlink is repointed, a real file or directory is never
272
306
  | `All apis must share one output directory when modelsDir is not set` | Set `modelsDir` |
273
307
  | `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
274
308
  | A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
309
+ | A screen shows stale data after a write that changes more than its own entity | Writes invalidate by identity since 0.3 — add an `invalidation` resolver for that endpoint (section 3), or `broadInvalidation` for the 0.2 behaviour |
275
310
  | Every request logs out after a 401 | `refreshPath` wrong, or the refresh response lacks `accessToken` |
276
311
  | Dates off by the zone offset | DDD date-times are UTC without offset: use `parseDddDateTime` |
277
312
  | 400 on a filter that looks right | Column kind / FULLTEXT / options: validate with `buildDefinedFilter` when `x-ddd-query` is available |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ Cache invalidation by identity. Minor release because the default output changes: writes that invalidated their whole
6
+ tag type now invalidate only the entity they write plus LIST.
7
+
8
+ ### Changed
9
+ - codegen: a mutation without `x-ddd-entity` derives the identity of the entity it writes and invalidates
10
+ `{ type, id }` + `{ type, id: 'LIST' }` instead of LIST + every cached entry of the tag type:
11
+ - a path parameter naming the tag's entity (`{bookId}` for `Books`), also with an action suffix
12
+ (`DELETE /books/{bookId}/cover`, `POST /books/{bookId}/publish`), or a parameter right after the tag's collection
13
+ segment that names no other entity (`/books/{id}`);
14
+ - else the entity property of the request DTO (`{ book: Book }` → `<body>.book.id`, or `<body>.id` when the body is
15
+ the entity). The id tag is only added while the body carries an id, so a create invalidates LIST alone. A body
16
+ with a set, a list or a second entity of the tag (merge, batch) has no single identity.
17
+ - Only a write without identity still invalidates LIST + the whole tag type.
18
+ - codegen: `x-ddd-entity` stays authoritative; its `body:<path>` identity on an upsert is now used as well
19
+ (LIST + the entity while the body carries an id) instead of invalidating the whole tag type.
20
+ - The enhanced file contains a small `tagWithId` helper when a body identity is used.
21
+
22
+ ### Added
23
+ - codegen: `invalidation?: (operation) => InvalidationTag[] | undefined` in `defineConfig`, globally and per api entry
24
+ (api entry first, the first resolver that returns a list wins; `undefined` keeps the default). It gets the endpoint
25
+ key, method, path, chosen tag, operation, `x-ddd-entity`, side-effect classification, path / body argument paths and
26
+ the default tags. Tags: `'Books'` (whole type), `{ type, id }` (literal id, e.g. `'LIST'`), `{ type, arg }` (id read
27
+ from the endpoint argument by a dotted path). Tag types introduced by a resolver are registered.
28
+ - codegen: `broadInvalidation`, a resolver that restores the 0.2 output.
29
+ - codegen: exported types `InvalidationTag`, `InvalidationOperation`, `InvalidationResolver`.
30
+
31
+ ### Migration
32
+ - Regenerate the SDK. Screens refetch less after a write.
33
+ - A screen that relied on the broad invalidation (e.g. an action that changes other entities of the same type, or a
34
+ single-entity query whose cache tag does not match the written id) may now show stale data. Fix it per endpoint
35
+ with an `invalidation` resolver, or keep the old behaviour entirely with
36
+ `defineConfig({ invalidation: broadInvalidation, … })`.
37
+
3
38
  ## 0.2.2
4
39
 
5
40
  ### Fixed
package/README.md CHANGED
@@ -20,7 +20,8 @@ those conventions into frontend code:
20
20
 
21
21
  It contains no UI components and no domain logic; apps bring their own design system and business screens.
22
22
  Works with the OpenAPI output of current mgamadeus/ddd backends. The `x-ddd-*` extensions (contract version 1) are used
23
- when a backend emits them; without them the generator falls back to path heuristics and prints a warning.
23
+ when a backend emits them; without them the generator falls back to path and request-body heuristics and prints a
24
+ warning.
24
25
 
25
26
  ## Usage
26
27
 
@@ -73,6 +74,27 @@ export default defineConfig({
73
74
  });
74
75
  ```
75
76
 
77
+ ### Cache invalidation
78
+
79
+ Each mutation invalidates the entity it writes plus the lists of its tag type (`{ type, id }` + `{ type, id: 'LIST' }`).
80
+ The identity comes from `x-ddd-entity` when present, else from a path parameter naming the entity (`{bookId}`, also
81
+ `/books/{bookId}/publish`) or from the request DTO's entity property (`book.id`; a create without id invalidates LIST
82
+ only). Only a write without identity invalidates its whole tag type. To change the tags of single endpoints, add a
83
+ resolver; returning `undefined` keeps the default:
84
+
85
+ ```ts
86
+ import { defineConfig } from '@mgamadeus/ddd-web/codegen';
87
+
88
+ export default defineConfig({
89
+ invalidation: (operation) =>
90
+ operation.path.endsWith('/merge') && operation.tag
91
+ ? [{ type: operation.tag, id: 'LIST' }, operation.tag] // 'Books' = every cached entry of the type
92
+ : undefined,
93
+ // or `invalidation: broadInvalidation` (also exported from /codegen): the 0.2 behaviour, writes invalidate their whole tag type
94
+ apis: [/* … each entry may have its own invalidation, checked first */],
95
+ });
96
+ ```
97
+
76
98
  ## Agent skill
77
99
 
78
100
  The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). Link it into an app's