@mgamadeus/ddd-web 0.3.1 → 0.4.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. Covers openapi-config.ts with defineConfig (schemaFile, apiFile, outputFile, modelsDir, skipUpdatePostTwins, sideEffects and responseHandlers overrides, invalidation resolver, baseApiImport, esmExtensions, workspace), the RTK Query SDK from ddd-web-sdk (--api, --schema, --skip-tsc; Enhanced/Tags files, cache tags by entity identity, file downloads via blobResponseHandler), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter, buildFulltextFilter), createDddBaseQuery (Bearer, shared refresh + retry, shouldRefresh, normalizeDddError), token storage, JWT helpers, contract types (x-ddd-*, DDD date-time, translations), link-skills, maintaining (pnpm, vitest, consumer check, trusted-publishing release, 0.x semver). Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, fixing token refresh, cache tags or refetch storms, downloading an Excel/ZIP/PDF export, or releasing ddd-web."
3
+ description: "Use and maintain @mgamadeus/ddd-web, the TS client of mgamadeus/ddd. Covers openapi-config.ts with defineConfig (schemaFile URL or local file, sideEffects, responseHandlers, invalidation), the RTK Query SDK from ddd-web-sdk (Enhanced/Tags files, cache tags by entity identity, typed tagTypes via mergeDddTagTypes, file downloads via blobResponseHandler, file uploads: generated multipartFiles argument, buildDddMultipartBody, upload with progress via baseQuery.upload), QueryOptions builders (buildQueryOptions, combineFilters, buildInFilter), createDddBaseQuery (Bearer, shared refresh + retry, relogin for guest or device sessions without refresh token, shouldRefresh, normalizeDddError), token storage, JWT helpers, contract types, link-skills, release. Use when wiring a frontend to a DDD backend, regenerating the SDK, building filters, uploading files, multipart, FormData, upload progress, fixing token refresh, guest login, cache tags that invalidate nothing, downloading an export, or releasing ddd-web."
4
4
  metadata:
5
5
  author: mgamadeus
6
- version: "1.2.0"
6
+ version: "1.3.0"
7
7
  package: "@mgamadeus/ddd-web"
8
8
  ---
9
9
 
@@ -21,7 +21,7 @@ frontend code. No UI components, no domain logic — apps bring their own design
21
21
  |---|---|---|
22
22
  | `@mgamadeus/ddd-web/codegen` | Node only (never in a browser bundle) | `defineConfig`, `generateSdk`, `linkSkills`, `loadSpec` / `validateSpec`; bins `ddd-web-sdk`, `ddd-web` |
23
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` |
24
+ | `@mgamadeus/ddd-web/api` | needs `@reduxjs/toolkit` 2 (peer) | `createDddBaseQuery` (+ `upload()`, `relogin`), `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 |
27
27
 
