tempest-react-sdk 0.67.0 → 0.68.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 +97 -93
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +41 -40
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/components/BottomSheet/BottomSheet.cjs +1 -1
- package/dist/components/BottomSheet/BottomSheet.cjs.map +1 -1
- package/dist/components/BottomSheet/BottomSheet.js +34 -30
- package/dist/components/BottomSheet/BottomSheet.js.map +1 -1
- package/dist/components/Card/Card.module.cjs.map +1 -1
- package/dist/components/Card/Card.module.js.map +1 -1
- package/dist/components/Combobox/Combobox.cjs +1 -1
- package/dist/components/Combobox/Combobox.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.js +78 -77
- package/dist/components/Combobox/Combobox.js.map +1 -1
- package/dist/components/Combobox/Combobox.module.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.module.js.map +1 -1
- package/dist/components/Command/Command.cjs +1 -1
- package/dist/components/Command/Command.js +4 -4
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +138 -127
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.js +5 -3
- package/dist/components/DataTable/use-dev-warnings.js.map +1 -1
- package/dist/components/Drawer/Drawer.cjs +1 -1
- package/dist/components/Drawer/Drawer.cjs.map +1 -1
- package/dist/components/Drawer/Drawer.js +43 -40
- package/dist/components/Drawer/Drawer.js.map +1 -1
- package/dist/components/FilterPanel/FilterPanel.cjs +2 -0
- package/dist/components/FilterPanel/FilterPanel.cjs.map +1 -0
- package/dist/components/FilterPanel/FilterPanel.js +75 -0
- package/dist/components/FilterPanel/FilterPanel.js.map +1 -0
- package/dist/components/FilterPanel/FilterPanel.module.cjs +3 -0
- package/dist/components/FilterPanel/FilterPanel.module.cjs.map +1 -0
- package/dist/components/FilterPanel/FilterPanel.module.js +12 -0
- package/dist/components/FilterPanel/FilterPanel.module.js.map +1 -0
- package/dist/components/Lightbox/Lightbox.cjs +1 -1
- package/dist/components/Lightbox/Lightbox.js +5 -5
- package/dist/components/Modal/Modal.cjs +1 -1
- package/dist/components/Modal/Modal.cjs.map +1 -1
- package/dist/components/Modal/Modal.js +44 -41
- package/dist/components/Modal/Modal.js.map +1 -1
- package/dist/components/Pagination/Pagination.cjs +1 -1
- package/dist/components/Pagination/Pagination.cjs.map +1 -1
- package/dist/components/Pagination/Pagination.js +31 -30
- package/dist/components/Pagination/Pagination.js.map +1 -1
- package/dist/components/Portal/tab-bridge.cjs +1 -1
- package/dist/components/Portal/tab-bridge.cjs.map +1 -1
- package/dist/components/Portal/tab-bridge.js +21 -23
- package/dist/components/Portal/tab-bridge.js.map +1 -1
- package/dist/components/Select/CaretIcon.cjs +2 -0
- package/dist/components/Select/CaretIcon.cjs.map +1 -0
- package/dist/components/Select/CaretIcon.js +21 -0
- package/dist/components/Select/CaretIcon.js.map +1 -0
- package/dist/components/Select/Select.cjs +1 -1
- package/dist/components/Select/Select.cjs.map +1 -1
- package/dist/components/Select/Select.js +33 -47
- package/dist/components/Select/Select.js.map +1 -1
- package/dist/components/Select/Select.module.cjs +1 -1
- package/dist/components/Select/Select.module.cjs.map +1 -1
- package/dist/components/Select/Select.module.js +4 -3
- package/dist/components/Select/Select.module.js.map +1 -1
- package/dist/components/Select/options.cjs +2 -0
- package/dist/components/Select/options.cjs.map +1 -0
- package/dist/components/Select/options.js +25 -0
- package/dist/components/Select/options.js.map +1 -0
- package/dist/components/Sidebar/Sidebar.cjs +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js +49 -43
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/active-nav-key.cjs +2 -0
- package/dist/components/Sidebar/active-nav-key.cjs.map +1 -0
- package/dist/components/Sidebar/active-nav-key.js +22 -0
- package/dist/components/Sidebar/active-nav-key.js.map +1 -0
- package/dist/hooks/tab-sequence.cjs +2 -0
- package/dist/hooks/tab-sequence.cjs.map +1 -0
- package/dist/hooks/tab-sequence.js +53 -0
- package/dist/hooks/tab-sequence.js.map +1 -0
- package/dist/hooks/use-deep-memo.cjs +1 -1
- package/dist/hooks/use-deep-memo.cjs.map +1 -1
- package/dist/hooks/use-deep-memo.js +1 -1
- package/dist/hooks/use-deep-memo.js.map +1 -1
- package/dist/hooks/use-draft-filters.cjs +2 -0
- package/dist/hooks/use-draft-filters.cjs.map +1 -0
- package/dist/hooks/use-draft-filters.js +49 -0
- package/dist/hooks/use-draft-filters.js.map +1 -0
- package/dist/hooks/use-focus-trap.cjs +1 -1
- package/dist/hooks/use-focus-trap.cjs.map +1 -1
- package/dist/hooks/use-focus-trap.js +31 -34
- package/dist/hooks/use-focus-trap.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +92 -80
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/credential-scope.cjs +1 -1
- package/dist/http/credential-scope.cjs.map +1 -1
- package/dist/http/credential-scope.js +5 -3
- package/dist/http/credential-scope.js.map +1 -1
- package/dist/http/csrf.cjs +2 -0
- package/dist/http/csrf.cjs.map +1 -0
- package/dist/http/csrf.js +46 -0
- package/dist/http/csrf.js.map +1 -0
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +131 -123
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js +41 -33
- package/dist/http/upload-with-progress.js.map +1 -1
- package/dist/query/use-paginated-query.cjs +1 -1
- package/dist/query/use-paginated-query.cjs.map +1 -1
- package/dist/query/use-paginated-query.js +47 -30
- package/dist/query/use-paginated-query.js.map +1 -1
- package/dist/styles/FilterPanel.css +2 -0
- package/dist/styles/component/Card.css +1 -1
- package/dist/styles/component/Combobox.css +4 -3
- package/dist/styles/component/FilterPanel.css +5 -0
- package/dist/styles/component/Select.css +13 -6
- package/dist/styles/core.css +4 -4
- package/dist/styles/data.css +4 -0
- package/dist/styles/forms.css +17 -9
- package/dist/styles/identity.css +1 -1
- package/dist/styles/manifest.json +6 -0
- package/dist/styles/tokens.css +4 -4
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +658 -22
- package/dist/tempest-react-sdk.js +347 -342
- package/dist/vite/tempest-csp.cjs +3 -0
- package/dist/vite/tempest-csp.cjs.map +1 -0
- package/dist/vite/tempest-csp.js +189 -0
- package/dist/vite/tempest-csp.js.map +1 -0
- package/dist/vite.cjs +1 -1
- package/dist/vite.d.ts +145 -0
- package/dist/vite.js +2 -1
- package/package.json +2 -2
- package/template/vite.config.ts +8 -1
- package/template-pwa/vite.config.ts +6 -0
package/dist/http/api-client.js
CHANGED
|
@@ -1,30 +1,31 @@
|
|
|
1
1
|
import { randomId as e } from "../utils/ids.js";
|
|
2
2
|
import { buildApiUrl as t } from "./build-url.js";
|
|
3
3
|
import { isTrustedCredentialTarget as n, reportSuppressedCredential as r } from "./credential-scope.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
4
|
+
import { csrfHeaders as i } from "./csrf.js";
|
|
5
|
+
import { decodeByContentType as a } from "./decode-response.js";
|
|
6
|
+
import { TempestApiError as o, buildApiError as s, isRetriableStatus as c } from "./errors.js";
|
|
7
|
+
import { retry as l } from "./retry.js";
|
|
8
|
+
import { withTimeout as u } from "./timeout.js";
|
|
8
9
|
//#region src/http/api-client.ts
|
|
9
|
-
var
|
|
10
|
+
var d = /* @__PURE__ */ new Set([
|
|
10
11
|
"GET",
|
|
11
12
|
"HEAD",
|
|
12
13
|
"OPTIONS"
|
|
13
14
|
]);
|
|
14
|
-
function
|
|
15
|
-
return !
|
|
15
|
+
function f(e, t) {
|
|
16
|
+
return !d.has(t) || !(e instanceof o) ? !1 : c(e.status);
|
|
16
17
|
}
|
|
17
|
-
function
|
|
18
|
+
function p(e) {
|
|
18
19
|
return e ? e === !0 ? {} : e : null;
|
|
19
20
|
}
|
|
20
|
-
var
|
|
21
|
-
function
|
|
21
|
+
var m = 15e3, h = 3e5;
|
|
22
|
+
function g(e) {
|
|
22
23
|
return typeof FormData < "u" && e instanceof FormData;
|
|
23
24
|
}
|
|
24
|
-
function
|
|
25
|
+
function _(e) {
|
|
25
26
|
return Math.round(performance.now() - e);
|
|
26
27
|
}
|
|
27
|
-
async function
|
|
28
|
+
async function v(e, t) {
|
|
28
29
|
let n;
|
|
29
30
|
try {
|
|
30
31
|
n = await e.clone().json();
|
|
@@ -35,72 +36,83 @@ async function _(e, t) {
|
|
|
35
36
|
n = null;
|
|
36
37
|
}
|
|
37
38
|
}
|
|
38
|
-
return new
|
|
39
|
+
return new o(s(e.status, n, e.headers, t));
|
|
39
40
|
}
|
|
40
|
-
function
|
|
41
|
-
let
|
|
42
|
-
function
|
|
41
|
+
function y(s) {
|
|
42
|
+
let c = s.fetcher ?? globalThis.fetch.bind(globalThis);
|
|
43
|
+
function d(e, t) {
|
|
43
44
|
if (t) return {};
|
|
44
|
-
let i =
|
|
45
|
-
return i ? n(e,
|
|
45
|
+
let i = s.getToken?.();
|
|
46
|
+
return i ? n(e, s.baseURL, s.trustedOrigins) ? { Authorization: `Bearer ${i}` } : (r(e, s.baseURL), {}) : {};
|
|
46
47
|
}
|
|
47
|
-
async function
|
|
48
|
-
let { body:
|
|
49
|
-
prefix:
|
|
50
|
-
params:
|
|
51
|
-
}),
|
|
52
|
-
...
|
|
48
|
+
async function y(e, n, r, a) {
|
|
49
|
+
let { body: l, params: f, headers: p, signal: _, timeout: v, ...y } = n, b = g(l), x = b ? s.uploadTimeout : s.timeout, S = v === void 0 ? x === void 0 ? b ? h : m : x : v, C = t(s.baseURL, e, {
|
|
50
|
+
prefix: s.prefix,
|
|
51
|
+
params: f
|
|
52
|
+
}), w = p, T = {
|
|
53
|
+
...b ? {} : { "Content-Type": "application/json" },
|
|
53
54
|
...r ? { "X-Request-ID": r } : {},
|
|
54
|
-
...
|
|
55
|
-
...
|
|
56
|
-
...
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
55
|
+
...s.headers,
|
|
56
|
+
...d(C, a),
|
|
57
|
+
...i({
|
|
58
|
+
method: y.method ?? "GET",
|
|
59
|
+
url: C,
|
|
60
|
+
reference: s.baseURL,
|
|
61
|
+
csrf: s.csrf,
|
|
62
|
+
trustedOrigins: s.trustedOrigins,
|
|
63
|
+
headers: {
|
|
64
|
+
...s.headers,
|
|
65
|
+
...w
|
|
66
|
+
}
|
|
67
|
+
}),
|
|
68
|
+
...w
|
|
69
|
+
}, E = u(_, S), D = {
|
|
70
|
+
...y,
|
|
71
|
+
signal: E.signal,
|
|
72
|
+
headers: T,
|
|
73
|
+
credentials: s.withCredentials ? "include" : y.credentials,
|
|
74
|
+
body: l == null ? void 0 : b ? l : JSON.stringify(l)
|
|
63
75
|
};
|
|
64
76
|
try {
|
|
65
|
-
return await
|
|
77
|
+
return await c(C, D);
|
|
66
78
|
} catch (e) {
|
|
67
|
-
throw
|
|
79
|
+
throw E.timedOut() ? new o({
|
|
68
80
|
status: 0,
|
|
69
|
-
detail: `A requisição excedeu ${
|
|
81
|
+
detail: `A requisição excedeu ${S}ms e foi abandonada.`
|
|
70
82
|
}) : e;
|
|
71
83
|
} finally {
|
|
72
|
-
|
|
84
|
+
E.dispose();
|
|
73
85
|
}
|
|
74
86
|
}
|
|
75
|
-
async function
|
|
76
|
-
let a =
|
|
77
|
-
if (!a) return
|
|
78
|
-
let
|
|
87
|
+
async function b(e, t, n, r, i) {
|
|
88
|
+
let a = s.logger;
|
|
89
|
+
if (!a) return y(e, t, n, i);
|
|
90
|
+
let o = performance.now();
|
|
79
91
|
try {
|
|
80
|
-
let
|
|
92
|
+
let s = await y(e, t, n, i), c = {
|
|
81
93
|
requestId: n,
|
|
82
|
-
status:
|
|
83
|
-
ms:
|
|
84
|
-
}, l = `${r} ${e} → ${
|
|
85
|
-
return
|
|
94
|
+
status: s.status,
|
|
95
|
+
ms: _(o)
|
|
96
|
+
}, l = `${r} ${e} → ${s.status}`;
|
|
97
|
+
return s.status >= 400 ? a.warn(l, c) : a.debug(l, c), s;
|
|
86
98
|
} catch (t) {
|
|
87
99
|
throw a.warn(`${r} ${e} → no response`, {
|
|
88
100
|
requestId: n,
|
|
89
|
-
ms:
|
|
101
|
+
ms: _(o),
|
|
90
102
|
error: t
|
|
91
103
|
}), t;
|
|
92
104
|
}
|
|
93
105
|
}
|
|
94
|
-
async function
|
|
95
|
-
if (
|
|
96
|
-
|
|
106
|
+
async function x(e, t) {
|
|
107
|
+
if (s.onUnauthorized) {
|
|
108
|
+
s.logger?.warn("unauthorized — calling onUnauthorized", {
|
|
97
109
|
requestId: t,
|
|
98
110
|
status: e.status
|
|
99
111
|
});
|
|
100
112
|
try {
|
|
101
|
-
await
|
|
113
|
+
await s.onUnauthorized(e);
|
|
102
114
|
} catch (n) {
|
|
103
|
-
|
|
115
|
+
s.logger?.warn("onUnauthorized threw — keeping the original response error", {
|
|
104
116
|
requestId: t,
|
|
105
117
|
status: e.status,
|
|
106
118
|
error: n
|
|
@@ -108,68 +120,68 @@ function v(o) {
|
|
|
108
120
|
}
|
|
109
121
|
}
|
|
110
122
|
}
|
|
111
|
-
async function
|
|
112
|
-
let { skipAuth: i = !1, skipAuthRetry: a = !1, ...
|
|
123
|
+
async function S(t, n, r) {
|
|
124
|
+
let { skipAuth: i = !1, skipAuthRetry: a = !1, ...o } = n, c = s.requestId ? s.requestId() : e(), l = (o.method ?? "GET").toUpperCase(), u = await b(t, o, c, l, i);
|
|
113
125
|
if (u.status === 401 && !i && !a) {
|
|
114
|
-
if (
|
|
126
|
+
if (s.refresh) {
|
|
115
127
|
try {
|
|
116
|
-
await
|
|
128
|
+
await s.refresh(), u = await b(t, o, c, l, i);
|
|
117
129
|
} catch {
|
|
118
|
-
throw await
|
|
130
|
+
throw await x(u, c), await v(u, c);
|
|
119
131
|
}
|
|
120
|
-
u.status === 401 && await
|
|
121
|
-
} else await
|
|
132
|
+
u.status === 401 && await x(u, c);
|
|
133
|
+
} else await x(u, c);
|
|
122
134
|
}
|
|
123
|
-
if (!u.ok) throw await
|
|
135
|
+
if (!u.ok) throw await v(u, c);
|
|
124
136
|
return r(u);
|
|
125
137
|
}
|
|
126
|
-
async function
|
|
127
|
-
let { retry: r, ...i } = t, a =
|
|
128
|
-
if (!a) return
|
|
129
|
-
let
|
|
130
|
-
return
|
|
138
|
+
async function C(e, t, n) {
|
|
139
|
+
let { retry: r, ...i } = t, a = p(r === void 0 ? s.retry : r);
|
|
140
|
+
if (!a) return S(e, i, n);
|
|
141
|
+
let o = (i.method ?? "GET").toUpperCase();
|
|
142
|
+
return l(() => S(e, i, n), {
|
|
131
143
|
...a,
|
|
132
|
-
shouldRetry: a.shouldRetry ?? ((e) =>
|
|
144
|
+
shouldRetry: a.shouldRetry ?? ((e) => f(e, o))
|
|
133
145
|
});
|
|
134
146
|
}
|
|
135
|
-
async function
|
|
136
|
-
return
|
|
147
|
+
async function w(e, t = {}) {
|
|
148
|
+
return C(e, t, a);
|
|
137
149
|
}
|
|
138
|
-
async function
|
|
139
|
-
return
|
|
150
|
+
async function T(e, t, n = "POST", r) {
|
|
151
|
+
return w(e, {
|
|
140
152
|
...r,
|
|
141
153
|
method: n,
|
|
142
154
|
body: t
|
|
143
155
|
});
|
|
144
156
|
}
|
|
145
157
|
return {
|
|
146
|
-
request:
|
|
147
|
-
get: (e, t) =>
|
|
158
|
+
request: w,
|
|
159
|
+
get: (e, t) => w(e, {
|
|
148
160
|
...t,
|
|
149
161
|
method: "GET"
|
|
150
162
|
}),
|
|
151
|
-
post: (e, t) =>
|
|
163
|
+
post: (e, t) => w(e, {
|
|
152
164
|
...t,
|
|
153
165
|
method: "POST"
|
|
154
166
|
}),
|
|
155
|
-
put: (e, t) =>
|
|
167
|
+
put: (e, t) => w(e, {
|
|
156
168
|
...t,
|
|
157
169
|
method: "PUT"
|
|
158
170
|
}),
|
|
159
|
-
patch: (e, t) =>
|
|
171
|
+
patch: (e, t) => w(e, {
|
|
160
172
|
...t,
|
|
161
173
|
method: "PATCH"
|
|
162
174
|
}),
|
|
163
|
-
delete: (e, t) =>
|
|
175
|
+
delete: (e, t) => w(e, {
|
|
164
176
|
...t,
|
|
165
177
|
method: "DELETE"
|
|
166
178
|
}),
|
|
167
|
-
blob: (e, t) =>
|
|
168
|
-
arrayBuffer: (e, t) =>
|
|
169
|
-
upload:
|
|
179
|
+
blob: (e, t) => C(e, { ...t }, (e) => e.blob()),
|
|
180
|
+
arrayBuffer: (e, t) => C(e, { ...t }, (e) => e.arrayBuffer()),
|
|
181
|
+
upload: T
|
|
170
182
|
};
|
|
171
183
|
}
|
|
172
184
|
//#endregion
|
|
173
|
-
export {
|
|
185
|
+
export { y as createApiClient };
|
|
174
186
|
|
|
175
187
|
//# sourceMappingURL=api-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...(headers as Record<string, string> | undefined),\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, init, requestId, method, skipAuth);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions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,CAAyB;EACtF,IAAI,CAAC,GAAc,OAAO,EAAW,GAAM,GAAM,CAAM;EAEvD,IAAM,KAAU,EAAK,UAAU,MAAA,CAAO,YAAY;EAClD,OAAO,QAAuB,EAAW,GAAM,GAAM,CAAM,GAAG;GAC1D,GAAG;GACH,aACI,EAAa,iBAAiB,MAAmB,EAAmB,GAAO,CAAM;EACzF,CAAC;CACL;CAEA,eAAe,EAAW,GAAc,IAA0B,CAAC,GAAe;EAC9E,OAAO,EAAO,GAAM,GAAS,CAAmB;CACpD;CAEA,eAAe,EACX,GACA,GACA,IAAmC,QACnC,GACU;EACV,OAAO,EAAW,GAAM;GAAE,GAAG;GAAS;GAAQ,MAAM;EAAS,CAAC;CAClE;CAEA,OAAO;EACH;EACA,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,OAAU,GAAc,MACpB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjB,EAAU,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxB,EAAiB,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,YAAY,CAAC;EAC/E;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **CSRF** is off unless you set `csrf`. With it, every unsafe request (anything\n * but `GET`/`HEAD`/`OPTIONS`/`TRACE`) echoes the `csrf_token` cookie in an\n * `X-CSRF-Token` header — the double-submit contract of `tempest-fastapi-sdk`'s\n * `CSRFMiddleware` — scoped to the same origins as the bearer token and sent on\n * `skipAuth` requests too. See {@link ApiClientConfig.csrf}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const callerHeaders = headers as Record<string, string> | undefined;\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...csrfHeaders({\n method: rest.method ?? \"GET\",\n url,\n reference: config.baseURL,\n csrf: config.csrf,\n trustedOrigins: config.trustedOrigins,\n headers: { ...config.headers, ...callerHeaders },\n }),\n ...callerHeaders,\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, init, requestId, method, skipAuth);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions) =>\n run<ArrayBuffer>(path, { ...options }, (response) => response.arrayBuffer()),\n upload,\n };\n}\n"],"mappings":";;;;;;;;;AAyBA,IAAM,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAkB,EAAM,MAAM;AACzC;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAGA,IAAM,IAAkB,MAGlB,IAAyB;AAE/B,SAAS,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAe,aAAgB;AAC9D;AAaA,SAAS,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAI,CAAS;AACnD;AAEA,eAAe,EAAW,GAAoB,GAAkD;CAC5F,IAAI;CACJ,IAAI;EACA,IAAO,MAAM,EAAS,MAAM,CAAC,CAAC,KAAK;CACvC,QAAQ;EACJ,IAAI;GACA,IAAO,MAAM,EAAS,KAAK;EA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CAAC;EAClD,OAAU,GAAc,MACpB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjB,EAAU,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxB,EAAiB,GAAM,EAAE,GAAG,EAAQ,IAAI,MAAa,EAAS,YAAY,CAAC;EAC/E;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/dev-mode.cjs");var t=new Set;function n(e){try{return new URL(e,globalThis.location?.href).origin}catch{return null}}function r(e,t,r=[]){let i=n(e);return i===null||i===n(t)||r.some(e=>n(e)===i)}function i(r,i){if(!e.isDevBuild())return;let
|
|
1
|
+
const e=require("../utils/dev-mode.cjs");var t=new Set;function n(e){try{return new URL(e,globalThis.location?.href).origin}catch{return null}}function r(e,t,r=[]){let i=n(e);return i===null||i===n(t)||r.some(e=>n(e)===i)}function i(r,i,a=`Authorization`){if(!e.isDevBuild())return;let o=n(r);if(o===null)return;let s=`${a} ${o}`;t.has(s)||(t.add(s),console.warn(`[tempest-react-sdk] ${a} was not sent to ${o}: the credential is scoped to ${n(i)??i}. Add the origin to trustedOrigins if it should receive the token.`))}exports.isTrustedCredentialTarget=r,exports.reportSuppressedCredential=i;
|
|
2
2
|
//# sourceMappingURL=credential-scope.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-scope.cjs","names":[],"sources":["../../src/http/credential-scope.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Origins already reported by {@link reportSuppressedCredential}, so a chunked\n * upload warns once instead of once per chunk.\n */\nconst reported = new Set<string>();\n\n/**\n * The origin a URL resolves to, or `null` when it has none to compare.\n *\n * Relative values resolve against the document, because that is what they mean\n * everywhere else in the SDK: an `endpoint` of `\"/api/uploads\"` and a `baseURL`\n * of `\"/api\"` are the shape you get behind a dev-server or a reverse proxy, and\n * both name the page's own origin. Comparing a resolved absolute target against\n * an unresolved relative reference is how the first draft of this function\n * withheld the credential from every client configured that way.\n *\n * `null` is reserved for the case with genuinely nothing to compare: a relative\n * URL outside a browsing context, where there is no document to resolve against.\n *\n * @param url - Absolute or relative URL.\n * @returns The origin, or `null` when it cannot be resolved.\n */\nfunction originOf(url: string): string | null {\n try {\n return new URL(url, globalThis.location?.href).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Whether a request to `target` may carry the caller's credential.\n *\n * The SDK writes `Authorization: Bearer` in three places, and until 0.66.0 none\n * of them looked at where the request was going. That is only safe while every\n * target URL is written by the app: a resumable upload takes its URL from the\n * server's `Location` header, and `createApiClient` lets an absolute path\n * override `baseURL` entirely, so a URL arriving over the network could decide\n * which origin received the token — and the file bytes with it.\n *\n * Handing an upload off to object storage on another host is ordinary `tus`\n * deployment, not an attack, which is exactly why the credential must be scoped\n * rather than the request blocked: the upload still goes through, it just goes\n * without the API's bearer token.\n *\n * Both sides are resolved against the document first, so a relative `baseURL`\n * or `endpoint` — the shape behind a dev-server or reverse proxy — compares\n * equal to the absolute URL the request actually goes to. Outside a browsing\n * context a relative target resolves to nothing and is allowed: there is no\n * origin for it to cross.\n *\n * @param target - The URL the request is about to go to.\n * @param reference - The origin the credential belongs to, normally the\n * client's `baseURL` or the upload `endpoint`.\n * @param trustedOrigins - Extra origins the app declared, for the legitimate\n * second host: a CDN, a signed upload endpoint.\n * @returns Whether the credential may be attached.\n *\n * @example\n * isTrustedCredentialTarget(\"https://api.acme.com/me\", \"https://api.acme.com\");\n * // true\n * isTrustedCredentialTarget(\"https://cdn.other/u/1\", \"https://api.acme.com\");\n * // false\n */\nexport function isTrustedCredentialTarget(\n target: string,\n reference: string,\n trustedOrigins: readonly string[] = [],\n): boolean {\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return true;\n if (targetOrigin === originOf(reference)) return true;\n return trustedOrigins.some((origin) => originOf(origin) === targetOrigin);\n}\n\n/**\n * Say once, in a development build, that a credential was withheld.\n *\n * Without it the symptom is a `401` from a host the developer never typed, and
|
|
1
|
+
{"version":3,"file":"credential-scope.cjs","names":[],"sources":["../../src/http/credential-scope.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Origins already reported by {@link reportSuppressedCredential}, so a chunked\n * upload warns once instead of once per chunk.\n */\nconst reported = new Set<string>();\n\n/**\n * The origin a URL resolves to, or `null` when it has none to compare.\n *\n * Relative values resolve against the document, because that is what they mean\n * everywhere else in the SDK: an `endpoint` of `\"/api/uploads\"` and a `baseURL`\n * of `\"/api\"` are the shape you get behind a dev-server or a reverse proxy, and\n * both name the page's own origin. Comparing a resolved absolute target against\n * an unresolved relative reference is how the first draft of this function\n * withheld the credential from every client configured that way.\n *\n * `null` is reserved for the case with genuinely nothing to compare: a relative\n * URL outside a browsing context, where there is no document to resolve against.\n *\n * @param url - Absolute or relative URL.\n * @returns The origin, or `null` when it cannot be resolved.\n */\nfunction originOf(url: string): string | null {\n try {\n return new URL(url, globalThis.location?.href).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Whether a request to `target` may carry the caller's credential.\n *\n * The SDK writes `Authorization: Bearer` in three places, and until 0.66.0 none\n * of them looked at where the request was going. That is only safe while every\n * target URL is written by the app: a resumable upload takes its URL from the\n * server's `Location` header, and `createApiClient` lets an absolute path\n * override `baseURL` entirely, so a URL arriving over the network could decide\n * which origin received the token — and the file bytes with it.\n *\n * Handing an upload off to object storage on another host is ordinary `tus`\n * deployment, not an attack, which is exactly why the credential must be scoped\n * rather than the request blocked: the upload still goes through, it just goes\n * without the API's bearer token.\n *\n * Both sides are resolved against the document first, so a relative `baseURL`\n * or `endpoint` — the shape behind a dev-server or reverse proxy — compares\n * equal to the absolute URL the request actually goes to. Outside a browsing\n * context a relative target resolves to nothing and is allowed: there is no\n * origin for it to cross.\n *\n * @param target - The URL the request is about to go to.\n * @param reference - The origin the credential belongs to, normally the\n * client's `baseURL` or the upload `endpoint`.\n * @param trustedOrigins - Extra origins the app declared, for the legitimate\n * second host: a CDN, a signed upload endpoint.\n * @returns Whether the credential may be attached.\n *\n * @example\n * isTrustedCredentialTarget(\"https://api.acme.com/me\", \"https://api.acme.com\");\n * // true\n * isTrustedCredentialTarget(\"https://cdn.other/u/1\", \"https://api.acme.com\");\n * // false\n */\nexport function isTrustedCredentialTarget(\n target: string,\n reference: string,\n trustedOrigins: readonly string[] = [],\n): boolean {\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return true;\n if (targetOrigin === originOf(reference)) return true;\n return trustedOrigins.some((origin) => originOf(origin) === targetOrigin);\n}\n\n/**\n * Say once, in a development build, that a credential was withheld.\n *\n * Without it the symptom is a `401` (or, for the CSRF header, a `403`) from a\n * host the developer never typed, and nothing in the app's code mentions the\n * origin that produced it. Keyed by credential and target origin, so a\n * hundred-chunk upload reports one line per header it withheld.\n *\n * Silent in production for the same reason {@link parseResponse} is: the origin\n * an app talks to is not something to print into a user's console or ship to an\n * error tracker.\n *\n * @param target - The URL whose request went out unauthenticated.\n * @param reference - The origin the credential was scoped to.\n * @param header - The header that was withheld. Default `\"Authorization\"`.\n */\nexport function reportSuppressedCredential(\n target: string,\n reference: string,\n header = \"Authorization\",\n): void {\n if (!isDevBuild()) return;\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return;\n const key = `${header} ${targetOrigin}`;\n if (reported.has(key)) return;\n reported.add(key);\n console.warn(\n `[tempest-react-sdk] ${header} was not sent to ${targetOrigin}: the credential is scoped to ${originOf(reference) ?? reference}. Add the origin to trustedOrigins if it should receive the token.`,\n );\n}\n\n/**\n * Forget which origins were already reported.\n *\n * Exported for tests, which assert the once-per-origin behaviour and would\n * otherwise leak state between cases.\n */\nexport function resetSuppressedCredentialReports(): void {\n reported.clear();\n}\n"],"mappings":"yCAMA,IAAM,EAAW,IAAI,IAkBrB,SAAS,EAAS,EAA4B,CAC1C,GAAI,CACA,OAAO,IAAI,IAAI,EAAK,WAAW,UAAU,IAAI,CAAC,CAAC,MACnD,MAAQ,CACJ,OAAO,IACX,CACJ,CAoCA,SAAgB,EACZ,EACA,EACA,EAAoC,CAAC,EAC9B,CACP,IAAM,EAAe,EAAS,CAAM,EAGpC,OAFI,IAAiB,MACjB,IAAiB,EAAS,CAAS,GAChC,EAAe,KAAM,GAAW,EAAS,CAAM,IAAM,CAAY,CAC5E,CAkBA,SAAgB,EACZ,EACA,EACA,EAAS,gBACL,CACJ,GAAI,CAAC,EAAA,WAAW,EAAG,OACnB,IAAM,EAAe,EAAS,CAAM,EACpC,GAAI,IAAiB,KAAM,OAC3B,IAAM,EAAM,GAAG,EAAO,GAAG,IACrB,EAAS,IAAI,CAAG,IACpB,EAAS,IAAI,CAAG,EAChB,QAAQ,KACJ,uBAAuB,EAAO,mBAAmB,EAAa,gCAAgC,EAAS,CAAS,GAAK,EAAU,mEACnI,EACJ"}
|
|
@@ -12,10 +12,12 @@ function r(e, t, r = []) {
|
|
|
12
12
|
let i = n(e);
|
|
13
13
|
return i === null || i === n(t) || r.some((e) => n(e) === i);
|
|
14
14
|
}
|
|
15
|
-
function i(r, i) {
|
|
15
|
+
function i(r, i, a = "Authorization") {
|
|
16
16
|
if (!e()) return;
|
|
17
|
-
let
|
|
18
|
-
|
|
17
|
+
let o = n(r);
|
|
18
|
+
if (o === null) return;
|
|
19
|
+
let s = `${a} ${o}`;
|
|
20
|
+
t.has(s) || (t.add(s), console.warn(`[tempest-react-sdk] ${a} was not sent to ${o}: the credential is scoped to ${n(i) ?? i}. Add the origin to trustedOrigins if it should receive the token.`));
|
|
19
21
|
}
|
|
20
22
|
//#endregion
|
|
21
23
|
export { r as isTrustedCredentialTarget, i as reportSuppressedCredential };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential-scope.js","names":[],"sources":["../../src/http/credential-scope.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Origins already reported by {@link reportSuppressedCredential}, so a chunked\n * upload warns once instead of once per chunk.\n */\nconst reported = new Set<string>();\n\n/**\n * The origin a URL resolves to, or `null` when it has none to compare.\n *\n * Relative values resolve against the document, because that is what they mean\n * everywhere else in the SDK: an `endpoint` of `\"/api/uploads\"` and a `baseURL`\n * of `\"/api\"` are the shape you get behind a dev-server or a reverse proxy, and\n * both name the page's own origin. Comparing a resolved absolute target against\n * an unresolved relative reference is how the first draft of this function\n * withheld the credential from every client configured that way.\n *\n * `null` is reserved for the case with genuinely nothing to compare: a relative\n * URL outside a browsing context, where there is no document to resolve against.\n *\n * @param url - Absolute or relative URL.\n * @returns The origin, or `null` when it cannot be resolved.\n */\nfunction originOf(url: string): string | null {\n try {\n return new URL(url, globalThis.location?.href).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Whether a request to `target` may carry the caller's credential.\n *\n * The SDK writes `Authorization: Bearer` in three places, and until 0.66.0 none\n * of them looked at where the request was going. That is only safe while every\n * target URL is written by the app: a resumable upload takes its URL from the\n * server's `Location` header, and `createApiClient` lets an absolute path\n * override `baseURL` entirely, so a URL arriving over the network could decide\n * which origin received the token — and the file bytes with it.\n *\n * Handing an upload off to object storage on another host is ordinary `tus`\n * deployment, not an attack, which is exactly why the credential must be scoped\n * rather than the request blocked: the upload still goes through, it just goes\n * without the API's bearer token.\n *\n * Both sides are resolved against the document first, so a relative `baseURL`\n * or `endpoint` — the shape behind a dev-server or reverse proxy — compares\n * equal to the absolute URL the request actually goes to. Outside a browsing\n * context a relative target resolves to nothing and is allowed: there is no\n * origin for it to cross.\n *\n * @param target - The URL the request is about to go to.\n * @param reference - The origin the credential belongs to, normally the\n * client's `baseURL` or the upload `endpoint`.\n * @param trustedOrigins - Extra origins the app declared, for the legitimate\n * second host: a CDN, a signed upload endpoint.\n * @returns Whether the credential may be attached.\n *\n * @example\n * isTrustedCredentialTarget(\"https://api.acme.com/me\", \"https://api.acme.com\");\n * // true\n * isTrustedCredentialTarget(\"https://cdn.other/u/1\", \"https://api.acme.com\");\n * // false\n */\nexport function isTrustedCredentialTarget(\n target: string,\n reference: string,\n trustedOrigins: readonly string[] = [],\n): boolean {\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return true;\n if (targetOrigin === originOf(reference)) return true;\n return trustedOrigins.some((origin) => originOf(origin) === targetOrigin);\n}\n\n/**\n * Say once, in a development build, that a credential was withheld.\n *\n * Without it the symptom is a `401` from a host the developer never typed, and
|
|
1
|
+
{"version":3,"file":"credential-scope.js","names":[],"sources":["../../src/http/credential-scope.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\n\n/**\n * Origins already reported by {@link reportSuppressedCredential}, so a chunked\n * upload warns once instead of once per chunk.\n */\nconst reported = new Set<string>();\n\n/**\n * The origin a URL resolves to, or `null` when it has none to compare.\n *\n * Relative values resolve against the document, because that is what they mean\n * everywhere else in the SDK: an `endpoint` of `\"/api/uploads\"` and a `baseURL`\n * of `\"/api\"` are the shape you get behind a dev-server or a reverse proxy, and\n * both name the page's own origin. Comparing a resolved absolute target against\n * an unresolved relative reference is how the first draft of this function\n * withheld the credential from every client configured that way.\n *\n * `null` is reserved for the case with genuinely nothing to compare: a relative\n * URL outside a browsing context, where there is no document to resolve against.\n *\n * @param url - Absolute or relative URL.\n * @returns The origin, or `null` when it cannot be resolved.\n */\nfunction originOf(url: string): string | null {\n try {\n return new URL(url, globalThis.location?.href).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Whether a request to `target` may carry the caller's credential.\n *\n * The SDK writes `Authorization: Bearer` in three places, and until 0.66.0 none\n * of them looked at where the request was going. That is only safe while every\n * target URL is written by the app: a resumable upload takes its URL from the\n * server's `Location` header, and `createApiClient` lets an absolute path\n * override `baseURL` entirely, so a URL arriving over the network could decide\n * which origin received the token — and the file bytes with it.\n *\n * Handing an upload off to object storage on another host is ordinary `tus`\n * deployment, not an attack, which is exactly why the credential must be scoped\n * rather than the request blocked: the upload still goes through, it just goes\n * without the API's bearer token.\n *\n * Both sides are resolved against the document first, so a relative `baseURL`\n * or `endpoint` — the shape behind a dev-server or reverse proxy — compares\n * equal to the absolute URL the request actually goes to. Outside a browsing\n * context a relative target resolves to nothing and is allowed: there is no\n * origin for it to cross.\n *\n * @param target - The URL the request is about to go to.\n * @param reference - The origin the credential belongs to, normally the\n * client's `baseURL` or the upload `endpoint`.\n * @param trustedOrigins - Extra origins the app declared, for the legitimate\n * second host: a CDN, a signed upload endpoint.\n * @returns Whether the credential may be attached.\n *\n * @example\n * isTrustedCredentialTarget(\"https://api.acme.com/me\", \"https://api.acme.com\");\n * // true\n * isTrustedCredentialTarget(\"https://cdn.other/u/1\", \"https://api.acme.com\");\n * // false\n */\nexport function isTrustedCredentialTarget(\n target: string,\n reference: string,\n trustedOrigins: readonly string[] = [],\n): boolean {\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return true;\n if (targetOrigin === originOf(reference)) return true;\n return trustedOrigins.some((origin) => originOf(origin) === targetOrigin);\n}\n\n/**\n * Say once, in a development build, that a credential was withheld.\n *\n * Without it the symptom is a `401` (or, for the CSRF header, a `403`) from a\n * host the developer never typed, and nothing in the app's code mentions the\n * origin that produced it. Keyed by credential and target origin, so a\n * hundred-chunk upload reports one line per header it withheld.\n *\n * Silent in production for the same reason {@link parseResponse} is: the origin\n * an app talks to is not something to print into a user's console or ship to an\n * error tracker.\n *\n * @param target - The URL whose request went out unauthenticated.\n * @param reference - The origin the credential was scoped to.\n * @param header - The header that was withheld. Default `\"Authorization\"`.\n */\nexport function reportSuppressedCredential(\n target: string,\n reference: string,\n header = \"Authorization\",\n): void {\n if (!isDevBuild()) return;\n const targetOrigin = originOf(target);\n if (targetOrigin === null) return;\n const key = `${header} ${targetOrigin}`;\n if (reported.has(key)) return;\n reported.add(key);\n console.warn(\n `[tempest-react-sdk] ${header} was not sent to ${targetOrigin}: the credential is scoped to ${originOf(reference) ?? reference}. Add the origin to trustedOrigins if it should receive the token.`,\n );\n}\n\n/**\n * Forget which origins were already reported.\n *\n * Exported for tests, which assert the once-per-origin behaviour and would\n * otherwise leak state between cases.\n */\nexport function resetSuppressedCredentialReports(): void {\n reported.clear();\n}\n"],"mappings":";;AAMA,IAAM,oBAAW,IAAI,IAAY;AAkBjC,SAAS,EAAS,GAA4B;CAC1C,IAAI;EACA,OAAO,IAAI,IAAI,GAAK,WAAW,UAAU,IAAI,CAAC,CAAC;CACnD,QAAQ;EACJ,OAAO;CACX;AACJ;AAoCA,SAAgB,EACZ,GACA,GACA,IAAoC,CAAC,GAC9B;CACP,IAAM,IAAe,EAAS,CAAM;CAGpC,OAFI,MAAiB,QACjB,MAAiB,EAAS,CAAS,KAChC,EAAe,MAAM,MAAW,EAAS,CAAM,MAAM,CAAY;AAC5E;AAkBA,SAAgB,EACZ,GACA,GACA,IAAS,iBACL;CACJ,IAAI,CAAC,EAAW,GAAG;CACnB,IAAM,IAAe,EAAS,CAAM;CACpC,IAAI,MAAiB,MAAM;CAC3B,IAAM,IAAM,GAAG,EAAO,GAAG;CACrB,EAAS,IAAI,CAAG,MACpB,EAAS,IAAI,CAAG,GAChB,QAAQ,KACJ,uBAAuB,EAAO,mBAAmB,EAAa,gCAAgC,EAAS,CAAS,KAAK,EAAU,mEACnI;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../utils/dev-mode.cjs"),t=require("./credential-scope.cjs");var n=`csrf_token`,r=`X-CSRF-Token`,i=new Set([`GET`,`HEAD`,`OPTIONS`,`TRACE`]),a=new Set;function o(e){if(typeof document>`u`)return null;let t=`${e}=`;for(let e of document.cookie.split(`;`)){let n=e.trim();if(!n.startsWith(t))continue;let r=n.slice(t.length);try{return decodeURIComponent(r)}catch{return r}}return null}function s(t){if(!e.isDevBuild()||a.has(t))return;a.add(t);let n=t===`getToken`?`csrf.getToken() returned nothing`:`no readable "${t}" cookie on this page`;console.warn(`[tempest-react-sdk] CSRF is enabled but ${n}, so the write went without the token. The cookie must be issued before the first write and must not be HttpOnly.`)}function c(e,t){return e?new Headers(e).has(t):!1}function l(e){let{method:n,url:r,reference:a,csrf:l,trustedOrigins:u,headers:d}=e;if(!l||i.has(n.toUpperCase()))return{};let f=l===!0?{}:l,p=f.headerName??`X-CSRF-Token`;if(c(d,p))return{};if(!t.isTrustedCredentialTarget(r,a,u))return t.reportSuppressedCredential(r,a,p),{};let m=f.cookieName??`csrf_token`,h=f.getToken?f.getToken():o(m);return h?{[p]:h}:(s(f.getToken?`getToken`:m),{})}exports.DEFAULT_CSRF_COOKIE_NAME=n,exports.DEFAULT_CSRF_HEADER_NAME=r,exports.csrfHeaders=l;
|
|
2
|
+
//# sourceMappingURL=csrf.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.cjs","names":[],"sources":["../../src/http/csrf.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\n\n/**\n * Default cookie the CSRF token is read from.\n *\n * Ported from `tempest-fastapi-sdk`'s `CSRF_COOKIE_NAME`\n * (`tempest_fastapi_sdk/api/middlewares/csrf.py`), which is the cookie its\n * `make_csrf_token_dependency()` sets and its `CSRFMiddleware` compares against.\n * Matching it is what lets `csrf: true` work against that backend with no\n * configuration on either side.\n */\nexport const DEFAULT_CSRF_COOKIE_NAME = \"csrf_token\";\n\n/**\n * Default header the CSRF token is echoed in.\n *\n * Ported from `tempest-fastapi-sdk`'s `CSRF_HEADER_NAME`, the header its\n * `CSRFMiddleware` reads on every unsafe request.\n */\nexport const DEFAULT_CSRF_HEADER_NAME = \"X-CSRF-Token\";\n\n/**\n * Where the CSRF token comes from and which header carries it.\n *\n * The default is the **double-submit cookie**: the server sets a cookie that is\n * deliberately not `HttpOnly`, the client reads it and echoes the value in a\n * header, and the server rejects a write whose header does not match the\n * cookie. A page on another site can make the browser *send* the cookie, but\n * cannot *read* it, so it cannot write the header.\n *\n * The token is read again on every request, so a server that rotates the\n * cookie is followed without any capture step: the browser's cookie jar is the\n * store. That is also why there is no \"read the token from a response header\"\n * mode — it would depend on `Access-Control-Expose-Headers`, and a missing\n * expose header fails silently, as a `403` on the second write.\n */\nexport interface CsrfOptions {\n /** Cookie to read the token from. Default {@link DEFAULT_CSRF_COOKIE_NAME}. */\n cookieName?: string;\n /** Header to send the token in. Default {@link DEFAULT_CSRF_HEADER_NAME}. */\n headerName?: string;\n /**\n * Supply the token yourself instead of reading `cookieName`.\n *\n * For the cases the cookie cannot serve: an API on another **site**, whose\n * cookie `document.cookie` cannot see, or a backend that hands the token\n * out in a response body. Called per request, like `getToken`.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Methods that must not change state, and so never carry the token.\n *\n * A deny list rather than an allow list of the four write verbs: RFC 9110\n * names the safe methods, and a custom method (`PROPFIND`, a tus extension)\n * is a write until proven otherwise. Sending the token to its own origin on\n * an unexpected verb costs nothing; omitting it costs a `403`.\n */\nconst SAFE_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"]);\n\n/** Token sources already reported empty, so a burst of writes warns once. */\nconst reportedMissing = new Set<string>();\n\n/**\n * Read one cookie from `document.cookie`, or `null` when it is absent.\n *\n * Returns `null` outside a document (a worker, a test without jsdom), where\n * there is no cookie jar to read. The value is URI-decoded when it can be,\n * and returned raw when it is not valid percent-encoding.\n *\n * @param name - The cookie name.\n * @returns The value, or `null`.\n */\nfunction readCookie(name: string): string | null {\n if (typeof document === \"undefined\") return null;\n const prefix = `${name}=`;\n for (const part of document.cookie.split(\";\")) {\n const entry = part.trim();\n if (!entry.startsWith(prefix)) continue;\n const raw = entry.slice(prefix.length);\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n }\n return null;\n}\n\n/**\n * Say once, in a development build, that CSRF is on but there is no token.\n *\n * The request still goes out, because the SDK cannot know whether this path\n * is guarded — `CSRFMiddleware` is commonly mounted with `exclude_paths`. When\n * it is guarded, the symptom is a `403 CSRF_VALIDATION_FAILED` with nothing\n * in the app's code pointing at the cause, and the three usual causes are all\n * on the server: the cookie was never issued, was issued `HttpOnly`, or was\n * issued for a domain this page cannot read.\n *\n * @param source - What was read: the cookie name, or `\"getToken\"`.\n */\nfunction reportMissingToken(source: string): void {\n if (!isDevBuild() || reportedMissing.has(source)) return;\n reportedMissing.add(source);\n const where =\n source === \"getToken\"\n ? \"csrf.getToken() returned nothing\"\n : `no readable \"${source}\" cookie on this page`;\n console.warn(\n `[tempest-react-sdk] CSRF is enabled but ${where}, so the write went without the token. The cookie must be issued before the first write and must not be HttpOnly.`,\n );\n}\n\n/**\n * Whether a header is already present, compared case-insensitively.\n *\n * Header names are case-insensitive, but object keys are not: a caller's\n * `\"x-csrf-token\"` next to the SDK's `\"X-CSRF-Token\"` would reach `fetch` as\n * two entries and be joined into `\"a, b\"`, which matches neither.\n *\n * @param headers - The headers the caller already set.\n * @param name - The header to look for.\n * @returns Whether it is set.\n */\nfunction hasHeader(headers: HeadersInit | undefined, name: string): boolean {\n if (!headers) return false;\n return new Headers(headers).has(name);\n}\n\n/** What {@link csrfHeaders} needs to decide. */\nexport interface CsrfHeadersInput {\n /** The HTTP method of the request. Case-insensitive. */\n method: string;\n /** The URL the request is going to. */\n url: string;\n /**\n * The origin the token belongs to, normally the API's `baseURL`. The token\n * is only sent to this origin or to one listed in `trustedOrigins`.\n */\n reference: string;\n /** The CSRF config. `undefined` or `false` turns the header off. */\n csrf: boolean | CsrfOptions | undefined;\n /** Extra origins allowed to receive the token. */\n trustedOrigins?: readonly string[];\n /** Headers the caller already set. A CSRF header among them is never replaced. */\n headers?: HeadersInit;\n}\n\n/**\n * The CSRF header a request should carry, or an empty object.\n *\n * Every request path in the SDK — `createApiClient`, `uploadWithProgress`,\n * `createResumableUpload` — asks this function, so the rules are one rule:\n *\n * - **Off unless configured.** Without `csrf`, nothing changes.\n * - **Unsafe methods only.** `GET`, `HEAD`, `OPTIONS` and `TRACE` never carry\n * it; they must not change state, and a token in a `GET` ends up in logs\n * and caches for nothing.\n * - **Never across an origin.** The token follows the same scope as the bearer\n * credential ({@link isTrustedCredentialTarget}), because a URL can come off\n * the network — a tus `Location`, a pagination link — and a CSRF token sent\n * to a third party is a token that third party can replay. Withheld tokens\n * are reported once per origin in a development build.\n * - **Your header wins.** A CSRF header you set by hand, in any casing, is\n * left alone.\n * - **Independent of auth.** It is sent on `skipAuth` requests too: login and\n * refresh are exactly the writes a cookie session exposes to forgery.\n *\n * Exported for the request you build by hand, so it follows the same rules.\n *\n * @example\n * const headers = csrfHeaders({\n * method: \"POST\",\n * url: \"https://api.acme.com/orders\",\n * reference: \"https://api.acme.com\",\n * csrf: true,\n * });\n * // { \"X-CSRF-Token\": \"<value of the csrf_token cookie>\" }\n *\n * @param input - The request and the CSRF config.\n * @returns A header record to spread into the request's headers.\n */\nexport function csrfHeaders(input: CsrfHeadersInput): Record<string, string> {\n const { method, url, reference, csrf, trustedOrigins, headers } = input;\n if (!csrf) return {};\n if (SAFE_METHODS.has(method.toUpperCase())) return {};\n const options: CsrfOptions = csrf === true ? {} : csrf;\n const headerName = options.headerName ?? DEFAULT_CSRF_HEADER_NAME;\n if (hasHeader(headers, headerName)) return {};\n if (!isTrustedCredentialTarget(url, reference, trustedOrigins)) {\n reportSuppressedCredential(url, reference, headerName);\n return {};\n }\n const cookieName = options.cookieName ?? DEFAULT_CSRF_COOKIE_NAME;\n const token = options.getToken ? options.getToken() : readCookie(cookieName);\n if (!token) {\n reportMissingToken(options.getToken ? \"getToken\" : cookieName);\n return {};\n }\n return { [headerName]: token };\n}\n\n/**\n * Forget which token sources were already reported empty.\n *\n * Exported for tests, which assert the once-per-source behaviour and would\n * otherwise leak state between cases.\n */\nexport function resetCsrfReports(): void {\n reportedMissing.clear();\n}\n"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AAQ,SAAW,EAAQ,SAAS,EAAI,EAAW,CAAU,EAK3E,OAJK,EAIE,EAAG,GAAa,CAAM,GAHzB,EAAmB,EAAQ,SAAW,WAAa,CAAU,EACtD,CAAC,EAGhB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { isDevBuild as e } from "../utils/dev-mode.js";
|
|
2
|
+
import { isTrustedCredentialTarget as t, reportSuppressedCredential as n } from "./credential-scope.js";
|
|
3
|
+
//#region src/http/csrf.ts
|
|
4
|
+
var r = "csrf_token", i = "X-CSRF-Token", a = /* @__PURE__ */ new Set([
|
|
5
|
+
"GET",
|
|
6
|
+
"HEAD",
|
|
7
|
+
"OPTIONS",
|
|
8
|
+
"TRACE"
|
|
9
|
+
]), o = /* @__PURE__ */ new Set();
|
|
10
|
+
function s(e) {
|
|
11
|
+
if (typeof document > "u") return null;
|
|
12
|
+
let t = `${e}=`;
|
|
13
|
+
for (let e of document.cookie.split(";")) {
|
|
14
|
+
let n = e.trim();
|
|
15
|
+
if (!n.startsWith(t)) continue;
|
|
16
|
+
let r = n.slice(t.length);
|
|
17
|
+
try {
|
|
18
|
+
return decodeURIComponent(r);
|
|
19
|
+
} catch {
|
|
20
|
+
return r;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
function c(t) {
|
|
26
|
+
if (!e() || o.has(t)) return;
|
|
27
|
+
o.add(t);
|
|
28
|
+
let n = t === "getToken" ? "csrf.getToken() returned nothing" : `no readable "${t}" cookie on this page`;
|
|
29
|
+
console.warn(`[tempest-react-sdk] CSRF is enabled but ${n}, so the write went without the token. The cookie must be issued before the first write and must not be HttpOnly.`);
|
|
30
|
+
}
|
|
31
|
+
function l(e, t) {
|
|
32
|
+
return e ? new Headers(e).has(t) : !1;
|
|
33
|
+
}
|
|
34
|
+
function u(e) {
|
|
35
|
+
let { method: r, url: i, reference: o, csrf: u, trustedOrigins: d, headers: f } = e;
|
|
36
|
+
if (!u || a.has(r.toUpperCase())) return {};
|
|
37
|
+
let p = u === !0 ? {} : u, m = p.headerName ?? "X-CSRF-Token";
|
|
38
|
+
if (l(f, m)) return {};
|
|
39
|
+
if (!t(i, o, d)) return n(i, o, m), {};
|
|
40
|
+
let h = p.cookieName ?? "csrf_token", g = p.getToken ? p.getToken() : s(h);
|
|
41
|
+
return g ? { [m]: g } : (c(p.getToken ? "getToken" : h), {});
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { r as DEFAULT_CSRF_COOKIE_NAME, i as DEFAULT_CSRF_HEADER_NAME, u as csrfHeaders };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=csrf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"csrf.js","names":[],"sources":["../../src/http/csrf.ts"],"sourcesContent":["import { isDevBuild } from \"../utils/dev-mode\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\n\n/**\n * Default cookie the CSRF token is read from.\n *\n * Ported from `tempest-fastapi-sdk`'s `CSRF_COOKIE_NAME`\n * (`tempest_fastapi_sdk/api/middlewares/csrf.py`), which is the cookie its\n * `make_csrf_token_dependency()` sets and its `CSRFMiddleware` compares against.\n * Matching it is what lets `csrf: true` work against that backend with no\n * configuration on either side.\n */\nexport const DEFAULT_CSRF_COOKIE_NAME = \"csrf_token\";\n\n/**\n * Default header the CSRF token is echoed in.\n *\n * Ported from `tempest-fastapi-sdk`'s `CSRF_HEADER_NAME`, the header its\n * `CSRFMiddleware` reads on every unsafe request.\n */\nexport const DEFAULT_CSRF_HEADER_NAME = \"X-CSRF-Token\";\n\n/**\n * Where the CSRF token comes from and which header carries it.\n *\n * The default is the **double-submit cookie**: the server sets a cookie that is\n * deliberately not `HttpOnly`, the client reads it and echoes the value in a\n * header, and the server rejects a write whose header does not match the\n * cookie. A page on another site can make the browser *send* the cookie, but\n * cannot *read* it, so it cannot write the header.\n *\n * The token is read again on every request, so a server that rotates the\n * cookie is followed without any capture step: the browser's cookie jar is the\n * store. That is also why there is no \"read the token from a response header\"\n * mode — it would depend on `Access-Control-Expose-Headers`, and a missing\n * expose header fails silently, as a `403` on the second write.\n */\nexport interface CsrfOptions {\n /** Cookie to read the token from. Default {@link DEFAULT_CSRF_COOKIE_NAME}. */\n cookieName?: string;\n /** Header to send the token in. Default {@link DEFAULT_CSRF_HEADER_NAME}. */\n headerName?: string;\n /**\n * Supply the token yourself instead of reading `cookieName`.\n *\n * For the cases the cookie cannot serve: an API on another **site**, whose\n * cookie `document.cookie` cannot see, or a backend that hands the token\n * out in a response body. Called per request, like `getToken`.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Methods that must not change state, and so never carry the token.\n *\n * A deny list rather than an allow list of the four write verbs: RFC 9110\n * names the safe methods, and a custom method (`PROPFIND`, a tus extension)\n * is a write until proven otherwise. Sending the token to its own origin on\n * an unexpected verb costs nothing; omitting it costs a `403`.\n */\nconst SAFE_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"]);\n\n/** Token sources already reported empty, so a burst of writes warns once. */\nconst reportedMissing = new Set<string>();\n\n/**\n * Read one cookie from `document.cookie`, or `null` when it is absent.\n *\n * Returns `null` outside a document (a worker, a test without jsdom), where\n * there is no cookie jar to read. The value is URI-decoded when it can be,\n * and returned raw when it is not valid percent-encoding.\n *\n * @param name - The cookie name.\n * @returns The value, or `null`.\n */\nfunction readCookie(name: string): string | null {\n if (typeof document === \"undefined\") return null;\n const prefix = `${name}=`;\n for (const part of document.cookie.split(\";\")) {\n const entry = part.trim();\n if (!entry.startsWith(prefix)) continue;\n const raw = entry.slice(prefix.length);\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n }\n return null;\n}\n\n/**\n * Say once, in a development build, that CSRF is on but there is no token.\n *\n * The request still goes out, because the SDK cannot know whether this path\n * is guarded — `CSRFMiddleware` is commonly mounted with `exclude_paths`. When\n * it is guarded, the symptom is a `403 CSRF_VALIDATION_FAILED` with nothing\n * in the app's code pointing at the cause, and the three usual causes are all\n * on the server: the cookie was never issued, was issued `HttpOnly`, or was\n * issued for a domain this page cannot read.\n *\n * @param source - What was read: the cookie name, or `\"getToken\"`.\n */\nfunction reportMissingToken(source: string): void {\n if (!isDevBuild() || reportedMissing.has(source)) return;\n reportedMissing.add(source);\n const where =\n source === \"getToken\"\n ? \"csrf.getToken() returned nothing\"\n : `no readable \"${source}\" cookie on this page`;\n console.warn(\n `[tempest-react-sdk] CSRF is enabled but ${where}, so the write went without the token. The cookie must be issued before the first write and must not be HttpOnly.`,\n );\n}\n\n/**\n * Whether a header is already present, compared case-insensitively.\n *\n * Header names are case-insensitive, but object keys are not: a caller's\n * `\"x-csrf-token\"` next to the SDK's `\"X-CSRF-Token\"` would reach `fetch` as\n * two entries and be joined into `\"a, b\"`, which matches neither.\n *\n * @param headers - The headers the caller already set.\n * @param name - The header to look for.\n * @returns Whether it is set.\n */\nfunction hasHeader(headers: HeadersInit | undefined, name: string): boolean {\n if (!headers) return false;\n return new Headers(headers).has(name);\n}\n\n/** What {@link csrfHeaders} needs to decide. */\nexport interface CsrfHeadersInput {\n /** The HTTP method of the request. Case-insensitive. */\n method: string;\n /** The URL the request is going to. */\n url: string;\n /**\n * The origin the token belongs to, normally the API's `baseURL`. The token\n * is only sent to this origin or to one listed in `trustedOrigins`.\n */\n reference: string;\n /** The CSRF config. `undefined` or `false` turns the header off. */\n csrf: boolean | CsrfOptions | undefined;\n /** Extra origins allowed to receive the token. */\n trustedOrigins?: readonly string[];\n /** Headers the caller already set. A CSRF header among them is never replaced. */\n headers?: HeadersInit;\n}\n\n/**\n * The CSRF header a request should carry, or an empty object.\n *\n * Every request path in the SDK — `createApiClient`, `uploadWithProgress`,\n * `createResumableUpload` — asks this function, so the rules are one rule:\n *\n * - **Off unless configured.** Without `csrf`, nothing changes.\n * - **Unsafe methods only.** `GET`, `HEAD`, `OPTIONS` and `TRACE` never carry\n * it; they must not change state, and a token in a `GET` ends up in logs\n * and caches for nothing.\n * - **Never across an origin.** The token follows the same scope as the bearer\n * credential ({@link isTrustedCredentialTarget}), because a URL can come off\n * the network — a tus `Location`, a pagination link — and a CSRF token sent\n * to a third party is a token that third party can replay. Withheld tokens\n * are reported once per origin in a development build.\n * - **Your header wins.** A CSRF header you set by hand, in any casing, is\n * left alone.\n * - **Independent of auth.** It is sent on `skipAuth` requests too: login and\n * refresh are exactly the writes a cookie session exposes to forgery.\n *\n * Exported for the request you build by hand, so it follows the same rules.\n *\n * @example\n * const headers = csrfHeaders({\n * method: \"POST\",\n * url: \"https://api.acme.com/orders\",\n * reference: \"https://api.acme.com\",\n * csrf: true,\n * });\n * // { \"X-CSRF-Token\": \"<value of the csrf_token cookie>\" }\n *\n * @param input - The request and the CSRF config.\n * @returns A header record to spread into the request's headers.\n */\nexport function csrfHeaders(input: CsrfHeadersInput): Record<string, string> {\n const { method, url, reference, csrf, trustedOrigins, headers } = input;\n if (!csrf) return {};\n if (SAFE_METHODS.has(method.toUpperCase())) return {};\n const options: CsrfOptions = csrf === true ? {} : csrf;\n const headerName = options.headerName ?? DEFAULT_CSRF_HEADER_NAME;\n if (hasHeader(headers, headerName)) return {};\n if (!isTrustedCredentialTarget(url, reference, trustedOrigins)) {\n reportSuppressedCredential(url, reference, headerName);\n return {};\n }\n const cookieName = options.cookieName ?? DEFAULT_CSRF_COOKIE_NAME;\n const token = options.getToken ? options.getToken() : readCookie(cookieName);\n if (!token) {\n reportMissingToken(options.getToken ? \"getToken\" : cookieName);\n return {};\n }\n return { [headerName]: token };\n}\n\n/**\n * Forget which token sources were already reported empty.\n *\n * Exported for tests, which assert the once-per-source behaviour and would\n * otherwise leak state between cases.\n */\nexport function resetCsrfReports(): void {\n reportedMissing.clear();\n}\n"],"mappings":";;;AAYA,IAAa,IAA2B,cAQ3B,IAA2B,gBAwClC,oBAAoC,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAW;AAAO,CAAC,GAG/E,oBAAkB,IAAI,IAAY;A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1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/base64.cjs"),t=require("./credential-scope.cjs"),n=require("./
|
|
1
|
+
const e=require("../utils/base64.cjs"),t=require("./credential-scope.cjs"),n=require("./csrf.cjs"),r=require("./errors.cjs"),i=require("./retry.cjs"),a=require("./idempotency.cjs");var o=`1.0.0`,s=5242880;function c(t){return e.bytesToBase64(new TextEncoder().encode(t))}function l(e){if(!e)return null;let t=Object.entries(e).map(([e,t])=>`${e} ${c(t)}`);return t.length>0?t.join(`,`):null}function u(e,t){let n=t,r=typeof n.name==`string`?n.name:`blob`,i=typeof n.lastModified==`number`?n.lastModified:0;return`${e}|${r}|${t.size}|${t.type}|${i}`}function d(e=`tempest-upload:`){function t(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}return{get(n){let r=t()?.getItem(e+n);if(!r)return null;try{return JSON.parse(r)}catch{return null}},set(n,r){t()?.setItem(e+n,JSON.stringify(r))},delete(n){t()?.removeItem(e+n)}}}function f(e){return new Promise((t,n)=>{let i=new XMLHttpRequest;i.open(e.method,e.url),i.withCredentials=e.withCredentials;for(let[t,n]of Object.entries(e.headers))i.setRequestHeader(t,n);if(e.onProgress){let t=e.onProgress;i.upload.onprogress=e=>t(e.loaded)}i.onload=()=>t({status:i.status,text:i.responseText,header:e=>i.getResponseHeader(e)}),i.onerror=()=>n(new r.TempestApiError({status:0,detail:`Falha de rede no upload resumível.`})),i.onabort=()=>n(new DOMException(`Aborted`,`AbortError`)),e.register(i),i.send(e.body)})}function p(e){let t=e.header(`Upload-Offset`);if(t===null)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function m(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}var h=new Set([409,412]);function g(e){return!r.isApiError(e)||h.has(e.status)?!0:r.isRetriableStatus(e.status)}function _(e,t){let n=m(e.text),i=r.buildApiError(e.status,n,{get:e.header}),a=typeof n==`object`&&!!n&&(`detail`in n||`message`in n);return new r.TempestApiError({...i,detail:a?i.detail:t})}function v(e){let t=typeof window>`u`?void 0:window.location.href;try{return new URL(e,t).href}catch{return e}}function y(e){let{endpoint:c,file:m,chunkSize:h=s,metadata:y,headers:b={},getToken:x,trustedOrigins:S,withCredentials:C=!1,csrf:w,key:T=u(c,m),storage:E=d(),retry:D,onProgress:O,onStateChange:k}=e,A=`idle`,j=0,M=null,N=null,P=null,F=null,I=0;function L(e){A!==e&&(A=e,k?.(e))}function R(e){O?.({loaded:e,total:m.size,fraction:m.size===0?1:e/m.size,resumedFrom:I})}function z(e,r){let i={...b,"Tus-Resumable":o},a=x?.();return a&&!(`Authorization`in i)&&(t.isTrustedCredentialTarget(e,c,S)?i.Authorization=`Bearer ${a}`:t.reportSuppressedCredential(e,c)),Object.assign(i,n.csrfHeaders({method:r,url:e,reference:c,csrf:w,trustedOrigins:S,headers:b})),i}function B(e){F=e}async function V(){E&&M&&N&&await E.set(T,{url:M,offset:j,size:m.size,idempotencyKey:N,updatedAt:Date.now()})}async function H(e){let t=await f({method:`HEAD`,url:e,headers:z(e,`HEAD`),withCredentials:C,register:B});if(t.status===404||t.status===410)throw new r.TempestApiError({status:t.status,detail:`O upload expirou no servidor. Comece de novo.`});let n=p(t);if(n===null)throw _(t,`HEAD sem Upload-Offset.`);return n}async function U(){let e=E?await E.get(T):null;if(e&&e.size===m.size&&(N=e.idempotencyKey,e.url))try{return j=await H(e.url),M=e.url,e.url}catch{j=0}L(`creating`),N??=a.generateIdempotencyKey(),M=null,j=0,E&&await E.set(T,{url:``,offset:0,size:m.size,idempotencyKey:N,updatedAt:Date.now()});let t={...z(c,`POST`),"Upload-Length":String(m.size),"Idempotency-Key":N},n=l(y);n&&(t[`Upload-Metadata`]=n);let r=await f({method:`POST`,url:c,headers:t,withCredentials:C,register:B});if(r.status!==201)throw _(r,`Criação do upload recusada.`);let i=r.header(`Location`);if(!i)throw _(r,`Criação do upload sem cabeçalho Location.`);return M=v(i),await V(),M}async function W(e,t){if(t.needed&&(j=await H(e),t.needed=!1,R(j),await V(),j>=m.size))return;let n=Math.min(j+h,m.size),r=j,i=await f({method:`PATCH`,url:e,headers:{...z(e,`PATCH`),"Content-Type":`application/offset+octet-stream`,"Upload-Offset":String(r)},body:m.slice(r,n),withCredentials:C,onProgress:e=>R(Math.min(r+e,m.size)),register:B});if(i.status===409||i.status===412)throw t.needed=!0,_(i,`Offset divergente — o servidor já tinha esses bytes.`);if(i.status!==204&&i.status!==200)throw _(i,`Chunk recusado pelo servidor.`);j=p(i)??n,R(j),await V()}async function G(){P=null;let e=await U();I=j,L(`uploading`),R(j);let t={needed:!1};for(;j<m.size&&!P;)await i.retry(()=>W(e,t),{retries:5,...D,shouldRetry:(e,n)=>{if(P||e instanceof DOMException&&e.name===`AbortError`)return!1;let r=D?.shouldRetry?.(e,n)??g(e);return r&&(t.needed=!0),r}});return P===`pause`?(L(`paused`),null):P===`abort`?(L(`aborted`),null):(L(`done`),E&&await E.delete(T),{url:e,size:m.size})}async function K(){try{return await G()}catch(e){if(P!==null||e instanceof DOMException&&e.name===`AbortError`)return L(P===`abort`?`aborted`:`paused`),null;throw L(`error`),e}finally{F=null}}function q(e){P=e,F?.abort(),F=null}return{start:K,resume:K,pause:()=>q(`pause`),abort:async({discard:e=!1}={})=>{q(`abort`),L(`aborted`),e&&(M&&await f({method:`DELETE`,url:M,headers:z(M,`DELETE`),withCredentials:C,register:()=>void 0}).catch(()=>void 0),E&&await E.delete(T))},get state(){return A},get offset(){return j},get url(){return M},key:T}}exports.DEFAULT_CHUNK_SIZE=s,exports.TUS_VERSION=o,exports.createLocalUploadStorage=d,exports.createResumableUpload=y,exports.uploadFingerprint=u;
|
|
2
2
|
//# sourceMappingURL=resumable-upload.cjs.map
|