tempest-react-sdk 0.80.0 → 0.82.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.
Files changed (247) hide show
  1. package/README.md +40 -10
  2. package/bin/create-tempest-app.e2e.test.mjs +31 -0
  3. package/bin/create-tempest-app.mjs +11 -1
  4. package/bin/lib/component/generate.test.mjs +13 -1
  5. package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
  6. package/bin/lib/doctor/vitest.mjs +120 -0
  7. package/bin/lib/doctor/vitest.test.mjs +139 -0
  8. package/bin/lib/fs/contain.mjs +7 -0
  9. package/bin/lib/openapi/escape.mjs +68 -4
  10. package/bin/lib/openapi/generate.hostile.test.mjs +150 -1
  11. package/bin/lib/openapi/generate.mjs +78 -13
  12. package/bin/lib/openapi/generate.test.mjs +13 -1
  13. package/bin/lib/openapi/pattern-risk.mjs +134 -0
  14. package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
  15. package/bin/tempest-gen.test.mjs +100 -0
  16. package/bin/tempest.mjs +24 -8
  17. package/dist/access/use-can.cjs +1 -1
  18. package/dist/access/use-can.cjs.map +1 -1
  19. package/dist/access/use-can.js +25 -28
  20. package/dist/access/use-can.js.map +1 -1
  21. package/dist/auth/create-tempest-auth.cjs +1 -1
  22. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  23. package/dist/auth/create-tempest-auth.js +234 -122
  24. package/dist/auth/create-tempest-auth.js.map +1 -1
  25. package/dist/auth/session-identity.cjs +2 -0
  26. package/dist/auth/session-identity.cjs.map +1 -0
  27. package/dist/auth/session-identity.js +12 -0
  28. package/dist/auth/session-identity.js.map +1 -0
  29. package/dist/br/boleto.cjs +1 -1
  30. package/dist/br/boleto.cjs.map +1 -1
  31. package/dist/br/boleto.js +2 -1
  32. package/dist/br/boleto.js.map +1 -1
  33. package/dist/br.d.ts +22 -3
  34. package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
  35. package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
  36. package/dist/components/AuthForm/AuthFieldControl.js +85 -0
  37. package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
  38. package/dist/components/AuthForm/AuthForm.cjs +2 -0
  39. package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
  40. package/dist/components/AuthForm/AuthForm.js +83 -0
  41. package/dist/components/AuthForm/AuthForm.js.map +1 -0
  42. package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
  43. package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
  44. package/dist/components/AuthForm/AuthForm.module.js +14 -0
  45. package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
  46. package/dist/components/AuthForm/AuthLinks.cjs +2 -0
  47. package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
  48. package/dist/components/AuthForm/AuthLinks.js +32 -0
  49. package/dist/components/AuthForm/AuthLinks.js.map +1 -0
  50. package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
  51. package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
  52. package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
  53. package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
  54. package/dist/components/AuthForm/LoginForm.cjs +2 -0
  55. package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
  56. package/dist/components/AuthForm/LoginForm.js +39 -0
  57. package/dist/components/AuthForm/LoginForm.js.map +1 -0
  58. package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
  59. package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
  60. package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
  61. package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
  62. package/dist/components/AuthForm/SignUpForm.cjs +2 -0
  63. package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
  64. package/dist/components/AuthForm/SignUpForm.js +32 -0
  65. package/dist/components/AuthForm/SignUpForm.js.map +1 -0
  66. package/dist/components/AuthForm/auth-defaults.cjs +2 -0
  67. package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
  68. package/dist/components/AuthForm/auth-defaults.js +54 -0
  69. package/dist/components/AuthForm/auth-defaults.js.map +1 -0
  70. package/dist/components/AuthForm/auth-schemas.cjs +2 -0
  71. package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
  72. package/dist/components/AuthForm/auth-schemas.js +26 -0
  73. package/dist/components/AuthForm/auth-schemas.js.map +1 -0
  74. package/dist/components/AuthPage/AuthPage.cjs +2 -0
  75. package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
  76. package/dist/components/AuthPage/AuthPage.js +97 -0
  77. package/dist/components/AuthPage/AuthPage.js.map +1 -0
  78. package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
  79. package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
  80. package/dist/components/AuthPage/AuthPage.module.js +24 -0
  81. package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
  82. package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
  83. package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
  84. package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
  85. package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
  86. package/dist/components/Button/Button.cjs +1 -1
  87. package/dist/components/Button/Button.cjs.map +1 -1
  88. package/dist/components/Button/Button.js +41 -40
  89. package/dist/components/Button/Button.js.map +1 -1
  90. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  91. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  92. package/dist/components/Chat/ChatAttachments.js +38 -38
  93. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  94. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  95. package/dist/components/FilterBar/filter-apply.js +7 -7
  96. package/dist/components/Form/Form.cjs +1 -1
  97. package/dist/components/Form/Form.cjs.map +1 -1
  98. package/dist/components/Form/Form.js +30 -32
  99. package/dist/components/Form/Form.js.map +1 -1
  100. package/dist/components/Layout/Layout.cjs +1 -1
  101. package/dist/components/Layout/Layout.cjs.map +1 -1
  102. package/dist/components/Layout/Layout.js +25 -24
  103. package/dist/components/Layout/Layout.js.map +1 -1
  104. package/dist/components/Layout/gap.cjs +2 -0
  105. package/dist/components/Layout/gap.cjs.map +1 -0
  106. package/dist/components/Layout/gap.js +15 -0
  107. package/dist/components/Layout/gap.js.map +1 -0
  108. package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
  109. package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
  110. package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
  111. package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
  112. package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
  113. package/dist/components/Sidebar/Sidebar.js.map +1 -1
  114. package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
  115. package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
  116. package/dist/components/Sidebar/SidebarEntry.js +30 -29
  117. package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
  118. package/dist/data/create-data-provider.cjs +1 -1
  119. package/dist/data/create-data-provider.cjs.map +1 -1
  120. package/dist/data/create-data-provider.js +1 -2
  121. package/dist/data/create-data-provider.js.map +1 -1
  122. package/dist/forms/index.js +7 -7
  123. package/dist/forms/masked-inputs.cjs +1 -1
  124. package/dist/forms/masked-inputs.cjs.map +1 -1
  125. package/dist/forms/masked-inputs.js +15 -15
  126. package/dist/forms/validate-form.cjs +1 -1
  127. package/dist/forms/validate-form.cjs.map +1 -1
  128. package/dist/forms/validate-form.js +6 -1
  129. package/dist/forms/validate-form.js.map +1 -1
  130. package/dist/forms/zod-resolver.cjs +1 -1
  131. package/dist/forms/zod-resolver.cjs.map +1 -1
  132. package/dist/forms/zod-resolver.js +8 -3
  133. package/dist/forms/zod-resolver.js.map +1 -1
  134. package/dist/http/api-client.cjs +1 -1
  135. package/dist/http/api-client.cjs.map +1 -1
  136. package/dist/http/api-client.js +137 -116
  137. package/dist/http/api-client.js.map +1 -1
  138. package/dist/http/credential-scope.cjs +1 -1
  139. package/dist/http/credential-scope.cjs.map +1 -1
  140. package/dist/http/credential-scope.js +33 -9
  141. package/dist/http/credential-scope.js.map +1 -1
  142. package/dist/http/presigned-post.cjs.map +1 -1
  143. package/dist/http/presigned-post.js.map +1 -1
  144. package/dist/http/resumable-upload.cjs +1 -1
  145. package/dist/http/resumable-upload.cjs.map +1 -1
  146. package/dist/http/resumable-upload.js +140 -134
  147. package/dist/http/resumable-upload.js.map +1 -1
  148. package/dist/http/upload-with-progress.cjs +1 -1
  149. package/dist/http/upload-with-progress.cjs.map +1 -1
  150. package/dist/http/upload-with-progress.js +17 -17
  151. package/dist/http/upload-with-progress.js.map +1 -1
  152. package/dist/http/use-describe-api-error.cjs +1 -1
  153. package/dist/http/use-describe-api-error.cjs.map +1 -1
  154. package/dist/http/use-describe-api-error.js +9 -9
  155. package/dist/oauth/GoogleSignIn.cjs +1 -1
  156. package/dist/oauth/GoogleSignIn.cjs.map +1 -1
  157. package/dist/oauth/GoogleSignIn.js +5 -4
  158. package/dist/oauth/GoogleSignIn.js.map +1 -1
  159. package/dist/offline/create-offline-sync.cjs +1 -1
  160. package/dist/offline/create-offline-sync.cjs.map +1 -1
  161. package/dist/offline/create-offline-sync.js +108 -68
  162. package/dist/offline/create-offline-sync.js.map +1 -1
  163. package/dist/query/offline-persistence.cjs +1 -1
  164. package/dist/query/offline-persistence.cjs.map +1 -1
  165. package/dist/query/offline-persistence.js +54 -44
  166. package/dist/query/offline-persistence.js.map +1 -1
  167. package/dist/sse/create-event-stream.cjs +1 -1
  168. package/dist/sse/create-event-stream.cjs.map +1 -1
  169. package/dist/sse/create-event-stream.js +48 -41
  170. package/dist/sse/create-event-stream.js.map +1 -1
  171. package/dist/sse/ticket-event-stream.cjs +1 -1
  172. package/dist/sse/ticket-event-stream.cjs.map +1 -1
  173. package/dist/sse/ticket-event-stream.js +48 -19
  174. package/dist/sse/ticket-event-stream.js.map +1 -1
  175. package/dist/sse/use-event-stream.cjs +1 -1
  176. package/dist/sse/use-event-stream.cjs.map +1 -1
  177. package/dist/sse/use-event-stream.js +19 -14
  178. package/dist/sse/use-event-stream.js.map +1 -1
  179. package/dist/styles/AuthForm.css +2 -0
  180. package/dist/styles/AuthPage.css +2 -0
  181. package/dist/styles/component/AuthForm.css +9 -0
  182. package/dist/styles/component/AuthPage.css +29 -0
  183. package/dist/styles/forms.css +36 -0
  184. package/dist/styles/manifest.json +63 -0
  185. package/dist/styles.css +1 -1
  186. package/dist/sw/background-sync.cjs +1 -1
  187. package/dist/sw/background-sync.cjs.map +1 -1
  188. package/dist/sw/background-sync.js +132 -112
  189. package/dist/sw/background-sync.js.map +1 -1
  190. package/dist/sw/cache.cjs +1 -1
  191. package/dist/sw/cache.cjs.map +1 -1
  192. package/dist/sw/cache.js +36 -30
  193. package/dist/sw/cache.js.map +1 -1
  194. package/dist/sw/create-push-handler.cjs +1 -1
  195. package/dist/sw/create-push-handler.cjs.map +1 -1
  196. package/dist/sw/create-push-handler.js +20 -10
  197. package/dist/sw/create-push-handler.js.map +1 -1
  198. package/dist/sw.d.ts +93 -28
  199. package/dist/tabular/compact.cjs +1 -1
  200. package/dist/tabular/compact.cjs.map +1 -1
  201. package/dist/tabular/compact.js +35 -16
  202. package/dist/tabular/compact.js.map +1 -1
  203. package/dist/tabular/manifest.cjs +1 -1
  204. package/dist/tabular/manifest.cjs.map +1 -1
  205. package/dist/tabular/manifest.js +33 -15
  206. package/dist/tabular/manifest.js.map +1 -1
  207. package/dist/tabular.d.ts +11 -1
  208. package/dist/tempest-react-sdk.cjs +1 -1
  209. package/dist/tempest-react-sdk.d.ts +1057 -83
  210. package/dist/tempest-react-sdk.js +373 -365
  211. package/dist/theme/initial-theme.cjs +4 -4
  212. package/dist/theme/initial-theme.cjs.map +1 -1
  213. package/dist/theme/initial-theme.js +8 -5
  214. package/dist/theme/initial-theme.js.map +1 -1
  215. package/dist/utils/compressed-storage.cjs +1 -1
  216. package/dist/utils/compressed-storage.cjs.map +1 -1
  217. package/dist/utils/compressed-storage.js +13 -7
  218. package/dist/utils/compressed-storage.js.map +1 -1
  219. package/dist/utils/format.cjs +1 -1
  220. package/dist/utils/format.cjs.map +1 -1
  221. package/dist/utils/format.js +25 -25
  222. package/dist/utils/numbers.cjs +1 -1
  223. package/dist/utils/numbers.cjs.map +1 -1
  224. package/dist/utils/numbers.js +7 -7
  225. package/dist/utils/objects.cjs +1 -1
  226. package/dist/utils/objects.cjs.map +1 -1
  227. package/dist/utils/objects.js +13 -7
  228. package/dist/utils/objects.js.map +1 -1
  229. package/dist/utils/safe-url.cjs +1 -1
  230. package/dist/utils/safe-url.cjs.map +1 -1
  231. package/dist/utils/safe-url.js +4 -1
  232. package/dist/utils/safe-url.js.map +1 -1
  233. package/dist/webrtc/peer-mesh.cjs +1 -1
  234. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  235. package/dist/webrtc/peer-mesh.js +7 -1
  236. package/dist/webrtc/peer-mesh.js.map +1 -1
  237. package/dist/ws/create-web-socket.cjs +1 -1
  238. package/dist/ws/create-web-socket.cjs.map +1 -1
  239. package/dist/ws/create-web-socket.js +77 -61
  240. package/dist/ws/create-web-socket.js.map +1 -1
  241. package/dist/ws/use-web-socket.cjs +1 -1
  242. package/dist/ws/use-web-socket.cjs.map +1 -1
  243. package/dist/ws/use-web-socket.js +4 -3
  244. package/dist/ws/use-web-socket.js.map +1 -1
  245. package/package.json +1 -1
  246. package/template-pwa/src/pwa.tsx +42 -0
  247. package/template-pwa/src/sw.ts +15 -10
