@mgamadeus/ddd-web 0.14.0 → 0.16.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 with defineConfig (schemaFile, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, mergeDddTagTypes, blobResponseHandler downloads, multipartFiles uploads, upload/download progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin, session-bound requests, shouldRefresh, normalizeDddError), token storage, JWT helpers, foreign global Request (MooTools: dddFetchApiRequestPlugin), link-skills, release. Use when wiring a frontend to a DDD backend, 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, 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), 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, release. Use when wiring a frontend to a DDD backend, 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 web, server or mobile errors to the issues log, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.4.2"
6
+ version: "1.5.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -24,6 +24,10 @@ frontend code. No UI components, no domain logic — apps bring their own design
24
24
  | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`, `getSessionKey`), `createDddRefresh`, `normalizeDddError`, downloads, multipart (`buildDddMultipartBody`), `mergeDddTagTypes`, `createAuthEndpoints` |
25
25
  | `@mgamadeus/ddd-web/auth` | anywhere | `TokenStorage` adapters, `decodeJwt`, `isExpired`, SSR-safe storage |
26
26
  | `@mgamadeus/ddd-web/contract` | types + small helpers | `x-ddd-*` types, error body, DDD date-time, translations, operators, `normalizeDddError` / `getErrorMessage` / `getErrorStatus` (also without RTK) |
27
+ | `@mgamadeus/ddd-web/issues` | anywhere (no DOM, no Node API: browser, Node, React Native) | client-errors reporter core: `createIssuesReporter`, normalise, redact, fingerprint, limits, drop rules, breadcrumbs, `buildRoutePattern` / `createIssuesRouteTracker`, `createFetchIssuesTransport` |
28
+ | `@mgamadeus/ddd-web/issues/browser` | browser | `createBrowserIssuesReporter`, `installBrowserIssueCapture`, `createBeaconIssuesTransport`, `createBrowserIssuesRouteTracker`, `captureRenderError` |
29
+ | `@mgamadeus/ddd-web/issues/node` | Node ≥ 20 | `createNodeIssuesReporter`, `createServerRequestErrorHandler` (`onRequestError` shape), `installNodeIssueCapture` |
30
+ | `@mgamadeus/ddd-web/issues/wire` | types + adapter | the `ClientIssueReport` wire types, `dddIssuesWireAdapter`, `DDD_ISSUES_REPORT_PATH` |
27
31
 
28
32
  ESM only, Node ≥ 20. Consumers may use npm or pnpm.
29
33
 
@@ -116,10 +120,15 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
116
120
  `invalidation` resolver in the config (`broadInvalidation` = the 0.2 behaviour). A spec without
117
121
  `info.x-ddd-contract` is read as a pre-contract DDD spec (warning); an unsupported contract number aborts.
118
122
 
123
+ - **Client errors go through `/issues`** to the application's client-errors endpoint (`logClientIssue`, Core ≥ 3.10.0):
124
+ one reporter per runtime, the route PATTERN set on every navigation, never a hand-written `window.onerror` + `fetch`.
125
+ Keep `/issues` free of DOM and Node APIs (`tsconfig.issues-core.json` checks it); platform code goes into
126
+ `/issues/browser` or `/issues/node`.
127
+
119
128
  ## References
120
129
 
121
130
  - [references/consumer.md](references/consumer.md) — every config option, CLI flag, generated file and cache-tag rule;
122
- the query builders and validators; base query, refresh, errors, downloads; token storage; contract helpers;
123
- troubleshooting.
131
+ the query builders and validators; base query, refresh, errors, downloads; the client-errors reporter; token storage;
132
+ contract helpers; troubleshooting.
124
133
  - [references/maintaining.md](references/maintaining.md) — repository layout, build and tests, the consumer check, the
125
134
  `x-ddd` contract and how it stays in step with `mgamadeus/ddd`, release workflow, versioning.
@@ -11,6 +11,7 @@
11
11
  7. Contract helpers (`/contract`)
12
12
  8. Agent skills (`link-skills`)
13
13
  5a. Pages with a foreign global `Request` (`/fetch-api-request`, `/vite`)
14
+ 5b. Client errors (`/issues`, `/issues/browser`, `/issues/node`, `/issues/wire`)
14
15
  9. Troubleshooting
15
16
 
16
17
  ## 1. Configuration (`openapi-config.ts`)
@@ -50,7 +51,7 @@ too). A plain RTK-codegen file with `export const apis = [...]` is accepted as w
50
51
  | `invalidation` | `(operation: InvalidationOperation) => InvalidationTag[] \| undefined`: overrides the tags a mutation invalidates; `undefined` keeps the default. `broadInvalidation` (exported) restores the 0.2 behaviour. See section 3. |
51
52
  | `workspace` | `{ envVar, envFiles?, urlKeys?, prompt? }`: resolves a workspace / subdomain value (CLI `--workspace` → env → URL sniffed from `.env` / `.env.local` → TTY prompt) into `process.env[envVar]` before the config is evaluated again. |
52
53
  | `tsconfig` | tsconfig of the final type check. Default `tsconfig.json` next to the config. |
53
- | `endpoints` | How endpoints and their body argument are named; off by default. `naming: 'path'`: a pure function of verb and path — `stripPathPrefix` (default `/api` or `/app/api`) cut, every `{param}/` cut out and only the LAST one kept, the rest split on `/ _ - .` and capitalised behind the verb, `By<LastInner>` appended, a trailing `{param}` becomes `By<Param>` where it stands (`POST /api/client/ai/conversations/{locationId}/purposed/{purposeName}` → `postClientAiConversationsPurposedByPurposeNameByLocationId`; `buildEndpointNameFromPath` is exported). `naming` may be a function `({ method, path, operation }) => name`. 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. Query and path parameters stay flat in the argument. |
54
+ | `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. |
54
55
  | `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. |
55
56
 
56
57
  ```ts
