@mgamadeus/ddd-web 0.0.1 → 0.2.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.
- package/.claude/skills/ddd-web-specialist/SKILL.md +110 -0
- package/.claude/skills/ddd-web-specialist/references/consumer.md +271 -0
- package/.claude/skills/ddd-web-specialist/references/maintaining.md +108 -0
- package/CHANGELOG.md +89 -0
- package/README.md +68 -2
- package/dist/api/index.d.ts +246 -0
- package/dist/api/index.js +265 -0
- package/dist/api/index.js.map +1 -0
- package/dist/auth/index.d.ts +109 -0
- package/dist/auth/index.js +146 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/chunk-OL742YG5.js +1514 -0
- package/dist/chunk-OL742YG5.js.map +1 -0
- package/dist/chunk-QLCE3QTP.js +123 -0
- package/dist/chunk-QLCE3QTP.js.map +1 -0
- package/dist/codegen/cli.js +77 -0
- package/dist/codegen/cli.js.map +1 -0
- package/dist/codegen/index.d.ts +342 -0
- package/dist/codegen/index.js +25 -0
- package/dist/codegen/index.js.map +1 -0
- package/dist/contract/index.d.ts +109 -0
- package/dist/contract/index.js +126 -0
- package/dist/contract/index.js.map +1 -0
- package/dist/errors-B4KabvNa.d.ts +22 -0
- package/dist/extensions-DToc6G5E.d.ts +208 -0
- package/dist/query/index.d.ts +372 -0
- package/dist/query/index.js +860 -0
- package/dist/query/index.js.map +1 -0
- package/dist/types-BhDMN3ZS.d.ts +35 -0
- package/package.json +58 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @mgamadeus/ddd-web
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> 0.x: a minor release may contain breaking changes, a patch never does — see CHANGELOG.md.
|
|
4
4
|
|
|
5
5
|
`@mgamadeus/ddd-web` is the frontend counterpart of [mgamadeus/ddd](https://packagist.org/packages/mgamadeus/ddd),
|
|
6
6
|
a PHP framework for domain-driven applications on top of Symfony and Doctrine, distributed via Composer/Packagist.
|
|
@@ -19,12 +19,78 @@ those conventions into frontend code:
|
|
|
19
19
|
- **contract**: TypeScript types for the DDD wire format
|
|
20
20
|
|
|
21
21
|
It contains no UI components and no domain logic; apps bring their own design system and business screens.
|
|
22
|
-
|
|
22
|
+
Works with the OpenAPI output of current mgamadeus/ddd backends. The `x-ddd-*` extensions (contract version 1) are used
|
|
23
|
+
when a backend emits them; without them the generator falls back to path heuristics and prints a warning.
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pnpm add @mgamadeus/ddd-web @reduxjs/toolkit
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
// openapi-config.ts
|
|
33
|
+
import { defineConfig } from '@mgamadeus/ddd-web/codegen';
|
|
34
|
+
|
|
35
|
+
export default defineConfig({
|
|
36
|
+
apis: [{
|
|
37
|
+
schemaFile: 'https://api.example.com/api/admin/documentation/openApi', // or a local snapshot file
|
|
38
|
+
apiFile: './src/api/baseApi.ts', apiImport: 'baseApi',
|
|
39
|
+
outputFile: './src/api/adminApi.ts', exportName: 'adminApi',
|
|
40
|
+
hooks: { queries: true, lazyQueries: true, mutations: true },
|
|
41
|
+
}],
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
pnpm exec ddd-web-sdk # generate the SDK
|
|
47
|
+
pnpm exec ddd-web link-skills # link the package's agent skills into .claude/skills
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Subpaths: `@mgamadeus/ddd-web/codegen`, `/query`, `/api`, `/auth`, `/contract`.
|
|
51
|
+
|
|
52
|
+
### File downloads
|
|
53
|
+
|
|
54
|
+
Endpoints whose 2xx responses are files (`application/octet-stream`, `application/zip`, `application/pdf`,
|
|
55
|
+
`application/vnd.*` such as Excel, `text/csv`, `image/*`, …) are generated with `blobResponseHandler` and return a
|
|
56
|
+
`DddFileResponse` (`{ blob, filename, contentType }`); text-only responses get `responseHandler: "text"`.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { downloadBlob } from '@mgamadeus/ddd-web/api';
|
|
60
|
+
|
|
61
|
+
const [trigger] = useLazyGetApiAdminLibraryBooksExportQuery();
|
|
62
|
+
const { blob, filename } = await trigger({}).unwrap();
|
|
63
|
+
downloadBlob(blob, filename ?? 'books.xlsx');
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
When a spec declares no or the wrong content type (e.g. `application/json` for an Excel export route), set the handler
|
|
67
|
+
in the config; overrides win over detection, the first match wins:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
export default defineConfig({
|
|
71
|
+
responseHandlers: [{ method: 'GET', path: /\/export$/, handler: 'blob' }], // 'blob' | 'text' | 'json'
|
|
72
|
+
apis: [/* … each entry may have its own responseHandlers, checked first */],
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Agent skill
|
|
77
|
+
|
|
78
|
+
The package ships the agent skill `ddd-web-specialist` (consumer guide + maintaining guide). Link it into an app's
|
|
79
|
+
`.claude/skills` with `pnpm exec ddd-web link-skills`.
|
|
23
80
|
|
|
24
81
|
## Development
|
|
25
82
|
|
|
26
83
|
pnpm only (version pinned in `package.json` → `packageManager`; enable with `corepack enable`).
|
|
27
84
|
|
|
85
|
+
```sh
|
|
86
|
+
pnpm install
|
|
87
|
+
pnpm typecheck && pnpm test && pnpm build
|
|
88
|
+
pnpm pack && test/consumer/run.sh mgamadeus-ddd-web-*.tgz pnpm /tmp/ddd-web-consumer # installed-package check
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Releases: push a tag `vX.Y.Z` matching `package.json`; the release workflow verifies the package and stages it on
|
|
92
|
+
npm (trusted publishing). A maintainer approves the staged version with `npm stage approve <stage-id>`.
|
|
93
|
+
|
|
28
94
|
## License
|
|
29
95
|
|
|
30
96
|
MIT
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
|
|
2
|
+
import { FetchArgs, BaseQueryFn, FetchBaseQueryError, FetchBaseQueryMeta, BaseQueryApi, FetchBaseQueryArgs, EndpointDefinitions, ApiModules, Api } from '@reduxjs/toolkit/query';
|
|
3
|
+
import { D as DddTokens } from '../types-BhDMN3ZS.js';
|
|
4
|
+
import { DddLoginRequest, DddAuthResponse, DddRefreshRequest } from '../auth/index.js';
|
|
5
|
+
import { DddExceptionDetail } from '../contract/index.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Debug passthrough: flags present in the page URL (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`) are forwarded to
|
|
9
|
+
* every API request as the query parameters a DDD backend understands.
|
|
10
|
+
*/
|
|
11
|
+
interface DddDebugOptions {
|
|
12
|
+
/** Where the flags come from. Default: `window.location.search` (nothing outside a browser). */
|
|
13
|
+
searchParams?: () => URLSearchParams | null | undefined;
|
|
14
|
+
/** Value of `XDEBUG_SESSION` when `?xdebug` is set. Default `1`. */
|
|
15
|
+
xdebugSessionKey?: string;
|
|
16
|
+
}
|
|
17
|
+
/** The debug flags active for one request. */
|
|
18
|
+
interface DddDebugFlags {
|
|
19
|
+
debug: boolean;
|
|
20
|
+
noCache: boolean;
|
|
21
|
+
xdebug: boolean;
|
|
22
|
+
errorsAsJson: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** Reads the active debug flags. */
|
|
25
|
+
declare function readDebugFlags(options?: DddDebugOptions): DddDebugFlags;
|
|
26
|
+
/**
|
|
27
|
+
* Adds the query parameters for the active debug flags to a request, never overwriting a parameter the caller set.
|
|
28
|
+
*/
|
|
29
|
+
declare function applyDebugParams(args: string | FetchArgs, flags: DddDebugFlags, xdebugSessionKey?: string): string | FetchArgs;
|
|
30
|
+
|
|
31
|
+
/** The raw (non-refreshing) base query handed to a refresh function. */
|
|
32
|
+
type DddRawBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
|
|
33
|
+
/** Everything a refresh function needs. */
|
|
34
|
+
interface DddRefreshContext {
|
|
35
|
+
/** The refresh token currently stored. */
|
|
36
|
+
refreshToken: string;
|
|
37
|
+
/** The underlying fetch base query (no auth retry, Bearer of the current access token still applied). */
|
|
38
|
+
baseQuery: DddRawBaseQuery;
|
|
39
|
+
api: BaseQueryApi;
|
|
40
|
+
extraOptions: unknown;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Exchanges a refresh token for a new token pair.
|
|
44
|
+
*
|
|
45
|
+
* @returns the new pair, or `null` when the refresh token was rejected (the base query then logs out).
|
|
46
|
+
* A missing `refreshToken` in the result keeps the stored one.
|
|
47
|
+
*/
|
|
48
|
+
type DddRefreshFn = (context: DddRefreshContext) => Promise<DddTokens | null>;
|
|
49
|
+
/**
|
|
50
|
+
* The default {@link DddRefreshFn}: `POST <path>` with `{ refreshToken }`, expecting the DDD `AuthPostResponseDto`
|
|
51
|
+
* `{ accessToken, refreshToken }`. DDD refresh tokens are stateless and re-issued with a renewed lifetime.
|
|
52
|
+
*
|
|
53
|
+
* @param path refresh endpoint relative to the base URL, e.g. `/api/admin/common/auth/refresh`
|
|
54
|
+
*/
|
|
55
|
+
declare function createDddRefresh(path: string): DddRefreshFn;
|
|
56
|
+
|
|
57
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
58
|
+
/** What `getTokens` can see: the request's Redux context (no dispatch). */
|
|
59
|
+
type DddRequestContext = Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type'>;
|
|
60
|
+
/** Context of the `headers` / `languageCode` hooks (RTK's `prepareHeaders` context). */
|
|
61
|
+
type DddHeadersContext = Parameters<NonNullable<FetchBaseQueryArgs['prepareHeaders']>>[1];
|
|
62
|
+
/** Decides whether a failed request is worth a token refresh and one retry. */
|
|
63
|
+
type DddShouldRefresh = (error: FetchBaseQueryError, request: FetchArgs) => boolean;
|
|
64
|
+
/** The base query returned by {@link createDddBaseQuery}. */
|
|
65
|
+
type DddBaseQuery = BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
|
|
66
|
+
/** Options of {@link createDddBaseQuery}. */
|
|
67
|
+
interface DddBaseQueryOptions {
|
|
68
|
+
/** API origin, e.g. `https://api.example.com`. Request URLs are relative to it. */
|
|
69
|
+
baseUrl: string;
|
|
70
|
+
/** Current tokens, typically read from the Redux state (`context.getState()`) or a {@link TokenStorage}. */
|
|
71
|
+
getTokens: (context: DddRequestContext) => MaybePromise<Partial<DddTokens> | null | undefined>;
|
|
72
|
+
/** Stores a freshly refreshed token pair (dispatch a Redux action, write storage, …). */
|
|
73
|
+
setTokens: (tokens: DddTokens, api: BaseQueryApi) => MaybePromise<void>;
|
|
74
|
+
/** Called once when the session cannot be recovered (no refresh token, or the refresh was rejected). */
|
|
75
|
+
onLogout: (api: BaseQueryApi) => MaybePromise<void>;
|
|
76
|
+
/** Custom refresh. Default: {@link createDddRefresh} on `refreshPath`. */
|
|
77
|
+
refresh?: DddRefreshFn;
|
|
78
|
+
/** Refresh endpoint for the default refresh, e.g. `/api/admin/common/auth/refresh`. Required without `refresh`. */
|
|
79
|
+
refreshPath?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Adds or changes headers after the Bearer header is set; return value as in RTK's `prepareHeaders`.
|
|
82
|
+
* `context.type` tells reads (`query`) from writes (`mutation`).
|
|
83
|
+
*/
|
|
84
|
+
headers?: (headers: Headers, context: DddHeadersContext) => MaybePromise<Headers | void>;
|
|
85
|
+
/**
|
|
86
|
+
* Shortcut for the DDD `languageCode` header. Return e.g. the form's editing language for mutations and the UI
|
|
87
|
+
* language for queries; a falsy value sends no header.
|
|
88
|
+
*/
|
|
89
|
+
languageCode?: (context: DddHeadersContext) => string | null | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Decides whether a failed request triggers a refresh and one retry. Default {@link defaultShouldRefresh}
|
|
92
|
+
* (status 401, auth endpoints excluded).
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* // Also refresh on 403, except for 403s that are business refusals:
|
|
96
|
+
* shouldRefresh: (error, request) =>
|
|
97
|
+
* (error.status === 401 || error.status === 403) && !isBusinessRefusal(error) && !isDddAuthRequest(request)
|
|
98
|
+
*/
|
|
99
|
+
shouldRefresh?: DddShouldRefresh;
|
|
100
|
+
/** Debug passthrough of page URL flags (`?debug`, `?noCache`, `?xdebug`, `?errorsAsJson`). Default off. */
|
|
101
|
+
debug?: boolean | DddDebugOptions;
|
|
102
|
+
/** Further `fetchBaseQuery` options (`fetchFn`, `timeout`, `credentials`, `paramsSerializer`, …). */
|
|
103
|
+
fetchOptions?: Omit<FetchBaseQueryArgs, 'baseUrl' | 'prepareHeaders'>;
|
|
104
|
+
}
|
|
105
|
+
/** URL path of a request argument. */
|
|
106
|
+
declare const getRequestUrl: (request: string | FetchArgs) => string;
|
|
107
|
+
/** True for the DDD auth endpoints (`…/common/auth/…`); they never trigger a refresh, they ARE the recovery. */
|
|
108
|
+
declare const isDddAuthRequest: (request: string | FetchArgs) => boolean;
|
|
109
|
+
/** Default refresh decision: HTTP 401 on anything but an auth endpoint. */
|
|
110
|
+
declare const defaultShouldRefresh: DddShouldRefresh;
|
|
111
|
+
/**
|
|
112
|
+
* Query-string serializer that skips `null` / `undefined` values (the generated SDK passes every optional parameter).
|
|
113
|
+
*/
|
|
114
|
+
declare const dddParamsSerializer: (params: Record<string, unknown>) => string;
|
|
115
|
+
/**
|
|
116
|
+
* Creates the RTK Query base query for a DDD backend.
|
|
117
|
+
*
|
|
118
|
+
* - Sends `Authorization: Bearer <accessToken>` from `getTokens()`.
|
|
119
|
+
* - On a refresh-worthy failure (`shouldRefresh`, default 401) runs ONE shared refresh and retries the request exactly
|
|
120
|
+
* once. Concurrent failures share that refresh and its result; a request whose failure predates a refresh that
|
|
121
|
+
* 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.
|
|
123
|
+
* - A refresh whose session was logged out or replaced while it ran is discarded (no `setTokens`, no retry).
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* export const baseApi = createApi({
|
|
127
|
+
* baseQuery: createDddBaseQuery({
|
|
128
|
+
* baseUrl: 'https://api.example.com',
|
|
129
|
+
* refreshPath: '/api/admin/common/auth/refresh',
|
|
130
|
+
* getTokens: ({ getState }) => (getState() as RootState).auth,
|
|
131
|
+
* setTokens: (tokens, { dispatch }) => dispatch(authActions.updateTokens(tokens)),
|
|
132
|
+
* onLogout: ({ dispatch }) => dispatch(authActions.logout()),
|
|
133
|
+
* }),
|
|
134
|
+
* endpoints: () => ({}),
|
|
135
|
+
* });
|
|
136
|
+
*/
|
|
137
|
+
declare function createDddBaseQuery(options: DddBaseQueryOptions): DddBaseQuery;
|
|
138
|
+
|
|
139
|
+
/** A DDD API error in one predictable shape, whatever produced it (RTK Query, a thrown Error, a raw body). */
|
|
140
|
+
interface DddNormalizedError {
|
|
141
|
+
/**
|
|
142
|
+
* HTTP status, or RTK Query's string status for non-HTTP failures (`FETCH_ERROR`, `TIMEOUT_ERROR`,
|
|
143
|
+
* `CUSTOM_ERROR`); a `PARSING_ERROR` reports the original HTTP status. `null` when unknown.
|
|
144
|
+
*/
|
|
145
|
+
status: number | string | null;
|
|
146
|
+
/** Human-readable message: the backend's `error` key first, then a text body, then generic fallbacks. */
|
|
147
|
+
message: string;
|
|
148
|
+
/** The backend's `validationErrors` exactly as received (present on validation 400s), else `null`. */
|
|
149
|
+
validationErrors: unknown;
|
|
150
|
+
/** `exceptionDetails.elements` of the backend body; empty when absent. */
|
|
151
|
+
details: DddExceptionDetail[];
|
|
152
|
+
/** The raw response body (parsed JSON, text, or `undefined`). */
|
|
153
|
+
body: unknown;
|
|
154
|
+
}
|
|
155
|
+
/** Message used when an error carries no message at all. */
|
|
156
|
+
declare const DEFAULT_ERROR_MESSAGE = "Request failed";
|
|
157
|
+
/**
|
|
158
|
+
* Normalises any API error into {@link DddNormalizedError}.
|
|
159
|
+
*
|
|
160
|
+
* Understands RTK Query's `FetchBaseQueryError` (`{ status, data }`, `{ status: 'FETCH_ERROR', error }`, …),
|
|
161
|
+
* `SerializedError` / `Error` (`message`), errors carrying a parsed `responseBody`, and a bare DDD error body.
|
|
162
|
+
* DDD error bodies put the message under `error` (not `message`).
|
|
163
|
+
*
|
|
164
|
+
* @param error whatever a request rejected with
|
|
165
|
+
* @param fallbackMessage message when nothing usable is found
|
|
166
|
+
*/
|
|
167
|
+
declare function normalizeDddError(error: unknown, fallbackMessage?: string): DddNormalizedError;
|
|
168
|
+
/**
|
|
169
|
+
* The message to show for an API error (`normalizeDddError(error).message`).
|
|
170
|
+
*
|
|
171
|
+
* @param error whatever a request rejected with
|
|
172
|
+
* @param fallbackMessage message when nothing usable is found
|
|
173
|
+
*/
|
|
174
|
+
declare function getErrorMessage(error: unknown, fallbackMessage?: string): string;
|
|
175
|
+
/** HTTP status of an API error, or `null` for non-HTTP failures. */
|
|
176
|
+
declare function getErrorStatus(error: unknown): number | null;
|
|
177
|
+
|
|
178
|
+
/** A binary response decoded by {@link blobResponseHandler}. */
|
|
179
|
+
interface DddFileResponse {
|
|
180
|
+
blob: Blob;
|
|
181
|
+
/** File name from `Content-Disposition`, else `null`. */
|
|
182
|
+
filename: string | null;
|
|
183
|
+
/** `Content-Type` of the response, else `null`. */
|
|
184
|
+
contentType: string | null;
|
|
185
|
+
}
|
|
186
|
+
/** Serializable summary returned by {@link createDownloadResponseHandler} (safe to keep in the Redux store). */
|
|
187
|
+
interface DddDownloadedFile {
|
|
188
|
+
filename: string;
|
|
189
|
+
contentType: string | null;
|
|
190
|
+
size: number;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Reads the file name from a `Content-Disposition` header. Prefers RFC 5987 `filename*=UTF-8''…` over `filename=`.
|
|
194
|
+
*
|
|
195
|
+
* @returns the decoded file name, or `null` when the header has none.
|
|
196
|
+
*/
|
|
197
|
+
declare function filenameFromContentDisposition(header: string | null | undefined): string | null;
|
|
198
|
+
/**
|
|
199
|
+
* Triggers a browser download for an in-memory blob. No-op outside a browser.
|
|
200
|
+
*
|
|
201
|
+
* The anchor is attached before clicking (some browsers ignore detached anchors) and the object URL is revoked on the
|
|
202
|
+
* next macrotask (revoking in the same task can cancel the download).
|
|
203
|
+
*/
|
|
204
|
+
declare function downloadBlob(blob: Blob, filename: string): void;
|
|
205
|
+
/**
|
|
206
|
+
* RTK Query `responseHandler` for binary endpoints: a successful response becomes a {@link DddFileResponse}, an error
|
|
207
|
+
* response is parsed as JSON/text like any other error.
|
|
208
|
+
*
|
|
209
|
+
* Blobs are not serializable; keep such endpoints out of the cache (e.g. use a mutation or `keepUnusedDataFor: 0`) or
|
|
210
|
+
* use {@link createDownloadResponseHandler}.
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* build.query<DddFileResponse, void>({ query: () => ({ url: '/export', responseHandler: blobResponseHandler }) })
|
|
214
|
+
*/
|
|
215
|
+
declare function blobResponseHandler(response: Response): Promise<DddFileResponse | unknown>;
|
|
216
|
+
/**
|
|
217
|
+
* Builds an RTK Query `responseHandler` that downloads a successful binary response right away and resolves to a
|
|
218
|
+
* serializable {@link DddDownloadedFile}. Error responses are parsed as JSON/text.
|
|
219
|
+
*
|
|
220
|
+
* @param fallbackFilename used when the response has no `Content-Disposition` file name
|
|
221
|
+
*/
|
|
222
|
+
declare function createDownloadResponseHandler(fallbackFilename?: string): (response: Response) => Promise<DddDownloadedFile | unknown>;
|
|
223
|
+
|
|
224
|
+
/** Options of {@link createAuthEndpoints}. */
|
|
225
|
+
interface DddAuthEndpointsOptions {
|
|
226
|
+
/** e.g. `/api/admin/common/auth/login` */
|
|
227
|
+
loginPath: string;
|
|
228
|
+
/** e.g. `/api/admin/common/auth/refresh` */
|
|
229
|
+
refreshPath: string;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Injects `authLogin` and `authRefresh` mutations for the DDD auth endpoints into an existing API.
|
|
233
|
+
* Pure `injectEndpoints`, no React; with an API created by `@reduxjs/toolkit/query/react` the usual hooks
|
|
234
|
+
* (`useAuthLoginMutation`, …) are generated as for any endpoint.
|
|
235
|
+
*
|
|
236
|
+
* The API must use the base query from {@link createDddBaseQuery}.
|
|
237
|
+
*
|
|
238
|
+
* Prefer the endpoints of your generated SDK when it already has them; this is for apps without one.
|
|
239
|
+
*/
|
|
240
|
+
declare function createAuthEndpoints<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, Enhancers extends keyof ApiModules<any, any, any, any>>(api: Api<DddBaseQuery, Definitions, ReducerPath, TagTypes, Enhancers>, options: DddAuthEndpointsOptions): Api<DddBaseQuery, Definitions & {
|
|
241
|
+
authLogin: _reduxjs_toolkit_query.MutationDefinition<DddLoginRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
|
|
242
|
+
authRefresh: _reduxjs_toolkit_query.MutationDefinition<DddRefreshRequest, DddBaseQuery, TagTypes, DddAuthResponse, ReducerPath, unknown>;
|
|
243
|
+
}, ReducerPath, TagTypes, Enhancers>;
|
|
244
|
+
|
|
245
|
+
export { DEFAULT_ERROR_MESSAGE, DddTokens, applyDebugParams, blobResponseHandler, createAuthEndpoints, createDddBaseQuery, createDddRefresh, createDownloadResponseHandler, dddParamsSerializer, defaultShouldRefresh, downloadBlob, filenameFromContentDisposition, getErrorMessage, getErrorStatus, getRequestUrl, isDddAuthRequest, normalizeDddError, readDebugFlags };
|
|
246
|
+
export type { DddAuthEndpointsOptions, DddBaseQuery, DddBaseQueryOptions, DddDebugFlags, DddDebugOptions, DddDownloadedFile, DddFileResponse, DddHeadersContext, DddNormalizedError, DddRawBaseQuery, DddRefreshContext, DddRefreshFn, DddRequestContext, DddShouldRefresh };
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// src/api/baseQuery.ts
|
|
2
|
+
import {
|
|
3
|
+
fetchBaseQuery
|
|
4
|
+
} from "@reduxjs/toolkit/query";
|
|
5
|
+
|
|
6
|
+
// src/api/debug.ts
|
|
7
|
+
var defaultSearchParams = () => typeof window !== "undefined" && window.location ? new URLSearchParams(window.location.search) : null;
|
|
8
|
+
function readDebugFlags(options = {}) {
|
|
9
|
+
const params = (options.searchParams ?? defaultSearchParams)() ?? null;
|
|
10
|
+
return {
|
|
11
|
+
debug: params?.has("debug") ?? false,
|
|
12
|
+
noCache: params?.has("noCache") ?? false,
|
|
13
|
+
xdebug: params?.has("xdebug") ?? false,
|
|
14
|
+
errorsAsJson: params?.has("errorsAsJson") ?? false
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
var appendToUrl = (url, key, value) => new RegExp(`[?&]${key}=`, "i").test(url) ? url : `${url}${url.includes("?") ? "&" : "?"}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
18
|
+
function applyDebugParams(args, flags, xdebugSessionKey = "1") {
|
|
19
|
+
const extra = [];
|
|
20
|
+
if (flags.debug) extra.push(["debug", "true"]);
|
|
21
|
+
if (flags.noCache) extra.push(["noCache", "true"]);
|
|
22
|
+
if (flags.xdebug) extra.push(["XDEBUG_SESSION", xdebugSessionKey]);
|
|
23
|
+
if (flags.errorsAsJson) extra.push(["errors_as_json", "1"]);
|
|
24
|
+
if (extra.length === 0) return args;
|
|
25
|
+
if (typeof args === "string") {
|
|
26
|
+
return extra.reduce((url, [key, value]) => appendToUrl(url, key, value), args);
|
|
27
|
+
}
|
|
28
|
+
const params = { ...args.params ?? {} };
|
|
29
|
+
for (const [key, value] of extra) {
|
|
30
|
+
if (params[key] === void 0 && !new RegExp(`[?&]${key}=`, "i").test(args.url)) params[key] = value;
|
|
31
|
+
}
|
|
32
|
+
return { ...args, params };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/api/refresh.ts
|
|
36
|
+
function createDddRefresh(path) {
|
|
37
|
+
return async ({ refreshToken, baseQuery, api, extraOptions }) => {
|
|
38
|
+
const result = await baseQuery({ url: path, method: "POST", body: { refreshToken } }, api, extraOptions);
|
|
39
|
+
const payload = result.data;
|
|
40
|
+
if (result.error || !payload?.accessToken) return null;
|
|
41
|
+
return { accessToken: payload.accessToken, refreshToken: payload.refreshToken ?? refreshToken };
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/api/baseQuery.ts
|
|
46
|
+
var getRequestUrl = (request) => typeof request === "string" ? request : request.url;
|
|
47
|
+
var isDddAuthRequest = (request) => getRequestUrl(request).includes("/common/auth/");
|
|
48
|
+
var defaultShouldRefresh = (error, request) => error.status === 401 && !isDddAuthRequest(request);
|
|
49
|
+
var dddParamsSerializer = (params) => Object.entries(params).filter(([, value]) => value !== null && value !== void 0).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join("&");
|
|
50
|
+
var toFetchArgs = (args) => typeof args === "string" ? { url: args } : args;
|
|
51
|
+
var withBearer = (args, accessToken) => {
|
|
52
|
+
if (!accessToken) return args;
|
|
53
|
+
const headers = new Headers();
|
|
54
|
+
const source = args.headers;
|
|
55
|
+
if (source instanceof Headers) source.forEach((value, key) => headers.set(key, value));
|
|
56
|
+
else if (Array.isArray(source)) source.forEach(([key, value]) => key !== void 0 && headers.set(key, value ?? ""));
|
|
57
|
+
else if (source) Object.entries(source).forEach(([key, value]) => value !== void 0 && headers.set(key, value));
|
|
58
|
+
if (!headers.has("authorization")) headers.set("authorization", `Bearer ${accessToken}`);
|
|
59
|
+
return { ...args, headers };
|
|
60
|
+
};
|
|
61
|
+
function createDddBaseQuery(options) {
|
|
62
|
+
const { getTokens, setTokens, onLogout, headers: headersHook, languageCode, fetchOptions } = options;
|
|
63
|
+
const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;
|
|
64
|
+
if (!options.refresh && !options.refreshPath) {
|
|
65
|
+
throw new Error("createDddBaseQuery: pass either `refresh` or `refreshPath`.");
|
|
66
|
+
}
|
|
67
|
+
const refresh = options.refresh ?? createDddRefresh(options.refreshPath);
|
|
68
|
+
const debugOptions = options.debug === true ? {} : options.debug ? options.debug : null;
|
|
69
|
+
const fetchQuery = fetchBaseQuery({
|
|
70
|
+
paramsSerializer: dddParamsSerializer,
|
|
71
|
+
...fetchOptions,
|
|
72
|
+
baseUrl: options.baseUrl,
|
|
73
|
+
prepareHeaders: async (headers, context) => {
|
|
74
|
+
const language = languageCode?.(context);
|
|
75
|
+
if (language) headers.set("languageCode", language);
|
|
76
|
+
if (debugOptions && readDebugFlags(debugOptions).debug) headers.set("x-debug", "true");
|
|
77
|
+
return await headersHook?.(headers, context) ?? headers;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
const rawBaseQuery = (args, api, extraOptions) => {
|
|
81
|
+
const finalArgs = debugOptions ? applyDebugParams(args, readDebugFlags(debugOptions), debugOptions.xdebugSessionKey) : args;
|
|
82
|
+
return fetchQuery(finalArgs, api, extraOptions);
|
|
83
|
+
};
|
|
84
|
+
let generation = 0;
|
|
85
|
+
let lastOutcome = null;
|
|
86
|
+
let inflight = null;
|
|
87
|
+
const currentAccessToken = async (api) => (await getTokens(api))?.accessToken ?? null;
|
|
88
|
+
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";
|
|
92
|
+
if (!pair?.accessToken) {
|
|
93
|
+
await onLogout(api);
|
|
94
|
+
return "failed";
|
|
95
|
+
}
|
|
96
|
+
await setTokens({ accessToken: pair.accessToken, refreshToken: pair.refreshToken ?? refreshToken }, api);
|
|
97
|
+
return "refreshed";
|
|
98
|
+
};
|
|
99
|
+
const recover = async (startGeneration, api, extraOptions) => {
|
|
100
|
+
if (generation === startGeneration && !inflight) {
|
|
101
|
+
inflight = (async () => {
|
|
102
|
+
try {
|
|
103
|
+
lastOutcome = await runRefresh(api, extraOptions);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
lastOutcome = "error";
|
|
106
|
+
throw error;
|
|
107
|
+
} finally {
|
|
108
|
+
generation++;
|
|
109
|
+
inflight = null;
|
|
110
|
+
}
|
|
111
|
+
})();
|
|
112
|
+
}
|
|
113
|
+
if (inflight) await inflight;
|
|
114
|
+
return lastOutcome;
|
|
115
|
+
};
|
|
116
|
+
return async (args, api, extraOptions) => {
|
|
117
|
+
while (inflight) await inflight.catch(() => void 0);
|
|
118
|
+
const startGeneration = generation;
|
|
119
|
+
const request = toFetchArgs(args);
|
|
120
|
+
const result = await rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);
|
|
121
|
+
if (!result.error || !shouldRefresh(result.error, request)) return result;
|
|
122
|
+
if (await recover(startGeneration, api, extraOptions) !== "refreshed") return result;
|
|
123
|
+
return rawBaseQuery(withBearer(request, await currentAccessToken(api)), api, extraOptions);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/api/errors.ts
|
|
128
|
+
var DEFAULT_ERROR_MESSAGE = "Request failed";
|
|
129
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
130
|
+
var nonEmptyString = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
|
|
131
|
+
var extractBody = (error) => {
|
|
132
|
+
if ("data" in error) return error.data;
|
|
133
|
+
if ("responseBody" in error) return error.responseBody;
|
|
134
|
+
if ("error" in error || "validationErrors" in error || "exceptionDetails" in error) return error;
|
|
135
|
+
return void 0;
|
|
136
|
+
};
|
|
137
|
+
var extractStatus = (error) => {
|
|
138
|
+
if (error.status === "PARSING_ERROR" && typeof error.originalStatus === "number") return error.originalStatus;
|
|
139
|
+
if (typeof error.status === "number" || typeof error.status === "string") return error.status;
|
|
140
|
+
if (typeof error.statusCode === "number") return error.statusCode;
|
|
141
|
+
return null;
|
|
142
|
+
};
|
|
143
|
+
function normalizeDddError(error, fallbackMessage = DEFAULT_ERROR_MESSAGE) {
|
|
144
|
+
if (!isRecord(error)) {
|
|
145
|
+
return {
|
|
146
|
+
status: null,
|
|
147
|
+
message: nonEmptyString(error) ?? fallbackMessage,
|
|
148
|
+
validationErrors: null,
|
|
149
|
+
details: [],
|
|
150
|
+
body: void 0
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const body = extractBody(error);
|
|
154
|
+
const dddBody = isRecord(body) ? body : null;
|
|
155
|
+
const bodyRecord = isRecord(body) ? body : null;
|
|
156
|
+
const message = nonEmptyString(dddBody?.error) ?? nonEmptyString(bodyRecord?.message) ?? // RTK's non-HTTP errors carry the reason in `error` (e.g. "TypeError: Failed to fetch").
|
|
157
|
+
(body === void 0 || typeof body === "string" ? nonEmptyString(error.error) : null) ?? // A non-JSON error body (e.g. a download endpoint answering with plain text) is the message itself.
|
|
158
|
+
nonEmptyString(body)?.trim() ?? nonEmptyString(error.message) ?? fallbackMessage;
|
|
159
|
+
return {
|
|
160
|
+
status: extractStatus(error),
|
|
161
|
+
message,
|
|
162
|
+
validationErrors: dddBody?.validationErrors ?? null,
|
|
163
|
+
details: dddBody?.exceptionDetails?.elements ?? [],
|
|
164
|
+
body
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function getErrorMessage(error, fallbackMessage = DEFAULT_ERROR_MESSAGE) {
|
|
168
|
+
return normalizeDddError(error, fallbackMessage).message;
|
|
169
|
+
}
|
|
170
|
+
function getErrorStatus(error) {
|
|
171
|
+
const status = normalizeDddError(error).status;
|
|
172
|
+
return typeof status === "number" ? status : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/api/download.ts
|
|
176
|
+
function filenameFromContentDisposition(header) {
|
|
177
|
+
if (!header) return null;
|
|
178
|
+
const extended = /filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(header);
|
|
179
|
+
if (extended?.[2]) {
|
|
180
|
+
try {
|
|
181
|
+
return decodeURIComponent(extended[2].trim().replace(/^"|"$/g, ""));
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const plain = /filename\s*=\s*("([^"]*)"|[^;]*)/i.exec(header);
|
|
186
|
+
const value = (plain?.[2] ?? plain?.[1] ?? "").trim();
|
|
187
|
+
if (!value) return null;
|
|
188
|
+
try {
|
|
189
|
+
return decodeURIComponent(value);
|
|
190
|
+
} catch {
|
|
191
|
+
return value;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function downloadBlob(blob, filename) {
|
|
195
|
+
if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") return;
|
|
196
|
+
const url = URL.createObjectURL(blob);
|
|
197
|
+
const anchor = document.createElement("a");
|
|
198
|
+
anchor.href = url;
|
|
199
|
+
anchor.download = filename;
|
|
200
|
+
anchor.rel = "noopener";
|
|
201
|
+
document.body.appendChild(anchor);
|
|
202
|
+
anchor.click();
|
|
203
|
+
anchor.remove();
|
|
204
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
205
|
+
}
|
|
206
|
+
var parseErrorBody = async (response) => {
|
|
207
|
+
const text = await response.text();
|
|
208
|
+
if (!text) return void 0;
|
|
209
|
+
try {
|
|
210
|
+
return JSON.parse(text);
|
|
211
|
+
} catch {
|
|
212
|
+
return text;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
async function blobResponseHandler(response) {
|
|
216
|
+
if (!response.ok) return parseErrorBody(response);
|
|
217
|
+
return {
|
|
218
|
+
blob: await response.blob(),
|
|
219
|
+
filename: filenameFromContentDisposition(response.headers.get("content-disposition")),
|
|
220
|
+
contentType: response.headers.get("content-type")
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function createDownloadResponseHandler(fallbackFilename = "download") {
|
|
224
|
+
return async (response) => {
|
|
225
|
+
if (!response.ok) return parseErrorBody(response);
|
|
226
|
+
const blob = await response.blob();
|
|
227
|
+
const filename = filenameFromContentDisposition(response.headers.get("content-disposition")) ?? fallbackFilename;
|
|
228
|
+
downloadBlob(blob, filename);
|
|
229
|
+
return { filename, contentType: response.headers.get("content-type"), size: blob.size };
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// src/api/endpoints.ts
|
|
234
|
+
function createAuthEndpoints(api, options) {
|
|
235
|
+
return api.injectEndpoints({
|
|
236
|
+
endpoints: (build) => ({
|
|
237
|
+
authLogin: build.mutation({
|
|
238
|
+
query: (body) => ({ url: options.loginPath, method: "POST", body })
|
|
239
|
+
}),
|
|
240
|
+
authRefresh: build.mutation({
|
|
241
|
+
query: (body) => ({ url: options.refreshPath, method: "POST", body })
|
|
242
|
+
})
|
|
243
|
+
})
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
export {
|
|
247
|
+
DEFAULT_ERROR_MESSAGE,
|
|
248
|
+
applyDebugParams,
|
|
249
|
+
blobResponseHandler,
|
|
250
|
+
createAuthEndpoints,
|
|
251
|
+
createDddBaseQuery,
|
|
252
|
+
createDddRefresh,
|
|
253
|
+
createDownloadResponseHandler,
|
|
254
|
+
dddParamsSerializer,
|
|
255
|
+
defaultShouldRefresh,
|
|
256
|
+
downloadBlob,
|
|
257
|
+
filenameFromContentDisposition,
|
|
258
|
+
getErrorMessage,
|
|
259
|
+
getErrorStatus,
|
|
260
|
+
getRequestUrl,
|
|
261
|
+
isDddAuthRequest,
|
|
262
|
+
normalizeDddError,
|
|
263
|
+
readDebugFlags
|
|
264
|
+
};
|
|
265
|
+
//# sourceMappingURL=index.js.map
|