@mgamadeus/ddd-web 0.15.0 → 0.16.1

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`)
@@ -412,6 +413,105 @@ 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 (reportPath)
463
+ // or: endpoint: 'https://api.internal/api/public/common/issues/report' | () => url — the FULL URL, wins over apiBaseUrl
464
+ serverToken: process.env.ISSUES_INGEST_SERVER_TOKEN, // → section WEB_SERVER
465
+ release: () => process.env.WEB_RELEASE ?? null,
466
+ });
467
+ export const onRequestError = createServerRequestErrorHandler(() => serverIssuesReporter); // Next.js instrumentation.ts
468
+ ```
469
+
470
+ `endpoint` (string or function) is the full URL and wins when both are set; `apiBaseUrl` stays for compatibility —
471
+ as a function it, too, returns the full URL (kept from 0.16.0; prefer `endpoint`). The browser reporter has only
472
+ `endpoint` (full URL, or a path of the page's origin).
473
+
474
+ `installNodeIssueCapture(reporter)` adds `uncaughtExceptionMonitor` (observes only) and a flush on `beforeExit`;
475
+ `{ unhandledRejections: true }` also reports rejections — that listener stops Node from exiting on one.
476
+
477
+ **React Native / anything else:** the core directly, with `createFetchIssuesTransport()`:
478
+
479
+ ```ts
480
+ import { createIssuesReporter, createFetchIssuesTransport, createIssuesRouteTracker } from '@mgamadeus/ddd-web/issues';
481
+
482
+ const reporter = createIssuesReporter({
483
+ runtime: 'react-native', app: 'mobile',
484
+ endpoint: () => `${apiBaseUrl}/api/public/common/issues/report`,
485
+ transport: createFetchIssuesTransport({ timeoutMs: 10_000 }),
486
+ context: () => ({ release: appVersion, userAgent: `ExampleApp/${appVersion} (${platform})`, locale }),
487
+ });
488
+ ErrorUtils.setGlobalHandler((error) => reporter.captureError(error, 'error'));
489
+ ```
490
+
491
+ Behaviour:
492
+ - **Redaction** before anything leaves the device: token path segments (default = the backend's
493
+ `redactPathSegments`; `createIssuesRedactor({ tokenPathSegments, additionalRules })` for the app's own), `*token*`
494
+ query values, e-mails, bearer / JWT tokens, UUIDs, international phone numbers, long hex path segments.
495
+ - **Drops** what the backend drops anyway (chunk loads, `Script error.`, `ResizeObserver loop`) plus extension errors,
496
+ `window.ethereum`, `AbortError` and automated browsers; `dropRules: [...ISSUE_DROP_RULES, own]` extends the list.
497
+ - **De-duplication:** a repeat of a queued event raises its `count`; `clientFingerprint` = `name | normalised message
498
+ | top frame` (informational — the backend builds its own hashes).
499
+ - **Caps:** `rateLimitMode` `session` (browser default: 3 per fingerprint, 25 per page session, stop after 3 failed
500
+ sends) or `windowed` (node / react-native default: 3 per fingerprint per 5 min, 60 per minute, exponential backoff).
501
+ Batches of ≤ 10 events / 48 KB after 2 s or at 5 events; an event over 16 KB loses breadcrumbs, then frames beyond
502
+ 10, the raw stack and the message beyond 256 characters. One retry on a network error or 5xx, none on a 4xx.
503
+ `limits` overrides any of it.
504
+ - **Breadcrumbs** (≤ 20, newest kept): failed requests, `console.error`, clicks (`data-issues-action`, else tag and
505
+ role — never text), navigations; not attached on `node` (a server's trail mixes requests).
506
+ - **Transports:** browser = fetch with `keepalive`, `credentials: 'omit'`, the fetch from before the capture wrapped
507
+ it; on `flush({ unloading: true })` a beacon (`text/plain`, no preflight) unless the request carries `Authorization`
508
+ or a server token (a beacon has no headers).
509
+ - **Typed body from the app's own SDK:** pass `wire: { toWireEvent, toRequestBody }` built from the generated
510
+ `ClientIssueEvent` / request DTO models; the default `dddIssuesWireAdapter` writes the same shape. Works with
511
+ `createIssuesReporter`, `createBrowserIssuesReporter` and `createNodeIssuesReporter` alike (all generic over the event
512
+ and body types, defaulting to the DDD ones; inferred from `wire`).
513
+ - The reporter never throws into its caller and never reports its own failures.
514
+
415
515
  ## 6. Tokens (`/auth`)
416
516
 
417
517
  - `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,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.1
4
+
5
+ ### Changed
6
+ - `createBrowserIssuesReporter` / `createNodeIssuesReporter` and `BrowserIssuesReporterOptions` /
7
+ `NodeIssuesReporterOptions` are generic over the wire event and request-body types, defaulting to the DDD ones: a
8
+ `wire` built from your generated models now type-checks with the adapters, not only with `createIssuesReporter`.
9
+ Existing calls compile unchanged.
10
+
11
+ ### Added
12
+ - `NodeIssuesReporterOptions.endpoint` (string or function): the full URL of the ingest endpoint; wins over
13
+ `apiBaseUrl` when both are set. `apiBaseUrl` keeps its behaviour (a function returns the full URL) for compatibility.
14
+ The browser reporter already takes `endpoint` and has no `apiBaseUrl`.
15
+
16
+ ## 0.16.0
17
+
18
+ ### Added
19
+ - Client-errors reporter for the issues log of a mgamadeus/ddd backend (`IssuesLogService::logClientIssue`, Core
20
+ 3.10.0 or newer; body `{ report: { client, events } }` of the `ClientIssueReport` value objects, default path
21
+ `/api/public/common/issues/report`):
22
+ - `@mgamadeus/ddd-web/issues`: the platform-free core — `createIssuesReporter` (redact, drop, de-duplicate by
23
+ `clientFingerprint` into `count`, session or windowed caps, batching ≤ 10 events / 48 KB, size shrinking, one retry,
24
+ backoff, bearer and server-token headers), `normalizeError` / `parseStack` (V8, SpiderMonkey, JavaScriptCore),
25
+ `createIssuesRedactor` / `redactUrl` / `redactText`, `buildClientFingerprint`, `ISSUES_LIMITS` /
26
+ `mergeIssuesLimits`, `ISSUE_DROP_RULES` / `findIssueDropRule`, breadcrumb builders and trail, `buildRoutePattern`
27
+ / `createIssuesRouteTracker`, `createFetchIssuesTransport`. No DOM, no Node API, no global read at import time:
28
+ loads in React Native.
29
+ - `@mgamadeus/ddd-web/issues/browser`: `createBrowserIssuesReporter`, `installBrowserIssueCapture` (uncaught errors,
30
+ unhandled rejections; breadcrumbs from failed requests, `console.error` and clicks; flush on `pagehide`),
31
+ `createBeaconIssuesTransport`, `createBrowserIssuesRouteTracker`, `captureRenderError`, `readOrCreateIssuesTabId`.
32
+ - `@mgamadeus/ddd-web/issues/node`: `createNodeIssuesReporter`, `createServerRequestErrorHandler` (the shape of an
33
+ `onRequestError` hook), `installNodeIssueCapture`.
34
+ - `@mgamadeus/ddd-web/issues/wire`: the wire types (`DddClientIssueReport`, `DddClientIssueEvent`, …,
35
+ `DddClientIssueIngestResult`), `dddIssuesWireAdapter`, `DDD_ISSUES_REPORT_PATH`.
36
+ - `pnpm typecheck` also checks the issues core without the DOM lib and without Node types
37
+ (`tsconfig.issues-core.json`).
38
+
3
39
  ## 0.15.0
4
40
 
5
41
  ### 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,55 @@ 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, // + the default report path; or `endpoint` = the full URL (wins)
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
+ Both adapters are generic over the wire types like the core: a `wire` built from your generated models
193
+ (`createNodeIssuesReporter({ …, wire: appIssuesWire })`) types the event and the body with them; without it the
194
+ DDD defaults apply.
195
+
196
+ React Native and other runtimes use `createIssuesReporter` from `/issues` with `createFetchIssuesTransport()`.
197
+ Everything is redacted on the device (tokens in paths and queries, e-mails, bearer / JWT tokens, UUIDs, phone numbers),
198
+ known noise is dropped, repeats are folded into `count`, and caps, batching, retry and backoff keep a broken page from
199
+ flooding the endpoint. Details: the agent skill, `references/consumer.md` › Client errors.
200
+
149
201
  ## Agent skill
150
202
 
151
203
  The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). Link it into an app's