@@ -92,6 +92,14 @@ const { data } = useGetApiAdminLibraryBooksListQuery({
92
92
  `DddFileResponse`: `const { blob, filename } = await trigger(args).unwrap(); downloadBlob(blob, filename ?? 'x.xlsx')`.
93
93
  When the spec declares JSON for such a route, add a `responseHandlers` override (`handler: 'blob'`) — never
94
94
  hand-write a stopgap endpoint.
95
+ - **File uploads** go through the generated `multipartFiles` argument (operations with a multipart request body); for
96
+ progress or cancel use `dddBaseQuery.upload()` in a `queryFn`. Never hand-write `new FormData()` with an own
97
+ `fetch` / `XMLHttpRequest` and an own token: it bypasses the session, the refresh and the headers hooks.
98
+ - **Sessions without refresh token** (guest, device, impersonation) recover through the `relogin` option — never a
99
+ placeholder refresh token.
100
+ - **Tag names come from the generated `<stem>Tags.ts`**: build `tagTypes` with `mergeDddTagTypes`, never retype a tag.
101
+ - **A route missing from the deployed spec** is generated from a local spec file or local backend (`schemaFile`,
102
+ `--schema`), not injected by hand.
95
103
  - **Never build filter strings by concatenation** — use the `query` builders; they escape strings, write lists as JSON
96
104
  and group `or` clauses (the backend parser has no precedence).
97
105
  - **One refresh policy:** pass `shouldRefresh` instead of wrapping the base query; auth endpoints never refresh.
@@ -4,7 +4,7 @@
4
4
 
5
5
  1. Configuration (`openapi-config.ts`)
6
6
  2. Generating the SDK (`ddd-web-sdk`)
7
- 3. Generated files and cache tags
7
+ 3. Generated files and cache tags (3a file downloads, 3b file uploads and upload progress)
8
8
  4. Query builders (`/query`)
9
9
  5. Base query, refresh and errors (`/api`)
10
10
  6. Tokens (`/auth`)
@@ -141,6 +141,25 @@ default is `[]`); api-entry resolver first, then the global one; an invalid resu
141
141
  `invalidation: broadInvalidation` restores the 0.2 output (every write without an `x-ddd-entity` path identity
142
142
  invalidates LIST + its whole tag type).
143
143
 
144
+ **Typed tags in hand-written code.** Build the base api's `tagTypes` from the generated lists, then every
145
+ `providesTags` / `invalidatesTags` of an own `injectEndpoints` file and every `baseApi.util.invalidateTags()` is checked
146
+ against the generated names — a mistyped tag does not compile instead of silently invalidating nothing:
147
+
148
+ ```ts
149
+ import { mergeDddTagTypes } from '@mgamadeus/ddd-web/api';
150
+ import { adminApiTagTypes } from './adminApiTags'; // the Tags files import nothing: no import cycle
151
+ import { clientApiTagTypes } from './clientApiTags';
152
+
153
+ export const baseApi = createApi({
154
+ baseQuery: dddBaseQuery,
155
+ tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']), // own tags second
156
+ endpoints: () => ({}),
157
+ });
158
+ ```
159
+
160
+ An own tag that differs from a generated one only by case (`ProspectActivities` next to the generated
161
+ `Prospectactivities`) is a compile error. Never list generated tag names by hand.
162
+
144
163
  ## 3a. File downloads and text responses
145
164
 
146
165
  The response handler of each endpoint follows its 2xx content types:
@@ -172,6 +191,46 @@ A `Blob` is not serializable: Redux Toolkit's serializable check warns about it
172
191
  the cache (`keepUnusedDataFor: 0` via `enhanceEndpoints`). Generated endpoints import the package's `api` entry, so the
173
192
  app needs `@reduxjs/toolkit` (the `api` peer) installed.
174
193
 
194
+ ## 3b. File uploads (multipart)
195
+
196
+ An operation whose request body offers `multipart/form-data` (a request DTO with `Parameter::FILES` properties) gets a
197
+ `multipartFiles` argument with one list per file field, and its body is built by `buildDddMultipartBody`:
198
+
199
+ | Operation accepts | Generated argument | Request |
200
+ |---|---|---|
201
+ | JSON and multipart | the JSON DTO argument as before + optional `multipartFiles` | JSON while no file is given; with a file `multipart/form-data`: the JSON envelope in the form field `body`, each file as `<field>[]` |
202
+ | multipart only | `multipartFiles` (required when the spec requires a file field) instead of RTK's body argument | always multipart |
203
+
204
+ ```ts
205
+ const [send] = usePostApiClientChatMessagesMutation();
206
+ await send({ chatMessageCreateRequestDto: { chatMessage: { body: 'see attachment' } }, multipartFiles: { attachmentFiles: [file] } }).unwrap();
207
+ ```
208
+
209
+ A file part is a `File` / `Blob`, or React Native's `{ uri, name, type }`. Never set a `Content-Type` header for such a
210
+ request. With `flattenArg` (the argument is the body itself) no files argument can be added: the generator warns and
211
+ the endpoint stays JSON-only. `File` objects in a mutation argument are not serializable — RTK Query's own actions are
212
+ exempt from the serializable check, do not copy them into other state.
213
+
214
+ **Upload with progress.** `fetch` reports no upload progress, so the base query has an `upload()` that sends the same
215
+ multipart form through `XMLHttpRequest` with the session of every other request (Bearer, `headers` / `languageCode`
216
+ hooks, the shared refresh and one retry). Use it in a `queryFn`, so hooks, cache tags and error handling stay RTK's:
217
+
218
+ ```ts
219
+ // dddBaseQuery = createDddBaseQuery({...}), exported next to baseApi
220
+ uploadAttachment: build.mutation<AttachmentResponse, { itemId: number; file: File; onProgress?: (loaded: number, total: number) => void; signal?: AbortSignal }>({
221
+ queryFn: async ({ itemId, file, onProgress, signal }, api, extraOptions) =>
222
+ (await dddBaseQuery.upload(
223
+ { url: `/api/client/items/${itemId}/attachments`, body: { caption: file.name }, files: { attachmentFiles: [file] }, onProgress, signal },
224
+ api, extraOptions,
225
+ )) as { data: AttachmentResponse } | { error: FetchBaseQueryError },
226
+ invalidatesTags: (_result, _error, { itemId }) => [{ type: 'Items', id: itemId }],
227
+ }),
228
+ ```
229
+
230
+ `onProgress(loaded, total)` restarts from 0 when the upload is repeated after a refresh. A cancelled upload (`signal`)
231
+ ends with an error for which `isDddUploadAborted(error)` is true; other errors have the base query's shape, so
232
+ `normalizeDddError` reads them.
233
+
175
234
  ## 4. Query builders (`/query`)
176
235
 
177
236
  The backend reads `filters`, `orderBy`, `expand`, `select`, `top`, `skip` (no `$` prefix). Default `top` is 50.
@@ -226,6 +285,8 @@ DDD date-time otherwise.
226
285
  | `setTokens(tokens, api)` | store a refreshed pair |
227
286
  | `onLogout(api)` | once, when the session cannot be recovered |
228
287
  | `refreshPath` / `refresh` | default refresh = `POST refreshPath { refreshToken }` → `{ accessToken, refreshToken }`; or a custom `DddRefreshFn` |
288
+ | `relogin(context)` | re-opens the session when the refresh cannot: `context.reason` is `'no-refresh-token'` (guest, device, impersonation sessions) or `'refresh-rejected'`; return the new tokens (`refreshToken: null` allowed) or `null` to log out |
289
+ | `createUploadRequest()` | the request object of `upload()`; default `new XMLHttpRequest()` |
229
290
  | `shouldRefresh(error, request)` | default `defaultShouldRefresh`: status 401 and not an auth route (`…/common/auth/…`, `isDddAuthRequest`) |
230
291
  | `languageCode(context)` | value of the DDD `languageCode` header; `context.type` tells queries from mutations (e.g. editing language on writes, UI language on reads) |
231
292
  | `headers(headers, context)` | further headers after the Bearer header |
@@ -236,6 +297,21 @@ Refresh behaviour: one refresh per session generation, shared by all requests th
236
297
  is retried once. A request that started before a finished refresh reuses its result; a late 401 after a failed refresh
237
298
  neither refreshes nor logs out again; a refresh that finishes after a logout or a new login is discarded.
238
299
 
300
+ A session without refresh token (a guest with a stored credential, a device login, an impersonation renewed through
301
+ another session) recovers through `relogin` — never store a placeholder refresh token to make the refresh run:
302
+
303
+ ```ts
304
+ relogin: async ({ reason, baseQuery, api, extraOptions }) => {
305
+ const credential = readGuestCredential();
306
+ if (!credential) return null; // → onLogout
307
+ const result = await baseQuery({ url: '/api/public/common/auth/guest', method: 'POST', body: { credential } }, api, extraOptions as {});
308
+ const data = result.data as { accessToken?: string; refreshToken?: string | null } | undefined;
309
+ return data?.accessToken ? { accessToken: data.accessToken, refreshToken: data.refreshToken ?? null } : null;
310
+ },
311
+ ```
312
+
313
+ It runs inside the shared refresh, so concurrent failures trigger it once.
314
+
239
315
  ```ts
240
316
  // also refresh on 403, except business refusals
241
317
  shouldRefresh: (error, request) =>
@@ -307,6 +383,10 @@ Idempotent; an existing symlink is repointed, a real file or directory is never
307
383
  | `type check failed — previous output restored` | Fix the reported type error (often app code using a renamed hook), or `--skip-tsc` to inspect |
308
384
  | A list does not refresh after a write | `<stem>Enhanced.ts` not imported; or the write has no tag — see section 3 |
309
385
  | A screen shows stale data after a write that changes more than its own entity | Writes invalidate by identity since 0.3 — add an `invalidation` resolver for that endpoint (section 3), or `broadInvalidation` for the 0.2 behaviour |
386
+ | A guest / device session logs out at the first 401 | It has no refresh token: pass `relogin` (section 5) |
387
+ | `multipart body not generated (…flattenArg…)` | The endpoint's argument is the body itself; drop `flattenArg` for it or send the files with `upload()` |
388
+ | An invalidation of a hand-written endpoint does nothing | Tag name in another case than the generated one: build `tagTypes` with `mergeDddTagTypes` (section 3) |
389
+ | A route is not in the deployed spec yet | Point `schemaFile` (or `--schema`) at a local spec file or the local backend and regenerate; no hand-written stopgap endpoint |
310
390
  | Every request logs out after a 401 | `refreshPath` wrong, or the refresh response lacks `accessToken` |
311
391
  | Dates off by the zone offset | DDD date-times are UTC without offset: use `parseDddDateTime` |
312
392
  | 400 on a filter that looks right | Column kind / FULLTEXT / options: validate with `buildDefinedFilter` when `x-ddd-query` is available |
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ File uploads, sessions without refresh token and typed cache tags. Minor release: the generated arguments of multipart
6
+ operations change.
7
+
8
+ ### Added
9
+ - codegen: an operation with a `multipart/form-data` request body gets a `multipartFiles` argument (one list per file
10
+ field) and sends `buildDddMultipartBody(<json body>, multipartFiles)`: JSON while no file is given, else multipart
11
+ with the JSON envelope in the form field `body` and each file as `<field>[]`. Skipped with a warning for an
12
+ endpoint with `flattenArg`.
13
+ - api: `buildDddMultipartBody`, `buildDddFormData`, `hasDddMultipartFiles`, types `DddMultipartFiles`, `DddFilePart`
14
+ (a `File` / `Blob` or React Native's `{ uri, name, type }`).
15
+ - api: `createDddBaseQuery()` returns a base query with `upload(request, api, extraOptions)`: a multipart upload
16
+ through `XMLHttpRequest` with progress (`onProgress`) and cancel (`signal`, `isDddUploadAborted`), sharing Bearer,
17
+ the `headers` / `languageCode` hooks, the refresh and one retry. Option `createUploadRequest`.
18
+ - api: option `relogin` — re-opens the session when no refresh token is stored or the refresh was rejected
19
+ (`DddReloginFn`, `DddReloginContext`). Without it the behaviour is unchanged.
20
+ - api: `mergeDddTagTypes(generated, own)` for the base api's `tagTypes`; an own tag that differs from a generated one
21
+ only by case does not compile.
22
+
23
+ ### Changed
24
+ - codegen: a multipart-only operation no longer has the body argument RTK codegen derived from the multipart schema
25
+ (it typed the files as a schema of the backend's upload class); pass `multipartFiles` instead.
26
+ - A refresh for a session without refresh token is discarded when the access token changed while it ran.
27
+
28
+ ### Replaces hand-written code
29
+ Search an app for these after the update and move them to the package:
30
+ - `new FormData(` together with `injectEndpoints`, `fetch(` or `XMLHttpRequest` → `multipartFiles` / `upload()`;
31
+ - a constant refresh token that only exists to make the refresh run (`getTokens` returning a marker) → `relogin`;
32
+ - a `tagTypes:` list that repeats generated tag names → `mergeDddTagTypes`.
33
+
3
34
  ## 0.3.1
4
35
 
5
36
  The repository moved to the ddd-framework organisation: github.com/ddd-framework/ddd-web. No code changes; the npm
package/README.md CHANGED
@@ -74,6 +74,38 @@ export default defineConfig({
74
74
  });
75
75
  ```
76
76
 
77
+ ### File uploads
78
+
79
+ Operations with a `multipart/form-data` request body get a `multipartFiles` argument; with a file the request is sent
80
+ as multipart (JSON envelope in the form field `body`), without one as JSON:
81
+
82
+ ```ts
83
+ await send({ messageCreateRequestDto: { message: { body: 'see attachment' } }, multipartFiles: { attachmentFiles: [file] } }).unwrap();
84
+ ```
85
+
86
+ For upload progress and cancel, `createDddBaseQuery(...)` returns a base query with `upload()` (XMLHttpRequest with the
87
+ same Bearer, headers, refresh and retry) to call from a `queryFn`:
88
+
89
+ ```ts
90
+ queryFn: ({ file, onProgress }, api, extraOptions) =>
91
+ dddBaseQuery.upload({ url: '/api/client/files', files: { files: [file] }, onProgress }, api, extraOptions),
92
+ ```
93
+
94
+ ### Sessions without refresh token
95
+
96
+ `relogin` re-opens a guest, device or impersonation session when there is no refresh token or it was rejected:
97
+
98
+ ```ts
99
+ createDddBaseQuery({ /* … */ relogin: async ({ reason, baseQuery, api, extraOptions }) => reopenGuestSession(baseQuery, api, extraOptions) });
100
+ ```
101
+
102
+ ### Typed cache tags
103
+
104
+ ```ts
105
+ import { mergeDddTagTypes } from '@mgamadeus/ddd-web/api';
106
+ tagTypes: mergeDddTagTypes([...adminApiTagTypes], ['Session']), // hand-written endpoints are checked against the generated names
107
+ ```
108
+
77
109
  ### Cache invalidation
78
110
 
79
111
  Each mutation invalidates the entity it writes plus the lists of its tag type (`{ type, id }` + `{ type, id: 'LIST' }`).
@@ -28,6 +28,33 @@ declare function readDebugFlags(options?: DddDebugOptions): DddDebugFlags;
28
28
  */
29
29
  declare function applyDebugParams(args: string | FetchArgs, flags: DddDebugFlags, xdebugSessionKey?: string): string | FetchArgs;
30
30
 
31
+ /**
32
+ * One file part: a `File` / `Blob` in a browser, or React Native's `{ uri, name, type }` file reference.
33
+ */
34
+ type DddFilePart = Blob | {
35
+ uri: string;
36
+ name: string;
37
+ type: string;
38
+ };
39
+ /** File parts per form field of a DDD request DTO (its `Parameter::FILES` properties). */
40
+ type DddMultipartFiles<Field extends string = string> = Partial<Record<Field, readonly DddFilePart[] | DddFilePart | null | undefined>>;
41
+ /** Form field a DDD backend reads the JSON envelope of a multipart request from. */
42
+ declare const DDD_MULTIPART_BODY_FIELD = "body";
43
+ /** True when at least one file part is present. */
44
+ declare function hasDddMultipartFiles(files: DddMultipartFiles | null | undefined): boolean;
45
+ /**
46
+ * The `multipart/form-data` body of a DDD request: the JSON envelope in the form field `body` (left out when
47
+ * `body` is `undefined`) and every file as a part named `<field>[]`. No `Content-Type` header must be set for it: the
48
+ * runtime adds the multipart boundary itself.
49
+ */
50
+ declare function buildDddFormData(body: unknown, files: DddMultipartFiles | null | undefined): FormData;
51
+ /**
52
+ * Request body of an endpoint that accepts JSON and file parts: `body` itself while no file is given (a plain JSON
53
+ * request), else the multipart form of {@link buildDddFormData}. Generated endpoints of operations with a
54
+ * `multipart/form-data` request body call it with their `multipartFiles` argument.
55
+ */
56
+ declare function buildDddMultipartBody<Body>(body: Body, files: DddMultipartFiles | null | undefined): Body | FormData;
57
+
31
58
  /** The raw (non-refreshing) base query handed to a refresh function. */
32
59
  type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
33
60
  /** Everything a refresh function needs. */
@@ -46,6 +73,22 @@ interface DddRefreshContext {
46
73
  * A missing `refreshToken` in the result keeps the stored one.
47
74
  */
48
75
  type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;
76
+ /** Everything a re-login function needs. */
77
+ interface DddReloginContext {
78
+ /** Why the refresh could not recover the session. */
79
+ reason: 'no-refresh-token' | 'refresh-rejected';
80
+ /** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */
81
+ baseQuery: DddRawBaseQuery;
82
+ api: BaseQueryApi;
83
+ extraOptions: unknown;
84
+ }
85
+ /**
86
+ * Re-opens a session without a usable refresh token (guest credential, device id, impersonation through another
87
+ * session, …).
88
+ *
89
+ * @returns the new tokens (`refreshToken: null` for a session that has none), or `null` to end the session.
90
+ */
91
+ type DddReloginFn = (context: DddReloginContext) => Promise<DddTokens | null>;
49
92
  /**
50
93
  * The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`
51
94
  * `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.
@@ -61,8 +104,52 @@ type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' |
61
104
  type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];
62
105
  /** Decides whether a failed request is worth a token refresh and one retry. */
63
106
  type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;
64
- /** The base query returned by {@link createDddBaseQuery}. */
107
+ /** The base query type of a DDD api (what {@link createAuthEndpoints} and wrappers accept). */
65
108
  type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
109
+ /** One upload sent by {@link DddUploadingBaseQuery.upload}. */
110
+ interface DddUploadRequest {
111
+ /** Path relative to the base URL. */
112
+ url: string;
113
+ /** Default `POST`. */
114
+ method?: string;
115
+ /** JSON envelope, sent in the form field `body`; left out when `undefined`. */
116
+ body?: unknown;
117
+ /** File parts per form field (the `Parameter::FILES` properties of the request DTO). */
118
+ files: DddMultipartFiles;
119
+ /** Query parameters; `null` / `undefined` values are skipped. */
120
+ params?: Record<string, unknown>;
121
+ /** Bytes of the request body sent so far. Called again from 0 when the upload is repeated after a refresh. */
122
+ onProgress?: (loaded: number, total: number) => void;
123
+ /** Aborting cancels the request; the result is then the error of {@link isDddUploadAborted}. */
124
+ signal?: AbortSignal;
125
+ }
126
+ /** Result of an upload: the shape an RTK `queryFn` returns. */
127
+ type DddUploadResult = {
128
+ data: unknown;
129
+ error?: undefined;
130
+ } | {
131
+ data?: undefined;
132
+ error: FetchBaseQueryError;
133
+ };
134
+ /** The base query returned by {@link createDddBaseQuery}: a {@link DddBaseQuery} that can also upload with progress. */
135
+ type DddUploadingBaseQuery = DddBaseQuery & {
136
+ /**
137
+ * Sends a multipart upload with progress (XMLHttpRequest: `fetch` reports no upload progress) through the same
138
+ * session as every request: Bearer, `headers` / `languageCode` hooks, one shared refresh and one retry.
139
+ *
140
+ * @example
141
+ * uploadAttachment: build.mutation<AttachmentResponse, { id: number; file: File; onProgress?: (loaded: number, total: number) => void }>({
142
+ * queryFn: ({ id, file, onProgress }, api, extraOptions) =>
143
+ * dddBaseQuery.upload({ url: `/api/client/items/${id}/attachments`, files: { attachmentFiles: [file] }, onProgress }, api, extraOptions) as
144
+ * Promise<{ data: AttachmentResponse } | { error: FetchBaseQueryError }>,
145
+ * }),
146
+ */
147
+ upload: (request: DddUploadRequest, api: BaseQueryApi, extraOptions?: unknown) => Promise<DddUploadResult>;
148
+ };
149
+ /** `error.error` of an upload cancelled through its `signal`. */
150
+ declare const DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
151
+ /** True for the error of an upload that was cancelled through its `signal`. */
152
+ declare const isDddUploadAborted: (error: unknown) => boolean;
66
153
  /** Options of {@link createDddBaseQuery}. */
67
154
  interface DddBaseQueryOptions {
68
155
  /** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */
@@ -77,6 +164,24 @@ interface DddBaseQueryOptions {
77
164
  refresh?: DddRefreshFn;
78
165
  /** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */
79
166
  refreshPath?: string;
167
+ /**
168
+ * Re-opens the session when the refresh cannot: no refresh token is stored (guest, impersonation or device
169
+ * sessions), or the refresh token was rejected. Return the new tokens, or `null` to end the session (`onLogout`).
170
+ * Without it a refresh-worthy failure without refresh token logs out directly.
171
+ *
172
+ * @example
173
+ * // A guest session is re-opened from its stored credential:
174
+ * relogin: async ({ baseQuery, api, extraOptions }) => {
175
+ * const credential = readGuestCredential();
176
+ * if (!credential) return null;
177
+ * const result = await baseQuery({ url: '/api/public/common/auth/guest', method: 'POST', body: { credential } }, api, extraOptions as {});
178
+ * const data = result.data as { accessToken?: string; refreshToken?: string | null } | undefined;
179
+ * return data?.accessToken ? { accessToken: data.accessToken, refreshToken: data.refreshToken ?? null } : null;
180
+ * },
181
+ */
182
+ relogin?: DddReloginFn;
183
+ /** Creates the request object of an upload. Default `new XMLHttpRequest()`. */
184
+ createUploadRequest?: () => XMLHttpRequest;
80
185
  /**
81
186
  * Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.
82
187
  * `context.type` tells reads (`query`) from writes (`mutation`).
@@ -119,7 +224,8 @@ declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
119
224
  * - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly
120
225
  * once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that
121
226
  * finished meanwhile reuses that refresh's result instead of refreshing again.
122
- * - No refresh token, or a rejected refresh → `onLogout()` once for that session and the original error is returned.
227
+ * - No refresh token, or a rejected refresh → `relogin()` when given; without it, or when it returns `null`,
228
+ * `onLogout()` once for that session and the original error is returned.
123
229
  * - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).
124
230
  *
125
231
  * @example
@@ -134,7 +240,30 @@ declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
134
240
  * endpoints: () => ({}),
135
241
  * });
136
242
  */
137
- declare function createDddBaseQuery(options: DddBaseQueryOptions): DddBaseQuery;
243
+ declare function createDddBaseQuery(options: DddBaseQueryOptions): DddUploadingBaseQuery;
244
+
245
+ /** The tags of `Extra` that differ from a tag of `Generated` only by case. */
246
+ type DddTagCaseConflict<Extra extends string, Generated extends string> = Extra extends Generated ? never : Lowercase<Extra> extends Lowercase<Generated> ? Extra : never;
247
+ type DddTagCheck<Generated extends readonly string[], Extra extends readonly string[]> = [
248
+ DddTagCaseConflict<Extra[number], Generated[number]>
249
+ ] extends [never] ? unknown : {
250
+ 'tag differs from a generated tag only by case': DddTagCaseConflict<Extra[number], Generated[number]>;
251
+ };
252
+ /**
253
+ * The `tagTypes` of a base api: the generated tag lists (`<stem>TagTypes` of the `<stem>Tags.ts` files) plus the
254
+ * app's own tags. With this list every `providesTags` / `invalidatesTags` of a hand-written endpoint and every
255
+ * `api.util.invalidateTags()` is checked against the generated names, so a mistyped tag does not compile. An own tag
256
+ * that differs from a generated one only by case (`ProspectActivities` next to the generated `Prospectactivities`)
257
+ * is rejected here: it would be a second tag that no generated endpoint provides.
258
+ *
259
+ * @example
260
+ * export const baseApi = createApi({
261
+ * baseQuery,
262
+ * tagTypes: mergeDddTagTypes([...adminApiTagTypes, ...clientApiTagTypes], ['Session']),
263
+ * endpoints: () => ({}),
264
+ * });
265
+ */
266
+ declare function mergeDddTagTypes<const Generated extends readonly string[], const Extra extends readonly string[] = readonly []>(generated: Generated, extra?: Extra & DddTagCheck<Generated, Extra>): (Generated[number] | Extra[number])[];
138
267
 
139
268
  /** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */
140
269
  interface DddNormalizedError {
@@ -266,5 +395,5 @@ declare function createAuthEndpoints<Definitions extends EndpointDefinitions, Re
266
395
  authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
267
396
  }, ReducerPath, TagTypes, Enhancers>;
268
397
 
269
- export { DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, isDddAuthRequest, normalizeDddError, readDebugFlags };
270
- export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFileResponse, DddHeadersContext, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddRequestContext, DddShouldRefresh };
398
+ export { DDD_MULTIPART_BODY_FIELD, DDD_UPLOAD_ABORTED, DEFAULT_ERROR_MESSAGE, DEFAULT_ERROR_MESSAGES, DddTokens, applyDebugParams, blobResponseHandler, buildDddFormData, buildDddMultipartBody, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, hasDddMultipartFiles, isDddAuthRequest, isDddUploadAborted, mergeDddTagTypes, normalizeDddError, readDebugFlags };
399
+ export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddErrorMessages, DddFilePart, DddFileResponse, DddHeadersContext, DddMultipartFiles, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddReloginContext, DddReloginFn, DddRequestContext, DddShouldRefresh, DddUploadRequest, DddUploadResult, DddUploadingBaseQuery };
package/dist/api/index.js CHANGED
@@ -32,6 +32,31 @@ function applyDebugParams(args, flags, xdebugSessionKey = "1") {
32
32
  return { ...args, params };
33
33
  }
34
34
 
35
+ // src/api/multipart.ts
36
+ var DDD_MULTIPART_BODY_FIELD = "body";
37
+ var partsOf = (value) => {
38
+ if (value === null || value === void 0) return [];
39
+ return Array.isArray(value) ? value : [value];
40
+ };
41
+ function hasDddMultipartFiles(files) {
42
+ return !!files && Object.values(files).some((value) => partsOf(value).length > 0);
43
+ }
44
+ function buildDddFormData(body, files) {
45
+ const formData = new FormData();
46
+ if (body !== void 0) formData.append(DDD_MULTIPART_BODY_FIELD, JSON.stringify(body));
47
+ for (const [field, value] of Object.entries(files ?? {})) {
48
+ for (const part of partsOf(value)) {
49
+ const name = typeof part.name === "string" ? part.name : "";
50
+ if (typeof Blob !== "undefined" && part instanceof Blob) formData.append(`${field}[]`, part, name || field);
51
+ else formData.append(`${field}[]`, part);
52
+ }
53
+ }
54
+ return formData;
55
+ }
56
+ function buildDddMultipartBody(body, files) {
57
+ return hasDddMultipartFiles(files) ? buildDddFormData(body, files) : body;
58
+ }
59
+
35
60
  // src/api/refresh.ts
36
61
  function createDddRefresh(path) {
37
62
  return async ({ refreshToken, baseQuery, api, extraOptions }) => {
@@ -43,6 +68,8 @@ function createDddRefresh(path) {
43
68
  }
44
69
 
45
70
  // src/api/baseQuery.ts
71
+ var DDD_UPLOAD_ABORTED = "DDD_UPLOAD_ABORTED";
72
+ var isDddUploadAborted = (error) => !!error && typeof error === "object" && error.status === "CUSTOM_ERROR" && error.error === DDD_UPLOAD_ABORTED;
46
73
  var getRequestUrl = (request) => typeof request === "string" ? request : request.url;
47
74
  var isDddAuthRequest = (request) => getRequestUrl(request).includes("/common/auth/");
48
75
  var defaultShouldRefresh = (error, request) => error.status === 401 && !isDddAuthRequest(request);
@@ -59,7 +86,7 @@ var withBearer = (args, accessToken) => {
59
86
  return { ...args, headers };
60
87
  };
61
88
  function createDddBaseQuery(options) {
62
- const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions } = options;
89
+ const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions, relogin } = options;
63
90
  const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;
64
91
  if (!options.refresh && !options.refreshPath) {
65
92
  throw new Error("createDddBaseQuery: pass either `refresh` or `refreshPath`.");
@@ -86,9 +113,21 @@ function createDddBaseQuery(options) {
86
113
  let inflight = null;
87
114
  const currentAccessToken = async (api) => (await getTokens(api))?.accessToken ?? null;
88
115
  const runRefresh = async (api, extraOptions) => {
89
- const refreshToken = (await getTokens(api))?.refreshToken ?? null;
90
- const pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;
91
- if (((await getTokens(api))?.refreshToken ?? null) !== refreshToken) return "superseded";
116
+ const before = await getTokens(api);
117
+ const refreshToken = before?.refreshToken ?? null;
118
+ const accessTokenBefore = before?.accessToken ?? null;
119
+ let pair = refreshToken ? await refresh({ refreshToken, baseQuery: rawBaseQuery, api, extraOptions }) : null;
120
+ if (!pair?.accessToken && relogin) {
121
+ pair = await relogin({
122
+ reason: refreshToken ? "refresh-rejected" : "no-refresh-token",
123
+ baseQuery: rawBaseQuery,
124
+ api,
125
+ extraOptions
126
+ });
127
+ }
128
+ const after = await getTokens(api);
129
+ if ((after?.refreshToken ?? null) !== refreshToken) return "superseded";
130
+ if (refreshToken === null && (after?.accessToken ?? null) !== accessTokenBefore) return "superseded";
92
131
  if (!pair?.accessToken) {
93
132
  await onLogout(api);
94
133
  return "failed";
@@ -113,7 +152,7 @@ function createDddBaseQuery(options) {
113
152
  if (inflight) await inflight;
114
153
  return lastOutcome;
115
154
  };
116
- return async (args, api, extraOptions) => {
155
+ const baseQuery = async (args, api, extraOptions) => {
117
156
  while (inflight) await inflight.catch(() => void 0);
118
157
  const startGeneration = generation;
119
158
  const request = toFetchArgs(args);
@@ -122,6 +161,76 @@ function createDddBaseQuery(options) {
122
161
  if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
123
162
  return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);
124
163
  };
164
+ const uploadHeaders = async (request, api, extraOptions) => {
165
+ const headers = new Headers();
166
+ const accessToken = await currentAccessToken(api);
167
+ if (accessToken) headers.set("authorization", `Bearer ${accessToken}`);
168
+ const context = {
169
+ getState: api.getState,
170
+ extra: api.extra,
171
+ endpoint: api.endpoint,
172
+ type: api.type,
173
+ forced: api.forced,
174
+ arg: { url: request.url, method: request.method ?? "POST" },
175
+ extraOptions
176
+ };
177
+ const language = languageCode?.(context);
178
+ if (language) headers.set("languageCode", language);
179
+ if (debugOptions && readDebugFlags(debugOptions).debug) headers.set("x-debug", "true");
180
+ return await headersHook?.(headers, context) ?? headers;
181
+ };
182
+ const sendUpload = async (request, api, extraOptions) => {
183
+ const headers = await uploadHeaders(request, api, extraOptions);
184
+ const query = request.params ? dddParamsSerializer(request.params) : "";
185
+ const url = `${options.baseUrl.replace(/\/+$/, "")}/${request.url.replace(/^\/+/, "")}${query ? `${request.url.includes("?") ? "&" : "?"}${query}` : ""}`;
186
+ return new Promise((resolve) => {
187
+ const { signal, onProgress } = request;
188
+ const aborted = { error: { status: "CUSTOM_ERROR", error: DDD_UPLOAD_ABORTED } };
189
+ if (signal?.aborted) return resolve(aborted);
190
+ const xhr = options.createUploadRequest ? options.createUploadRequest() : new XMLHttpRequest();
191
+ const onAbort = () => xhr.abort();
192
+ signal?.addEventListener("abort", onAbort, { once: true });
193
+ const finish = (result) => {
194
+ signal?.removeEventListener("abort", onAbort);
195
+ resolve(result);
196
+ };
197
+ xhr.open(request.method ?? "POST", url);
198
+ headers.forEach((value, name) => xhr.setRequestHeader(name, value));
199
+ if (onProgress && xhr.upload) {
200
+ xhr.upload.onprogress = (event) => {
201
+ if (event.lengthComputable) onProgress(event.loaded, event.total);
202
+ };
203
+ }
204
+ xhr.onload = () => {
205
+ const text = xhr.responseText;
206
+ let data;
207
+ try {
208
+ data = text ? JSON.parse(text) : void 0;
209
+ } catch {
210
+ data = text;
211
+ }
212
+ if (xhr.status >= 200 && xhr.status < 300) finish({ data: data ?? null });
213
+ else finish({ error: { status: xhr.status, data } });
214
+ };
215
+ xhr.onerror = () => finish({ error: { status: "FETCH_ERROR", error: "The upload did not reach the server." } });
216
+ xhr.onabort = () => finish(aborted);
217
+ xhr.send(buildDddFormData(request.body, request.files));
218
+ });
219
+ };
220
+ const upload = async (request, api, extraOptions) => {
221
+ while (inflight) await inflight.catch(() => void 0);
222
+ const startGeneration = generation;
223
+ const result = await sendUpload(request, api, extraOptions);
224
+ if (!result.error || !shouldRefresh(result.error, { url: request.url, method: request.method ?? "POST" })) return result;
225
+ if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
226
+ return sendUpload(request, api, extraOptions);
227
+ };
228
+ return Object.assign(baseQuery, { upload });
229
+ }
230
+
231
+ // src/api/tags.ts
232
+ function mergeDddTagTypes(generated, extra) {
233
+ return [.../* @__PURE__ */ new Set([...generated, ...extra ?? []])];
125
234
  }
126
235
 
127
236
  // src/api/errors.ts
@@ -270,10 +379,14 @@ function createAuthEndpoints(api, options) {
270
379
  });
271
380
  }
272
381
  export {
382
+ DDD_MULTIPART_BODY_FIELD,
383
+ DDD_UPLOAD_ABORTED,
273
384
  DEFAULT_ERROR_MESSAGE,
274
385
  DEFAULT_ERROR_MESSAGES,
275
386
  applyDebugParams,
276
387
  blobResponseHandler,
388
+ buildDddFormData,
389
+ buildDddMultipartBody,
277
390
  createAuthEndpoints,
278
391
  createDddBaseQuery,
279
392
  createDddRefresh,
@@ -285,7 +398,10 @@ export {
285
398
  getErrorMessage,
286
399
  getErrorStatus,
287
400
  getRequestUrl,
401
+ hasDddMultipartFiles,
288
402
  isDddAuthRequest,
403
+ isDddUploadAborted,
404
+ mergeDddTagTypes,
289
405
  normalizeDddError,
290
406
  readDebugFlags
291
407
  };