@@ -1,9 +1,9 @@
1
- import { randomId as e } from "../utils/ids.js";
2
- import { buildApiUrl as t } from "./build-url.js";
3
- import { isTrustedCredentialTarget as n, reportSuppressedCredential as r } from "./credential-scope.js";
4
- import { csrfHeaders as i } from "./csrf.js";
5
- import { decodeByContentType as a } from "./decode-response.js";
6
- import { SessionSupersededError as o, TempestApiError as s, buildApiError as c, isRetriableStatus as l } from "./errors.js";
1
+ import { SessionSupersededError as e, TempestApiError as t, buildApiError as n, isRetriableStatus as r } from "./errors.js";
2
+ import { randomId as i } from "../utils/ids.js";
3
+ import { buildApiUrl as a } from "./build-url.js";
4
+ import { isTrustedCredentialTarget as o, reportSuppressedCredential as s } from "./credential-scope.js";
5
+ import { csrfHeaders as c } from "./csrf.js";
6
+ import { decodeByContentType as l } from "./decode-response.js";
7
7
  import { retry as u } from "./retry.js";
8
8
  import { withTimeout as d } from "./timeout.js";
9
9
  //#region src/http/api-client.ts
@@ -12,188 +12,209 @@ var f = /* @__PURE__ */ new Set([
12
12
  "HEAD",
13
13
  "OPTIONS"
14
14
  ]);
