@nubitio/core 1.0.3 → 1.1.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.
- package/README.md +50 -0
- package/dist/index.cjs +105 -16
- package/dist/index.d.cts +113 -1
- package/dist/index.d.mts +113 -1
- package/dist/index.mjs +103 -17
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -111,6 +111,56 @@ const httpConfig = {
|
|
|
111
111
|
|
|
112
112
|
You can also provide a full `refreshFn` if you want the client to still participate in refresh, but with your own logic (e.g. refreshing a Bearer token).
|
|
113
113
|
|
|
114
|
+
### Dynamic headers (Bearer tokens)
|
|
115
|
+
|
|
116
|
+
Apps that keep an access token in memory or storage — instead of relying solely on the cookie session — use `getAuthHeaders`. It is called before _every_ request (including the built-in refresh request), so a rotated token is picked up without reconstructing the client:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const httpClient = createCoreHttpClient({
|
|
120
|
+
baseUrl: '/api/',
|
|
121
|
+
getAuthHeaders: () => {
|
|
122
|
+
const token = tokenStore.get(); // read fresh each call, not captured once
|
|
123
|
+
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Omit it (or return `{}`) to keep pure cookie-based behavior.
|
|
129
|
+
|
|
130
|
+
### CSRF tokens
|
|
131
|
+
|
|
132
|
+
Backends that protect state-changing requests (POST/PUT/PATCH/DELETE) with a CSRF token — a common `X-CSRF-Token` / cookie double-submit setup — use `getCsrfToken`. It is only consulted for those methods; GET/HEAD never trigger a token lookup.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const httpClient = createCoreHttpClient({
|
|
136
|
+
baseUrl: '/api/',
|
|
137
|
+
getCsrfToken: () => readCookie('CSRF_TOKEN'),
|
|
138
|
+
// csrfHeaderName: 'X-CSRF-Token', (default)
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Return `undefined` to skip the header for a given call.
|
|
143
|
+
|
|
144
|
+
### Correlation ids
|
|
145
|
+
|
|
146
|
+
Set `enableCorrelationId` to attach a per-request `X-Request-Id` (configurable via `correlationIdHeaderName`) that your backend can log alongside its own traces:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
const httpClient = createCoreHttpClient({
|
|
150
|
+
baseUrl: '/api/',
|
|
151
|
+
enableCorrelationId: true,
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
- The id is returned on `CoreHttpResponse.correlationId` and `CoreHttpError.correlationId`, so an error UI can show a support reference — including when the request never received a response at all (network failure, timeout), because the id is minted client-side before sending.
|
|
156
|
+
- One 401 → refresh → retry sequence keeps a single id across both attempts.
|
|
157
|
+
- Requests to an absolute `http(s)://` URL are left untouched (no header added), so third-party calls don't gain a custom header that could trigger a CORS preflight.
|
|
158
|
+
- `getCorrelationId` overrides generation (deterministic tests, or reusing an id minted earlier, e.g. for an offline-queued mutation). `generateCorrelationId` is exported for the latter case.
|
|
159
|
+
|
|
160
|
+
### Header precedence
|
|
161
|
+
|
|
162
|
+
For any single request, headers are merged in this order, with later entries winning: static locale → `getAuthHeaders` → `getCsrfToken` → correlation id → the call's own `config.headers`. A specific call can therefore override anything the config-level hooks produced.
|
|
163
|
+
|
|
114
164
|
See `CoreHttpClientConfig` for all options.
|
|
115
165
|
|
|
116
166
|
## Key exports
|
package/dist/index.cjs
CHANGED
|
@@ -995,7 +995,43 @@ function discoverMercureFromResponse(response, data) {
|
|
|
995
995
|
if (topicOrigin) setDiscoveredTopicOrigin(topicOrigin);
|
|
996
996
|
}
|
|
997
997
|
//#endregion
|
|
998
|
+
//#region packages/core/http/correlationId.ts
|
|
999
|
+
/**
|
|
1000
|
+
* Generates a client-side correlation id for one logical HTTP request.
|
|
1001
|
+
*
|
|
1002
|
+
* Prefers the standard `crypto.randomUUID()`. Falls back to a timestamp +
|
|
1003
|
+
* random token in environments where it is unavailable (insecure/non-HTTPS
|
|
1004
|
+
* contexts, older browsers, some test runners) so requests are never blocked
|
|
1005
|
+
* just because a correlation id could not be minted.
|
|
1006
|
+
*
|
|
1007
|
+
* Used by {@link CoreHttpClient} when `enableCorrelationId` is on. Exported
|
|
1008
|
+
* so an app can pre-generate an id for a request it hasn't sent yet — for
|
|
1009
|
+
* example an offline-queued mutation — and pass it back in via
|
|
1010
|
+
* `CoreHttpClientConfig.getCorrelationId` (or `CoreRequestConfig.headers`)
|
|
1011
|
+
* so the id logged in the offline queue matches the one the backend sees.
|
|
1012
|
+
*/
|
|
1013
|
+
function generateCorrelationId() {
|
|
1014
|
+
const cryptoRef = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
1015
|
+
if (cryptoRef && typeof cryptoRef.randomUUID === "function") return cryptoRef.randomUUID();
|
|
1016
|
+
return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
1017
|
+
}
|
|
1018
|
+
//#endregion
|
|
998
1019
|
//#region packages/core/http/CoreHttpClient.ts
|
|
1020
|
+
/** Default value of {@link CoreHttpClientConfig.csrfHeaderName}. */
|
|
1021
|
+
const DEFAULT_CSRF_HEADER_NAME = "X-CSRF-Token";
|
|
1022
|
+
/** Default value of {@link CoreHttpClientConfig.correlationIdHeaderName}. */
|
|
1023
|
+
const DEFAULT_CORRELATION_ID_HEADER_NAME = "X-Request-Id";
|
|
1024
|
+
/**
|
|
1025
|
+
* HTTP methods `getCsrfToken` is consulted for. Matches the conventional
|
|
1026
|
+
* "safe methods don't need CSRF protection" rule (GET/HEAD never mutate
|
|
1027
|
+
* state), so read requests never pay the cost of a token lookup.
|
|
1028
|
+
*/
|
|
1029
|
+
const CSRF_PROTECTED_METHODS = new Set([
|
|
1030
|
+
"POST",
|
|
1031
|
+
"PUT",
|
|
1032
|
+
"PATCH",
|
|
1033
|
+
"DELETE"
|
|
1034
|
+
]);
|
|
999
1035
|
function joinUrl(baseUrl, url) {
|
|
1000
1036
|
if (/^https?:\/\//.test(url) || url.startsWith("/")) return url;
|
|
1001
1037
|
return `${baseUrl.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
|
|
@@ -1025,12 +1061,24 @@ function withParams(url, params) {
|
|
|
1025
1061
|
if (!query) return url;
|
|
1026
1062
|
return `${url}${url.includes("?") ? "&" : "?"}${query}`;
|
|
1027
1063
|
}
|
|
1028
|
-
function createHttpError(message, status, data) {
|
|
1064
|
+
function createHttpError(message, status, data, correlationId) {
|
|
1029
1065
|
return Object.assign(new Error(message), {
|
|
1030
1066
|
status,
|
|
1031
|
-
data
|
|
1067
|
+
data,
|
|
1068
|
+
correlationId
|
|
1032
1069
|
});
|
|
1033
1070
|
}
|
|
1071
|
+
/**
|
|
1072
|
+
* A fully-qualified `http(s)://` URL targets a different origin than the
|
|
1073
|
+
* app's own `baseUrl` (or is at least not guaranteed to be the same one —
|
|
1074
|
+
* see `joinUrl`, which passes these through unchanged). Root-relative
|
|
1075
|
+
* (`/path`) and bare relative (`path`) URLs always resolve against this
|
|
1076
|
+
* app's own origin/baseUrl, so they're the only ones eligible for the
|
|
1077
|
+
* correlation-id header.
|
|
1078
|
+
*/
|
|
1079
|
+
function isExternalUrl(url) {
|
|
1080
|
+
return /^https?:\/\//.test(url);
|
|
1081
|
+
}
|
|
1034
1082
|
async function readResponseBody(response, responseType) {
|
|
1035
1083
|
if (response.status === 204) return;
|
|
1036
1084
|
if (responseType === "arraybuffer") return await response.arrayBuffer();
|
|
@@ -1044,26 +1092,59 @@ var CoreHttpClient = class {
|
|
|
1044
1092
|
constructor(config = {}) {
|
|
1045
1093
|
this.config = config;
|
|
1046
1094
|
}
|
|
1047
|
-
|
|
1095
|
+
/**
|
|
1096
|
+
* Builds the full header set for one request: static locale, then dynamic
|
|
1097
|
+
* auth headers, then CSRF (mutating methods only), then correlation id,
|
|
1098
|
+
* then the caller's own `extraHeaders` — which always win, so a specific
|
|
1099
|
+
* call can still override anything the config-level hooks produced.
|
|
1100
|
+
*/
|
|
1101
|
+
async headers(method, extraHeaders, correlationId) {
|
|
1048
1102
|
const browserLocale = typeof navigator !== "undefined" ? navigator.language?.split("-")[0] : void 0;
|
|
1103
|
+
const locale = this.config.locale ?? browserLocale ?? "en";
|
|
1104
|
+
const authHeaders = this.config.getAuthHeaders ? await this.config.getAuthHeaders() : void 0;
|
|
1105
|
+
let csrfHeader;
|
|
1106
|
+
if (this.config.getCsrfToken && CSRF_PROTECTED_METHODS.has(method)) {
|
|
1107
|
+
const token = await this.config.getCsrfToken(method);
|
|
1108
|
+
if (token) csrfHeader = { [this.config.csrfHeaderName ?? "X-CSRF-Token"]: token };
|
|
1109
|
+
}
|
|
1110
|
+
const correlationHeader = correlationId !== void 0 ? { [this.config.correlationIdHeaderName ?? "X-Request-Id"]: correlationId } : void 0;
|
|
1049
1111
|
return {
|
|
1050
|
-
"Accept-Language":
|
|
1112
|
+
"Accept-Language": locale,
|
|
1113
|
+
...authHeaders,
|
|
1114
|
+
...csrfHeader,
|
|
1115
|
+
...correlationHeader,
|
|
1051
1116
|
...extraHeaders
|
|
1052
1117
|
};
|
|
1053
1118
|
}
|
|
1119
|
+
/** A fresh correlation id for one logical request, or undefined when disabled/not applicable. */
|
|
1120
|
+
correlationIdFor(url) {
|
|
1121
|
+
if (!this.config.enableCorrelationId || isExternalUrl(url)) return void 0;
|
|
1122
|
+
return (this.config.getCorrelationId ?? generateCorrelationId)();
|
|
1123
|
+
}
|
|
1054
1124
|
/**
|
|
1055
1125
|
* Built-in cookie-based refresh (the original behavior).
|
|
1056
1126
|
* Only used when `refreshFn` is not provided in config.
|
|
1127
|
+
*
|
|
1128
|
+
* Carries the same auth/CSRF headers as an ordinary request — a
|
|
1129
|
+
* CSRF-protected backend protects its refresh endpoint too — and its own
|
|
1130
|
+
* correlation id, minted fresh rather than borrowed from whichever
|
|
1131
|
+
* request(s) triggered it, since one shared refresh can be triggered by
|
|
1132
|
+
* several concurrent requests at once (see the dedup logic below) and
|
|
1133
|
+
* there is no single "right" id to inherit from among them.
|
|
1057
1134
|
*/
|
|
1058
1135
|
async performBuiltInRefresh() {
|
|
1059
1136
|
const refreshPath = this.config.refreshPath ?? "auth/refresh";
|
|
1060
1137
|
const refreshUrl = joinUrl(this.config.baseUrl ?? "/api/", refreshPath);
|
|
1061
|
-
this.refreshPromise ??=
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1138
|
+
this.refreshPromise ??= (async () => {
|
|
1139
|
+
const correlationId = this.correlationIdFor(refreshPath);
|
|
1140
|
+
const headers = await this.headers("POST", void 0, correlationId);
|
|
1141
|
+
const response = await globalThis.fetch(refreshUrl, {
|
|
1142
|
+
method: "POST",
|
|
1143
|
+
headers,
|
|
1144
|
+
credentials: this.config.credentials ?? "include"
|
|
1145
|
+
});
|
|
1146
|
+
if (!response.ok) throw createHttpError("Session refresh failed", response.status, await this.safeErrorData(response), correlationId);
|
|
1147
|
+
})().finally(() => {
|
|
1067
1148
|
this.refreshPromise = null;
|
|
1068
1149
|
});
|
|
1069
1150
|
return this.refreshPromise;
|
|
@@ -1079,9 +1160,10 @@ var CoreHttpClient = class {
|
|
|
1079
1160
|
return {};
|
|
1080
1161
|
}
|
|
1081
1162
|
}
|
|
1082
|
-
async request(method, url, body, config, retryOnUnauthorized = true) {
|
|
1163
|
+
async request(method, url, body, config, retryOnUnauthorized = true, inheritedCorrelationId) {
|
|
1083
1164
|
const requestUrl = withParams(joinUrl(this.config.baseUrl ?? "/api/", url), config?.params);
|
|
1084
|
-
const
|
|
1165
|
+
const correlationId = inheritedCorrelationId ?? this.correlationIdFor(url);
|
|
1166
|
+
const headers = await this.headers(method, config?.headers, correlationId);
|
|
1085
1167
|
if (body !== void 0 && body !== null && !(body instanceof FormData)) headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
1086
1168
|
const response = await globalThis.fetch(requestUrl, {
|
|
1087
1169
|
method,
|
|
@@ -1097,20 +1179,24 @@ var CoreHttpClient = class {
|
|
|
1097
1179
|
response,
|
|
1098
1180
|
data,
|
|
1099
1181
|
headers: response.headers,
|
|
1100
|
-
status: response.status
|
|
1182
|
+
status: response.status,
|
|
1183
|
+
correlationId
|
|
1101
1184
|
};
|
|
1102
1185
|
}
|
|
1103
1186
|
const errorData = await this.safeErrorData(response);
|
|
1104
|
-
const error = createHttpError(errorData.detail ?? errorData.message ?? "HTTP request failed", response.status, errorData);
|
|
1187
|
+
const error = createHttpError(errorData.detail ?? errorData.message ?? "HTTP request failed", response.status, errorData, correlationId);
|
|
1105
1188
|
const loginPath = this.config.loginPath ?? "auth/login";
|
|
1106
1189
|
const refreshPath = this.config.refreshPath ?? "auth/refresh";
|
|
1107
1190
|
const isAuthEndpoint = url.includes(loginPath) || url.includes(refreshPath);
|
|
1108
1191
|
const shouldAutoRefresh = this.config.autoRefresh !== false;
|
|
1109
1192
|
if (response.status === 401 && retryOnUnauthorized && !isAuthEndpoint && shouldAutoRefresh) try {
|
|
1110
1193
|
await this.performRefresh();
|
|
1111
|
-
return this.request(method, url, body, config, false);
|
|
1194
|
+
return this.request(method, url, body, config, false, correlationId);
|
|
1112
1195
|
} catch (refreshError) {
|
|
1113
|
-
const unauthorizedError = refreshError instanceof Error ? Object.assign(refreshError, {
|
|
1196
|
+
const unauthorizedError = refreshError instanceof Error ? Object.assign(refreshError, {
|
|
1197
|
+
status: 401,
|
|
1198
|
+
correlationId
|
|
1199
|
+
}) : error;
|
|
1114
1200
|
this.config.onUnauthorized?.(unauthorizedError);
|
|
1115
1201
|
throw unauthorizedError;
|
|
1116
1202
|
}
|
|
@@ -1435,6 +1521,8 @@ exports.CoreHttpClient = CoreHttpClient;
|
|
|
1435
1521
|
exports.CoreHttpProvider = CoreHttpProvider;
|
|
1436
1522
|
exports.CoreProvider = CoreProvider;
|
|
1437
1523
|
exports.CoreRuntimeProvider = CoreRuntimeProvider;
|
|
1524
|
+
exports.DEFAULT_CORRELATION_ID_HEADER_NAME = DEFAULT_CORRELATION_ID_HEADER_NAME;
|
|
1525
|
+
exports.DEFAULT_CSRF_HEADER_NAME = DEFAULT_CSRF_HEADER_NAME;
|
|
1438
1526
|
exports.DEFAULT_TIMEZONE = DEFAULT_TIMEZONE;
|
|
1439
1527
|
exports.DateUtils = DateUtils;
|
|
1440
1528
|
exports.FeatureFlagsProvider = FeatureFlagsProvider;
|
|
@@ -1456,6 +1544,7 @@ exports.extractTopicOriginFromPayload = extractTopicOriginFromPayload;
|
|
|
1456
1544
|
exports.formatMinorUnits = formatMinorUnits;
|
|
1457
1545
|
exports.formatMoney = formatMoney;
|
|
1458
1546
|
exports.fromMinorUnits = fromMinorUnits;
|
|
1547
|
+
exports.generateCorrelationId = generateCorrelationId;
|
|
1459
1548
|
exports.getCoreApiBaseUrl = getCoreApiBaseUrl;
|
|
1460
1549
|
exports.getCoreCurrency = getCoreCurrency;
|
|
1461
1550
|
exports.getCoreLocale = getCoreLocale;
|
package/dist/index.d.cts
CHANGED
|
@@ -473,6 +473,12 @@ interface CoreHttpResponse<T> {
|
|
|
473
473
|
data: T;
|
|
474
474
|
headers: Headers;
|
|
475
475
|
status: number;
|
|
476
|
+
/**
|
|
477
|
+
* The correlation id sent with this request under `correlationIdHeaderName`,
|
|
478
|
+
* present only when `enableCorrelationId` is on and the request resolved
|
|
479
|
+
* against `baseUrl` (see {@link CoreHttpClientConfig.enableCorrelationId}).
|
|
480
|
+
*/
|
|
481
|
+
correlationId?: string;
|
|
476
482
|
}
|
|
477
483
|
interface CoreHttpErrorData {
|
|
478
484
|
detail?: string;
|
|
@@ -483,7 +489,13 @@ interface CoreHttpErrorData {
|
|
|
483
489
|
interface CoreHttpError extends Error {
|
|
484
490
|
status?: number;
|
|
485
491
|
data?: CoreHttpErrorData;
|
|
492
|
+
/** The correlation id sent with the request that failed, if enabled. See {@link CoreHttpResponse.correlationId}. */
|
|
493
|
+
correlationId?: string;
|
|
486
494
|
}
|
|
495
|
+
/** Default value of {@link CoreHttpClientConfig.csrfHeaderName}. */
|
|
496
|
+
declare const DEFAULT_CSRF_HEADER_NAME = "X-CSRF-Token";
|
|
497
|
+
/** Default value of {@link CoreHttpClientConfig.correlationIdHeaderName}. */
|
|
498
|
+
declare const DEFAULT_CORRELATION_ID_HEADER_NAME = "X-Request-Id";
|
|
487
499
|
interface CoreHttpClientConfig {
|
|
488
500
|
baseUrl?: string;
|
|
489
501
|
credentials?: RequestCredentials;
|
|
@@ -520,15 +532,98 @@ interface CoreHttpClientConfig {
|
|
|
520
532
|
refreshFn?: (client: CoreHttpClient) => Promise<void>;
|
|
521
533
|
onUnauthorized?: (error: CoreHttpError) => void;
|
|
522
534
|
onError?: (error: CoreHttpError) => void;
|
|
535
|
+
/**
|
|
536
|
+
* Supplies request headers that can change between calls — most commonly
|
|
537
|
+
* an `Authorization: Bearer <token>` header for apps that keep the access
|
|
538
|
+
* token in memory or storage instead of relying solely on the cookie
|
|
539
|
+
* session. Called before every request, including the built-in refresh
|
|
540
|
+
* request, so a fresh token is always read rather than captured once at
|
|
541
|
+
* client construction time.
|
|
542
|
+
*
|
|
543
|
+
* Omitting this (or returning an empty object) adds no headers — the
|
|
544
|
+
* client still works purely on cookies, exactly as before this option
|
|
545
|
+
* existed.
|
|
546
|
+
*
|
|
547
|
+
* Example:
|
|
548
|
+
* getAuthHeaders: () => {
|
|
549
|
+
* const token = tokenStore.get();
|
|
550
|
+
* return token ? { Authorization: `Bearer ${token}` } : {};
|
|
551
|
+
* }
|
|
552
|
+
*/
|
|
553
|
+
getAuthHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
554
|
+
/**
|
|
555
|
+
* Supplies a CSRF token to attach to state-changing requests (POST, PUT,
|
|
556
|
+
* PATCH, DELETE — see `CSRF_PROTECTED_METHODS`). Not called for GET/HEAD.
|
|
557
|
+
* Return `undefined` to skip the header for a given call (e.g. no token
|
|
558
|
+
* available yet).
|
|
559
|
+
*
|
|
560
|
+
* Example (cookie double-submit pattern):
|
|
561
|
+
* getCsrfToken: () => readCookie('CSRF_TOKEN')
|
|
562
|
+
*/
|
|
563
|
+
getCsrfToken?: (method: string) => string | undefined | Promise<string | undefined>;
|
|
564
|
+
/**
|
|
565
|
+
* Header name the token from `getCsrfToken` is sent under.
|
|
566
|
+
* @default "X-CSRF-Token"
|
|
567
|
+
*/
|
|
568
|
+
csrfHeaderName?: string;
|
|
569
|
+
/**
|
|
570
|
+
* When true, every request that resolves against `baseUrl` carries a
|
|
571
|
+
* generated correlation id under `correlationIdHeaderName`. The same id is
|
|
572
|
+
* reused across a 401 → refresh → retry sequence, and is returned on
|
|
573
|
+
* `CoreHttpResponse.correlationId` / `CoreHttpError.correlationId` so an
|
|
574
|
+
* app can surface it in a support/error UI — including when the request
|
|
575
|
+
* never receives a response at all (network failure, timeout), since the
|
|
576
|
+
* id is generated client-side before the request is sent.
|
|
577
|
+
*
|
|
578
|
+
* Requests to a fully-qualified `http(s)://` URL on a different origin
|
|
579
|
+
* (see `joinUrl`) never receive the header, regardless of this setting:
|
|
580
|
+
* correlation ids are for your own backend, and adding a custom header to
|
|
581
|
+
* a third-party request can turn a "simple" CORS request into a
|
|
582
|
+
* preflighted one for APIs that don't expect it.
|
|
583
|
+
*
|
|
584
|
+
* Disabled by default — opting in is an explicit choice because it adds a
|
|
585
|
+
* header to every internal request.
|
|
586
|
+
*
|
|
587
|
+
* @default false
|
|
588
|
+
*/
|
|
589
|
+
enableCorrelationId?: boolean;
|
|
590
|
+
/**
|
|
591
|
+
* Header name the correlation id is sent under. Match this to whatever
|
|
592
|
+
* your backend reads (Nubit backends read `X-Request-Id` by convention).
|
|
593
|
+
* @default "X-Request-Id"
|
|
594
|
+
*/
|
|
595
|
+
correlationIdHeaderName?: string;
|
|
596
|
+
/**
|
|
597
|
+
* Overrides how the correlation id is generated. Defaults to
|
|
598
|
+
* {@link generateCorrelationId}. Mainly useful for tests that need a
|
|
599
|
+
* deterministic id, or apps that want to reuse an id minted earlier (e.g.
|
|
600
|
+
* for a request that was queued while offline).
|
|
601
|
+
*/
|
|
602
|
+
getCorrelationId?: () => string;
|
|
523
603
|
}
|
|
524
604
|
declare class CoreHttpClient {
|
|
525
605
|
private readonly config;
|
|
526
606
|
private refreshPromise;
|
|
527
607
|
constructor(config?: CoreHttpClientConfig);
|
|
608
|
+
/**
|
|
609
|
+
* Builds the full header set for one request: static locale, then dynamic
|
|
610
|
+
* auth headers, then CSRF (mutating methods only), then correlation id,
|
|
611
|
+
* then the caller's own `extraHeaders` — which always win, so a specific
|
|
612
|
+
* call can still override anything the config-level hooks produced.
|
|
613
|
+
*/
|
|
528
614
|
private headers;
|
|
615
|
+
/** A fresh correlation id for one logical request, or undefined when disabled/not applicable. */
|
|
616
|
+
private correlationIdFor;
|
|
529
617
|
/**
|
|
530
618
|
* Built-in cookie-based refresh (the original behavior).
|
|
531
619
|
* Only used when `refreshFn` is not provided in config.
|
|
620
|
+
*
|
|
621
|
+
* Carries the same auth/CSRF headers as an ordinary request — a
|
|
622
|
+
* CSRF-protected backend protects its refresh endpoint too — and its own
|
|
623
|
+
* correlation id, minted fresh rather than borrowed from whichever
|
|
624
|
+
* request(s) triggered it, since one shared refresh can be triggered by
|
|
625
|
+
* several concurrent requests at once (see the dedup logic below) and
|
|
626
|
+
* there is no single "right" id to inherit from among them.
|
|
532
627
|
*/
|
|
533
628
|
private performBuiltInRefresh;
|
|
534
629
|
private performRefresh;
|
|
@@ -555,6 +650,23 @@ declare function CoreHttpProvider({
|
|
|
555
650
|
}: CoreHttpProviderProps): React.JSX.Element;
|
|
556
651
|
declare function useCoreHttpClient(): CoreHttpClient;
|
|
557
652
|
//#endregion
|
|
653
|
+
//#region packages/core/http/correlationId.d.ts
|
|
654
|
+
/**
|
|
655
|
+
* Generates a client-side correlation id for one logical HTTP request.
|
|
656
|
+
*
|
|
657
|
+
* Prefers the standard `crypto.randomUUID()`. Falls back to a timestamp +
|
|
658
|
+
* random token in environments where it is unavailable (insecure/non-HTTPS
|
|
659
|
+
* contexts, older browsers, some test runners) so requests are never blocked
|
|
660
|
+
* just because a correlation id could not be minted.
|
|
661
|
+
*
|
|
662
|
+
* Used by {@link CoreHttpClient} when `enableCorrelationId` is on. Exported
|
|
663
|
+
* so an app can pre-generate an id for a request it hasn't sent yet — for
|
|
664
|
+
* example an offline-queued mutation — and pass it back in via
|
|
665
|
+
* `CoreHttpClientConfig.getCorrelationId` (or `CoreRequestConfig.headers`)
|
|
666
|
+
* so the id logged in the offline queue matches the one the backend sees.
|
|
667
|
+
*/
|
|
668
|
+
declare function generateCorrelationId(): string;
|
|
669
|
+
//#endregion
|
|
558
670
|
//#region packages/core/runtime/CoreRuntimeContext.d.ts
|
|
559
671
|
type CoreNotificationType = 'success' | 'error' | 'warning' | 'info';
|
|
560
672
|
interface CoreRuntime {
|
|
@@ -816,4 +928,4 @@ declare class MercureManager {
|
|
|
816
928
|
/** Singleton instance — shared across the entire application. */
|
|
817
929
|
declare const mercureManager: MercureManager;
|
|
818
930
|
//#endregion
|
|
819
|
-
export { type CoreConfig, CoreConfigProvider, type CoreConfigProviderProps, CoreHttpClient, type CoreHttpClientConfig, type CoreHttpError, type CoreHttpErrorData, CoreHttpProvider, type CoreHttpProviderProps, type CoreHttpResponse, type CoreNotificationType, CoreProvider, type CoreProviderProps, type CoreRequestConfig, type CoreResponseType, type CoreRuntime, CoreRuntimeProvider, type CoreRuntimeProviderProps, type CoreTranslationKeys, DEFAULT_TIMEZONE, type DataGridEventNames, type DataRecord, DateUtils, type DialogEventNames, type EventSubscription, type FeatureFlagClient, type FeatureFlagEvaluationContext, type FeatureFlagValues, FeatureFlagsProvider, type FeatureFlagsProviderProps, type FormEventNames, type FormatMoneyOptions, type GridData, mercureManager as MercureManager, type MercureManager as MercureManagerType, MercureProvider, type MercureProviderProps, type MoneyValue, type ScopedFormEventNames, StaticFeatureFlagClient, type ToolbarButtonItem, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|
|
931
|
+
export { type CoreConfig, CoreConfigProvider, type CoreConfigProviderProps, CoreHttpClient, type CoreHttpClientConfig, type CoreHttpError, type CoreHttpErrorData, CoreHttpProvider, type CoreHttpProviderProps, type CoreHttpResponse, type CoreNotificationType, CoreProvider, type CoreProviderProps, type CoreRequestConfig, type CoreResponseType, type CoreRuntime, CoreRuntimeProvider, type CoreRuntimeProviderProps, type CoreTranslationKeys, DEFAULT_CORRELATION_ID_HEADER_NAME, DEFAULT_CSRF_HEADER_NAME, DEFAULT_TIMEZONE, type DataGridEventNames, type DataRecord, DateUtils, type DialogEventNames, type EventSubscription, type FeatureFlagClient, type FeatureFlagEvaluationContext, type FeatureFlagValues, FeatureFlagsProvider, type FeatureFlagsProviderProps, type FormEventNames, type FormatMoneyOptions, type GridData, mercureManager as MercureManager, type MercureManager as MercureManagerType, MercureProvider, type MercureProviderProps, type MoneyValue, type ScopedFormEventNames, StaticFeatureFlagClient, type ToolbarButtonItem, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, generateCorrelationId, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|
package/dist/index.d.mts
CHANGED
|
@@ -473,6 +473,12 @@ interface CoreHttpResponse<T> {
|
|
|
473
473
|
data: T;
|
|
474
474
|
headers: Headers;
|
|
475
475
|
status: number;
|
|
476
|
+
/**
|
|
477
|
+
* The correlation id sent with this request under `correlationIdHeaderName`,
|
|
478
|
+
* present only when `enableCorrelationId` is on and the request resolved
|
|
479
|
+
* against `baseUrl` (see {@link CoreHttpClientConfig.enableCorrelationId}).
|
|
480
|
+
*/
|
|
481
|
+
correlationId?: string;
|
|
476
482
|
}
|
|
477
483
|
interface CoreHttpErrorData {
|
|
478
484
|
detail?: string;
|
|
@@ -483,7 +489,13 @@ interface CoreHttpErrorData {
|
|
|
483
489
|
interface CoreHttpError extends Error {
|
|
484
490
|
status?: number;
|
|
485
491
|
data?: CoreHttpErrorData;
|
|
492
|
+
/** The correlation id sent with the request that failed, if enabled. See {@link CoreHttpResponse.correlationId}. */
|
|
493
|
+
correlationId?: string;
|
|
486
494
|
}
|
|
495
|
+
/** Default value of {@link CoreHttpClientConfig.csrfHeaderName}. */
|
|
496
|
+
declare const DEFAULT_CSRF_HEADER_NAME = "X-CSRF-Token";
|
|
497
|
+
/** Default value of {@link CoreHttpClientConfig.correlationIdHeaderName}. */
|
|
498
|
+
declare const DEFAULT_CORRELATION_ID_HEADER_NAME = "X-Request-Id";
|
|
487
499
|
interface CoreHttpClientConfig {
|
|
488
500
|
baseUrl?: string;
|
|
489
501
|
credentials?: RequestCredentials;
|
|
@@ -520,15 +532,98 @@ interface CoreHttpClientConfig {
|
|
|
520
532
|
refreshFn?: (client: CoreHttpClient) => Promise<void>;
|
|
521
533
|
onUnauthorized?: (error: CoreHttpError) => void;
|
|
522
534
|
onError?: (error: CoreHttpError) => void;
|
|
535
|
+
/**
|
|
536
|
+
* Supplies request headers that can change between calls — most commonly
|
|
537
|
+
* an `Authorization: Bearer <token>` header for apps that keep the access
|
|
538
|
+
* token in memory or storage instead of relying solely on the cookie
|
|
539
|
+
* session. Called before every request, including the built-in refresh
|
|
540
|
+
* request, so a fresh token is always read rather than captured once at
|
|
541
|
+
* client construction time.
|
|
542
|
+
*
|
|
543
|
+
* Omitting this (or returning an empty object) adds no headers — the
|
|
544
|
+
* client still works purely on cookies, exactly as before this option
|
|
545
|
+
* existed.
|
|
546
|
+
*
|
|
547
|
+
* Example:
|
|
548
|
+
* getAuthHeaders: () => {
|
|
549
|
+
* const token = tokenStore.get();
|
|
550
|
+
* return token ? { Authorization: `Bearer ${token}` } : {};
|
|
551
|
+
* }
|
|
552
|
+
*/
|
|
553
|
+
getAuthHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
554
|
+
/**
|
|
555
|
+
* Supplies a CSRF token to attach to state-changing requests (POST, PUT,
|
|
556
|
+
* PATCH, DELETE — see `CSRF_PROTECTED_METHODS`). Not called for GET/HEAD.
|
|
557
|
+
* Return `undefined` to skip the header for a given call (e.g. no token
|
|
558
|
+
* available yet).
|
|
559
|
+
*
|
|
560
|
+
* Example (cookie double-submit pattern):
|
|
561
|
+
* getCsrfToken: () => readCookie('CSRF_TOKEN')
|
|
562
|
+
*/
|
|
563
|
+
getCsrfToken?: (method: string) => string | undefined | Promise<string | undefined>;
|
|
564
|
+
/**
|
|
565
|
+
* Header name the token from `getCsrfToken` is sent under.
|
|
566
|
+
* @default "X-CSRF-Token"
|
|
567
|
+
*/
|
|
568
|
+
csrfHeaderName?: string;
|
|
569
|
+
/**
|
|
570
|
+
* When true, every request that resolves against `baseUrl` carries a
|
|
571
|
+
* generated correlation id under `correlationIdHeaderName`. The same id is
|
|
572
|
+
* reused across a 401 → refresh → retry sequence, and is returned on
|
|
573
|
+
* `CoreHttpResponse.correlationId` / `CoreHttpError.correlationId` so an
|
|
574
|
+
* app can surface it in a support/error UI — including when the request
|
|
575
|
+
* never receives a response at all (network failure, timeout), since the
|
|
576
|
+
* id is generated client-side before the request is sent.
|
|
577
|
+
*
|
|
578
|
+
* Requests to a fully-qualified `http(s)://` URL on a different origin
|
|
579
|
+
* (see `joinUrl`) never receive the header, regardless of this setting:
|
|
580
|
+
* correlation ids are for your own backend, and adding a custom header to
|
|
581
|
+
* a third-party request can turn a "simple" CORS request into a
|
|
582
|
+
* preflighted one for APIs that don't expect it.
|
|
583
|
+
*
|
|
584
|
+
* Disabled by default — opting in is an explicit choice because it adds a
|
|
585
|
+
* header to every internal request.
|
|
586
|
+
*
|
|
587
|
+
* @default false
|
|
588
|
+
*/
|
|
589
|
+
enableCorrelationId?: boolean;
|
|
590
|
+
/**
|
|
591
|
+
* Header name the correlation id is sent under. Match this to whatever
|
|
592
|
+
* your backend reads (Nubit backends read `X-Request-Id` by convention).
|
|
593
|
+
* @default "X-Request-Id"
|
|
594
|
+
*/
|
|
595
|
+
correlationIdHeaderName?: string;
|
|
596
|
+
/**
|
|
597
|
+
* Overrides how the correlation id is generated. Defaults to
|
|
598
|
+
* {@link generateCorrelationId}. Mainly useful for tests that need a
|
|
599
|
+
* deterministic id, or apps that want to reuse an id minted earlier (e.g.
|
|
600
|
+
* for a request that was queued while offline).
|
|
601
|
+
*/
|
|
602
|
+
getCorrelationId?: () => string;
|
|
523
603
|
}
|
|
524
604
|
declare class CoreHttpClient {
|
|
525
605
|
private readonly config;
|
|
526
606
|
private refreshPromise;
|
|
527
607
|
constructor(config?: CoreHttpClientConfig);
|
|
608
|
+
/**
|
|
609
|
+
* Builds the full header set for one request: static locale, then dynamic
|
|
610
|
+
* auth headers, then CSRF (mutating methods only), then correlation id,
|
|
611
|
+
* then the caller's own `extraHeaders` — which always win, so a specific
|
|
612
|
+
* call can still override anything the config-level hooks produced.
|
|
613
|
+
*/
|
|
528
614
|
private headers;
|
|
615
|
+
/** A fresh correlation id for one logical request, or undefined when disabled/not applicable. */
|
|
616
|
+
private correlationIdFor;
|
|
529
617
|
/**
|
|
530
618
|
* Built-in cookie-based refresh (the original behavior).
|
|
531
619
|
* Only used when `refreshFn` is not provided in config.
|
|
620
|
+
*
|
|
621
|
+
* Carries the same auth/CSRF headers as an ordinary request — a
|
|
622
|
+
* CSRF-protected backend protects its refresh endpoint too — and its own
|
|
623
|
+
* correlation id, minted fresh rather than borrowed from whichever
|
|
624
|
+
* request(s) triggered it, since one shared refresh can be triggered by
|
|
625
|
+
* several concurrent requests at once (see the dedup logic below) and
|
|
626
|
+
* there is no single "right" id to inherit from among them.
|
|
532
627
|
*/
|
|
533
628
|
private performBuiltInRefresh;
|
|
534
629
|
private performRefresh;
|
|
@@ -555,6 +650,23 @@ declare function CoreHttpProvider({
|
|
|
555
650
|
}: CoreHttpProviderProps): React.JSX.Element;
|
|
556
651
|
declare function useCoreHttpClient(): CoreHttpClient;
|
|
557
652
|
//#endregion
|
|
653
|
+
//#region packages/core/http/correlationId.d.ts
|
|
654
|
+
/**
|
|
655
|
+
* Generates a client-side correlation id for one logical HTTP request.
|
|
656
|
+
*
|
|
657
|
+
* Prefers the standard `crypto.randomUUID()`. Falls back to a timestamp +
|
|
658
|
+
* random token in environments where it is unavailable (insecure/non-HTTPS
|
|
659
|
+
* contexts, older browsers, some test runners) so requests are never blocked
|
|
660
|
+
* just because a correlation id could not be minted.
|
|
661
|
+
*
|
|
662
|
+
* Used by {@link CoreHttpClient} when `enableCorrelationId` is on. Exported
|
|
663
|
+
* so an app can pre-generate an id for a request it hasn't sent yet — for
|
|
664
|
+
* example an offline-queued mutation — and pass it back in via
|
|
665
|
+
* `CoreHttpClientConfig.getCorrelationId` (or `CoreRequestConfig.headers`)
|
|
666
|
+
* so the id logged in the offline queue matches the one the backend sees.
|
|
667
|
+
*/
|
|
668
|
+
declare function generateCorrelationId(): string;
|
|
669
|
+
//#endregion
|
|
558
670
|
//#region packages/core/runtime/CoreRuntimeContext.d.ts
|
|
559
671
|
type CoreNotificationType = 'success' | 'error' | 'warning' | 'info';
|
|
560
672
|
interface CoreRuntime {
|
|
@@ -816,4 +928,4 @@ declare class MercureManager {
|
|
|
816
928
|
/** Singleton instance — shared across the entire application. */
|
|
817
929
|
declare const mercureManager: MercureManager;
|
|
818
930
|
//#endregion
|
|
819
|
-
export { type CoreConfig, CoreConfigProvider, type CoreConfigProviderProps, CoreHttpClient, type CoreHttpClientConfig, type CoreHttpError, type CoreHttpErrorData, CoreHttpProvider, type CoreHttpProviderProps, type CoreHttpResponse, type CoreNotificationType, CoreProvider, type CoreProviderProps, type CoreRequestConfig, type CoreResponseType, type CoreRuntime, CoreRuntimeProvider, type CoreRuntimeProviderProps, type CoreTranslationKeys, DEFAULT_TIMEZONE, type DataGridEventNames, type DataRecord, DateUtils, type DialogEventNames, type EventSubscription, type FeatureFlagClient, type FeatureFlagEvaluationContext, type FeatureFlagValues, FeatureFlagsProvider, type FeatureFlagsProviderProps, type FormEventNames, type FormatMoneyOptions, type GridData, mercureManager as MercureManager, type MercureManager as MercureManagerType, MercureProvider, type MercureProviderProps, type MoneyValue, type ScopedFormEventNames, StaticFeatureFlagClient, type ToolbarButtonItem, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|
|
931
|
+
export { type CoreConfig, CoreConfigProvider, type CoreConfigProviderProps, CoreHttpClient, type CoreHttpClientConfig, type CoreHttpError, type CoreHttpErrorData, CoreHttpProvider, type CoreHttpProviderProps, type CoreHttpResponse, type CoreNotificationType, CoreProvider, type CoreProviderProps, type CoreRequestConfig, type CoreResponseType, type CoreRuntime, CoreRuntimeProvider, type CoreRuntimeProviderProps, type CoreTranslationKeys, DEFAULT_CORRELATION_ID_HEADER_NAME, DEFAULT_CSRF_HEADER_NAME, DEFAULT_TIMEZONE, type DataGridEventNames, type DataRecord, DateUtils, type DialogEventNames, type EventSubscription, type FeatureFlagClient, type FeatureFlagEvaluationContext, type FeatureFlagValues, FeatureFlagsProvider, type FeatureFlagsProviderProps, type FormEventNames, type FormatMoneyOptions, type GridData, mercureManager as MercureManager, type MercureManager as MercureManagerType, MercureProvider, type MercureProviderProps, type MoneyValue, type ScopedFormEventNames, StaticFeatureFlagClient, type ToolbarButtonItem, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, generateCorrelationId, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|
package/dist/index.mjs
CHANGED
|
@@ -970,7 +970,43 @@ function discoverMercureFromResponse(response, data) {
|
|
|
970
970
|
if (topicOrigin) setDiscoveredTopicOrigin(topicOrigin);
|
|
971
971
|
}
|
|
972
972
|
//#endregion
|
|
973
|
+
//#region packages/core/http/correlationId.ts
|
|
974
|
+
/**
|
|
975
|
+
* Generates a client-side correlation id for one logical HTTP request.
|
|
976
|
+
*
|
|
977
|
+
* Prefers the standard `crypto.randomUUID()`. Falls back to a timestamp +
|
|
978
|
+
* random token in environments where it is unavailable (insecure/non-HTTPS
|
|
979
|
+
* contexts, older browsers, some test runners) so requests are never blocked
|
|
980
|
+
* just because a correlation id could not be minted.
|
|
981
|
+
*
|
|
982
|
+
* Used by {@link CoreHttpClient} when `enableCorrelationId` is on. Exported
|
|
983
|
+
* so an app can pre-generate an id for a request it hasn't sent yet — for
|
|
984
|
+
* example an offline-queued mutation — and pass it back in via
|
|
985
|
+
* `CoreHttpClientConfig.getCorrelationId` (or `CoreRequestConfig.headers`)
|
|
986
|
+
* so the id logged in the offline queue matches the one the backend sees.
|
|
987
|
+
*/
|
|
988
|
+
function generateCorrelationId() {
|
|
989
|
+
const cryptoRef = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
990
|
+
if (cryptoRef && typeof cryptoRef.randomUUID === "function") return cryptoRef.randomUUID();
|
|
991
|
+
return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
992
|
+
}
|
|
993
|
+
//#endregion
|
|
973
994
|
//#region packages/core/http/CoreHttpClient.ts
|
|
995
|
+
/** Default value of {@link CoreHttpClientConfig.csrfHeaderName}. */
|
|
996
|
+
const DEFAULT_CSRF_HEADER_NAME = "X-CSRF-Token";
|
|
997
|
+
/** Default value of {@link CoreHttpClientConfig.correlationIdHeaderName}. */
|
|
998
|
+
const DEFAULT_CORRELATION_ID_HEADER_NAME = "X-Request-Id";
|
|
999
|
+
/**
|
|
1000
|
+
* HTTP methods `getCsrfToken` is consulted for. Matches the conventional
|
|
1001
|
+
* "safe methods don't need CSRF protection" rule (GET/HEAD never mutate
|
|
1002
|
+
* state), so read requests never pay the cost of a token lookup.
|
|
1003
|
+
*/
|
|
1004
|
+
const CSRF_PROTECTED_METHODS = new Set([
|
|
1005
|
+
"POST",
|
|
1006
|
+
"PUT",
|
|
1007
|
+
"PATCH",
|
|
1008
|
+
"DELETE"
|
|
1009
|
+
]);
|
|
974
1010
|
function joinUrl(baseUrl, url) {
|
|
975
1011
|
if (/^https?:\/\//.test(url) || url.startsWith("/")) return url;
|
|
976
1012
|
return `${baseUrl.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
|
|
@@ -1000,12 +1036,24 @@ function withParams(url, params) {
|
|
|
1000
1036
|
if (!query) return url;
|
|
1001
1037
|
return `${url}${url.includes("?") ? "&" : "?"}${query}`;
|
|
1002
1038
|
}
|
|
1003
|
-
function createHttpError(message, status, data) {
|
|
1039
|
+
function createHttpError(message, status, data, correlationId) {
|
|
1004
1040
|
return Object.assign(new Error(message), {
|
|
1005
1041
|
status,
|
|
1006
|
-
data
|
|
1042
|
+
data,
|
|
1043
|
+
correlationId
|
|
1007
1044
|
});
|
|
1008
1045
|
}
|
|
1046
|
+
/**
|
|
1047
|
+
* A fully-qualified `http(s)://` URL targets a different origin than the
|
|
1048
|
+
* app's own `baseUrl` (or is at least not guaranteed to be the same one —
|
|
1049
|
+
* see `joinUrl`, which passes these through unchanged). Root-relative
|
|
1050
|
+
* (`/path`) and bare relative (`path`) URLs always resolve against this
|
|
1051
|
+
* app's own origin/baseUrl, so they're the only ones eligible for the
|
|
1052
|
+
* correlation-id header.
|
|
1053
|
+
*/
|
|
1054
|
+
function isExternalUrl(url) {
|
|
1055
|
+
return /^https?:\/\//.test(url);
|
|
1056
|
+
}
|
|
1009
1057
|
async function readResponseBody(response, responseType) {
|
|
1010
1058
|
if (response.status === 204) return;
|
|
1011
1059
|
if (responseType === "arraybuffer") return await response.arrayBuffer();
|
|
@@ -1019,26 +1067,59 @@ var CoreHttpClient = class {
|
|
|
1019
1067
|
constructor(config = {}) {
|
|
1020
1068
|
this.config = config;
|
|
1021
1069
|
}
|
|
1022
|
-
|
|
1070
|
+
/**
|
|
1071
|
+
* Builds the full header set for one request: static locale, then dynamic
|
|
1072
|
+
* auth headers, then CSRF (mutating methods only), then correlation id,
|
|
1073
|
+
* then the caller's own `extraHeaders` — which always win, so a specific
|
|
1074
|
+
* call can still override anything the config-level hooks produced.
|
|
1075
|
+
*/
|
|
1076
|
+
async headers(method, extraHeaders, correlationId) {
|
|
1023
1077
|
const browserLocale = typeof navigator !== "undefined" ? navigator.language?.split("-")[0] : void 0;
|
|
1078
|
+
const locale = this.config.locale ?? browserLocale ?? "en";
|
|
1079
|
+
const authHeaders = this.config.getAuthHeaders ? await this.config.getAuthHeaders() : void 0;
|
|
1080
|
+
let csrfHeader;
|
|
1081
|
+
if (this.config.getCsrfToken && CSRF_PROTECTED_METHODS.has(method)) {
|
|
1082
|
+
const token = await this.config.getCsrfToken(method);
|
|
1083
|
+
if (token) csrfHeader = { [this.config.csrfHeaderName ?? "X-CSRF-Token"]: token };
|
|
1084
|
+
}
|
|
1085
|
+
const correlationHeader = correlationId !== void 0 ? { [this.config.correlationIdHeaderName ?? "X-Request-Id"]: correlationId } : void 0;
|
|
1024
1086
|
return {
|
|
1025
|
-
"Accept-Language":
|
|
1087
|
+
"Accept-Language": locale,
|
|
1088
|
+
...authHeaders,
|
|
1089
|
+
...csrfHeader,
|
|
1090
|
+
...correlationHeader,
|
|
1026
1091
|
...extraHeaders
|
|
1027
1092
|
};
|
|
1028
1093
|
}
|
|
1094
|
+
/** A fresh correlation id for one logical request, or undefined when disabled/not applicable. */
|
|
1095
|
+
correlationIdFor(url) {
|
|
1096
|
+
if (!this.config.enableCorrelationId || isExternalUrl(url)) return void 0;
|
|
1097
|
+
return (this.config.getCorrelationId ?? generateCorrelationId)();
|
|
1098
|
+
}
|
|
1029
1099
|
/**
|
|
1030
1100
|
* Built-in cookie-based refresh (the original behavior).
|
|
1031
1101
|
* Only used when `refreshFn` is not provided in config.
|
|
1102
|
+
*
|
|
1103
|
+
* Carries the same auth/CSRF headers as an ordinary request — a
|
|
1104
|
+
* CSRF-protected backend protects its refresh endpoint too — and its own
|
|
1105
|
+
* correlation id, minted fresh rather than borrowed from whichever
|
|
1106
|
+
* request(s) triggered it, since one shared refresh can be triggered by
|
|
1107
|
+
* several concurrent requests at once (see the dedup logic below) and
|
|
1108
|
+
* there is no single "right" id to inherit from among them.
|
|
1032
1109
|
*/
|
|
1033
1110
|
async performBuiltInRefresh() {
|
|
1034
1111
|
const refreshPath = this.config.refreshPath ?? "auth/refresh";
|
|
1035
1112
|
const refreshUrl = joinUrl(this.config.baseUrl ?? "/api/", refreshPath);
|
|
1036
|
-
this.refreshPromise ??=
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1113
|
+
this.refreshPromise ??= (async () => {
|
|
1114
|
+
const correlationId = this.correlationIdFor(refreshPath);
|
|
1115
|
+
const headers = await this.headers("POST", void 0, correlationId);
|
|
1116
|
+
const response = await globalThis.fetch(refreshUrl, {
|
|
1117
|
+
method: "POST",
|
|
1118
|
+
headers,
|
|
1119
|
+
credentials: this.config.credentials ?? "include"
|
|
1120
|
+
});
|
|
1121
|
+
if (!response.ok) throw createHttpError("Session refresh failed", response.status, await this.safeErrorData(response), correlationId);
|
|
1122
|
+
})().finally(() => {
|
|
1042
1123
|
this.refreshPromise = null;
|
|
1043
1124
|
});
|
|
1044
1125
|
return this.refreshPromise;
|
|
@@ -1054,9 +1135,10 @@ var CoreHttpClient = class {
|
|
|
1054
1135
|
return {};
|
|
1055
1136
|
}
|
|
1056
1137
|
}
|
|
1057
|
-
async request(method, url, body, config, retryOnUnauthorized = true) {
|
|
1138
|
+
async request(method, url, body, config, retryOnUnauthorized = true, inheritedCorrelationId) {
|
|
1058
1139
|
const requestUrl = withParams(joinUrl(this.config.baseUrl ?? "/api/", url), config?.params);
|
|
1059
|
-
const
|
|
1140
|
+
const correlationId = inheritedCorrelationId ?? this.correlationIdFor(url);
|
|
1141
|
+
const headers = await this.headers(method, config?.headers, correlationId);
|
|
1060
1142
|
if (body !== void 0 && body !== null && !(body instanceof FormData)) headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
|
|
1061
1143
|
const response = await globalThis.fetch(requestUrl, {
|
|
1062
1144
|
method,
|
|
@@ -1072,20 +1154,24 @@ var CoreHttpClient = class {
|
|
|
1072
1154
|
response,
|
|
1073
1155
|
data,
|
|
1074
1156
|
headers: response.headers,
|
|
1075
|
-
status: response.status
|
|
1157
|
+
status: response.status,
|
|
1158
|
+
correlationId
|
|
1076
1159
|
};
|
|
1077
1160
|
}
|
|
1078
1161
|
const errorData = await this.safeErrorData(response);
|
|
1079
|
-
const error = createHttpError(errorData.detail ?? errorData.message ?? "HTTP request failed", response.status, errorData);
|
|
1162
|
+
const error = createHttpError(errorData.detail ?? errorData.message ?? "HTTP request failed", response.status, errorData, correlationId);
|
|
1080
1163
|
const loginPath = this.config.loginPath ?? "auth/login";
|
|
1081
1164
|
const refreshPath = this.config.refreshPath ?? "auth/refresh";
|
|
1082
1165
|
const isAuthEndpoint = url.includes(loginPath) || url.includes(refreshPath);
|
|
1083
1166
|
const shouldAutoRefresh = this.config.autoRefresh !== false;
|
|
1084
1167
|
if (response.status === 401 && retryOnUnauthorized && !isAuthEndpoint && shouldAutoRefresh) try {
|
|
1085
1168
|
await this.performRefresh();
|
|
1086
|
-
return this.request(method, url, body, config, false);
|
|
1169
|
+
return this.request(method, url, body, config, false, correlationId);
|
|
1087
1170
|
} catch (refreshError) {
|
|
1088
|
-
const unauthorizedError = refreshError instanceof Error ? Object.assign(refreshError, {
|
|
1171
|
+
const unauthorizedError = refreshError instanceof Error ? Object.assign(refreshError, {
|
|
1172
|
+
status: 401,
|
|
1173
|
+
correlationId
|
|
1174
|
+
}) : error;
|
|
1089
1175
|
this.config.onUnauthorized?.(unauthorizedError);
|
|
1090
1176
|
throw unauthorizedError;
|
|
1091
1177
|
}
|
|
@@ -1405,4 +1491,4 @@ function useMercureSubscription(apiUrl, onUpdate, enabled = true) {
|
|
|
1405
1491
|
]);
|
|
1406
1492
|
}
|
|
1407
1493
|
//#endregion
|
|
1408
|
-
export { CoreConfigProvider, CoreHttpClient, CoreHttpProvider, CoreProvider, CoreRuntimeProvider, DEFAULT_TIMEZONE, DateUtils, FeatureFlagsProvider, mercureManager as MercureManager, MercureProvider, StaticFeatureFlagClient, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|
|
1494
|
+
export { CoreConfigProvider, CoreHttpClient, CoreHttpProvider, CoreProvider, CoreRuntimeProvider, DEFAULT_CORRELATION_ID_HEADER_NAME, DEFAULT_CSRF_HEADER_NAME, DEFAULT_TIMEZONE, DateUtils, FeatureFlagsProvider, mercureManager as MercureManager, MercureProvider, StaticFeatureFlagClient, buildMercureCollectionTopic, configureCore, configureCoreDate, coreTranslationsEn, coreTranslationsEs, createCoreHttpClient, createCrudEvents, createScopedEventBus, discoverMercureFromResponse, dispatch, extractMercureHubUrl, extractTopicOriginFromPayload, formatMinorUnits, formatMoney, fromMinorUnits, generateCorrelationId, getCoreApiBaseUrl, getCoreCurrency, getCoreLocale, getCoreTimezone, getDiscoveredMercureTopicOrigin, getMercureTopicOrigin, initCoreI18n, isMoneyValue, parseLinkHeader, parseMoney, parseMoneyInput, resolveMercureTopicOrigin, sumMoney, toMinorUnits, useBooleanFlag, useCoreConfig, useCoreHttpClient, useCoreRuntime, useCoreTranslation, useDiscoveredMercureTopicOrigin, useEvents, useFeatureFlags, useMercureHub, useMercureSubscription, useNumberFlag, useObjectFlag, useStringFlag };
|