@@ -412,6 +413,98 @@ export default defineConfig({ plugins: [react(), dddFetchApiRequestPlugin()] });
412
413
  - `isFetchApiRequest` / `isFetchApiRequestConstructor` check the `[object Request]` tag, not `instanceof`: a request from
413
414
  the frame is no instance of the page's `Request`.
414
415
 
416
+ ## 5b. Client errors (`/issues`, `/issues/browser`, `/issues/node`, `/issues/wire`)
417
+
418
+ One reporter for a browser, the app's Node server and a React Native app. It sends to the client-errors endpoint of
419
+ a mgamadeus/ddd backend: the application's controller hands the body to `IssuesLogService::logClientIssue()` (Core
420
+ 3.10.0 or newer), and the events land in the issues log with the backend's errors (sections WEB, WEB_SERVER).
421
+
422
+ **Server contract.** `POST` (default path `DDD_ISSUES_REPORT_PATH` = `/api/public/common/issues/report`, the route of
423
+ the issues-log guide; the application owns it) with the body `{ report: { client, events } }`:
424
+ `client` = `ClientIssueContext` (`runtime` `browser` · `node` · `react-native`, `app`, `release`, `tabId`,
425
+ `userAgent` (node / RN only), `viewportWidth`, `viewportHeight`, `locale`); `events.elements` = 1–10
426
+ `ClientIssueEvent` (`occurredAt`, `kind` `error` · `unhandledrejection` · `react-render` · `server-request` · `manual`,
427
+ `level` `error` · `warning`, `name`, `message`, `frames.elements` (innermost first), `rawStack` (only without frames),
428
+ `url`, `routePattern`, `requestMethod`, `httpStatus`, `breadcrumbs.elements`, `tags.elements`, `count`,
429
+ `clientFingerprint`). Answer: `ClientIssueIngestResult` (`accepted`, `dropped`, `dropReasons`). Headers:
430
+ `Authorization: Bearer …` when `getAuthorization` returns a token (the controller attributes the account), the server
431
+ token (`X-Issues-Server-Token` by default, `serverTokenHeader`) from the app's own server (section WEB_SERVER). The
432
+ reporter's caps equal the backend's; the backend enforces them again.
433
+
434
+ **Browser** (in the client entry, before hydration):
435
+
436
+ ```ts
437
+ import { createBrowserIssuesReporter, installBrowserIssueCapture, captureRenderError } from '@mgamadeus/ddd-web/issues/browser';
438
+
439
+ export const issuesReporter = createBrowserIssuesReporter({
440
+ app: 'web',
441
+ endpoint: `${apiBaseUrl}/api/public/common/issues/report`, // default: that path on the page's origin
442
+ release: () => document.documentElement.dataset.release ?? null, // the key the source maps are uploaded under
443
+ getAuthorization: () => tokenStorage.read().accessToken, // or later: issuesReporter.setAuthorizationReader(…)
444
+ }); // null during SSR
445
+ if (issuesReporter) installBrowserIssueCapture(issuesReporter); // error, unhandledrejection, breadcrumbs, pagehide flush
446
+
447
+ // error boundary: an error with a `digest` came from the server and is reported there
448
+ captureRenderError(issuesReporter, error);
449
+ ```
450
+
451
+ Route tracking: `createBrowserIssuesRouteTracker(reporter).trackRoute(pathname, params)` on every route change (e.g.
452
+ an effect on the router's path and params). It sets the route PATTERN (`/books/[bookId]`), which names the issue on
453
+ the backend, and adds a navigation breadcrumb.
454
+
455
+ **Node server:**
456
+
457
+ ```ts
458
+ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgamadeus/ddd-web/issues/node';
459
+
460
+ const serverIssuesReporter = createNodeIssuesReporter({
461
+ app: 'web',
462
+ apiBaseUrl: process.env.API_INTERNAL_URL, // + DDD_ISSUES_REPORT_PATH
463
+ serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // → section WEB_SERVER
464
+ release: () => process.env.WEB_RELEASE ?? null,
465
+ });
466
+ export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter); // Next.js instrumentation.ts
467
+ ```
468
+
469
+ `installNodeIssueCapture(reporter)` adds `uncaughtExceptionMonitor` (observes only) and a flush on `beforeExit`;
470
+ `{ unhandledRejections: true }` also reports rejections — that listener stops Node from exiting on one.
471
+
472
+ **React Native / anything else:** the core directly, with `createFetchIssuesTransport()`:
473
+
474
+ ```ts
475
+ import { createIssuesReporter, createFetchIssuesTransport, createIssuesRouteTracker } from '@mgamadeus/ddd-web/issues';
476
+
477
+ const reporter = createIssuesReporter({
478
+ runtime: 'react-native', app: 'mobile',
479
+ endpoint: () => `${apiBaseUrl}/api/public/common/issues/report`,
480
+ transport: createFetchIssuesTransport({ timeoutMs: 10_000 }),
481
+ context: () => ({ release: appVersion, userAgent: `ExampleApp/${appVersion} (${platform})`, locale }),
482
+ });
483
+ ErrorUtils.setGlobalHandler((error) => reporter.captureError(error, 'error'));
484
+ ```
485
+
486
+ Behaviour:
487
+ - **Redaction** before anything leaves the device: token path segments (default = the backend's
488
+ `redactPathSegments`; `createIssuesRedactor({ tokenPathSegments, additionalRules })` for the app's own), `*token*`
489
+ query values, e-mails, bearer / JWT tokens, UUIDs, international phone numbers, long hex path segments.
490
+ - **Drops** what the backend drops anyway (chunk loads, `Script error.`, `ResizeObserver loop`) plus extension errors,
491
+ `window.ethereum`, `AbortError` and automated browsers; `dropRules: [...ISSUE_DROP_RULES, own]` extends the list.
492
+ - **De-duplication:** a repeat of a queued event raises its `count`; `clientFingerprint` = `name | normalised message
493
+ | top frame` (informational — the backend builds its own hashes).
494
+ - **Caps:** `rateLimitMode` `session` (browser default: 3 per fingerprint, 25 per page session, stop after 3 failed
495
+ sends) or `windowed` (node / react-native default: 3 per fingerprint per 5 min, 60 per minute, exponential backoff).
496
+ Batches of ≤ 10 events / 48 KB after 2 s or at 5 events; an event over 16 KB loses breadcrumbs, then frames beyond
497
+ 10, the raw stack and the message beyond 256 characters. One retry on a network error or 5xx, none on a 4xx.
498
+ `limits` overrides any of it.
499
+ - **Breadcrumbs** (≤ 20, newest kept): failed requests, `console.error`, clicks (`data-issues-action`, else tag and
500
+ role — never text), navigations; not attached on `node` (a server's trail mixes requests).
501
+ - **Transports:** browser = fetch with `keepalive`, `credentials: 'omit'`, the fetch from before the capture wrapped
502
+ it; on `flush({ unloading: true })` a beacon (`text/plain`, no preflight) unless the request carries `Authorization`
503
+ or a server token (a beacon has no headers).
504
+ - **Typed body from the app's own SDK:** pass `wire: { toWireEvent, toRequestBody }` built from the generated
505
+ `ClientIssueEvent` / request DTO models; the default `dddIssuesWireAdapter` writes the same shape.
506
+ - The reporter never throws into its caller and never reports its own failures.
507
+
415
508
  ## 6. Tokens (`/auth`)
416
509
 
417
510
  - `TokenStorage` = `read()` / `write({ accessToken?, refreshToken? })` (`undefined` keeps, `null` removes) /
@@ -19,6 +19,10 @@ src/
19
19
  definition-driven validators (definition.ts) — no React, no RTK
20
20
  api/ createDddBaseQuery, refresh coordination, errors, downloads, debug passthrough, auth endpoints
21
21
  auth/ token storage adapters, JWT helpers, SSR-safe storage
22
+ issues/ client-errors reporter: core (capture model, normalize, redact, fingerprint, limits, filters,
23
+ breadcrumbs, route pattern, transport, reporter) — no DOM, no Node API, checked by
24
+ tsconfig.issues-core.json and test/issues/core-without-dom.test.ts; wire/ (DDD ClientIssueReport shape),
25
+ browser/, node/ (adapters)
22
26
  codegen/ cli.ts (bins), config.ts (defineConfig, loadConfig), generate.ts (pipeline), spec.ts (load + validate),
23
27
  registry / models / rtk / endpoints / enhance / tags / response-handlers (text + file detection,
24
28
  AST-based injection that aborts on a miss) / repair / output (atomic commit),
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Added
6
+ - Client-errors reporter for the issues log of a mgamadeus/ddd backend (`IssuesLogService::logClientIssue`, Core
7
+ 3.10.0 or newer; body `{ report: { client, events } }` of the `ClientIssueReport` value objects, default path
8
+ `/api/public/common/issues/report`):
9
+ - `@mgamadeus/ddd-web/issues`: the platform-free core — `createIssuesReporter` (redact, drop, de-duplicate by
10
+ `clientFingerprint` into `count`, session or windowed caps, batching ≤ 10 events / 48 KB, size shrinking, one retry,
11
+ backoff, bearer and server-token headers), `normalizeError` / `parseStack` (V8, SpiderMonkey, JavaScriptCore),
12
+ `createIssuesRedactor` / `redactUrl` / `redactText`, `buildClientFingerprint`, `ISSUES_LIMITS` /
13
+ `mergeIssuesLimits`, `ISSUE_DROP_RULES` / `findIssueDropRule`, breadcrumb builders and trail, `buildRoutePattern`
14
+ / `createIssuesRouteTracker`, `createFetchIssuesTransport`. No DOM, no Node API, no global read at import time:
15
+ loads in React Native.
16
+ - `@mgamadeus/ddd-web/issues/browser`: `createBrowserIssuesReporter`, `installBrowserIssueCapture` (uncaught errors,
17
+ unhandled rejections; breadcrumbs from failed requests, `console.error` and clicks; flush on `pagehide`),
18
+ `createBeaconIssuesTransport`, `createBrowserIssuesRouteTracker`, `captureRenderError`, `readOrCreateIssuesTabId`.
19
+ - `@mgamadeus/ddd-web/issues/node`: `createNodeIssuesReporter`, `createServerRequestErrorHandler` (the shape of an
20
+ `onRequestError` hook), `installNodeIssueCapture`.
21
+ - `@mgamadeus/ddd-web/issues/wire`: the wire types (`DddClientIssueReport`, `DddClientIssueEvent`, …,
22
+ `DddClientIssueIngestResult`), `dddIssuesWireAdapter`, `DDD_ISSUES_REPORT_PATH`.
23
+ - `pnpm typecheck` also checks the issues core without the DOM lib and without Node types
24
+ (`tsconfig.issues-core.json`).
25
+
26
+ ## 0.15.0
27
+
28
+ ### Added
29
+ - `endpoints.requestBuilders: 'all'`: `<stem>Requests.ts` holds the request builder of every operation of the
30
+ document (their argument types are written), while the api file injects only what `filterEndpoints` keeps.
31
+
32
+ ### Changed
33
+ - Parameters `in: cookie` leave the generated endpoints by default (`endpoints.cookieParameters: 'drop'`): a browser
34
+ sends its cookies itself and RTK Query's `FetchArgs` has no field for them — a request builder carrying `cookies`
35
+ failed the type check. `cookieParameters: 'keep'` restores the former output.
36
+
3
37
  ## 0.14.0
4
38
 
5
39
  ### Added
package/README.md CHANGED
@@ -17,6 +17,8 @@ those conventions into frontend code:
17
17
  file downloads
18
18
  - **auth**: token-pair utilities and a pluggable storage adapter
19
19
  - **contract**: TypeScript types for the DDD wire format
20
+ - **issues**: a client-errors reporter for browsers, Node servers and React Native apps that sends to the backend's
21
+ issues log
20
22
 
21
23
  It contains no UI components and no domain logic; apps bring their own design system and business screens.
22
24
  Works with the OpenAPI output of current mgamadeus/ddd backends. The `x-ddd-*` extensions (contract version 1) are used
@@ -48,8 +50,9 @@ pnpm exec ddd-web-sdk # generate the SDK
48
50
  pnpm exec ddd-web link-skills # link the package's agent skills into .claude/skills
49
51
  ```
50
52
 
51
- Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`, `/fetch-api-request` and `/vite`
52
- (pages whose global `Request` is not the Fetch API's, e.g. MooTools or Prototype: `dddFetchApiRequestPlugin()`).
53
+ Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`, `/fetch-api-request`, `/vite`
54
+ (pages whose global `Request` is not the Fetch API's, e.g. MooTools or Prototype: `dddFetchApiRequestPlugin()`) and
55
+ `/issues`, `/issues/browser`, `/issues/node`, `/issues/wire` (client errors, below).
53
56
 
54
57
  ### File downloads
55
58
 
@@ -146,6 +149,51 @@ export default defineConfig({
146
149
  });
147
150
  ```
148
151
 
152
+ ### Client errors
153
+
154
+ `@mgamadeus/ddd-web/issues` reports the errors of a browser, the app's Node server or a React Native app to the
155
+ client-errors endpoint of a mgamadeus/ddd backend (`IssuesLogService::logClientIssue`, Core 3.10.0 or newer; the
156
+ application declares the route, by default `POST /api/public/common/issues/report`). The core has no DOM, framework
157
+ or Node dependency; the platform adapters are separate entries.
158
+
159
+ ```ts
160
+ // browser, before hydration
161
+ import {
162
+ createBrowserIssuesReporter,
163
+ createBrowserIssuesRouteTracker,
164
+ installBrowserIssueCapture,
165
+ } from '@mgamadeus/ddd-web/issues/browser';
166
+
167
+ const issuesReporter = createBrowserIssuesReporter({
168
+ app: 'web',
169
+ endpoint: 'https://api.example.com/api/public/common/issues/report',
170
+ release: () => document.documentElement.dataset.release ?? null,
171
+ getAuthorization: () => tokenStorage.read().accessToken,
172
+ });
173
+ if (issuesReporter) installBrowserIssueCapture(issuesReporter); // uncaught errors, rejections, breadcrumbs, unload flush
174
+ const issuesRouteTracker = issuesReporter && createBrowserIssuesRouteTracker(issuesReporter);
175
+
176
+ // on every route change: the route PATTERN names the issue on the backend
177
+ issuesRouteTracker?.trackRoute(pathname, params); // → /books/[bookId]
178
+ ```
179
+
180
+ ```ts
181
+ // Node server (e.g. Next.js instrumentation.ts)
182
+ import { createNodeIssuesReporter, createServerRequestErrorHandler } from '@mgamadeus/ddd-web/issues/node';
183
+
184
+ const serverIssuesReporter = createNodeIssuesReporter({
185
+ app: 'web',
186
+ apiBaseUrl: process.env.API_INTERNAL_URL,
187
+ serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // the backend files these as WEB_SERVER
188
+ });
189
+ export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter);
190
+ ```
191
+
192
+ React Native and other runtimes use `createIssuesReporter` from `/issues` with `createFetchIssuesTransport()`.
193
+ Everything is redacted on the device (tokens in paths and queries, e-mails, bearer / JWT tokens, UUIDs, phone numbers),
194
+ known noise is dropped, repeats are folded into `count`, and caps, batching, retry and backoff keep a broken page from
195
+ flooding the endpoint. Details: the agent skill, `references/consumer.md` › Client errors.
196
+
149
197
  ## Agent skill
150
198
 
151
199
  The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). Link it into an app's
@@ -494,9 +494,13 @@ function buildEndpointNameFromPath(method, path11, stripPathPrefix = DEFAULT_STR
494
494
  function prepareDocumentForEndpoints(doc, options) {
495
495
  const naming = options.naming ?? "rtk";
496
496
  const bodyArg = options.bodyArg ?? "rtk";
497
+ const dropsCookieParameters = (options.cookieParameters ?? "drop") === "drop";
497
498
  const endpointNamesByPlaceholder = /* @__PURE__ */ new Map();
498
- if (naming === "rtk" && bodyArg === "rtk") return { doc, endpointNamesByPlaceholder };
499
+ if (naming === "rtk" && bodyArg === "rtk" && !(dropsCookieParameters && hasCookieParameters(doc))) {
500
+ return { doc, endpointNamesByPlaceholder };
501
+ }
499
502
  const prepared = structuredClone(doc);
503
+ if (dropsCookieParameters) dropCookieParameters(prepared);
500
504
  const pathByName = /* @__PURE__ */ new Map();
501
505
  for (const [path11, item] of Object.entries(prepared.paths ?? {})) {
502
506
  if (!item) continue;
@@ -533,6 +537,35 @@ function restoreEndpointNames(code, locations, endpointNamesByPlaceholder) {
533
537
  for (const [key, location] of locations) restoredLocations.set(restore(key), location);
534
538
  return { code: restore(code), locations: restoredLocations };
535
539
  }
540
+ var isCookieParameter = (parameter, doc) => {
541
+ const resolved = resolveParameter(parameter, doc);
542
+ return typeof resolved === "object" && resolved !== null && resolved.in === "cookie";
543
+ };
544
+ function resolveParameter(parameter, doc) {
545
+ const ref = parameter?.$ref;
546
+ if (typeof ref !== "string" || !ref.startsWith("#/components/parameters/")) return parameter;
547
+ return doc.components?.parameters?.[ref.slice("#/components/parameters/".length)];
548
+ }
549
+ function hasCookieParameters(doc) {
550
+ for (const item of Object.values(doc.paths ?? {})) {
551
+ if (!item) continue;
552
+ const lists = [item.parameters, ...HTTP_METHODS.map((method) => item[method]?.parameters)];
553
+ if (lists.some((list2) => Array.isArray(list2) && list2.some((parameter) => isCookieParameter(parameter, doc)))) return true;
554
+ }
555
+ return false;
556
+ }
557
+ function dropCookieParameters(doc) {
558
+ for (const item of Object.values(doc.paths ?? {})) {
559
+ if (!item) continue;
560
+ if (Array.isArray(item.parameters)) item.parameters = item.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
561
+ for (const method of HTTP_METHODS) {
562
+ const operation = item[method];
563
+ if (operation && Array.isArray(operation.parameters)) {
564
+ operation.parameters = operation.parameters.filter((parameter) => !isCookieParameter(parameter, doc));
565
+ }
566
+ }
567
+ }
568
+ }
536
569
  function titleRequestBody(operation) {
537
570
  const content = operation.requestBody?.content;
538
571
  for (const media of Object.values(content ?? {})) {
@@ -1836,7 +1869,7 @@ function buildRegistry(docs, logger) {
1836
1869
  }
1837
1870
 
1838
1871
  // src/codegen/repair.ts
1839
- function resolveParameter(doc, parameter) {
1872
+ function resolveParameter2(doc, parameter) {
1840
1873
  let current = parameter;
1841
1874
  for (let hops = 0; current?.$ref !== void 0 && hops < 10; hops++) {
1842
1875
  const match = /^#\/components\/parameters\/(.+)$/.exec(current.$ref);
@@ -1853,7 +1886,7 @@ function repairMissingPathParameters(doc, logger) {
1853
1886
  if (placeholders.length === 0) continue;
1854
1887
  const pathLevel = doc.paths?.[path11]?.parameters ?? [];
1855
1888
  const declared = new Set(
1856
- [...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
1889
+ [...pathLevel, ...operation.parameters ?? []].map((parameter) => resolveParameter2(doc, parameter)).filter((parameter) => parameter !== null && parameter.in === "path").map((parameter) => parameter.name)
1857
1890
  );
1858
1891
  const missing = placeholders.filter((name) => !declared.has(name));
1859
1892
  if (missing.length > 0) repairs.push({ path: path11, method, names: missing });
@@ -2126,22 +2159,15 @@ async function generateSdk(options = {}) {
2126
2159
  const modelOptions = loaded.config.models ?? {};
2127
2160
  const prepared = prepareDocumentForModels(doc, modelOptions);
2128
2161
  const preparedEndpoints = prepareDocumentForEndpoints(prepared.doc, loaded.config.endpoints ?? {});
2129
- const generated = await runRtkCodegen(
2130
- api,
2131
- preparedEndpoints.doc,
2132
- index,
2133
- path9.join(specDir, `${i}.json`),
2134
- prettierConfigFile,
2135
- (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName
2136
- );
2137
- const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
2162
+ const endpointOptions = loaded.config.endpoints ?? {};
2163
+ const esm = api.config.esmExtensions === true;
2138
2164
  const extractOptions = {
2139
2165
  apiFilePath: api.outputFile,
2140
2166
  modelsDir,
2141
2167
  registry,
2142
2168
  files,
2143
2169
  logger,
2144
- esm: api.config.esmExtensions === true,
2170
+ esm,
2145
2171
  documentModels: prepared.documentModels,
2146
2172
  enumConsts: modelOptions.enums === "const",
2147
2173
  constsByFile,
@@ -2149,42 +2175,46 @@ async function generateSdk(options = {}) {
2149
2175
  writeIndex: modelOptions.index !== false,
2150
2176
  uniqueNameByPath
2151
2177
  };
2152
- if (modelOptions.scope === "all" && api.config.filterEndpoints !== void 0) {
2153
- const unfiltered = await runRtkCodegen(
2154
- { ...api, config: { ...api.config, filterEndpoints: void 0 } },
2155
- preparedEndpoints.doc,
2156
- index,
2157
- path9.join(specDir, `${i}-all.json`),
2158
- prettierConfigFile,
2159
- (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName
2160
- );
2161
- const unfilteredCode = restoreEndpointNames(unfiltered.code, unfiltered.locations, preparedEndpoints.endpointNamesByPlaceholder).code;
2162
- extractModels({ ...extractOptions, apiSource: unfilteredCode, modelsOnly: true });
2163
- logger.info(" models of all operations written (models.scope all)");
2164
- }
2165
- const endpoints = parseApiEndpoints(rtk.code, logger, rtk.locations);
2166
- const handlerEndpoints = detectResponseHandlerEndpoints(doc, endpoints, api.responseHandlers);
2167
- const responseKinds = /* @__PURE__ */ new Map();
2168
- for (const endpoint of endpoints) {
2169
- const kind = handlerEndpoints.get(endpoint.key);
2170
- if (kind && endpoint.responseType) responseKinds.set(endpoint.responseType, kind);
2178
+ const endpointNameOf = (rtkName) => preparedEndpoints.endpointNamesByPlaceholder.get(rtkName) ?? rtkName;
2179
+ const runPass = async (passApi, specName, modelsOnly) => {
2180
+ const generated = await runRtkCodegen(passApi, preparedEndpoints.doc, index, path9.join(specDir, specName), prettierConfigFile, endpointNameOf);
2181
+ const rtk = restoreEndpointNames(generated.code, generated.locations, preparedEndpoints.endpointNamesByPlaceholder);
2182
+ const endpoints2 = parseApiEndpoints(rtk.code, logger, rtk.locations);
2183
+ const handlerEndpoints2 = detectResponseHandlerEndpoints(doc, endpoints2, api.responseHandlers);
2184
+ const responseKinds = /* @__PURE__ */ new Map();
2185
+ for (const endpoint of endpoints2) {
2186
+ const kind = handlerEndpoints2.get(endpoint.key);
2187
+ if (kind && endpoint.responseType) responseKinds.set(endpoint.responseType, kind);
2188
+ }
2189
+ const multipart = injectMultipartBodies(rtk.code, detectMultipartEndpoints(doc, endpoints2), logger);
2190
+ const apiSource = extractModels({ ...extractOptions, apiSource: multipart.source, responseKinds, modelsOnly });
2191
+ const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints2);
2192
+ const finalApiSource2 = multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
2193
+ ${withHandlers}` : withHandlers;
2194
+ return { endpoints: endpoints2, handlerEndpoints: handlerEndpoints2, multipartCount: multipart.injected.length, finalApiSource: finalApiSource2 };
2195
+ };
2196
+ const buildersOfAllOperations = endpointOptions.requestBuilders === "all" && api.config.filterEndpoints !== void 0;
2197
+ let requestsSourceOfAllOperations = null;
2198
+ if ((modelOptions.scope === "all" || buildersOfAllOperations) && api.config.filterEndpoints !== void 0) {
2199
+ const unfiltered = await runPass({ ...api, config: { ...api.config, filterEndpoints: void 0 } }, `${i}-all.json`, !buildersOfAllOperations);
2200
+ if (buildersOfAllOperations) {
2201
+ const requestsStem = `${api.stem}Requests`;
2202
+ requestsSourceOfAllOperations = splitRequestBuilders(unfiltered.finalApiSource, requestsStem, `./${requestsStem}`).requestsSource;
2203
+ logger.info(" request builders of all operations (endpoints.requestBuilders all)");
2204
+ }
2205
+ if (modelOptions.scope === "all") logger.info(" models of all operations written (models.scope all)");
2171
2206
  }
2207
+ const { endpoints, handlerEndpoints, multipartCount, finalApiSource } = await runPass(api, `${i}.json`, false);
2172
2208
  const fileCount = [...handlerEndpoints.values()].filter((kind) => kind === "blob").length;
2173
2209
  if (fileCount > 0) logger.info(` ${fileCount} file download endpoint(s) (blobResponseHandler)`);
2174
- const multipart = injectMultipartBodies(rtk.code, detectMultipartEndpoints(doc, endpoints), logger);
2175
- if (multipart.injected.length > 0) logger.info(` ${multipart.injected.length} multipart endpoint(s) (multipartFiles)`);
2176
- const esm = api.config.esmExtensions === true;
2177
- const apiSource = extractModels({ ...extractOptions, apiSource: multipart.source, responseKinds });
2210
+ if (multipartCount > 0) logger.info(` ${multipartCount} multipart endpoint(s) (multipartFiles)`);
2178
2211
  if (!write) continue;
2179
- const withHandlers = injectResponseHandlers(apiSource, handlerEndpoints);
2180
- const finalApiSource = multipart.injected.length > 0 ? `${MULTIPART_IMPORT}
2181
- ${withHandlers}` : withHandlers;
2182
- if (loaded.config.endpoints?.requestBuilders) {
2212
+ if (endpointOptions.requestBuilders) {
2183
2213
  const requestsStem = `${api.stem}Requests`;
2184
2214
  const split = splitRequestBuilders(finalApiSource, requestsStem, esm ? `./${requestsStem}.js` : `./${requestsStem}`);
2185
2215
  files.set(api.outputFile, split.apiSource);
2186
- files.set(path9.join(api.outputDir, `${requestsStem}.ts`), split.requestsSource);
2187
- logger.info(` ${split.count} request builder(s) in ${requestsStem}.ts`);
2216
+ files.set(path9.join(api.outputDir, `${requestsStem}.ts`), requestsSourceOfAllOperations ?? split.requestsSource);
2217
+ logger.info(` ${split.count} request builder(s) used by ${api.stem}.ts`);
2188
2218
  } else {
2189
2219
  files.set(api.outputFile, finalApiSource);
2190
2220
  }
@@ -2299,4 +2329,4 @@ export {
2299
2329
  generateSdk,
2300
2330
  linkSkills
2301
2331
  };
2302
- //# sourceMappingURL=chunk-HVYT2X4V.js.map
2332
+ //# sourceMappingURL=chunk-6CQEUZ3B.js.map