@mgamadeus/ddd-web 0.0.1 → 0.2.2

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.
@@ -0,0 +1,110 @@
1
+ ---
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."
4
+ metadata:
5
+ author: mgamadeus
6
+ version: "1.1.0"
7
+ package: "@mgamadeus/ddd-web"
8
+ ---
9
+
10
+ # ddd-web Specialist
11
+
12
+ `@mgamadeus/ddd-web` is the frontend counterpart of `mgamadeus/ddd` (PHP, Symfony + Doctrine). A DDD backend publishes
13
+ one OpenAPI document per API audience (admin, public, client, …) with shared conventions; this package turns them into
14
+ frontend code. No UI components, no domain logic — apps bring their own design system and screens.
15
+
16
+ > Backend patterns (entities, endpoints, QueryOptions, the OpenAPI generator): the `ddd-*` skills of `mgamadeus/ddd`.
17
+
18
+ ## Subpaths
19
+
20
+ | Import | Runs in | Content |
21
+ |---|---|---|
22
+ | `@mgamadeus/ddd-web/codegen` | Node only (never in a browser bundle) | `defineConfig`, `generateSdk`, `linkSkills`, `loadSpec` / `validateSpec`; bins `ddd-web-sdk`, `ddd-web` |
23
+ | `@mgamadeus/ddd-web/query` | anywhere, no React | QueryOptions builders and definition-driven validators |
24
+ | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery`, `createDddRefresh`, `normalizeDddError`, downloads, `createAuthEndpoints` |
25
+ | `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
26
+ | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators |
27
+
28
+ ESM only, Node ≥ 20. Consumers may use npm or pnpm.
29
+
30
+ ## Quick start
31
+
32
+ ```sh
33
+ pnpm add @mgamadeus/ddd-web @reduxjs/toolkit react react-redux
34
+ ```
35
+
36
+ ```ts
37
+ // src/api/baseApi.ts — the one RTK api the generated endpoints are injected into
38
+ import { createApi } from '@reduxjs/toolkit/query/react';
39
+ import { createDddBaseQuery } from '@mgamadeus/ddd-web/api';
40
+
41
+ export const baseApi = createApi({
42
+ baseQuery: createDddBaseQuery({
43
+ baseUrl: 'https://api.example.com',
44
+ refreshPath: '/api/admin/common/auth/refresh',
45
+ getTokens: ({ getState }) => (getState() as RootState).auth,
46
+ setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),
47
+ onLogout: ({ dispatch }) => dispatch(authActions.logout()),
48
+ }),
49
+ endpoints: () => ({}),
50
+ });
51
+ ```
52
+
53
+ ```ts
54
+ // openapi-config.ts (next to package.json)
55
+ import { defineConfig } from '@mgamadeus/ddd-web/codegen';
56
+
57
+ export default defineConfig({
58
+ apis: [{
59
+ schemaFile: 'https://api.example.com/api/admin/documentation/openApi', // or './openapi/admin.json'
60
+ apiFile: './src/api/baseApi.ts', apiImport: 'baseApi',
61
+ outputFile: './src/api/adminApi.ts', exportName: 'adminApi',
62
+ hooks: { queries: true, lazyQueries: true, mutations: true },
63
+ }],
64
+ });
65
+ ```
66
+
67
+ ```sh
68
+ pnpm exec ddd-web-sdk # writes adminApi.ts, adminApiEnhanced.ts, adminApiTags.ts and ../models
69
+ pnpm exec ddd-web link-skills # links this skill into .claude/skills/
70
+ ```
71
+
72
+ Import `adminApiEnhanced` once (e.g. in the store setup) and use the hooks from `adminApi`:
73
+
74
+ ```ts
75
+ import './api/adminApiEnhanced';
76
+ import { useGetApiAdminLibraryBooksListQuery } from './api/adminApi';
77
+ import { buildQueryOptions, buildInFilter } from '@mgamadeus/ddd-web/query';
78
+
79
+ const { data } = useGetApiAdminLibraryBooksListQuery({
80
+ ...buildQueryOptions({ filters: [buildInFilter('status', ['DRAFT', 'PUBLISHED'])], orderBy: 'title asc', top: 20 }),
81
+ });
82
+ ```
83
+
84
+ ## Rules
85
+
86
+ - **Never edit generated files** (`<stem>.ts`, `<stem>Enhanced.ts`, `<stem>Tags.ts`, the models directory). Change the
87
+ config, an override or the backend, then regenerate. The output is replaced atomically and rolled back when the
88
+ final `tsc --noEmit` fails.
89
+ - **Regenerate after every backend change** to a route, DTO or entity the app uses; hook names derive from verb + path
90
+ (`useGetApiAdminLibraryBooksListQuery`), so a renamed route is a renamed hook and shows up as a type error.
91
+ - **File routes** (Excel, ZIP, PDF, …) are generated with `blobResponseHandler` and return
92
+ `DddFileResponse`: `const { blob, filename } = await trigger(args).unwrap(); downloadBlob(blob, filename ?? 'x.xlsx')`.
93
+ When the spec declares JSON for such a route, add a `responseHandlers` override (`handler: 'blob'`) — never
94
+ hand-write a stopgap endpoint.
95
+ - **Never build filter strings by concatenation** — use the `query` builders; they escape strings, write lists as JSON
96
+ and group `or` clauses (the backend parser has no precedence).
97
+ - **One refresh policy:** pass `shouldRefresh` instead of wrapping the base query; auth endpoints never refresh.
98
+ - **The spec must keep its `<SchemaDefinition schemaRef="…"/>` tag markup** — never fetch it with
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.
103
+
104
+ ## References
105
+
106
+ - [references/consumer.md](references/consumer.md) — every config option, CLI flag, generated file and cache-tag rule;
107
+ the query builders and validators; base query, refresh, errors, downloads; token storage; contract helpers;
108
+ troubleshooting.
109
+ - [references/maintaining.md](references/maintaining.md) — repository layout, build and tests, the consumer check, the
110
+ `x-ddd` contract and how it stays in step with `mgamadeus/ddd`, release workflow, versioning.
@@ -0,0 +1,277 @@
1
+ # Using @mgamadeus/ddd-web in an app
2
+
3
+ ## Contents
4
+
5
+ 1. Configuration (`openapi-config.ts`)
6
+ 2. Generating the SDK (`ddd-web-sdk`)
7
+ 3. Generated files and cache tags
8
+ 4. Query builders (`/query`)
9
+ 5. Base query, refresh and errors (`/api`)
10
+ 6. Tokens (`/auth`)
11
+ 7. Contract helpers (`/contract`)
12
+ 8. Agent skills (`link-skills`)
13
+ 9. Troubleshooting
14
+
15
+ ## 1. Configuration (`openapi-config.ts`)
16
+
17
+ `export default defineConfig({...})` (loaded with jiti, so `.ts` works without a build step; `.js` / `.mjs` / `.cjs`
18
+ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as well. The config may read env variables
19
+ — it is re-evaluated after the workspace value is resolved.
20
+
21
+ **Per api entry (`apis[]`, one per OpenAPI document / audience):**
22
+
23
+ | Option | Meaning |
24
+ |---|---|
25
+ | `schemaFile` (required) | Spec source: `https://…/api/<audience>/documentation/openApi` or a local JSON snapshot (relative to the config file). A snapshot makes generation reproducible and offline. |
26
+ | `apiFile` (required) | Module exporting the base api: a relative path, or a bare specifier used verbatim (`@/api/baseApi`). |
27
+ | `apiImport` | Named export in `apiFile`. Default `api`. |
28
+ | `outputFile` (required) | Generated endpoints file, e.g. `./src/api/adminApi.ts`. Tags and Enhanced files go next to it. |
29
+ | `exportName` | Name for `--api`. Default: stem of `outputFile`. |
30
+ | `hooks` | `true` or `{ queries, lazyQueries, mutations }`. |
31
+ | `audience` | Prefix stripped from operation tags (`Admin Books` → `Books`). Default: stem without `Api`. |
32
+ | `baseApiImport` | Import specifier of the base api used by `<stem>Enhanced.ts`. Default: `apiFile` relative to the output dir. |
33
+ | `skipUpdatePostTwins` | Overrides the global setting for this api. |
34
+ | `sideEffects` | Overrides checked before the global ones (first match wins). |
35
+ | `responseHandlers` | Overrides checked before the global ones (first match wins). |
36
+ | `esmExtensions` | `true` for `moduleResolution: nodenext`: generated relative imports end in `.js`. |
37
+ | any other key | Passed to RTK codegen (`argSuffix`, `flattenArg`, `endpointOverrides`, `filterEndpoints`, …). |
38
+
39
+ **Global options:**
40
+
41
+ | Option | Meaning |
42
+ |---|---|
43
+ | `modelsDir` | Model output directory. Default `<dir of the first outputFile>/../models`; without it every api must share one output directory. |
44
+ | `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
+ | `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
+ | `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. |
47
+ | `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
+ | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
49
+
50
+ ```ts
51
+ export default defineConfig({
52
+ skipUpdatePostTwins: true,
53
+ sideEffects: [
54
+ { method: 'GET', path: /\/books\/\{bookId\}\/generateSummary$/, sideEffects: true }, // writing GET → mutation
55
+ { method: 'POST', path: '/api/admin/library/books/search', sideEffects: false }, // reading POST → query
56
+ ],
57
+ responseHandlers: [
58
+ { method: 'GET', path: /\/export$/, handler: 'blob' }, // Excel export declared as JSON
59
+ ],
60
+ apis: [
61
+ { schemaFile: './openapi/admin.json', apiFile: './src/api/baseApi.ts', apiImport: 'baseApi',
62
+ outputFile: './src/api/adminApi.ts', hooks: true },
63
+ { schemaFile: './openapi/public.json', apiFile: './src/api/baseApi.ts', apiImport: 'baseApi',
64
+ outputFile: './src/api/publicApi.ts', hooks: true },
65
+ ],
66
+ });
67
+ ```
68
+
69
+ ## 2. Generating the SDK (`ddd-web-sdk`)
70
+
71
+ ```text
72
+ ddd-web-sdk [options] (same as: ddd-web sdk [options])
73
+ --config <path> config file (default openapi-config.ts)
74
+ --api <exportName> generate only this api
75
+ --schema <url|file> spec source for the selected api (needs exactly one api, i.e. with --api)
76
+ --workspace <value> value for config.workspace.envVar (alias --subdomain)
77
+ --skip-prettier do not format the generated files
78
+ --skip-tsc do not type-check after generation
79
+ ddd-web link-skills link the package's agent skills into .claude/skills/
80
+ ```
81
+
82
+ Pipeline: load every spec once → validate the DDD contract parts → namespace registry from the `SchemaDefinition`
83
+ tags → RTK codegen per api → models → Enhanced endpoints (cache tags) → prettier → `tsc --noEmit`. Models are shared
84
+ between apis: an `--api` run still reads every configured spec to rebuild shared models (a spec that cannot be loaded
85
+ keeps its models from the previous output, with a warning). Programmatic use: `generateSdk({ config, api, schema,
86
+ skipTsc, logger })` from `/codegen`.
87
+
88
+ Add a script: `"gen:sdk": "ddd-web-sdk"`. Commit the generated files and, if you use snapshots, the snapshot.
89
+
90
+ ## 3. Generated files and cache tags
91
+
92
+ | File | Content |
93
+ |---|---|
94
+ | `<stem>.ts` | RTK `injectEndpoints` on the base api: endpoints, hooks (names path-derived) |
95
+ | `<stem>Enhanced.ts` | `baseApi.enhanceEndpoints({ addTagTypes, endpoints })` — `providesTags` / `invalidatesTags`; import once |
96
+ | `<stem>Tags.ts` | `<stem>TagTypes` (const list) and `<Stem>TagType` (union) |
97
+ | `models/…` | one file per schema in its namespace folder (`App/Domain/…`), barrel `index.ts`; same leaf names in different namespaces get unique exported names |
98
+
99
+ Tag per endpoint: the entity of `x-ddd-entity` when present, else the operation tag, else the last path segment that
100
+ names a known tag (warning when none is found — the endpoint gets no tags).
101
+
102
+ | Endpoint | With `x-ddd-entity` | Without (path heuristic) |
103
+ |---|---|---|
104
+ | 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 |
108
+ | mutation without side effects | invalidates nothing | invalidates nothing |
109
+
110
+ ## 3a. File downloads and text responses
111
+
112
+ The response handler of each endpoint follows its 2xx content types:
113
+
114
+ | 2xx content types | Generated | Result type |
115
+ |---|---|---|
116
+ | only file types: `application/octet-stream`, `application/zip`, `application/pdf`, `application/vnd.*` (Excel, Word, …), `text/csv`, `image/*`, `audio/*`, `video/*`, `font/*` (never `…json`) — text types may be mixed in | `responseHandler: blobResponseHandler` (imported from `@mgamadeus/ddd-web/api`) | `DddFileResponse` = `{ blob, filename, contentType }` |
117
+ | only `text/html`, `text/plain`, `text/xml` | `responseHandler: "text"` | `string` |
118
+ | anything else (JSON, mixed JSON and file) | RTK JSON parsing | the RTK type |
119
+
120
+ A `responseHandlers` override wins over detection. The handler is injected on the syntax tree of the generated api
121
+ file, independent of formatting; if it cannot be injected for a detected or overridden endpoint, `ddd-web-sdk` aborts
122
+ and lists the endpoints instead of generating a result type the request does not match. Error responses of blob endpoints are still parsed as JSON/text,
123
+ so `normalizeDddError` works as usual. Download in a component:
124
+
125
+ ```ts
126
+ import { downloadBlob } from '@mgamadeus/ddd-web/api';
127
+ import { useLazyGetApiAdminLibraryBooksExportQuery } from './api/adminApi';
128
+
129
+ const [trigger, { isFetching }] = useLazyGetApiAdminLibraryBooksExportQuery();
130
+ const onExport = async () => {
131
+ const { blob, filename } = await trigger({ noCache: true }).unwrap();
132
+ downloadBlob(blob, filename ?? 'books.xlsx'); // filename comes from Content-Disposition, else null
133
+ };
134
+ ```
135
+
136
+ A `Blob` is not serializable: Redux Toolkit's serializable check warns about it in development. Ignore the path
137
+ (`serializableCheck: { ignoredActionPaths: ['payload.blob'], ignoredPaths: [/\.blob$/] }`) or keep the data out of
138
+ the cache (`keepUnusedDataFor: 0` via `enhanceEndpoints`). Generated endpoints import the package's `api` entry, so the
139
+ app needs `@reduxjs/toolkit` (the `api` peer) installed.
140
+
141
+ ## 4. Query builders (`/query`)
142
+
143
+ The backend reads `filters`, `orderBy`, `expand`, `select`, `top`, `skip` (no `$` prefix). Default `top` is 50.
144
+
145
+ ```ts
146
+ import {
147
+ buildQueryOptions, combineFilters, anyOfFilters, buildFieldFilter, buildInFilter, buildNotInFilter,
148
+ buildBetweenFilter, buildNullFilter, buildContainsFilter, buildFulltextFilter, buildIntEqFilter, buildFullDayFilter,
149
+ pageToSkip,
150
+ } from '@mgamadeus/ddd-web/query';
151
+
152
+ const filters = combineFilters(
153
+ buildFieldFilter('status', 'PUBLISHED'), // status eq 'PUBLISHED'
154
+ anyOfFilters(buildNullFilter('deletedAt'), buildFieldFilter('archived', false)), // grouped: ( … or … )
155
+ buildFulltextFilter('title', search, { mode: 'fb' }), // title fb 'dune*' — undefined for a blank term
156
+ buildIntEqFilter(search, 'id', { stripLeadingChar: '#' }), // undefined unless numeric
157
+ buildFullDayFilter(day, 'createdAt'), // undefined unless a real YYYY-MM-DD
158
+ );
159
+ const params = buildQueryOptions({
160
+ filters, // string or list of clauses (AND-combined)
161
+ orderBy: [{ property: 'createdAt', direction: 'desc' }, 'title'],
162
+ expand: { author: { select: ['id', 'name'] }, reviews: { filters: "rating ge '4'", top: 5 } },
163
+ select: ['id', 'title', 'author.name'],
164
+ top: 20,
165
+ skip: pageToSkip(pageIndex, 20),
166
+ }, { maxTop: 100 }); // above maxTop: throw (default) or topOverflow: 'clamp'
167
+ ```
168
+
169
+ - Builders that return `undefined` are skipped by `combineFilters` / `anyOfFilters` — pass search input straight in.
170
+ - Lists (`in`, `ni`, `bw`) are written as JSON (`["a","b"]`); strings are single-quoted with `\'` / `\\` escaped
171
+ (`escapeFilterString`, alias `escapeOData`).
172
+ - `ft` / `fb` need a FULLTEXT index on the backend property (otherwise 400).
173
+ - `buildContainsFilter(property, term)` writes `eq '*term*'` (LIKE), e.g. for plain translatable columns.
174
+ - `sanitizeSearchInput`, `buildStaticArgsKey`, `buildColumnSearchesKey` build stable cache / reset keys.
175
+
176
+ **Definition-driven** (when the operation carries `x-ddd-query`): `buildDefinedFilter(query, property, operator,
177
+ value)` validates
178
+ property, operator, column kind, options and value rules; `buildDefinedQueryOptions(query, input)` validates
179
+ `orderBy`, `expand`, `select` and `maxTop`; both throw `QueryValidationError` with every `QueryIssue` (the cases the
180
+ backend would answer 400 for). `validateFilter(query, { property, operator, value })`, `validateOrderBy`, `validateExpand`,
181
+ `validateSelect` return the issues without throwing. A `Date` value is written as `Y-m-d` on a `DAY` filter, as a UTC
182
+ DDD date-time otherwise.
183
+
184
+ ## 5. Base query, refresh and errors (`/api`)
185
+
186
+ `createDddBaseQuery(options)`:
187
+
188
+ | Option | Meaning |
189
+ |---|---|
190
+ | `baseUrl` | API origin; request URLs are relative to it |
191
+ | `getTokens(context)` | current `{ accessToken, refreshToken }` (Redux state or a `TokenStorage`) |
192
+ | `setTokens(tokens, api)` | store a refreshed pair |
193
+ | `onLogout(api)` | once, when the session cannot be recovered |
194
+ | `refreshPath` / `refresh` | default refresh = `POST refreshPath { refreshToken }` → `{ accessToken, refreshToken }`; or a custom `DddRefreshFn` |
195
+ | `shouldRefresh(error, request)` | default `defaultShouldRefresh`: status 401 and not an auth route (`…/common/auth/…`, `isDddAuthRequest`) |
196
+ | `languageCode(context)` | value of the DDD `languageCode` header; `context.type` tells queries from mutations (e.g. editing language on writes, UI language on reads) |
197
+ | `headers(headers, context)` | further headers after the Bearer header |
198
+ | `debug` | pass page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) through to API requests; default off |
199
+ | `fetchOptions` | further `fetchBaseQuery` options; the default `paramsSerializer` (`dddParamsSerializer`) drops `null` / `undefined` |
200
+
201
+ Refresh behaviour: one refresh per session generation, shared by all requests that fail meanwhile; each failed request
202
+ is retried once. A request that started before a finished refresh reuses its result; a late 401 after a failed refresh
203
+ neither refreshes nor logs out again; a refresh that finishes after a logout or a new login is discarded.
204
+
205
+ ```ts
206
+ // also refresh on 403, except business refusals
207
+ shouldRefresh: (error, request) =>
208
+ (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request),
209
+ ```
210
+
211
+ Errors: `normalizeDddError(error)` → `{ status, message, validationErrors, details, body }` from an RTK error, a thrown
212
+ `Error` or a raw body (`error` key first, then a text body); `getErrorMessage`, `getErrorStatus` for UI code. A
213
+ response that is not JSON (an HTML error page, a PHP fatal, a proxy 502 — RTK's `PARSING_ERROR`) counts as an HTTP
214
+ error: `status` is the HTTP status, the message `Server error (HTTP 500)` / `Request failed (HTTP 404)`, never the
215
+ `SyntaxError` text or the body (kept in `body`). `FETCH_ERROR` / `TIMEOUT_ERROR` read `The server could not be
216
+ reached` / `The request timed out`. Translate them with the third argument:
217
+ `getErrorMessage(error, t('Request failed'), { serverError: (status) => t('Server error (%s)', status), networkError: t('Offline') })`
218
+ (`DddErrorMessages`, defaults `DEFAULT_ERROR_MESSAGES`).
219
+ Downloads (generated endpoints get `blobResponseHandler` automatically, see 3a): `createDownloadResponseHandler(fallbackName)` as an endpoint's `responseHandler` saves the blob
220
+ and resolves to a serializable `{ filename, contentType, size }`; `blobResponseHandler` returns `{ blob, filename,
221
+ contentType }` instead; `downloadBlob`, `filenameFromContentDisposition` (RFC 5987) for own
222
+ handlers. Apps without a generated auth endpoint: `createAuthEndpoints(api, { loginPath, refreshPath })` injects
223
+ `authLogin` / `authRefresh`.
224
+
225
+ ## 6. Tokens (`/auth`)
226
+
227
+ - `TokenStorage` = `read()` / `write({ accessToken?, refreshToken? })` (`undefined` keeps, `null` removes) /
228
+ `clear()`; implementations never throw.
229
+ - `createLocalStorageTokenStorage({ accessKey, refreshKey, serialize, deserialize, storage })` keeps an existing
230
+ storage format, e.g. the access token inside a JSON object:
231
+
232
+ ```ts
233
+ createLocalStorageTokenStorage({
234
+ accessKey: 'session', refreshKey: 'session_refresh',
235
+ serialize: (jwt, previous) => JSON.stringify({ ...(previous ? JSON.parse(previous) : {}), jwt }),
236
+ deserialize: (raw) => JSON.parse(raw).jwt,
237
+ });
238
+ ```
239
+ - `createMemoryTokenStorage()` for tests and SSR; `safeLocalStorage` / `safeSessionStorage` / `createSafeStorage` never
240
+ throw (private mode, SSR).
241
+ - `decodeJwt(token)`, `getTokenExpiry(token)`, `isExpired(token, skewSeconds)` — an invalid expiry claim counts as
242
+ expired.
243
+ - The Redux auth slice stays in the app (it binds the app's endpoints and user model).
244
+
245
+ ## 7. Contract helpers (`/contract`)
246
+
247
+ - DDD `DateTime` serialises `Y-m-d H:i:s` in UTC **without offset** — `new Date(value)` would read local time. Use
248
+ `parseDddDateTime` / `parseDddDateTimeMs` / `formatDddDateTime`, and `formatDddDate` / `isValidDddDate` for `Y-m-d`.
249
+ - `normalizeTranslationsStore` / `normalizeTranslationInfos`: PHP sends an empty map as `[]`; these return `{}`.
250
+ `buildTranslationKey` / `parseTranslationKey` for translation map keys.
251
+ - `hasSideEffects(method, operation)`, `getContractInfo(document)`, `parseEntityIdentity('path:bookId')`,
252
+ `isHiddenProperty`, `isPreservedOnOmission`, `isTranslatableProperty`.
253
+ - Types: `DddErrorBody`, `DddExceptionDetail(s)`, `FilterOperator` (`eq ne gt ge lt le in ni bw ft fb`),
254
+ `QueryOptionsParams`, `DddQueryDefinition`, `DddEntityInfo`, `ChangeHistory`, `TranslationInfos`, … The `x-ddd-*`
255
+ types describe the extensions; a backend that does not emit them yet is read with the documented defaults.
256
+
257
+ ## 8. Agent skills (`link-skills`)
258
+
259
+ `pnpm exec ddd-web link-skills` symlinks every skill directory of the installed package into `.claude/skills/`.
260
+ Idempotent; an existing symlink is repointed, a real file or directory is never touched. Run it after install (e.g. in
261
+ `postinstall`) and commit the symlinks if the app versions its `.claude/skills`.
262
+
263
+ ## 9. Troubleshooting
264
+
265
+ | Symptom | Cause / fix |
266
+ |---|---|
267
+ | `no <SchemaDefinition schemaRef="…"/> markup in tags[].description` | Spec fetched with `removeSchemaTags=1` — fetch it without |
268
+ | `DDD contract … is not supported` | The backend emits a newer contract than this package version: update `@mgamadeus/ddd-web` |
269
+ | `no info.x-ddd-contract — assuming a pre-contract DDD spec` | Backend without the contract extensions; works with heuristics |
270
+ | `No tag for <endpoint> — no cache tags generated` | Operation without a matching tag: add a tag on the backend controller or an `endpointOverrides` |
271
+ | `--schema needs exactly one api` | Combine with `--api <exportName>` |
272
+ | `All apis must share one output directory when modelsDir is not set` | Set `modelsDir` |
273
+ | `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
274
+ | A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
275
+ | Every request logs out after a 401 | `refreshPath` wrong, or the refresh response lacks `accessToken` |
276
+ | Dates off by the zone offset | DDD date-times are UTC without offset: use `parseDddDateTime` |
277
+ | 400 on a filter that looks right | Column kind / FULLTEXT / options: validate with `buildDefinedFilter` when `x-ddd-query` is available |
@@ -0,0 +1,107 @@
1
+ # Maintaining @mgamadeus/ddd-web
2
+
3
+ ## Contents
4
+
5
+ 1. Repository layout
6
+ 2. Build, tests and the consumer check
7
+ 3. The contract with mgamadeus/ddd
8
+ 4. Release
9
+ 5. Versioning and changelog
10
+ 6. Rules for changes
11
+
12
+ ## 1. Repository layout
13
+
14
+ ```text
15
+ src/
16
+ contract/ x-ddd-* types and defaults, error body, operators, QueryOptions params, translations, change history,
17
+ DDD date-time — no runtime dependencies
18
+ query/ builders (literals, filters, structure, order-by, select, expand, paging, keys, values) and the
19
+ definition-driven validators (definition.ts) — no React, no RTK
20
+ api/ createDddBaseQuery, refresh coordination, errors, downloads, debug passthrough, auth endpoints
21
+ auth/ token storage adapters, JWT helpers, SSR-safe storage
22
+ codegen/ cli.ts (bins), config.ts (defineConfig, loadConfig), generate.ts (pipeline), spec.ts (load + validate),
23
+ registry / models / rtk / endpoints / enhance / tags / response-handlers (text + file detection,
24
+ AST-based injection that aborts on a miss) / repair / output (atomic commit),
25
+ workspace.ts, link-skills.ts
26
+ test/ vitest suites per subpath; fixtures/specs/sample-admin.json (neutral sample: books, authors);
27
+ consumer/ (installed-package check); fixtures/private/ is ignored — never commit app specs
28
+ scripts/ clean.mjs (dist cleaned once before tsup), check-package.mjs (exports / bin targets, --require-skills)
29
+ .claude/skills/ddd-web-specialist/ this skill — shipped in the tarball, linked into apps by `ddd-web link-skills`
30
+ ```
31
+
32
+ Each subpath is its own tsup entry with its own `.d.ts`; `codegen` is Node-only and must never be imported from the
33
+ other subpaths. `@reduxjs/toolkit` is an optional peer (only `api` needs it); `codegen` depends on
34
+ `@rtk-query/codegen-openapi`, `jiti` and `prettier`.
35
+
36
+ ## 2. Build, tests and the consumer check
37
+
38
+ pnpm only (version pinned in `package.json` → `packageManager`; `corepack enable`). One lockfile.
39
+
40
+ ```sh
41
+ pnpm install
42
+ pnpm typecheck && pnpm test && pnpm build
43
+ node scripts/check-package.mjs . # every exports / bin target exists in dist
44
+ pnpm pack --dry-run # what the tarball would contain (dist, .claude/skills, docs)
45
+ pnpm pack && test/consumer/run.sh mgamadeus-ddd-web-*.tgz pnpm /tmp/ddd-web-consumer
46
+ ```
47
+
48
+ `test/consumer/run.sh <tarball> <npm|pnpm> <workDir>` installs the tarball into a fresh project and checks it as a user
49
+ would: tarball contents, runtime imports of every subpath, a strict TypeScript consumer with `moduleResolution`
50
+ `bundler` and `nodenext`, `ddd-web-sdk` on the sample spec (with `esmExtensions` for nodenext) plus a type check of the
51
+ generated SDK, and `link-skills`. CI (`.github/workflows/ci.yml`) runs all of this for npm and pnpm on every push to
52
+ `main` and every pull request, and fails on `workspace:` / `link:` / `file:` specifiers in `package.json`.
53
+
54
+ Test expectations:
55
+ - A codegen change gets a regression test against `test/fixtures/specs/sample-admin.json` (extend the sample — books,
56
+ authors — rather than adding an app's spec).
57
+ - A `query` change states the backend rule it mirrors (`FiltersOptionsParser`, `FiltersOptions` column-kind
58
+ validation) and tests the boundary.
59
+ - Refresh changes test concurrency: parallel 401s, a late 401 after a failed refresh, logout during a refresh.
60
+
61
+ ## 3. The contract with mgamadeus/ddd
62
+
63
+ The codegen depends on what the DDD OpenAPI generator emits:
64
+ - **Implicit parts:** `tags[].description` with `<SchemaDefinition schemaRef="…"/>`; dotted schema names
65
+ (`App.Domain.…`, `DDD.…`) that become model folders; the error body `{ error, validationErrors, exceptionDetails }`;
66
+ the QueryOptions grammar; `#[Update]` serving PATCH and POST on one path.
67
+ - **Extensions** (types in `src/contract/extensions.ts`, all optional): `info.x-ddd-contract` (`{ contract, ddd }`),
68
+ operation `x-ddd-query`, `x-ddd-side-effects`, `x-ddd-entity`, `x-ddd-cache-ttl`; property `x-ddd-translatable`,
69
+ `x-ddd-hidden`, `x-ddd-preserve-on-omission`; schema `x-ddd-roles-required-for-update`. Every extension has a
70
+ documented default when absent; the codegen must keep working on a spec without any of them.
71
+ - `SUPPORTED_CONTRACT` (`src/codegen/spec.ts`) is the contract range this version understands; outside it the codegen
72
+ aborts with an update hint. Raise `max` only together with support for the new contract.
73
+
74
+ How both sides stay in step: a change to the OpenAPI output in `mgamadeus/ddd` shows up in its golden spec test, is
75
+ listed as a contract change in its changelog and is checked against this package's CI (sample spec + consumer check)
76
+ before it is released. On this side, a new contract number means: types in `contract`, behaviour in `codegen` /
77
+ `query`, a sample-spec case, `SUPPORTED_CONTRACT`, a changelog entry.
78
+
79
+ ## 4. Release
80
+
81
+ 1. Update `CHANGELOG.md` (move "Unreleased" to the version) and set `version` in `package.json`.
82
+ 2. Commit, push, then tag: `git tag vX.Y.Z && git push origin vX.Y.Z` — the tag must equal `v` + the `package.json`
83
+ version.
84
+ 3. `.github/workflows/release.yml` (tags `v*`): version check, install, typecheck, test, build, pack, tarball check
85
+ **with `--require-skills`** (fails without a `.claude/skills/*/SKILL.md`), consumer checks with npm and pnpm, then
86
+ `npm publish <tarball> --provenance` via trusted publishing (OIDC, no token; npm ≥ 11.5.1). Versions with a
87
+ prerelease suffix (`x.y.z-…`) go to the dist-tag `next`, others to `latest`. The version is public when the run is
88
+ green; no manual step.
89
+
90
+ The verified tarball itself is published — nothing is rebuilt after the checks. A failed release is fixed with a new
91
+ patch version; never re-tag a published version.
92
+
93
+ ## 5. Versioning and changelog
94
+
95
+ Semver. In `0.x` a minor version may break the API, a patch never does. Every breaking change gets a migration note in
96
+ `CHANGELOG.md` (what to change in `openapi-config.ts`, which export was renamed, whether to regenerate). Hook names are
97
+ part of the API: a change to how they are derived is breaking.
98
+
99
+ ## 6. Rules for changes
100
+
101
+ - No UI components, no styling, no app domain logic; generic only. Examples and fixtures stay neutral (books,
102
+ authors, `example.com`).
103
+ - This repository is public: no local paths, no app-specific names, no internal procedures in code, docs, tests or
104
+ commit messages.
105
+ - Keep `contract` and `query` free of React and RTK; keep `codegen` out of browser entry points.
106
+ - Update this skill (and the README) together with any change to options, CLI flags, generated files or behaviour
107
+ described here.
package/CHANGELOG.md ADDED
@@ -0,0 +1,103 @@
1
+ # Changelog
2
+
3
+ ## 0.2.2
4
+
5
+ ### Fixed
6
+ - api: `normalizeDddError` / `getErrorMessage` / `getErrorStatus` treat a response that is not JSON (RTK
7
+ `PARSING_ERROR`: an HTML error page, a PHP fatal, a proxy 502) as an HTTP error — `status` is the HTTP status and the
8
+ message is `Server error (HTTP <status>)` (≥ 500) or `Request failed (HTTP <status>)`, never the parser's
9
+ `SyntaxError: Unexpected token '<' …` text and never the body (it stays in `body`).
10
+ - api: `FETCH_ERROR` and `TIMEOUT_ERROR` get readable messages (`The server could not be reached`,
11
+ `The request timed out`) instead of the browser's error text.
12
+
13
+ ### Added
14
+ - api: `DddErrorMessages` / `DEFAULT_ERROR_MESSAGES` and a third argument of `normalizeDddError` / `getErrorMessage`
15
+ to replace (e.g. translate) these texts.
16
+
17
+ ## 0.2.1
18
+
19
+ ### Fixed
20
+ - codegen: the `responseHandler` (`blobResponseHandler` / `"text"`) is injected on the TypeScript syntax tree of the
21
+ generated api file instead of by line patterns. Endpoints whose long names prettier wraps onto their own line
22
+ (`key:` / `build.query<` / type arguments on separate lines) silently got no handler in 0.2.0 while their result
23
+ type already said `DddFileResponse` / `string`.
24
+ - codegen: generation aborts with an error listing each endpoint (and the reason) when a detected or overridden
25
+ handler cannot be injected, instead of skipping it.
26
+
27
+ ### Migration
28
+ - Regenerate the SDK; affected long-named download and text endpoints now get their handler.
29
+
30
+ ## 0.2.0
31
+
32
+ ### Added
33
+ - codegen: file responses are detected by their 2xx content types (`application/octet-stream`, `application/zip`,
34
+ `application/pdf`, `application/vnd.*` incl. spreadsheet types, `text/csv`, `image/*`, `audio/*`, `video/*`,
35
+ `font/*`; never `…json`). Such endpoints get `responseHandler: blobResponseHandler` (imported from
36
+ `@mgamadeus/ddd-web/api`) and the result type `DddFileResponse` (`{ blob, filename, contentType }`).
37
+ - codegen: `responseHandlers` overrides in `defineConfig`, globally and per api entry:
38
+ `{ method?, path: string | RegExp, handler: 'blob' | 'text' | 'json' }`, matched like `sideEffects` (api entry
39
+ first, first match wins). Overrides win over detection; `json` turns a detected handler off. For specs that declare
40
+ no or the wrong content type, e.g. `application/json` for an Excel export route.
41
+ - codegen: exported types `ResponseHandlerOverride` and `OperationMatcher`.
42
+
43
+ ### Changed
44
+ - codegen: a forced `text` handler on a JSON-declared response types the result as `string`.
45
+
46
+ ### Migration
47
+ - Regenerate the SDK. Endpoints that return files now resolve to `DddFileResponse` instead of a JSON-parsed body —
48
+ replace hand-written download endpoints with the generated hooks:
49
+ `const { blob, filename } = await trigger(args).unwrap(); downloadBlob(blob, filename ?? 'export.xlsx')`.
50
+ - An app with file endpoints imports `@mgamadeus/ddd-web/api` from generated code, so `@reduxjs/toolkit` (the
51
+ optional peer of `api`) must be installed — it already is for any RTK Query app.
52
+
53
+ ## 0.1.0
54
+
55
+ First usable release.
56
+ - Port of the DDD contract client (codegen, query, api, auth, contract).
57
+
58
+ ### Fixed (review round 1)
59
+ - Build: the parallel tsup configs no longer clean each other's output (`dist/codegen/index.d.ts` was missing);
60
+ `pnpm build` cleans `dist` once up front.
61
+ - codegen: the atomic output swap registers each restore right after its backup move — a failure between moving the
62
+ old output away and moving the new one in restores the old output; a failed restore keeps the backup and names it.
63
+ - codegen: models with the same leaf name in different namespaces stay separate files with unique exported names
64
+ (`Item`, `BooksItem`, …); the barrel exports every model file instead of dropping same-leaf entries.
65
+ - codegen: `--api` runs rebuild shared models from every configured spec, so fields contributed by other apis are kept.
66
+ - codegen: user `endpointOverrides` without `type` (e.g. only `parameterFilter`) no longer displace the
67
+ `x-ddd-side-effects` classification; an explicit user `type` still wins.
68
+ - codegen: `skipUpdatePostTwins` honours `x-ddd-entity` (only upsert twins of the same entity) and, without it,
69
+ requires identical summary, parameters, request body, responses and side-effect classification.
70
+ - codegen: writes without `x-ddd-entity` invalidate the whole entity tag (LIST + all ids).
71
+ - codegen: endpoints are matched to their operation through the generation itself, not by parsing URLs back —
72
+ entity tags and side effects now survive `encodePathParams` and `flattenArg`.
73
+ - codegen: `esmExtensions` applies to model imports, the models barrel and the api's models import (`index.js`).
74
+ - codegen: only text-only endpoints get a `string` response type (binary downloads stay as RTK types them).
75
+ - codegen: `$ref` path parameters are resolved before deciding a placeholder is undeclared.
76
+ - codegen: RegExp side-effect overrides with `g` / `y` flags match statelessly.
77
+ - codegen: the `x-ddd-*` types and the side-effect default come from `contract` (`hasSideEffects`; OPTIONS/TRACE
78
+ now count as reads); the codegen's tolerant input types derive from them.
79
+ - codegen: `ddd-web link-skills` says clearly when the installed package ships no skills or is not installed.
80
+ - api: token refresh shares one result per session generation: waiting requests retry even if the refreshed token
81
+ string is unchanged, a late 401 after a failed refresh does not log out again, and a refresh that finishes after a
82
+ logout or session change is discarded.
83
+ - api: `async-mutex` dependency removed.
84
+ - api: a non-empty string error body is used as the error message.
85
+ - auth: an injected token storage and a failing serializer can no longer make `TokenStorage` throw.
86
+ - auth: a present but invalid expiry claim counts as expired.
87
+ - contract: date-times with an offset are calendar-checked (`2026-02-30T00:00:00Z` → `null`).
88
+ - query: join keywords directly after a quote, bracket, number or `null` are recognised (`a eq '1'or b eq '2'`), so
89
+ `combineFilters` groups such clauses correctly.
90
+ - query: list literals are written as JSON lists (`["a","b"]`), so any string — also with newlines or other
91
+ control characters — reaches the backend unchanged (`formatFilterListItem`).
92
+ - query: `buildStaticArgsKey` / `buildColumnSearchesKey` serialise sorted `[name, value]` pairs as JSON
93
+ (collision-free).
94
+
95
+ ### CI / release
96
+ - CI checks every `exports` / `bin` target in the build and in the packed tarball, compiles a strict TypeScript
97
+ consumer (bundler and nodenext) against the installed tarball with npm and pnpm, runs `ddd-web-sdk` on the sample
98
+ spec there and type-checks the generated SDK (`test/consumer/run.sh`).
99
+ - Release workflow (`v*` tags): tag = version check, full verification, skills required in the tarball, staged
100
+ publish via npm trusted publishing (`npm stage publish`, npm ≥ 11.15.0; approve with `npm stage approve`).
101
+
102
+ ## 0.0.1
103
+ - Placeholder release to reserve the package name.