15
- function p(e, t) {
16
- return !f.has(t) || !(e instanceof s) ? !1 : l(e.status);
15
+ function p(e, n) {
16
+ return !f.has(n) || !(e instanceof t) || e.code === h ? !1 : r(e.status);
17
17
  }
18
18
  function m(e) {
19
19
  return e ? e === !0 ? {} : e : null;
20
20
  }
21
- var h = 15e3, g = 3e5;
22
- function _(e) {
21
+ var h = "REDIRECT_REFUSED";
22
+ function g(e) {
23
+ return e.type === "opaqueredirect" || e.status >= 300 && e.status < 400 && e.status !== 304;
24
+ }
25
+ var _ = 15e3, v = 3e5;
26
+ function y(e) {
23
27
  return typeof FormData < "u" && e instanceof FormData;
24
28
  }
25
- function v(e) {
29
+ function b(e) {
26
30
  return Math.round(performance.now() - e);
27
31
  }
28
- async function y(e, t) {
29
- let n;
32
+ function x(e) {
33
+ return e.replace(/[?#][^]*/, "").replace(/^([^/]*\/\/)[^/]*@/, "$1");
34
+ }
35
+ async function S(e, r) {
36
+ let i;
30
37
  try {
31
- n = await e.clone().json();
38
+ i = await e.clone().json();
32
39
  } catch {
33
40
  try {
34
- n = await e.text();
41
+ i = await e.text();
35
42
  } catch {
36
- n = null;
43
+ i = null;
37
44
  }
38
45
  }
39
- return new s(c(e.status, n, e.headers, t));
46
+ return new t(n(e.status, i, e.headers, r));
40
47
  }
41
- function b(c) {
42
- let l = c.fetcher ?? globalThis.fetch.bind(globalThis);
43
- function f(e, t) {
44
- if (t) return {};
45
- let i = c.getToken?.();
46
- return i ? n(e, c.baseURL, c.trustedOrigins) ? { Authorization: `Bearer ${i}` } : (r(e, c.baseURL), {}) : {};
48
+ function C(n) {
49
+ let r = n.fetcher ?? globalThis.fetch.bind(globalThis);
50
+ function f(e, t, r) {
51
+ let i = r ? null : n.getToken?.();
52
+ if (!t) {
53
+ i && s(e, n.baseURL);
54
+ let t = Object.keys(n.headers ?? {});
55
+ return t.length > 0 && s(e, n.baseURL, t.join(", ")), {};
56
+ }
57
+ return {
58
+ ...n.headers,
59
+ ...i ? { Authorization: `Bearer ${i}` } : {}
60
+ };
47
61
  }
48
- async function b(e, n, r, a) {
49
- let { body: o, params: u, headers: p, signal: m, timeout: v, ...y } = n, b = _(o), x = b ? c.uploadTimeout : c.timeout, S = v === void 0 ? x === void 0 ? b ? g : h : x : v, C = t(c.baseURL, e, {
50
- prefix: c.prefix,
51
- params: u
52
- }), w = p, T = {
53
- ...b ? {} : { "Content-Type": "application/json" },
54
- ...r ? { "X-Request-ID": r } : {},
55
- ...c.headers,
56
- ...f(C, a),
57
- ...i({
58
- method: y.method ?? "GET",
59
- url: C,
60
- reference: c.baseURL,
61
- csrf: c.csrf,
62
- trustedOrigins: c.trustedOrigins,
62
+ async function C(e, i, a, o, s) {
63
+ let { body: l, headers: u, signal: p, timeout: m, ...b } = a, x = y(l), S = x ? n.uploadTimeout : n.timeout, C = m === void 0 ? S === void 0 ? x ? v : _ : S : m, w = u, T = {
64
+ ...x ? {} : { "Content-Type": "application/json" },
65
+ ...o ? { "X-Request-ID": o } : {},
66
+ ...f(e, i, s),
67
+ ...c({
68
+ method: b.method ?? "GET",
69
+ url: e,
70
+ reference: n.baseURL,
71
+ csrf: n.csrf,
72
+ trustedOrigins: n.trustedOrigins,
63
73
  headers: {
64
- ...c.headers,
74
+ ...n.headers,
65
75
  ...w
66
76
  }
67
77
  }),
68
78
  ...w
69
- }, E = d(m, S), D = {
70
- ...y,
71
- signal: E.signal,
79
+ }, E = i && b.redirect === void 0 && Object.keys(n.headers ?? {}).length > 0, D = d(p, C), O = {
80
+ ...b,
81
+ ...E ? { redirect: "manual" } : {},
82
+ signal: D.signal,
72
83
  headers: T,
73
- credentials: c.withCredentials ? "include" : y.credentials,
74
- body: o == null ? void 0 : b ? o : JSON.stringify(o)
75
- };
84
+ credentials: n.withCredentials ? "include" : b.credentials,
85
+ body: l == null ? void 0 : x ? l : JSON.stringify(l)
86
+ }, k;
76
87
  try {
77
- return await l(C, D);
88
+ k = await r(e, O);
78
89
  } catch (e) {
79
- throw E.timedOut() ? new s({
90
+ throw D.timedOut() ? new t({
80
91
  status: 0,
81
- detail: `A requisição excedeu ${S}ms e foi abandonada.`
92
+ detail: `A requisição excedeu ${C}ms e foi abandonada.`
82
93
  }) : e;
83
94
  } finally {
84
- E.dispose();
95
+ D.dispose();
85
96
  }
97
+ if (E && g(k)) throw new t({
98
+ status: k.status,
99
+ code: h,
100
+ requestId: o,
101
+ detail: "Redirect não seguido: a requisição levava os headers fixos do cliente."
102
+ });
103
+ return k;
86
104
  }
87
- async function x(e, t, n, r, i) {
88
- let a = c.logger;
89
- if (!a) return b(e, t, n, i);
90
- let o = performance.now();
105
+ async function w(e, t, r, i, a, o, s) {
106
+ let c = n.logger;
107
+ if (!c) return C(t, r, i, a, s);
108
+ let l = `${o} ${x(e)}`, u = performance.now();
91
109
  try {
92
- let s = await b(e, t, n, i), c = {
93
- requestId: n,
94
- status: s.status,
95
- ms: v(o)
96
- }, l = `${r} ${e} → ${s.status}`;
97
- return s.status >= 400 ? a.warn(l, c) : a.debug(l, c), s;
98
- } catch (t) {
99
- throw a.warn(`${r} ${e} → no response`, {
100
- requestId: n,
101
- ms: v(o),
102
- error: t
103
- }), t;
110
+ let e = await C(t, r, i, a, s), n = {
111
+ requestId: a,
112
+ status: e.status,
113
+ ms: b(u)
114
+ }, o = `${l} → ${e.status}`;
115
+ return e.status >= 400 ? c.warn(o, n) : c.debug(o, n), e;
116
+ } catch (e) {
117
+ throw c.warn(`${l} → no response`, {
118
+ requestId: a,
119
+ ms: b(u),
120
+ error: e
121
+ }), e;
104
122
  }
105
123
  }
106
- async function S(e, t, n) {
107
- if (c.onUnauthorized) {
108
- c.logger?.warn("unauthorized — calling onUnauthorized", {
109
- requestId: t,
110
- status: e.status
124
+ async function T(t, r, i) {
125
+ if (n.onUnauthorized) {
126
+ n.logger?.warn("unauthorized — calling onUnauthorized", {
127
+ requestId: r,
128
+ status: t.status
111
129
  });
112
130
  try {
113
- await c.onUnauthorized(e, n);
114
- } catch (n) {
115
- if (n instanceof o) throw n;
116
- c.logger?.warn("onUnauthorized threw — keeping the original response error", {
117
- requestId: t,
118
- status: e.status,
119
- error: n
131
+ await n.onUnauthorized(t, i);
132
+ } catch (i) {
133
+ if (i instanceof e) throw i;
134
+ n.logger?.warn("onUnauthorized threw — keeping the original response error", {
135
+ requestId: r,
136
+ status: t.status,
137
+ error: i
120
138
  });
121
139
  }
122
140
  }
123
141
  }
124
- function C(e) {
142
+ function E(e) {
125
143
  return {
126
- token: e ? null : c.getToken?.() ?? null,
127
- epoch: c.getSessionEpoch?.() ?? null
144
+ token: e ? null : n.getToken?.() ?? null,
145
+ epoch: n.getSessionEpoch?.() ?? null
128
146
  };
129
147
  }
130
- async function w(t, n, r) {
131
- let { skipAuth: i = !1, skipAuthRetry: a = !1, ...s } = n, l = c.requestId ? c.requestId() : e(), u = (s.method ?? "GET").toUpperCase(), d = C(i), f = await x(t, s, l, u, i);
132
- if (f.status === 401 && !i && !a) {
133
- if (c.refresh) {
134
- let e;
148
+ async function D(t, r, s) {
149
+ let { skipAuth: c = !1, skipAuthRetry: l = !1, params: u, ...d } = r, f = n.requestId ? n.requestId() : i(), p = (d.method ?? "GET").toUpperCase(), m = a(n.baseURL, t, {
150
+ prefix: n.prefix,
151
+ params: u
152
+ }), h = o(m, n.baseURL, n.trustedOrigins), g = E(c), _ = await w(t, m, h, d, f, p, c);
153
+ if (_.status === 401 && h && !c && !l) {
154
+ if (n.refresh) {
155
+ let r;
135
156
  try {
136
- await c.refresh(d), e = C(i), f = await x(t, s, l, u, i);
137
- } catch (e) {
138
- throw e instanceof o ? e : (await S(f, l, d), await y(f, l));
157
+ await n.refresh(g), r = E(c), _ = await w(t, m, h, d, f, p, c);
158
+ } catch (t) {
159
+ throw t instanceof e ? t : (await T(_, f, g), await S(_, f));
139
160
  }
140
- f.status === 401 && await S(f, l, e);
141
- } else await S(f, l, d);
161
+ _.status === 401 && await T(_, f, r);
162
+ } else await T(_, f, g);
142
163
  }
143
- if (!f.ok) throw await y(f, l);
144
- return r(f);
164
+ if (!_.ok) throw await S(_, f);
165
+ return s(_);
145
166
  }
146
- async function T(e, t, n) {
147
- let { retry: r, ...i } = t, a = m(r === void 0 ? c.retry : r);
148
- if (!a) return w(e, i, n);
149
- let o = (i.method ?? "GET").toUpperCase();
150
- return u(() => w(e, i, n), {
151
- ...a,
152
- shouldRetry: a.shouldRetry ?? ((e) => p(e, o))
167
+ async function O(e, t, r) {
168
+ let { retry: i, ...a } = t, o = m(i === void 0 ? n.retry : i);
169
+ if (!o) return D(e, a, r);
170
+ let s = (a.method ?? "GET").toUpperCase();
171
+ return u(() => D(e, a, r), {
172
+ ...o,
173
+ shouldRetry: o.shouldRetry ?? ((e) => p(e, s))
153
174
  });
154
175
  }
155
- async function E(e, t = {}) {
156
- return T(e, t, a);
176
+ async function k(e, t = {}) {
177
+ return O(e, t, l);
157
178
  }
158
- async function D(e, t, n = "POST", r) {
159
- return E(e, {
179
+ async function A(e, t, n = "POST", r) {
180
+ return k(e, {
160
181
  ...r,
161
182
  method: n,
162
183
  body: t
163
184
  });
164
185
  }
165
186
  return {
166
- request: E,
167
- get: (e, t) => E(e, {
187
+ request: k,
188
+ get: (e, t) => k(e, {
168
189
  ...t,
169
190
  method: "GET"
170
191
  }),
171
- post: (e, t) => E(e, {
192
+ post: (e, t) => k(e, {
172
193
  ...t,
173
194
  method: "POST"
174
195
  }),
175
- put: (e, t) => E(e, {
196
+ put: (e, t) => k(e, {
176
197
  ...t,
177
198
  method: "PUT"
178
199
  }),
179
- patch: (e, t) => E(e, {
200
+ patch: (e, t) => k(e, {
180
201
  ...t,
181
202
  method: "PATCH"
182
203
  }),
183
- delete: (e, t) => E(e, {
204
+ delete: (e, t) => k(e, {
184
205
  ...t,
185
206
  method: "DELETE"
186
207
  }),
187
- blob: (e, t) => T(e, { ...t }, (e) => e.blob()),
188
- arrayBuffer: (e, t) => T(e, { ...t }, (e) => e.arrayBuffer()),
189
- upload: D,
190
- url: (e, n) => t(c.baseURL, e, {
191
- prefix: c.prefix,
192
- params: n
208
+ blob: (e, t) => O(e, { ...t }, (e) => e.blob()),
209
+ arrayBuffer: (e, t) => O(e, { ...t }, (e) => e.arrayBuffer()),
210
+ upload: A,
211
+ url: (e, t) => a(n.baseURL, e, {
212
+ prefix: n.prefix,
213
+ params: t
193
214
  })
194
215
  };
195
216
  }
196
217
  //#endregion
197
- export { b as createApiClient };
218
+ export { C as createApiClient };
198
219
 
199
220
  //# sourceMappingURL=api-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.js","names":["retryWithBackoff","IDEMPOTENT_METHODS","isRetriableFailure","method","error","TempestApiError","isRetriableStatus","resolveRetry","config","DEFAULT_TIMEOUT","DEFAULT_UPLOAD_TIMEOUT","isFormData","body","elapsedMs","startedAt","parseError","response","buildApiError","sentRequestId","createApiClient","fetcher","authHeaders","skipAuth","token","isTrustedCredentialTarget","url","reportSuppressedCredential","rawRequest","rest","options","isForm","configured","limit","timeout","buildApiUrl","path","callerHeaders","headers","finalHeaders","requestId","csrfHeaders","timed","withTimeout","signal","init","cause","send","log","entry","line","notifyUnauthorized","context","SessionSupersededError","authContext","attempt","randomId","sent","skipAuthRetry","replayed","decode","run","perRequest","retryOptions","retry","request","decodeByContentType","upload","formData"],"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 {\n buildApiError,\n SessionSupersededError,\n TempestApiError,\n isRetriableStatus,\n} from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestAuthContext, 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 /**\n * Call `onUnauthorized`, keeping the request's own error unless the hook\n * says the attempt belongs to an ended session.\n *\n * @param response - The `401` that ended the attempt.\n * @param requestId - Correlation id for the log.\n * @param context - The credential and session the attempt left with.\n * @throws {SessionSupersededError} When `onUnauthorized` threw it.\n */\n async function notifyUnauthorized(\n response: Response,\n requestId: string,\n context: RequestAuthContext,\n ): 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, context);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw 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 /**\n * The credential and session an attempt leaves with, read just before it is\n * sent.\n *\n * @param skipAuth - Whether the attempt goes out without credentials.\n * @returns The context handed to `refresh` and `onUnauthorized`.\n */\n function authContext(skipAuth: boolean): RequestAuthContext {\n return {\n token: skipAuth ? null : (config.getToken?.() ?? null),\n epoch: config.getSessionEpoch?.() ?? null,\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 const sent = authContext(skipAuth);\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n let replayed: RequestAuthContext;\n try {\n await config.refresh(sent);\n replayed = authContext(skipAuth);\n response = await send(path, init, requestId, method, skipAuth);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw error;\n await notifyUnauthorized(response, requestId, sent);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId, replayed);\n }\n } else {\n await notifyUnauthorized(response, requestId, sent);\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 url: (path: string, params?: RequestOptions[\"params\"]) =>\n buildApiUrl(config.baseURL, path, { prefix: config.prefix, params }),\n };\n}\n"],"mappings":";;;;;;;;;AA8BA,IAAMC,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAASC,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAACD,EAAmB,IAAIE,CAAM,KAC9B,EAAEC,aAAiBC,KAAyB,KACzCC,EAAkBF,EAAM,MAAM;AACzC;AAQA,SAASG,EAAa,GAAiE;CAEnF,OADKC,IACEA,MAAW,KAAO,CAAC,IAAIA,IADV;AAExB;AAGA,IAAMC,IAAkB,MAGlBC,IAAyB;AAE/B,SAASC,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAeC,aAAgB;AAC9D;AAaA,SAASC,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAIC,CAAS;AACnD;AAEA,eAAeC,EAAW,GAAoB,GAAkD;CAC5F,IAAIH;CACJ,IAAI;EACA,IAAO,MAAMI,EAAS,MAAM,CAAC,CAAC,KAAK;CACvC,QAAQ;EACJ,IAAI;GACA,IAAO,MAAMA,EAAS,KAAK;EAC/B,QAAQ;GACJ,IAAO;EACX;CACJ;CACA,OAAO,IAAIX,EACPY,EAAcD,EAAS,QAAQJ,GAAMI,EAAS,SAASE,CAAa,CACxE;AACJ;AA0DA,SAAgBC,EAAgB,GAAoC;CAChE,IAAMC,IAAUZ,EAAO,WAAW,WAAW,MAAM,KAAK,UAAU;CAalE,SAASa,EAAY,GAAa,GAA2C;EACzE,IAAIC,GAAU,OAAO,CAAC;EACtB,IAAMC,IAAQf,EAAO,WAAW;EAMhC,OALKe,IACAC,EAA0BC,GAAKjB,EAAO,SAASA,EAAO,cAAc,IAIlE,EAAE,eAAe,UAAUe,IAAQ,KAHtCG,EAA2BD,GAAKjB,EAAO,OAAO,GACvC,CAAC,KAHO,CAAC;CA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eC,EACX,GACA,GACA,IAAmC,QACnC,GACU;EACV,OAAOF,EAAW7B,GAAM;GAAE,GAAGN;GAAS;GAAQ,MAAMsC;EAAS,CAAC;CAClE;CAEA,OAAO;EACH;EACA,MAAS,GAAc,MACnBH,EAAW7B,GAAM;GAAE,GAAGN;GAAS,QAAQ;EAAM,CAAC;EAClD,OAAU,GAAc,MACpBmC,EAAW7B,GAAM;GAAE,GAAGN;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnBmC,EAAW7B,GAAM;GAAE,GAAGN;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrBmC,EAAW7B,GAAM;GAAE,GAAGN;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtBmC,EAAW7B,GAAM;GAAE,GAAGN;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjB+B,EAAUzB,GAAM,EAAE,GAAGN,EAAQ,IAAI,MAAab,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxB4C,EAAiBzB,GAAM,EAAE,GAAGN,EAAQ,IAAI,MAAab,EAAS,YAAY,CAAC;EAC/E;EACA,MAAM,GAAc,MAChBkB,EAAY1B,EAAO,SAAS2B,GAAM;GAAE,QAAQ3B,EAAO;GAAQ;EAAO,CAAC;CAC3E;AACJ"}
1
+ {"version":3,"file":"api-client.js","names":["retryWithBackoff","IDEMPOTENT_METHODS","isRetriableFailure","method","error","TempestApiError","REDIRECT_REFUSED","isRetriableStatus","resolveRetry","config","isStoppedRedirect","response","DEFAULT_TIMEOUT","DEFAULT_UPLOAD_TIMEOUT","isFormData","body","elapsedMs","startedAt","pathForLog","path","parseError","buildApiError","sentRequestId","createApiClient","fetcher","scopedHeaders","token","skipAuth","inScope","reportSuppressedCredential","url","names","rawRequest","rest","options","isForm","configured","limit","timeout","callerHeaders","headers","finalHeaders","requestId","csrfHeaders","holdRedirects","timed","withTimeout","signal","init","cause","send","log","target","entry","line","notifyUnauthorized","context","SessionSupersededError","authContext","attempt","randomId","buildApiUrl","isTrustedCredentialTarget","sent","skipAuthRetry","replayed","decode","run","perRequest","retryOptions","retry","request","decodeByContentType","upload","formData"],"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 {\n buildApiError,\n SessionSupersededError,\n TempestApiError,\n isRetriableStatus,\n} from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestAuthContext, 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 if (error.code === REDIRECT_REFUSED) 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/**\n * The `code` of the {@link TempestApiError} thrown when a request carrying the\n * client's static `headers` is answered with a redirect.\n *\n * Kept out of the built-in retry policy: the status is `0` in a browser, which\n * would otherwise read as a network failure, and replaying gets the same\n * redirect back.\n */\nconst REDIRECT_REFUSED = \"REDIRECT_REFUSED\";\n\n/**\n * Whether `response` is a redirect that `redirect: \"manual\"` stopped.\n *\n * Two shapes, measured: a browser hands back an `opaqueredirect` with status\n * `0` and no readable headers (Chrome 150, #554); a server runtime such as\n * Node's `fetch` hands back the real `3xx` with its `Location`. `304` is a\n * cache answer, not a redirect.\n *\n * @param response - What the fetcher resolved with.\n * @returns Whether the request was redirected and not followed.\n */\nfunction isStoppedRedirect(response: Response): boolean {\n if (response.type === \"opaqueredirect\") return true;\n return response.status >= 300 && response.status < 400 && response.status !== 304;\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\n/**\n * The request path as the log line shows it: no query, no fragment, no userinfo.\n *\n * The logger promises never to write the query string, and `params` was never\n * the only way one gets in: a call site can write `\"/files?access_token=…\"`\n * inline, and an absolute path — the signed upload endpoint or CDN URL that\n * `buildApiUrl` passes through untouched — carries its signature in the query\n * and may carry `user:password@` in the authority. Everything from the first\n * `?` or `#` is dropped and the userinfo of an absolute (or scheme-relative)\n * URL is removed; the host and the path stay, because they are what makes the\n * line useful. Pure string work, no `URL` round trip, so a path that would not\n * parse is still logged instead of throwing inside the logging branch.\n *\n * @param path - The path exactly as the call site passed it.\n * @returns The path without query, fragment or credentials.\n */\nfunction pathForLog(path: string): string {\n return path.replace(/[?#][^]*/, \"\").replace(/^([^/]*\\/\\/)[^/]*@/, \"$1\");\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}. Since 0.82.0 the static\n * {@link ApiClientConfig.headers} follow the same scope, and a `401` from\n * outside it is thrown without `refresh` or `onUnauthorized` — it answered a\n * request that never carried this session's credential.\n *\n * **Redirects.** The scope is checked against the URL the request starts at;\n * where a redirect then goes is the transport's call. For `Authorization` that\n * is safe: browsers strip it on a cross-origin redirect, measured in Chrome 150\n * for `fetch` and XHR on `301`/`302`/`303`/`307`/`308` (#554). They strip\n * nothing else, so a request carrying the static {@link ApiClientConfig.headers}\n * goes out with `redirect: \"manual\"`, and a redirect answering it is thrown as a\n * {@link TempestApiError} with `code: \"REDIRECT_REFUSED\"` instead of being\n * followed. It cannot be followed by hand: a browser's manual redirect is an\n * opaque response whose `Location` is unreadable. A `redirect` set on the call\n * always wins.\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 headers that belong to the client's credential scope — the static\n * `config.headers` and the `Authorization` header — 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. Static headers ride\n * with the token since 0.82.0: an `X-Api-Key` set once on the client is as\n * much a credential as the bearer (#530).\n *\n * @param url - The absolute URL the request is going to.\n * @param inScope - Whether `url` is inside the credential scope.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The headers, or an empty object.\n */\n function scopedHeaders(\n url: string,\n inScope: boolean,\n skipAuth: boolean,\n ): Record<string, string> {\n const token = skipAuth ? null : config.getToken?.();\n if (!inScope) {\n if (token) reportSuppressedCredential(url, config.baseURL);\n const names = Object.keys(config.headers ?? {});\n if (names.length > 0) reportSuppressedCredential(url, config.baseURL, names.join(\", \"));\n return {};\n }\n return { ...config.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}) };\n }\n\n async function rawRequest(\n url: string,\n inScope: boolean,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, 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 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 ...scopedHeaders(url, inScope, 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 holdRedirects =\n inScope && rest.redirect === undefined && Object.keys(config.headers ?? {}).length > 0;\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n ...(holdRedirects ? { redirect: \"manual\" as const } : {}),\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 let response: Response;\n try {\n response = 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 if (holdRedirects && isStoppedRedirect(response)) {\n throw new TempestApiError({\n status: response.status,\n code: REDIRECT_REFUSED,\n requestId,\n detail: \"Redirect não seguido: a requisição levava os headers fixos do cliente.\",\n });\n }\n return response;\n }\n\n async function send(\n path: string,\n url: string,\n inScope: boolean,\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(url, inScope, options, requestId, skipAuth);\n\n const target = `${method} ${pathForLog(path)}`;\n const startedAt = performance.now();\n try {\n const response = await rawRequest(url, inScope, options, requestId, skipAuth);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${target} → ${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(`${target} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n /**\n * Call `onUnauthorized`, keeping the request's own error unless the hook\n * says the attempt belongs to an ended session.\n *\n * @param response - The `401` that ended the attempt.\n * @param requestId - Correlation id for the log.\n * @param context - The credential and session the attempt left with.\n * @throws {SessionSupersededError} When `onUnauthorized` threw it.\n */\n async function notifyUnauthorized(\n response: Response,\n requestId: string,\n context: RequestAuthContext,\n ): 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, context);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw 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 /**\n * The credential and session an attempt leaves with, read just before it is\n * sent.\n *\n * @param skipAuth - Whether the attempt goes out without credentials.\n * @returns The context handed to `refresh` and `onUnauthorized`.\n */\n function authContext(skipAuth: boolean): RequestAuthContext {\n return {\n token: skipAuth ? null : (config.getToken?.() ?? null),\n epoch: config.getSessionEpoch?.() ?? null,\n };\n }\n\n /**\n * One request, with the `401` refresh-and-replay around it.\n *\n * The refresh path runs only for a target inside the credential scope. A\n * `401` from any other origin answers a request that never carried this\n * session's credential, so it says nothing about the session; until 0.82.0\n * it still drove `refresh()` and `onUnauthorized()`, so a foreign host could\n * spend a refresh and end the user's session (#530).\n *\n * @param path - The path as the call site wrote it.\n * @param options - Request options, policy fields included.\n * @param decode - How to turn the response into a value.\n * @returns The decoded value.\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, params, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n const inScope = isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins);\n const sent = authContext(skipAuth);\n let response = await send(path, url, inScope, init, requestId, method, skipAuth);\n\n if (response.status === 401 && inScope && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n let replayed: RequestAuthContext;\n try {\n await config.refresh(sent);\n replayed = authContext(skipAuth);\n response = await send(path, url, inScope, init, requestId, method, skipAuth);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw error;\n await notifyUnauthorized(response, requestId, sent);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId, replayed);\n }\n } else {\n await notifyUnauthorized(response, requestId, sent);\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 url: (path: string, params?: RequestOptions[\"params\"]) =>\n buildApiUrl(config.baseURL, path, { prefix: config.prefix, params }),\n };\n}\n"],"mappings":";;;;;;;;;AA8BA,IAAMC,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAASC,EAAmB,GAAgB,GAAyB;CAIjE,OAHI,CAACD,EAAmB,IAAIE,CAAM,KAC9B,EAAEC,aAAiBC,MACnBD,EAAM,SAASE,IAAyB,KACrCC,EAAkBH,EAAM,MAAM;AACzC;AAQA,SAASI,EAAa,GAAiE;CAEnF,OADKC,IACEA,MAAW,KAAO,CAAC,IAAIA,IADV;AAExB;AAUA,IAAMH,IAAmB;AAazB,SAASI,EAAkB,GAA6B;CAEpD,OADIC,EAAS,SAAS,oBACfA,EAAS,UAAU,OAAOA,EAAS,SAAS,OAAOA,EAAS,WAAW;AAClF;AAGA,IAAMC,IAAkB,MAGlBC,IAAyB;AAE/B,SAASC,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAeC,aAAgB;AAC9D;AAaA,SAASC,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAIC,CAAS;AACnD;AAkBA,SAASC,EAAW,GAAsB;CACtC,OAAOC,EAAK,QAAQ,YAAY,EAAE,CAAC,CAAC,QAAQ,sBAAsB,IAAI;AAC1E;AAEA,eAAeC,EAAW,GAAoB,GAAkD;CAC5F,IAAIL;CACJ,IAAI;EACA,IAAO,MAAMJ,EAAS,MAAM,CAAC,CAAC,KAAK;CACvC,QAAQ;EACJ,IAAI;GACA,IAAO,MAAMA,EAAS,KAAK;EAC/B,QAAQ;GACJ,IAAO;EACX;CACJ;CACA,OAAO,IAAIN,EACPgB,EAAcV,EAAS,QAAQI,GAAMJ,EAAS,SAASW,CAAa,CACxE;AACJ;AAwEA,SAAgBC,EAAgB,GAAoC;CAChE,IAAMC,IAAUf,EAAO,WAAW,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QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrBqC,EAAWpD,GAAM;GAAE,GAAGe;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtBqC,EAAWpD,GAAM;GAAE,GAAGe;GAAS,QAAQ;EAAS,CAAC;EACrD,OAAO,GAAc,MACjBiC,EAAUhD,GAAM,EAAE,GAAGe,EAAQ,IAAI,MAAavB,EAAS,KAAK,CAAC;EACjE,cAAc,GAAc,MACxBwD,EAAiBhD,GAAM,EAAE,GAAGe,EAAQ,IAAI,MAAavB,EAAS,YAAY,CAAC;EAC/E;EACA,MAAM,GAAc,MAChBkD,EAAYpD,EAAO,SAASU,GAAM;GAAE,QAAQV,EAAO;GAAQ;EAAO,CAAC;CAC3E;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,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;
1
+ const e=require("../utils/dev-mode.cjs");var t=new Set,n=`http://relative.invalid`;function r(e){try{return new URL(e,globalThis.location?.href).origin}catch{return null}}function i(e){let t=globalThis.document?.baseURI??globalThis.location?.href;if(t!==void 0)try{return new URL(e,t).origin}catch{return`invalid`}try{return new URL(e).origin}catch{try{return new URL(e,n),`relative`}catch{return`invalid`}}}function a(e){try{return new URL(e,globalThis.document?.baseURI??globalThis.location?.href).href}catch{return null}}function o(e,t,n=[]){let a=i(e);return a===`relative`?!0:a===`invalid`||a===`null`?!1:a===r(t)||n.some(e=>r(e)===a)}function s(n,i,a=`Authorization`){if(!e.isDevBuild())return;let o=r(n);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 ${r(i)??i}. Add the origin to trustedOrigins if it should receive the token.`))}exports.isTrustedCredentialTarget=o,exports.reportSuppressedCredential=s,exports.resolveRequestUrl=a;
2
2
  //# sourceMappingURL=credential-scope.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"credential-scope.cjs","names":["isDevBuild","require_dev_mode","reported","originOf","url","isTrustedCredentialTarget","targetOrigin","target","reference","trustedOrigins","origin","reportSuppressedCredential","key","header"],"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":"A,yCAMA,IAAME,EAAW,IAAI,IAkBrB,SAASC,EAAS,EAA4B,CAC1C,GAAI,CACA,OAAO,IAAI,IAAIC,EAAK,WAAW,UAAU,IAAI,CAAC,CAAC,MACnD,MAAQ,CACJ,OAAO,IACX,CACJ,CAoCA,SAAgBC,EACZ,EACA,EACA,EAAoC,CAAC,EAC9B,CACP,IAAMC,EAAeH,EAASI,CAAM,EAGpC,OAFID,IAAiB,MACjBA,IAAiBH,EAASK,CAAS,GAChCC,EAAe,KAAM,GAAWN,EAASO,CAAM,IAAMJ,CAAY,CAC5E,CAkBA,SAAgBK,EACZ,EACA,EACA,EAAS,gBACL,CACJ,GAAI,CAACX,EAAAA,WAAW,EAAG,OACnB,IAAMM,EAAeH,EAASI,CAAM,EACpC,GAAID,IAAiB,KAAM,OAC3B,IAAMM,EAAM,GAAGC,EAAO,GAAGP,IACrBJ,EAAS,IAAIU,CAAG,IACpBV,EAAS,IAAIU,CAAG,EAChB,QAAQ,KACJ,uBAAuBC,EAAO,mBAAmBP,EAAa,gCAAgCH,EAASK,CAAS,GAAKA,EAAU,mEACnI,EACJ,C"}
1
+ {"version":3,"file":"credential-scope.cjs","names":["isDevBuild","require_dev_mode","reported","DETACHED_BASE","originOf","url","targetOriginOf","base","target","resolveRequestUrl","isTrustedCredentialTarget","targetOrigin","reference","trustedOrigins","origin","reportSuppressedCredential","key","header"],"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 * A base no real request resolves against, used only to tell a relative\n * reference from one that does not parse when there is no document at all.\n */\nconst DETACHED_BASE = \"http://relative.invalid\";\n\n/**\n * The origin a credential reference names, or `null` when it has none.\n *\n * A reference — `baseURL`, `endpoint`, `credentialOrigin`, a trusted origin —\n * is the trust anchor, so a relative one resolves against the page's own\n * address (`location.href`), never against a `<base href>`: an injected\n * `<base>` must not be able to move the anchor onto its own host.\n *\n * Relative references are the shape you get behind a dev-server or a reverse\n * proxy, and they name the page's own origin. Comparing a resolved absolute\n * target against an unresolved relative reference is how the first draft of\n * this function withheld the credential from every client configured that way.\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 * Where a request to `target` actually goes, as the transport resolves it.\n *\n * `XMLHttpRequest.open()` and `fetch()` resolve a relative URL against the\n * document's base URL (`document.baseURI`), which a `<base href>` changes and\n * `location.href` does not. Until 0.82.0 the target was resolved against the\n * page's address, so under an injected `<base>` a relative `url` and a relative\n * `credentialOrigin` compared equal while the request went to the `<base>` host\n * with the token (#530). A worker has no document; its base is its location.\n *\n * Three answers, because the caller treats them differently:\n *\n * - an origin — compare it;\n * - `\"relative\"` — a relative target with nothing to resolve it against\n * (outside any browsing context): there is no origin for it to cross;\n * - `\"invalid\"` — a target that does not parse. Refused: the check used to\n * fail open here, so a custom `fetcher` that accepts such a string received\n * the credential (#530).\n *\n * An opaque origin (`data:`, `file:`) comes back as the string `\"null\"`, which\n * the caller also refuses: two opaque origins are never the same origin, yet\n * `\"null\" === \"null\"`.\n *\n * @param target - The URL the request is about to go to.\n * @returns The origin, `\"relative\"` or `\"invalid\"`.\n */\nfunction targetOriginOf(target: string): string {\n const base = globalThis.document?.baseURI ?? globalThis.location?.href;\n if (base !== undefined) {\n try {\n return new URL(target, base).origin;\n } catch {\n return \"invalid\";\n }\n }\n try {\n return new URL(target).origin;\n } catch {\n try {\n new URL(target, DETACHED_BASE);\n return \"relative\";\n } catch {\n return \"invalid\";\n }\n }\n}\n\n/**\n * Resolve a URL the way the transport will, against the document base URL.\n *\n * Exported for the resumable upload, which has to resolve a relative tus\n * `Location` against the creation endpoint as the request actually went out.\n *\n * @param url - Absolute or relative URL.\n * @returns The absolute URL, or `null` when it does not resolve.\n */\nexport function resolveRequestUrl(url: string): string | null {\n try {\n return new URL(url, globalThis.document?.baseURI ?? globalThis.location?.href).href;\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 first, so a relative `baseURL` or `endpoint` — the\n * shape behind a dev-server or reverse proxy — compares equal to the absolute\n * URL the request actually goes to. The target resolves against the document\n * base URL, where the transport sends it; the reference against the page's\n * own address, which a `<base href>` cannot move. Outside a browsing context a\n * relative target is allowed — there is no origin for it to cross — and a\n * target that does not parse is refused rather than trusted.\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 = targetOriginOf(target);\n if (targetOrigin === \"relative\") return true;\n if (targetOrigin === \"invalid\" || targetOrigin === \"null\") return false;\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":"A,yCAMA,IAAME,EAAW,IAAI,IAMfC,EAAgB,0BAkBtB,SAASC,EAAS,EAA4B,CAC1C,GAAI,CACA,OAAO,IAAI,IAAIC,EAAK,WAAW,UAAU,IAAI,CAAC,CAAC,MACnD,MAAQ,CACJ,OAAO,IACX,CACJ,CA4BA,SAASC,EAAe,EAAwB,CAC5C,IAAMC,EAAO,WAAW,UAAU,SAAW,WAAW,UAAU,KAClE,GAAIA,IAAS,IAAA,GACT,GAAI,CACA,OAAO,IAAI,IAAIC,EAAQD,CAAI,CAAC,CAAC,MACjC,MAAQ,CACJ,MAAO,SACX,CAEJ,GAAI,CACA,OAAO,IAAI,IAAIC,CAAM,CAAC,CAAC,MAC3B,MAAQ,CACJ,GAAI,CAEA,OADA,IAAI,IAAIA,EAAQL,CAAa,EACtB,UACX,MAAQ,CACJ,MAAO,SACX,CACJ,CACJ,CAWA,SAAgBM,EAAkB,EAA4B,CAC1D,GAAI,CACA,OAAO,IAAI,IAAIJ,EAAK,WAAW,UAAU,SAAW,WAAW,UAAU,IAAI,CAAC,CAAC,IACnF,MAAQ,CACJ,OAAO,IACX,CACJ,CAsCA,SAAgBK,EACZ,EACA,EACA,EAAoC,CAAC,EAC9B,CACP,IAAMC,EAAeL,EAAeE,CAAM,EAI1C,OAHIG,IAAiB,WAAmB,GACpCA,IAAiB,WAAaA,IAAiB,OAAe,GAC9DA,IAAiBP,EAASQ,CAAS,GAChCC,EAAe,KAAM,GAAWT,EAASU,CAAM,IAAMH,CAAY,CAC5E,CAkBA,SAAgBI,EACZ,EACA,EACA,EAAS,gBACL,CACJ,GAAI,CAACf,EAAAA,WAAW,EAAG,OACnB,IAAMW,EAAeP,EAASI,CAAM,EACpC,GAAIG,IAAiB,KAAM,OAC3B,IAAMK,EAAM,GAAGC,EAAO,GAAGN,IACrBT,EAAS,IAAIc,CAAG,IACpBd,EAAS,IAAIc,CAAG,EAChB,QAAQ,KACJ,uBAAuBC,EAAO,mBAAmBN,EAAa,gCAAgCP,EAASQ,CAAS,GAAKA,EAAU,mEACnI,EACJ,C"}
@@ -1,25 +1,49 @@
1
1
  import { isDevBuild as e } from "../utils/dev-mode.js";
2
2
  //#region src/http/credential-scope.ts
3
- var t = /* @__PURE__ */ new Set();
4
- function n(e) {
3
+ var t = /* @__PURE__ */ new Set(), n = "http://relative.invalid";
4
+ function r(e) {
5
5
  try {
6
6
  return new URL(e, globalThis.location?.href).origin;
7
7
  } catch {
8
8
  return null;
9
9
  }
10
10
  }
11
- function r(e, t, r = []) {
12
- let i = n(e);
13
- return i === null || i === n(t) || r.some((e) => n(e) === i);
11
+ function i(e) {
12
+ let t = globalThis.document?.baseURI ?? globalThis.location?.href;
13
+ if (t !== void 0) try {
14
+ return new URL(e, t).origin;
15
+ } catch {
16
+ return "invalid";
17
+ }
18
+ try {
19
+ return new URL(e).origin;
20
+ } catch {
21
+ try {
22
+ return new URL(e, n), "relative";
23
+ } catch {
24
+ return "invalid";
25
+ }
26
+ }
27
+ }
28
+ function a(e) {
29
+ try {
30
+ return new URL(e, globalThis.document?.baseURI ?? globalThis.location?.href).href;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ function o(e, t, n = []) {
36
+ let a = i(e);
37
+ return a === "relative" ? !0 : a === "invalid" || a === "null" ? !1 : a === r(t) || n.some((e) => r(e) === a);
14
38
  }
15
- function i(r, i, a = "Authorization") {
39
+ function s(n, i, a = "Authorization") {
16
40
  if (!e()) return;
17
- let o = n(r);
41
+ let o = r(n);
18
42
  if (o === null) return;
19
43
  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.`));
44
+ t.has(s) || (t.add(s), console.warn(`[tempest-react-sdk] ${a} was not sent to ${o}: the credential is scoped to ${r(i) ?? i}. Add the origin to trustedOrigins if it should receive the token.`));
21
45
  }
22
46
  //#endregion
23
- export { r as isTrustedCredentialTarget, i as reportSuppressedCredential };
47
+ export { o as isTrustedCredentialTarget, s as reportSuppressedCredential, a as resolveRequestUrl };
24
48
 
25
49
  //# sourceMappingURL=credential-scope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"credential-scope.js","names":["reported","originOf","url","isTrustedCredentialTarget","targetOrigin","target","reference","trustedOrigins","origin","reportSuppressedCredential","isDevBuild","key","header"],"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,IAAMA,oBAAW,IAAI,IAAY;AAkBjC,SAASC,EAAS,GAA4B;CAC1C,IAAI;EACA,OAAO,IAAI,IAAIC,GAAK,WAAW,UAAU,IAAI,CAAC,CAAC;CACnD,QAAQ;EACJ,OAAO;CACX;AACJ;AAoCA,SAAgBC,EACZ,GACA,GACA,IAAoC,CAAC,GAC9B;CACP,IAAMC,IAAeH,EAASI,CAAM;CAGpC,OAFID,MAAiB,QACjBA,MAAiBH,EAASK,CAAS,KAChCC,EAAe,MAAM,MAAWN,EAASO,CAAM,MAAMJ,CAAY;AAC5E;AAkBA,SAAgBK,EACZ,GACA,GACA,IAAS,iBACL;CACJ,IAAI,CAACC,EAAW,GAAG;CACnB,IAAMN,IAAeH,EAASI,CAAM;CACpC,IAAID,MAAiB,MAAM;CAC3B,IAAMO,IAAM,GAAGC,EAAO,GAAGR;CACzB,AAAIJ,EAAS,IAAIW,CAAG,MACpBX,EAAS,IAAIW,CAAG,GAChB,QAAQ,KACJ,uBAAuBC,EAAO,mBAAmBR,EAAa,gCAAgCH,EAASK,CAAS,KAAKA,EAAU,mEACnI;AACJ"}
1
+ {"version":3,"file":"credential-scope.js","names":["reported","DETACHED_BASE","originOf","url","targetOriginOf","base","target","resolveRequestUrl","isTrustedCredentialTarget","targetOrigin","reference","trustedOrigins","origin","reportSuppressedCredential","isDevBuild","key","header"],"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 * A base no real request resolves against, used only to tell a relative\n * reference from one that does not parse when there is no document at all.\n */\nconst DETACHED_BASE = \"http://relative.invalid\";\n\n/**\n * The origin a credential reference names, or `null` when it has none.\n *\n * A reference — `baseURL`, `endpoint`, `credentialOrigin`, a trusted origin —\n * is the trust anchor, so a relative one resolves against the page's own\n * address (`location.href`), never against a `<base href>`: an injected\n * `<base>` must not be able to move the anchor onto its own host.\n *\n * Relative references are the shape you get behind a dev-server or a reverse\n * proxy, and they name the page's own origin. Comparing a resolved absolute\n * target against an unresolved relative reference is how the first draft of\n * this function withheld the credential from every client configured that way.\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 * Where a request to `target` actually goes, as the transport resolves it.\n *\n * `XMLHttpRequest.open()` and `fetch()` resolve a relative URL against the\n * document's base URL (`document.baseURI`), which a `<base href>` changes and\n * `location.href` does not. Until 0.82.0 the target was resolved against the\n * page's address, so under an injected `<base>` a relative `url` and a relative\n * `credentialOrigin` compared equal while the request went to the `<base>` host\n * with the token (#530). A worker has no document; its base is its location.\n *\n * Three answers, because the caller treats them differently:\n *\n * - an origin — compare it;\n * - `\"relative\"` — a relative target with nothing to resolve it against\n * (outside any browsing context): there is no origin for it to cross;\n * - `\"invalid\"` — a target that does not parse. Refused: the check used to\n * fail open here, so a custom `fetcher` that accepts such a string received\n * the credential (#530).\n *\n * An opaque origin (`data:`, `file:`) comes back as the string `\"null\"`, which\n * the caller also refuses: two opaque origins are never the same origin, yet\n * `\"null\" === \"null\"`.\n *\n * @param target - The URL the request is about to go to.\n * @returns The origin, `\"relative\"` or `\"invalid\"`.\n */\nfunction targetOriginOf(target: string): string {\n const base = globalThis.document?.baseURI ?? globalThis.location?.href;\n if (base !== undefined) {\n try {\n return new URL(target, base).origin;\n } catch {\n return \"invalid\";\n }\n }\n try {\n return new URL(target).origin;\n } catch {\n try {\n new URL(target, DETACHED_BASE);\n return \"relative\";\n } catch {\n return \"invalid\";\n }\n }\n}\n\n/**\n * Resolve a URL the way the transport will, against the document base URL.\n *\n * Exported for the resumable upload, which has to resolve a relative tus\n * `Location` against the creation endpoint as the request actually went out.\n *\n * @param url - Absolute or relative URL.\n * @returns The absolute URL, or `null` when it does not resolve.\n */\nexport function resolveRequestUrl(url: string): string | null {\n try {\n return new URL(url, globalThis.document?.baseURI ?? globalThis.location?.href).href;\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 first, so a relative `baseURL` or `endpoint` — the\n * shape behind a dev-server or reverse proxy — compares equal to the absolute\n * URL the request actually goes to. The target resolves against the document\n * base URL, where the transport sends it; the reference against the page's\n * own address, which a `<base href>` cannot move. Outside a browsing context a\n * relative target is allowed — there is no origin for it to cross — and a\n * target that does not parse is refused rather than trusted.\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 = targetOriginOf(target);\n if (targetOrigin === \"relative\") return true;\n if (targetOrigin === \"invalid\" || targetOrigin === \"null\") return false;\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,IAAMA,oBAAW,IAAI,IAAY,GAM3BC,IAAgB;AAkBtB,SAASC,EAAS,GAA4B;CAC1C,IAAI;EACA,OAAO,IAAI,IAAIC,GAAK,WAAW,UAAU,IAAI,CAAC,CAAC;CACnD,QAAQ;EACJ,OAAO;CACX;AACJ;AA4BA,SAASC,EAAe,GAAwB;CAC5C,IAAMC,IAAO,WAAW,UAAU,WAAW,WAAW,UAAU;CAClE,IAAIA,MAAS,KAAA,GACT,IAAI;EACA,OAAO,IAAI,IAAIC,GAAQD,CAAI,CAAC,CAAC;CACjC,QAAQ;EACJ,OAAO;CACX;CAEJ,IAAI;EACA,OAAO,IAAI,IAAIC,CAAM,CAAC,CAAC;CAC3B,QAAQ;EACJ,IAAI;GAEA,OADA,IAAI,IAAIA,GAAQL,CAAa,GACtB;EACX,QAAQ;GACJ,OAAO;EACX;CACJ;AACJ;AAWA,SAAgBM,EAAkB,GAA4B;CAC1D,IAAI;EACA,OAAO,IAAI,IAAIJ,GAAK,WAAW,UAAU,WAAW,WAAW,UAAU,IAAI,CAAC,CAAC;CACnF,QAAQ;EACJ,OAAO;CACX;AACJ;AAsCA,SAAgBK,EACZ,GACA,GACA,IAAoC,CAAC,GAC9B;CACP,IAAMC,IAAeL,EAAeE,CAAM;CAI1C,OAHIG,MAAiB,aAAmB,KACpCA,MAAiB,aAAaA,MAAiB,SAAe,KAC9DA,MAAiBP,EAASQ,CAAS,KAChCC,EAAe,MAAM,MAAWT,EAASU,CAAM,MAAMH,CAAY;AAC5E;AAkBA,SAAgBI,EACZ,GACA,GACA,IAAS,iBACL;CACJ,IAA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