tempest-react-sdk 0.48.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/audio/sfx-pool.cjs +1 -1
- package/dist/audio/sfx-pool.cjs.map +1 -1
- package/dist/audio/sfx-pool.js +16 -7
- package/dist/audio/sfx-pool.js.map +1 -1
- package/dist/audio/use-sfx-pool.cjs +1 -1
- package/dist/audio/use-sfx-pool.cjs.map +1 -1
- package/dist/audio/use-sfx-pool.js +3 -8
- package/dist/audio/use-sfx-pool.js.map +1 -1
- package/dist/auth/passkey.cjs +1 -1
- package/dist/auth/passkey.cjs.map +1 -1
- package/dist/auth/passkey.js +79 -81
- package/dist/auth/passkey.js.map +1 -1
- package/dist/charts.cjs +1 -1
- package/dist/charts.js +4 -4
- package/dist/components/BarList/BarList.cjs +1 -1
- package/dist/components/BarList/BarList.cjs.map +1 -1
- package/dist/components/BarList/BarList.js +31 -24
- package/dist/components/BarList/BarList.js.map +1 -1
- package/dist/components/BarList/bar-list-model.cjs +1 -1
- package/dist/components/BarList/bar-list-model.cjs.map +1 -1
- package/dist/components/BarList/bar-list-model.js +5 -5
- package/dist/components/BarList/bar-list-model.js.map +1 -1
- package/dist/components/ClickOutside/ClickOutside.cjs +1 -1
- package/dist/components/ClickOutside/ClickOutside.cjs.map +1 -1
- package/dist/components/ClickOutside/ClickOutside.js +13 -14
- package/dist/components/ClickOutside/ClickOutside.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +124 -122
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/FilterBar/filter-apply.cjs +1 -1
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
- package/dist/components/FilterBar/filter-apply.js +35 -38
- package/dist/components/FilterBar/filter-apply.js.map +1 -1
- package/dist/components/FilterBar/filter-query.cjs +1 -1
- package/dist/components/FilterBar/filter-query.cjs.map +1 -1
- package/dist/components/FilterBar/filter-query.js +16 -13
- package/dist/components/FilterBar/filter-query.js.map +1 -1
- package/dist/geo/use-position-tracker.cjs +1 -1
- package/dist/geo/use-position-tracker.cjs.map +1 -1
- package/dist/geo/use-position-tracker.js +25 -26
- package/dist/geo/use-position-tracker.js.map +1 -1
- package/dist/hooks/use-async.cjs +1 -1
- package/dist/hooks/use-async.cjs.map +1 -1
- package/dist/hooks/use-async.js +27 -30
- package/dist/hooks/use-async.js.map +1 -1
- package/dist/hooks/use-click-outside.cjs +1 -1
- package/dist/hooks/use-click-outside.cjs.map +1 -1
- package/dist/hooks/use-click-outside.js +8 -9
- package/dist/hooks/use-click-outside.js.map +1 -1
- package/dist/hooks/use-countdown.cjs +1 -1
- package/dist/hooks/use-countdown.cjs.map +1 -1
- package/dist/hooks/use-countdown.js +8 -13
- package/dist/hooks/use-countdown.js.map +1 -1
- package/dist/hooks/use-event-listener.cjs +1 -1
- package/dist/hooks/use-event-listener.cjs.map +1 -1
- package/dist/hooks/use-event-listener.js +6 -6
- package/dist/hooks/use-event-listener.js.map +1 -1
- package/dist/hooks/use-interval.cjs +1 -1
- package/dist/hooks/use-interval.cjs.map +1 -1
- package/dist/hooks/use-interval.js +5 -6
- package/dist/hooks/use-interval.js.map +1 -1
- package/dist/hooks/use-latest-ref.cjs.map +1 -1
- package/dist/hooks/use-latest-ref.js.map +1 -1
- package/dist/hooks/use-long-press-handlers.cjs +1 -1
- package/dist/hooks/use-long-press-handlers.cjs.map +1 -1
- package/dist/hooks/use-long-press-handlers.js +8 -10
- package/dist/hooks/use-long-press-handlers.js.map +1 -1
- package/dist/hooks/use-long-press.cjs +1 -1
- package/dist/hooks/use-long-press.cjs.map +1 -1
- package/dist/hooks/use-long-press.js +6 -6
- package/dist/hooks/use-long-press.js.map +1 -1
- package/dist/hooks/use-online.cjs +1 -1
- package/dist/hooks/use-online.cjs.map +1 -1
- package/dist/hooks/use-online.js +10 -10
- package/dist/hooks/use-online.js.map +1 -1
- package/dist/hooks/use-service-worker-update.cjs +1 -1
- package/dist/hooks/use-service-worker-update.cjs.map +1 -1
- package/dist/hooks/use-service-worker-update.js +24 -25
- package/dist/hooks/use-service-worker-update.js.map +1 -1
- package/dist/hooks/use-stable-callback.cjs +1 -1
- package/dist/hooks/use-stable-callback.cjs.map +1 -1
- package/dist/hooks/use-stable-callback.js +4 -3
- package/dist/hooks/use-stable-callback.js.map +1 -1
- package/dist/hooks/use-timeout.cjs +1 -1
- package/dist/hooks/use-timeout.cjs.map +1 -1
- package/dist/hooks/use-timeout.js +5 -6
- package/dist/hooks/use-timeout.js.map +1 -1
- package/dist/hooks/use-typewriter.cjs +1 -1
- package/dist/hooks/use-typewriter.cjs.map +1 -1
- package/dist/hooks/use-typewriter.js +9 -18
- package/dist/hooks/use-typewriter.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +11 -16
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/describe-api-error.cjs +1 -1
- package/dist/http/describe-api-error.cjs.map +1 -1
- package/dist/http/describe-api-error.js +12 -15
- package/dist/http/describe-api-error.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +18 -6
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +60 -61
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +20 -16
- package/dist/http/retry.js.map +1 -1
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +2 -2
- package/dist/http/use-describe-api-error.js.map +1 -1
- package/dist/i18n/create-i18n.cjs +1 -1
- package/dist/i18n/create-i18n.cjs.map +1 -1
- package/dist/i18n/create-i18n.js +6 -6
- package/dist/i18n/create-i18n.js.map +1 -1
- package/dist/icons/material-symbols.cjs +1 -1
- package/dist/icons/material-symbols.cjs.map +1 -1
- package/dist/icons/material-symbols.js +136 -5
- package/dist/icons/material-symbols.js.map +1 -1
- package/dist/icons.d.ts +17 -5
- package/dist/offline/create-offline-sync.cjs +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js +17 -9
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/offline/use-offline-sync.cjs +1 -1
- package/dist/offline/use-offline-sync.cjs.map +1 -1
- package/dist/offline/use-offline-sync.js +7 -8
- package/dist/offline/use-offline-sync.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +13 -12
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/query/retry-policy.cjs +1 -1
- package/dist/query/retry-policy.cjs.map +1 -1
- package/dist/query/retry-policy.js +3 -3
- package/dist/query/retry-policy.js.map +1 -1
- package/dist/sse/use-event-stream.cjs +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js +19 -20
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/tabular/use-tabular-predictor.cjs +1 -1
- package/dist/tabular/use-tabular-predictor.cjs.map +1 -1
- package/dist/tabular/use-tabular-predictor.js +20 -17
- package/dist/tabular/use-tabular-predictor.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +363 -149
- package/dist/tempest-react-sdk.js +143 -143
- package/dist/theme/ThemeProvider.cjs +1 -1
- package/dist/theme/ThemeProvider.cjs.map +1 -1
- package/dist/theme/ThemeProvider.js +12 -17
- package/dist/theme/ThemeProvider.js.map +1 -1
- package/dist/utils/base64.cjs +2 -0
- package/dist/utils/base64.cjs.map +1 -0
- package/dist/utils/base64.js +16 -0
- package/dist/utils/base64.js.map +1 -0
- package/dist/utils/compare-values.cjs +1 -1
- package/dist/utils/compare-values.cjs.map +1 -1
- package/dist/utils/compare-values.js +4 -3
- package/dist/utils/compare-values.js.map +1 -1
- package/dist/utils/compressed-storage.cjs +1 -1
- package/dist/utils/compressed-storage.cjs.map +1 -1
- package/dist/utils/compressed-storage.js +16 -46
- package/dist/utils/compressed-storage.js.map +1 -1
- package/dist/utils/storage.cjs +1 -1
- package/dist/utils/storage.cjs.map +1 -1
- package/dist/utils/storage.js +37 -17
- package/dist/utils/storage.js.map +1 -1
- package/dist/vision/use-camera-stream.cjs +1 -1
- package/dist/vision/use-camera-stream.cjs.map +1 -1
- package/dist/vision/use-camera-stream.js +34 -33
- package/dist/vision/use-camera-stream.js.map +1 -1
- package/dist/vite/base-url.cjs +2 -0
- package/dist/vite/base-url.cjs.map +1 -0
- package/dist/vite/base-url.js +8 -0
- package/dist/vite/base-url.js.map +1 -0
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +54 -29
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/dist/vite/tempest-pwa-manifest.cjs +2 -2
- package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
- package/dist/vite/tempest-pwa-manifest.js +15 -14
- package/dist/vite/tempest-pwa-manifest.js.map +1 -1
- package/dist/vite.d.ts +2 -2
- package/dist/ws/use-web-socket.cjs +1 -1
- package/dist/ws/use-web-socket.cjs.map +1 -1
- package/dist/ws/use-web-socket.js +40 -42
- package/dist/ws/use-web-socket.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,23 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { bytesToBase64 as e } from "../utils/base64.js";
|
|
2
|
+
import { TempestApiError as t, buildApiError as n } from "./errors.js";
|
|
3
|
+
import { retry as r } from "./retry.js";
|
|
4
|
+
import { generateIdempotencyKey as i } from "./idempotency.js";
|
|
4
5
|
//#region src/http/resumable-upload.ts
|
|
5
|
-
var
|
|
6
|
-
function
|
|
7
|
-
|
|
8
|
-
for (let e of t) n += String.fromCharCode(e);
|
|
9
|
-
return btoa(n);
|
|
6
|
+
var a = "1.0.0", o = 5242880;
|
|
7
|
+
function s(t) {
|
|
8
|
+
return e(new TextEncoder().encode(t));
|
|
10
9
|
}
|
|
11
|
-
function
|
|
10
|
+
function c(e) {
|
|
12
11
|
if (!e) return null;
|
|
13
|
-
let t = Object.entries(e).map(([e, t]) => `${e} ${
|
|
12
|
+
let t = Object.entries(e).map(([e, t]) => `${e} ${s(t)}`);
|
|
14
13
|
return t.length > 0 ? t.join(",") : null;
|
|
15
14
|
}
|
|
16
|
-
function
|
|
15
|
+
function l(e, t) {
|
|
17
16
|
let n = t, r = typeof n.name == "string" ? n.name : "blob", i = typeof n.lastModified == "number" ? n.lastModified : 0;
|
|
18
17
|
return `${e}|${r}|${t.size}|${t.type}|${i}`;
|
|
19
18
|
}
|
|
20
|
-
function
|
|
19
|
+
function u(e = "tempest-upload:") {
|
|
21
20
|
function t() {
|
|
22
21
|
try {
|
|
23
22
|
return typeof localStorage > "u" ? null : localStorage;
|
|
@@ -43,32 +42,32 @@ function l(e = "tempest-upload:") {
|
|
|
43
42
|
}
|
|
44
43
|
};
|
|
45
44
|
}
|
|
46
|
-
function
|
|
45
|
+
function d(e) {
|
|
47
46
|
return new Promise((n, r) => {
|
|
48
47
|
let i = new XMLHttpRequest();
|
|
49
|
-
i.open(
|
|
50
|
-
for (let [
|
|
51
|
-
if (
|
|
52
|
-
let
|
|
53
|
-
i.upload.onprogress = (
|
|
48
|
+
i.open(e.method, e.url), i.withCredentials = e.withCredentials;
|
|
49
|
+
for (let [t, n] of Object.entries(e.headers)) i.setRequestHeader(t, n);
|
|
50
|
+
if (e.onProgress) {
|
|
51
|
+
let t = e.onProgress;
|
|
52
|
+
i.upload.onprogress = (e) => t(e.loaded);
|
|
54
53
|
}
|
|
55
54
|
i.onload = () => n({
|
|
56
55
|
status: i.status,
|
|
57
56
|
text: i.responseText,
|
|
58
57
|
header: (e) => i.getResponseHeader(e)
|
|
59
|
-
}), i.onerror = () => r(new
|
|
58
|
+
}), i.onerror = () => r(new t({
|
|
60
59
|
status: 0,
|
|
61
60
|
detail: "Falha de rede no upload resumível."
|
|
62
|
-
})), i.onabort = () => r(new DOMException("Aborted", "AbortError")),
|
|
61
|
+
})), i.onabort = () => r(new DOMException("Aborted", "AbortError")), e.register(i), i.send(e.body);
|
|
63
62
|
});
|
|
64
63
|
}
|
|
65
|
-
function
|
|
64
|
+
function f(e) {
|
|
66
65
|
let t = e.header("Upload-Offset");
|
|
67
66
|
if (t === null) return null;
|
|
68
67
|
let n = Number(t);
|
|
69
68
|
return Number.isFinite(n) && n >= 0 ? n : null;
|
|
70
69
|
}
|
|
71
|
-
function
|
|
70
|
+
function p(e) {
|
|
72
71
|
if (!e) return null;
|
|
73
72
|
try {
|
|
74
73
|
return JSON.parse(e);
|
|
@@ -76,14 +75,14 @@ function f(e) {
|
|
|
76
75
|
return e;
|
|
77
76
|
}
|
|
78
77
|
}
|
|
79
|
-
function
|
|
80
|
-
let i =
|
|
81
|
-
return new
|
|
78
|
+
function m(e, r) {
|
|
79
|
+
let i = p(e.text), a = n(e.status, i, { get: e.header }), o = typeof i == "object" && !!i && ("detail" in i || "message" in i);
|
|
80
|
+
return new t({
|
|
82
81
|
...a,
|
|
83
82
|
detail: o ? a.detail : r
|
|
84
83
|
});
|
|
85
84
|
}
|
|
86
|
-
function
|
|
85
|
+
function h(e) {
|
|
87
86
|
let t = typeof window > "u" ? void 0 : window.location.href;
|
|
88
87
|
try {
|
|
89
88
|
return new URL(e, t).href;
|
|
@@ -91,23 +90,23 @@ function m(e) {
|
|
|
91
90
|
return e;
|
|
92
91
|
}
|
|
93
92
|
}
|
|
94
|
-
function
|
|
95
|
-
let { endpoint:
|
|
93
|
+
function g(e) {
|
|
94
|
+
let { endpoint: n, file: s, chunkSize: p = o, metadata: g, headers: _ = {}, getToken: v, withCredentials: y = !1, key: b = l(n, s), storage: x = u(), retry: S, onProgress: C, onStateChange: w } = e, T = "idle", E = 0, D = null, O = null, k = null, A = null, j = 0;
|
|
96
95
|
function M(e) {
|
|
97
96
|
T !== e && (T = e, w?.(e));
|
|
98
97
|
}
|
|
99
98
|
function N(e) {
|
|
100
99
|
C?.({
|
|
101
100
|
loaded: e,
|
|
102
|
-
total:
|
|
103
|
-
fraction:
|
|
101
|
+
total: s.size,
|
|
102
|
+
fraction: s.size === 0 ? 1 : e / s.size,
|
|
104
103
|
resumedFrom: j
|
|
105
104
|
});
|
|
106
105
|
}
|
|
107
106
|
function P() {
|
|
108
107
|
let e = {
|
|
109
108
|
..._,
|
|
110
|
-
"Tus-Resumable":
|
|
109
|
+
"Tus-Resumable": a
|
|
111
110
|
}, t = v?.();
|
|
112
111
|
return t && !("Authorization" in e) && (e.Authorization = `Bearer ${t}`), e;
|
|
113
112
|
}
|
|
@@ -118,62 +117,62 @@ function h(t) {
|
|
|
118
117
|
!x || !D || !O || await x.set(b, {
|
|
119
118
|
url: D,
|
|
120
119
|
offset: E,
|
|
121
|
-
size:
|
|
120
|
+
size: s.size,
|
|
122
121
|
idempotencyKey: O,
|
|
123
122
|
updatedAt: Date.now()
|
|
124
123
|
});
|
|
125
124
|
}
|
|
126
|
-
async function L(
|
|
127
|
-
let n = await
|
|
125
|
+
async function L(e) {
|
|
126
|
+
let n = await d({
|
|
128
127
|
method: "HEAD",
|
|
129
|
-
url:
|
|
128
|
+
url: e,
|
|
130
129
|
headers: P(),
|
|
131
130
|
withCredentials: y,
|
|
132
131
|
register: F
|
|
133
132
|
});
|
|
134
|
-
if (n.status === 404 || n.status === 410) throw new
|
|
133
|
+
if (n.status === 404 || n.status === 410) throw new t({
|
|
135
134
|
status: n.status,
|
|
136
135
|
detail: "O upload expirou no servidor. Comece de novo."
|
|
137
136
|
});
|
|
138
|
-
let r =
|
|
139
|
-
if (r === null) throw
|
|
137
|
+
let r = f(n);
|
|
138
|
+
if (r === null) throw m(n, "HEAD sem Upload-Offset.");
|
|
140
139
|
return r;
|
|
141
140
|
}
|
|
142
141
|
async function R() {
|
|
143
142
|
let e = x ? await x.get(b) : null;
|
|
144
|
-
if (e && e.size ===
|
|
143
|
+
if (e && e.size === s.size && (O = e.idempotencyKey, e.url)) try {
|
|
145
144
|
return E = await L(e.url), D = e.url, e.url;
|
|
146
145
|
} catch {
|
|
147
146
|
E = 0;
|
|
148
147
|
}
|
|
149
|
-
M("creating"), O ??=
|
|
148
|
+
M("creating"), O ??= i(), D = null, E = 0, x && await x.set(b, {
|
|
150
149
|
url: "",
|
|
151
150
|
offset: 0,
|
|
152
|
-
size:
|
|
151
|
+
size: s.size,
|
|
153
152
|
idempotencyKey: O,
|
|
154
153
|
updatedAt: Date.now()
|
|
155
154
|
});
|
|
156
155
|
let t = {
|
|
157
156
|
...P(),
|
|
158
|
-
"Upload-Length": String(
|
|
157
|
+
"Upload-Length": String(s.size),
|
|
159
158
|
"Idempotency-Key": O
|
|
160
|
-
},
|
|
161
|
-
|
|
162
|
-
let
|
|
159
|
+
}, r = c(g);
|
|
160
|
+
r && (t["Upload-Metadata"] = r);
|
|
161
|
+
let a = await d({
|
|
163
162
|
method: "POST",
|
|
164
|
-
url:
|
|
163
|
+
url: n,
|
|
165
164
|
headers: t,
|
|
166
165
|
withCredentials: y,
|
|
167
166
|
register: F
|
|
168
167
|
});
|
|
169
|
-
if (
|
|
170
|
-
let
|
|
171
|
-
if (!
|
|
172
|
-
return D =
|
|
168
|
+
if (a.status !== 201) throw m(a, "Criação do upload recusada.");
|
|
169
|
+
let o = a.header("Location");
|
|
170
|
+
if (!o) throw m(a, "Criação do upload sem cabeçalho Location.");
|
|
171
|
+
return D = h(o), await I(), D;
|
|
173
172
|
}
|
|
174
173
|
async function z(e, t) {
|
|
175
|
-
if (t.needed && (E = await L(e), t.needed = !1, N(E), await I(), E >=
|
|
176
|
-
let n = Math.min(E +
|
|
174
|
+
if (t.needed && (E = await L(e), t.needed = !1, N(E), await I(), E >= s.size)) return;
|
|
175
|
+
let n = Math.min(E + p, s.size), r = E, i = await d({
|
|
177
176
|
method: "PATCH",
|
|
178
177
|
url: e,
|
|
179
178
|
headers: {
|
|
@@ -181,28 +180,28 @@ function h(t) {
|
|
|
181
180
|
"Content-Type": "application/offset+octet-stream",
|
|
182
181
|
"Upload-Offset": String(r)
|
|
183
182
|
},
|
|
184
|
-
body:
|
|
183
|
+
body: s.slice(r, n),
|
|
185
184
|
withCredentials: y,
|
|
186
|
-
onProgress: (e) => N(Math.min(r + e,
|
|
185
|
+
onProgress: (e) => N(Math.min(r + e, s.size)),
|
|
187
186
|
register: F
|
|
188
187
|
});
|
|
189
|
-
if (i.status === 409 || i.status === 412) throw t.needed = !0,
|
|
190
|
-
if (i.status !== 204 && i.status !== 200) throw
|
|
191
|
-
E =
|
|
188
|
+
if (i.status === 409 || i.status === 412) throw t.needed = !0, m(i, "Offset divergente — o servidor já tinha esses bytes.");
|
|
189
|
+
if (i.status !== 204 && i.status !== 200) throw m(i, "Chunk recusado pelo servidor.");
|
|
190
|
+
E = f(i) ?? n, N(E), await I();
|
|
192
191
|
}
|
|
193
192
|
async function B() {
|
|
194
193
|
k = null;
|
|
195
194
|
let e = await R();
|
|
196
195
|
j = E, M("uploading"), N(E);
|
|
197
196
|
let t = { needed: !1 };
|
|
198
|
-
for (; E <
|
|
197
|
+
for (; E < s.size && !k;) await r(() => z(e, t), {
|
|
199
198
|
retries: 5,
|
|
200
199
|
...S,
|
|
201
200
|
shouldRetry: (e, n) => k || e instanceof DOMException && e.name === "AbortError" ? !1 : (t.needed = !0, S?.shouldRetry?.(e, n) ?? !0)
|
|
202
201
|
});
|
|
203
202
|
return k === "pause" ? (M("paused"), null) : k === "abort" ? (M("aborted"), null) : (M("done"), x && await x.delete(b), {
|
|
204
203
|
url: e,
|
|
205
|
-
size:
|
|
204
|
+
size: s.size
|
|
206
205
|
});
|
|
207
206
|
}
|
|
208
207
|
async function V() {
|
|
@@ -223,7 +222,7 @@ function h(t) {
|
|
|
223
222
|
resume: V,
|
|
224
223
|
pause: () => H("pause"),
|
|
225
224
|
abort: async ({ discard: e = !1 } = {}) => {
|
|
226
|
-
H("abort"), M("aborted"), e && (D && await
|
|
225
|
+
H("abort"), M("aborted"), e && (D && await d({
|
|
227
226
|
method: "DELETE",
|
|
228
227
|
url: D,
|
|
229
228
|
headers: P(),
|
|
@@ -244,6 +243,6 @@ function h(t) {
|
|
|
244
243
|
};
|
|
245
244
|
}
|
|
246
245
|
//#endregion
|
|
247
|
-
export {
|
|
246
|
+
export { o as DEFAULT_CHUNK_SIZE, a as TUS_VERSION, u as createLocalUploadStorage, g as createResumableUpload, l as uploadFingerprint };
|
|
248
247
|
|
|
249
248
|
//# sourceMappingURL=resumable-upload.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { buildApiError, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n withCredentials = false,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n function baseHeaders(): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) result.Authorization = `Bearer ${token}`;\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n resync.needed = true;\n return retryOptions?.shouldRetry?.(error, attempt) ?? true;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;AAYA,IAAa,IAAc,SAGd,IAAqB;AA8IlC,SAAS,EAAW,GAAuB;CACvC,IAAM,IAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,GACxC,IAAS;CACb,KAAK,IAAM,KAAQ,GAAO,KAAU,OAAO,aAAa,CAAI;CAC5D,OAAO,KAAK,CAAM;AACtB;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OAAO,QAAQ,CAAQ,CAAC,CAAC,KAAK,CAAC,GAAM,OAAW,GAAG,EAAK,GAA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A,gBAAgB,KAAA;GACpB,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS,GAExB,KAAS,MAAM,EAAQ,OAAO,CAAG;EACzC;EACA,IAAI,QAAQ;GACR,OAAO;EACX;EACA,IAAI,SAAS;GACT,OAAO;EACX;EACA,IAAI,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"resumable-upload.js","names":[],"sources":["../../src/http/resumable-upload.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — a resumable upload is one long-lived\n * state machine: chunk the file, negotiate the offset the server already has, upload\n * with retry and backoff, honour pause, resume and abort, and report progress\n * throughout. Every stage reads the same cursor and the same abort signal, and\n * createResumableUpload is the closure that owns them.\n */\nimport { bytesToBase64 } from \"@/utils/base64\";\nimport { buildApiError, TempestApiError } from \"./errors\";\nimport { generateIdempotencyKey } from \"./idempotency\";\nimport { retry, type RetryOptions } from \"./retry\";\n\n/** The tus protocol version this client speaks. */\nexport const TUS_VERSION = \"1.0.0\";\n\n/** Default chunk size: 5 MiB, the size most tus servers are tuned for. */\nexport const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024;\n\n/**\n * Where a resumable upload is.\n *\n * `\"paused\"` and `\"aborted\"` are both \"not running\", but only `\"paused\"` keeps the\n * persisted offset — `abort({ discard: true })` throws it away.\n */\nexport type ResumableUploadState =\n \"idle\" | \"creating\" | \"uploading\" | \"paused\" | \"done\" | \"error\" | \"aborted\";\n\n/** Byte-level progress for a resumable upload. */\nexport interface ResumableUploadProgress {\n /** Bytes the server holds, including anything a resume skipped. */\n loaded: number;\n /** Total size of the file. */\n total: number;\n /** `loaded / total`, between 0 and 1. */\n fraction: number;\n /** Bytes already on the server when this run started. `0` on a fresh upload. */\n resumedFrom: number;\n}\n\n/** What has to survive a page reload for a resume to be possible. */\nexport interface ResumableUploadRecord {\n /** Upload URL the creation POST returned, absolute. */\n url: string;\n /** Last offset the server confirmed. */\n offset: number;\n /** File size, so a different file under the same key is not resumed into. */\n size: number;\n /** Idempotency key of the creation request, reused if creation is retried. */\n idempotencyKey: string;\n /** Epoch ms of the last write, so an app can sweep stale records. */\n updatedAt: number;\n}\n\n/**\n * Persistence for resume state. Sync or async — both are awaited.\n *\n * Implement it over anything: the default is `localStorage`, and\n * `createOfflineStore` from `@/offline` slots in when you already have a Dexie\n * database open.\n */\nexport interface ResumableUploadStorage {\n /** Read the record for `key`, or `null`. */\n get(key: string): Promise<ResumableUploadRecord | null> | ResumableUploadRecord | null;\n /** Write the record for `key`. */\n set(key: string, record: ResumableUploadRecord): Promise<void> | void;\n /** Forget the record for `key`. */\n delete(key: string): Promise<void> | void;\n}\n\n/** Options for {@link createResumableUpload}. */\nexport interface ResumableUploadOptions {\n /** tus creation endpoint, e.g. `\"/api/uploads\"`. */\n endpoint: string;\n /** The bytes to upload. A `File` also supplies the default resume key. */\n file: Blob | File;\n /** Bytes per `PATCH`. Default {@link DEFAULT_CHUNK_SIZE}. */\n chunkSize?: number;\n /** Sent as `Upload-Metadata` (base64-encoded values), e.g. `{ filename }`. */\n metadata?: Record<string, string>;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n /** Returns the current bearer token, read before each request. */\n getToken?: () => string | null | undefined;\n /** Send cookies. Default `false`. */\n withCredentials?: boolean;\n /**\n * Resume key. Defaults to a fingerprint of endpoint + file name/size/mtime, so\n * picking the same file after a reload resumes instead of restarting.\n */\n key?: string;\n /**\n * Where to persist resume state. Defaults to `localStorage`. Pass `null` to\n * disable persistence — resume then only survives a network blip, not a reload.\n */\n storage?: ResumableUploadStorage | null;\n /** Backoff for a failed chunk. Forwarded to `retry`. Default 5 attempts. */\n retry?: RetryOptions;\n /** Called on every upload-progress tick and after every confirmed chunk. */\n onProgress?: (progress: ResumableUploadProgress) => void;\n /** Called whenever {@link ResumableUpload.state} changes. */\n onStateChange?: (state: ResumableUploadState) => void;\n}\n\n/** What a finished upload resolves with. */\nexport interface ResumableUploadResult {\n /** The tus upload URL — hand this to your API to link the stored file. */\n url: string;\n /** Total bytes uploaded. */\n size: number;\n}\n\n/** A resumable upload in progress. Build one with {@link createResumableUpload}. */\nexport interface ResumableUpload {\n /**\n * Create (or re-attach to) the upload and push chunks until it is complete.\n *\n * Resolves `null` when the run stopped because of `pause()` or `abort()` —\n * neither is a failure. Rejects with a `TempestApiError` when the server\n * refused and the retries ran out.\n */\n start(): Promise<ResumableUploadResult | null>;\n /** Stop after the in-flight chunk is dropped, keeping the resume point. */\n pause(): void;\n /** Continue from the server's offset. Same resolution contract as `start`. */\n resume(): Promise<ResumableUploadResult | null>;\n /**\n * Stop for good.\n *\n * @param options - `discard: true` also sends `DELETE` (tus termination) and\n * forgets the persisted record, so the next `start()` uploads from zero.\n */\n abort(options?: { discard?: boolean }): Promise<void>;\n /** Current state. */\n readonly state: ResumableUploadState;\n /** Bytes the server has confirmed. */\n readonly offset: number;\n /** The upload URL, once creation succeeded. */\n readonly url: string | null;\n /** The resume key in use. */\n readonly key: string;\n}\n\ninterface RawResponse {\n status: number;\n text: string;\n header(name: string): string | null;\n}\n\n/**\n * Encode a string as standard base64 (padded), UTF-8 first.\n *\n * `Upload-Metadata` carries base64 values precisely so a filename with accents\n * survives an HTTP header, so the UTF-8 step is not optional: `btoa` alone throws\n * on any code point above U+00FF. Only that step is specific here — the\n * bytes-to-text half is {@link bytesToBase64}.\n *\n * @param value - Text to encode.\n * @returns Padded base64.\n */\nfunction base64Utf8(value: string): string {\n return bytesToBase64(new TextEncoder().encode(value));\n}\n\n/**\n * Build the `Upload-Metadata` header value: comma-separated `key base64(value)`.\n *\n * @param metadata - Plain string map.\n * @returns The header value, or `null` when there is nothing to send.\n */\nfunction encodeMetadata(metadata: Record<string, string> | undefined): string | null {\n if (!metadata) return null;\n const parts = Object.entries(metadata).map(([name, value]) => `${name} ${base64Utf8(value)}`);\n return parts.length > 0 ? parts.join(\",\") : null;\n}\n\n/**\n * A stable-enough identity for a file, used as the default resume key.\n *\n * Name + size + last-modified is what the tus reference clients fingerprint on:\n * it is cheap (hashing the bytes of a 400 MB recording is not) and it changes\n * whenever the file does, which is the property that matters — resuming into the\n * wrong file would corrupt it silently.\n *\n * @param endpoint - Creation endpoint, so the same file to two servers is two uploads.\n * @param file - The blob or file being uploaded.\n * @returns A key safe to use in `localStorage`.\n */\nexport function uploadFingerprint(endpoint: string, file: Blob | File): string {\n const named = file as File;\n const name = typeof named.name === \"string\" ? named.name : \"blob\";\n const modified = typeof named.lastModified === \"number\" ? named.lastModified : 0;\n return `${endpoint}|${name}|${file.size}|${file.type}|${modified}`;\n}\n\n/**\n * `localStorage`-backed resume storage — the default.\n *\n * `localStorage` and not IndexedDB on purpose. The record is four fields and a\n * URL; the requirement is only that it survives a reload, and pulling Dexie in for\n * that would put an IndexedDB dependency in the bundle of every app that uploads a\n * file. Apps that already have `createOfflineStore` open can pass their own\n * {@link ResumableUploadStorage} instead.\n *\n * @param prefix - Key prefix. Default `\"tempest-upload:\"`.\n * @returns A storage that no-ops when `localStorage` is unavailable.\n */\nexport function createLocalUploadStorage(prefix = \"tempest-upload:\"): ResumableUploadStorage {\n function backend(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage;\n } catch {\n return null;\n }\n }\n\n return {\n get(key) {\n const raw = backend()?.getItem(prefix + key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as ResumableUploadRecord;\n } catch {\n return null;\n }\n },\n set(key, record) {\n backend()?.setItem(prefix + key, JSON.stringify(record));\n },\n delete(key) {\n backend()?.removeItem(prefix + key);\n },\n };\n}\n\n/**\n * Send one request over `XMLHttpRequest`.\n *\n * `XMLHttpRequest` rather than `fetch` for the same reason `uploadWithProgress`\n * uses it — `fetch` still cannot report upload progress in any browser — plus one\n * more: tus answers every write with the new `Upload-Offset` in a **response\n * header**, and `uploadWithProgress` only hands back a parsed body, so it could\n * not be reused here.\n *\n * @param init - Method, URL, headers, optional body and progress callback.\n * @returns Status, raw text and a header reader.\n */\nfunction sendRequest(init: {\n method: \"POST\" | \"HEAD\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: Blob;\n withCredentials: boolean;\n onProgress?: (loaded: number) => void;\n register: (xhr: XMLHttpRequest) => void;\n}): Promise<RawResponse> {\n return new Promise<RawResponse>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method, init.url);\n xhr.withCredentials = init.withCredentials;\n for (const [name, value] of Object.entries(init.headers)) {\n xhr.setRequestHeader(name, value);\n }\n if (init.onProgress) {\n const report = init.onProgress;\n xhr.upload.onprogress = (event: ProgressEvent) => report(event.loaded);\n }\n xhr.onload = () =>\n resolve({\n status: xhr.status,\n text: xhr.responseText,\n header: (name) => xhr.getResponseHeader(name),\n });\n xhr.onerror = () =>\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload resumível.\",\n }),\n );\n xhr.onabort = () => reject(new DOMException(\"Aborted\", \"AbortError\"));\n init.register(xhr);\n xhr.send(init.body);\n });\n}\n\nfunction parseOffset(response: RawResponse): number | null {\n const raw = response.header(\"Upload-Offset\");\n if (raw === null) return null;\n const value = Number(raw);\n return Number.isFinite(value) && value >= 0 ? value : null;\n}\n\n/**\n * Read an error body without assuming it is JSON.\n *\n * A tus proxy that rejects a chunk often answers with plain text or an HTML error\n * page, and `JSON.parse` throwing there would replace a useful status with a parse\n * error.\n *\n * @param text - Raw response text.\n * @returns The parsed object, the raw text, or `null` when the body was empty.\n */\nfunction parseErrorBody(text: string): unknown {\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * Turn a refused tus response into a `TempestApiError`.\n *\n * The fallback `detail` is used unless the server sent a real error envelope,\n * because `buildApiError`'s own fallback (`\"Erro 409\"`) says nothing about which\n * step of the protocol broke — and that is the whole diagnostic value here.\n *\n * @param response - The raw response that was not acceptable.\n * @param detail - Message to use when the body carries none.\n * @returns The error to throw.\n */\nfunction failed(response: RawResponse, detail: string): TempestApiError {\n const body = parseErrorBody(response.text);\n const envelope = buildApiError(response.status, body, { get: response.header });\n const hasDetail =\n typeof body === \"object\" && body !== null && (\"detail\" in body || \"message\" in body);\n return new TempestApiError({ ...envelope, detail: hasDetail ? envelope.detail : detail });\n}\n\n/**\n * Resolve a `Location` header against the page, so a relative upload URL works.\n *\n * tus servers are free to answer creation with either an absolute URL or a\n * path, and the spec does not prefer one — a client that only handles absolute\n * URLs breaks against half the implementations.\n *\n * @param value - The raw `Location` header.\n * @returns An absolute URL, or the input when there is no base to resolve against.\n */\nfunction resolveUploadUrl(value: string): string {\n const base = typeof window === \"undefined\" ? undefined : window.location.href;\n try {\n return new URL(value, base).href;\n } catch {\n return value;\n }\n}\n\n/**\n * Chunked, resumable upload speaking the **tus 1.0.0** protocol (core plus the\n * *creation* and *termination* extensions).\n *\n * ## Why tus and not a bespoke scheme\n *\n * A resumable client whose wire format is undocumented cannot be integrated, and\n * inventing one means the backend is ours forever. tus is a published spec with\n * off-the-shelf servers (`tusd`, `tuspy`, `tus-node-server`), so a caller can point\n * this at something they did not write.\n *\n * ## What the backend must implement\n *\n * Every request carries `Tus-Resumable: 1.0.0`.\n *\n * | Step | Request | Expected response |\n * | --- | --- | --- |\n * | Create | `POST {endpoint}` + `Upload-Length`, `Upload-Metadata`, `Idempotency-Key` | `201` + `Location` (the upload URL, absolute or endpoint-relative) |\n * | Probe | `HEAD {uploadUrl}` | `200`/`204` + `Upload-Offset` |\n * | Write | `PATCH {uploadUrl}` + `Upload-Offset`, `Content-Type: application/offset+octet-stream`, chunk body | `204` + the new `Upload-Offset`; `409` when the offset does not match |\n * | Discard | `DELETE {uploadUrl}` | `204` |\n *\n * ## The failure that actually happens\n *\n * A chunk that the server stored but whose response never arrived. The client\n * cannot tell that from a chunk that was lost, and re-sending it blindly would\n * duplicate bytes. Two things prevent that:\n *\n * - **Writes are addressed, not appended.** Every `PATCH` states the offset it\n * writes at, so a retry after a lost response is asked to write bytes the server\n * already has and answers `409`. On any retry the client re-reads the truth with\n * `HEAD` first and continues from there.\n * - **Creation carries an `Idempotency-Key`** (from `generateIdempotencyKey`),\n * persisted before the first attempt and reused on retry. tus has no idempotent\n * creation of its own, so without this a lost `201` leaves an orphan upload on\n * the server. A backend that honours the header returns the same `Location`; one\n * that ignores it still works, it just keeps the orphan.\n *\n * @param options - Endpoint, file, and the knobs above.\n * @returns A handle with `start`/`pause`/`resume`/`abort` and live `state`/`offset`.\n *\n * @example\n * const upload = createResumableUpload({\n * endpoint: \"/api/uploads\",\n * file: recording,\n * metadata: { filename: \"nota.webm\", ticket: ticketId },\n * getToken: () => auth.getToken(),\n * onProgress: ({ fraction }) => setPercent(Math.round(fraction * 100)),\n * });\n *\n * const done = await upload.start();\n * if (done) await api.post(\"/api/tickets/1/audio\", { body: { url: done.url } });\n */\nexport function createResumableUpload(options: ResumableUploadOptions): ResumableUpload {\n const {\n endpoint,\n file,\n chunkSize = DEFAULT_CHUNK_SIZE,\n metadata,\n headers = {},\n getToken,\n withCredentials = false,\n key = uploadFingerprint(endpoint, file),\n storage = createLocalUploadStorage(),\n retry: retryOptions,\n onProgress,\n onStateChange,\n } = options;\n\n let state: ResumableUploadState = \"idle\";\n let offset = 0;\n let url: string | null = null;\n let idempotencyKey: string | null = null;\n let stopping: \"pause\" | \"abort\" | null = null;\n let inFlight: XMLHttpRequest | null = null;\n let resumedFrom = 0;\n\n function setState(next: ResumableUploadState): void {\n if (state === next) return;\n state = next;\n onStateChange?.(next);\n }\n\n function report(loaded: number): void {\n onProgress?.({\n loaded,\n total: file.size,\n fraction: file.size === 0 ? 1 : loaded / file.size,\n resumedFrom,\n });\n }\n\n function baseHeaders(): Record<string, string> {\n const result: Record<string, string> = { ...headers, \"Tus-Resumable\": TUS_VERSION };\n const token = getToken?.();\n if (token && !(\"Authorization\" in result)) result.Authorization = `Bearer ${token}`;\n return result;\n }\n\n function register(xhr: XMLHttpRequest): void {\n inFlight = xhr;\n }\n\n async function persist(): Promise<void> {\n if (!storage || !url || !idempotencyKey) return;\n await storage.set(key, {\n url,\n offset,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n /**\n * Ask the server how much it holds. The only source of truth after any failure.\n */\n async function probe(target: string): Promise<number> {\n const response = await sendRequest({\n method: \"HEAD\",\n url: target,\n headers: baseHeaders(),\n withCredentials,\n register,\n });\n if (response.status === 404 || response.status === 410) {\n throw new TempestApiError({\n status: response.status,\n detail: \"O upload expirou no servidor. Comece de novo.\",\n });\n }\n const confirmed = parseOffset(response);\n if (confirmed === null) throw failed(response, \"HEAD sem Upload-Offset.\");\n return confirmed;\n }\n\n /**\n * Re-attach to a persisted upload, or create a new one.\n *\n * The persisted record is only trusted when the file size still matches, and the\n * offset it holds is re-checked with `HEAD` — the client's copy can be ahead of\n * the server's whenever the last response was lost.\n */\n async function ensureUpload(): Promise<string> {\n const stored = storage ? await storage.get(key) : null;\n if (stored && stored.size === file.size) {\n idempotencyKey = stored.idempotencyKey;\n if (stored.url) {\n try {\n offset = await probe(stored.url);\n url = stored.url;\n return stored.url;\n } catch {\n offset = 0;\n }\n }\n }\n\n setState(\"creating\");\n idempotencyKey ??= generateIdempotencyKey();\n url = null;\n offset = 0;\n if (storage) {\n await storage.set(key, {\n url: \"\",\n offset: 0,\n size: file.size,\n idempotencyKey,\n updatedAt: Date.now(),\n });\n }\n\n const creationHeaders: Record<string, string> = {\n ...baseHeaders(),\n \"Upload-Length\": String(file.size),\n \"Idempotency-Key\": idempotencyKey,\n };\n const encoded = encodeMetadata(metadata);\n if (encoded) creationHeaders[\"Upload-Metadata\"] = encoded;\n\n const response = await sendRequest({\n method: \"POST\",\n url: endpoint,\n headers: creationHeaders,\n withCredentials,\n register,\n });\n if (response.status !== 201) throw failed(response, \"Criação do upload recusada.\");\n const locationHeader = response.header(\"Location\");\n if (!locationHeader) throw failed(response, \"Criação do upload sem cabeçalho Location.\");\n\n url = resolveUploadUrl(locationHeader);\n await persist();\n return url;\n }\n\n /** Push one chunk, resyncing the offset first when a previous attempt failed. */\n async function writeChunk(target: string, resync: { needed: boolean }): Promise<void> {\n if (resync.needed) {\n offset = await probe(target);\n resync.needed = false;\n report(offset);\n await persist();\n if (offset >= file.size) return;\n }\n\n const end = Math.min(offset + chunkSize, file.size);\n const from = offset;\n const response = await sendRequest({\n method: \"PATCH\",\n url: target,\n headers: {\n ...baseHeaders(),\n \"Content-Type\": \"application/offset+octet-stream\",\n \"Upload-Offset\": String(from),\n },\n body: file.slice(from, end),\n withCredentials,\n onProgress: (loaded) => report(Math.min(from + loaded, file.size)),\n register,\n });\n\n if (response.status === 409 || response.status === 412) {\n resync.needed = true;\n throw failed(response, \"Offset divergente — o servidor já tinha esses bytes.\");\n }\n if (response.status !== 204 && response.status !== 200) {\n throw failed(response, \"Chunk recusado pelo servidor.\");\n }\n\n offset = parseOffset(response) ?? end;\n report(offset);\n await persist();\n }\n\n /**\n * Drive the whole upload: attach or create, then chunk until complete.\n *\n * The `shouldRetry` predicate does double duty — besides deciding, it arms\n * `resync` so the next attempt re-reads the server's offset with `HEAD` before\n * writing. That is deliberate: it is the one place that sees *every* chunk\n * failure, whatever the cause, and after any failure the client's idea of the\n * offset is exactly what cannot be trusted.\n *\n * @returns The result, or `null` when `pause`/`abort` stopped the run.\n */\n async function run(): Promise<ResumableUploadResult | null> {\n stopping = null;\n const target = await ensureUpload();\n resumedFrom = offset;\n setState(\"uploading\");\n report(offset);\n\n const resync = { needed: false };\n while (offset < file.size) {\n if (stopping) break;\n await retry(() => writeChunk(target, resync), {\n retries: 5,\n ...retryOptions,\n shouldRetry: (error, attempt) => {\n if (stopping) return false;\n if (error instanceof DOMException && error.name === \"AbortError\") return false;\n resync.needed = true;\n return retryOptions?.shouldRetry?.(error, attempt) ?? true;\n },\n });\n }\n\n if (stopping === \"pause\") {\n setState(\"paused\");\n return null;\n }\n if (stopping === \"abort\") {\n setState(\"aborted\");\n return null;\n }\n\n setState(\"done\");\n if (storage) await storage.delete(key);\n return { url: target, size: file.size };\n }\n\n async function guarded(): Promise<ResumableUploadResult | null> {\n try {\n return await run();\n } catch (error) {\n if (\n stopping !== null ||\n (error instanceof DOMException && error.name === \"AbortError\")\n ) {\n setState(stopping === \"abort\" ? \"aborted\" : \"paused\");\n return null;\n }\n setState(\"error\");\n throw error;\n } finally {\n inFlight = null;\n }\n }\n\n function stop(reason: \"pause\" | \"abort\"): void {\n stopping = reason;\n inFlight?.abort();\n inFlight = null;\n }\n\n return {\n start: guarded,\n resume: guarded,\n pause: () => stop(\"pause\"),\n abort: async ({ discard = false } = {}) => {\n stop(\"abort\");\n setState(\"aborted\");\n if (!discard) return;\n if (url) {\n await sendRequest({\n method: \"DELETE\",\n url,\n headers: baseHeaders(),\n withCredentials,\n register: () => undefined,\n }).catch(() => undefined);\n }\n if (storage) await storage.delete(key);\n },\n get state() {\n return state;\n },\n get offset() {\n return offset;\n },\n get url() {\n return url;\n },\n key,\n };\n}\n"],"mappings":";;;;;AAaA,IAAa,IAAc,SAGd,IAAqB;AA+IlC,SAAS,EAAW,GAAuB;CACvC,OAAO,EAAc,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACxD;AAQA,SAAS,EAAe,GAA6D;CACjF,IAAI,CAAC,GAAU,OAAO;CACtB,IAAM,IAAQ,OAAO,QAAQ,CAAQ,CAAC,CAAC,KAAK,CAAC,GAAM,OAAW,GAAG,EAAK,GAAG,EAAW,CAAK,GAAG;CAC5F,OAAO,EAAM,SAAS,IAAI,EAAM,KAAK,GAAG,IAAI;AAChD;AAcA,SAAgB,EAAkB,GAAkB,GAA2B;CAC3E,IAAM,IAAQ,GACR,IAAO,OAAO,EAAM,QAAS,WAAW,EAAM,OAAO,QACrD,IAAW,OAAO,EAAM,gBAAiB,WAAW,EAAM,eAAe;CAC/E,OAAO,GAAG,EAAS,GAAG,EAAK,GAAG,EAAK,KAAK,GAAG,EAAK,KAAK,GAAG;AAC5D;AAcA,SAAgB,EAAyB,IAAS,mBAA2C;CACzF,SAAS,IAA0B;EAC/B,IAAI;GACA,OAAO,OAAO,eAAiB,MAAc,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ACb,KACA,aAAiB,gBAAgB,EAAM,SAAS,eAAqB,MACzE,EAAO,SAAS,IACT,GAAc,cAAc,GAAO,CAAO,KAAK;EAE9D,CAAC;EAcL,OAXI,MAAa,WACb,EAAS,QAAQ,GACV,QAEP,MAAa,WACb,EAAS,SAAS,GACX,SAGX,EAAS,MAAM,GACX,KAAS,MAAM,EAAQ,OAAO,CAAG,GAC9B;GAAE,KAAK;GAAQ,MAAM,EAAK;EAAK;CAC1C;CAEA,eAAe,IAAiD;EAC5D,IAAI;GACA,OAAO,MAAM,EAAI;EACrB,SAAS,GAAO;GACZ,IACI,MAAa,QACZ,aAAiB,gBAAgB,EAAM,SAAS,cAGjD,OADA,EAAS,MAAa,UAAU,YAAY,QAAQ,GAC7C;GAGX,MADA,EAAS,OAAO,GACV;EACV,UAAU;GACN,IAAW;EACf;CACJ;CAEA,SAAS,EAAK,GAAiC;EAG3C,AAFA,IAAW,GACX,GAAU,MAAM,GAChB,IAAW;CACf;CAEA,OAAO;EACH,OAAO;EACP,QAAQ;EACR,aAAa,EAAK,OAAO;EACzB,OAAO,OAAO,EAAE,aAAU,OAAU,CAAC,MAAM;GACvC,EAAK,OAAO,GACZ,EAAS,SAAS,GACb,MACD,KACA,MAAM,EAAY;IACd,QAAQ;IACR;IACA,SAAS,EAAY;IACrB;IACA,gBAAgB,KAAA;GACpB,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS,GAExB,KAAS,MAAM,EAAQ,OAAO,CAAG;EACzC;EACA,IAAI,QAAQ;GACR,OAAO;EACX;EACA,IAAI,SAAS;GACT,OAAO;EACX;EACA,IAAI,MAAM;GACN,OAAO;EACX;EACA;CACJ;AACJ"}
|
package/dist/http/retry.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}async function
|
|
1
|
+
const e=require("./errors.cjs");function t(t){return!e.isApiError(t)||e.isRetriableStatus(t.status)}function n(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))},{once:!0})})}async function r(e,r={}){let{retries:i=3,initialDelay:a=300,maxDelay:o=1e4,respectRetryAfter:s=!0,shouldRetry:c=t,onRetry:l,signal:u}=r,d=0,f;for(;d<i;){if(u?.aborted)throw new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(f=e,d+=1,d>=i||!c(e,d))throw e;let t=s&&typeof e?.retryAfter==`number`?e.retryAfter*1e3:null,r=Math.min(t===null?a*2**(d-1):t,o);l?.({attempt:d,delay:r,error:e}),await n(r,u)}}throw f}exports.retry=r;
|
|
2
2
|
//# sourceMappingURL=retry.cjs.map
|
package/dist/http/retry.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.cjs","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"retry.cjs","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"./errors\";\n\nexport interface RetryOptions {\n /** Max attempts (including the first). Default: 3. */\n retries?: number;\n /** Initial backoff in ms. Doubles each attempt, capped at `maxDelay`. Default: 300. */\n initialDelay?: number;\n /** Maximum delay between attempts. Default: 10_000. */\n maxDelay?: number;\n /**\n * Honor a `Retry-After` hint on the thrown error (`error.retryAfter`, in\n * seconds — populated by {@link createApiClient} on `429`/`503`). When\n * present it overrides the exponential backoff for that attempt. The value\n * is capped at `maxDelay`. Default: true.\n */\n respectRetryAfter?: boolean;\n /**\n * Return false to stop retrying for a specific error.\n *\n * Default: replay anything that is not a recognisable API error — a\n * transport failure has no status to judge — and, for one that is, only the\n * statuses {@link isRetriableStatus} accepts. A `403` on an admin-only\n * endpoint and a `404` for a deleted record are the server's final answer;\n * repeating them spends the caller's time to show the same error twice.\n */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n /** Called before each retry with the upcoming delay. */\n onRetry?: (info: { attempt: number; delay: number; error: unknown }) => void;\n /** Cancel pending retries. */\n signal?: AbortSignal;\n}\n\n/**\n * The default {@link RetryOptions.shouldRetry}.\n *\n * Permissive about what it cannot classify and strict about what it can: an\n * error with no API shape may well be a transport failure, while an API error\n * carrying a deliberate refusal will answer the same on every attempt.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the helper should try again.\n */\nfunction defaultShouldRetry(error: unknown): boolean {\n return !isApiError(error) || isRetriableStatus(error.status);\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n },\n { once: true },\n );\n });\n}\n\n/**\n * Run `factory()` with exponential backoff. Each attempt awaits an\n * increasing delay capped at `maxDelay`. Throws the last error if every\n * attempt fails.\n *\n * @example\n * const data = await retry(() => api.get(\"/flaky\"), { retries: 5 });\n */\nexport async function retry<T>(factory: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const {\n retries = 3,\n initialDelay = 300,\n maxDelay = 10_000,\n respectRetryAfter = true,\n shouldRetry = defaultShouldRetry,\n onRetry,\n signal,\n } = options;\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt < retries) {\n if (signal?.aborted) throw new DOMException(\"Aborted\", \"AbortError\");\n try {\n return await factory();\n } catch (error) {\n lastError = error;\n attempt += 1;\n if (attempt >= retries || !shouldRetry(error, attempt)) {\n throw error;\n }\n const retryAfter =\n respectRetryAfter &&\n typeof (error as { retryAfter?: unknown })?.retryAfter === \"number\"\n ? (error as { retryAfter: number }).retryAfter * 1000\n : null;\n const delay =\n retryAfter !== null\n ? Math.min(retryAfter, maxDelay)\n : Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n onRetry?.({ attempt, delay, error });\n await wait(delay, signal);\n }\n }\n\n throw lastError;\n}\n"],"mappings":"gCA0CA,SAAS,EAAmB,EAAyB,CACjD,MAAO,CAAC,EAAA,WAAW,CAAK,GAAK,EAAA,kBAAkB,EAAM,MAAM,CAC/D,CAEA,SAAS,EAAK,EAAY,EAAqC,CAC3D,OAAO,IAAI,SAAe,EAAS,IAAW,CAC1C,GAAI,GAAQ,QAAS,CACjB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,MACJ,CACA,IAAM,EAAQ,WAAW,EAAS,CAAE,EACpC,GAAQ,iBACJ,YACM,CACF,aAAa,CAAK,EAClB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,CACpD,EACA,CAAE,KAAM,EAAK,CACjB,CACJ,CAAC,CACL,CAUA,eAAsB,EAAS,EAA2B,EAAwB,CAAC,EAAe,CAC9F,GAAM,CACF,UAAU,EACV,eAAe,IACf,WAAW,IACX,oBAAoB,GACpB,cAAc,EACd,UACA,UACA,EAEA,EAAU,EACV,EAEJ,KAAO,EAAU,GAAS,CACtB,GAAI,GAAQ,QAAS,MAAM,IAAI,aAAa,UAAW,YAAY,EACnE,GAAI,CACA,OAAO,MAAM,EAAQ,CACzB,OAAS,EAAO,CAGZ,GAFA,EAAY,EACZ,GAAW,EACP,GAAW,GAAW,CAAC,EAAY,EAAO,CAAO,EACjD,MAAM,EAEV,IAAM,EACF,GACA,OAAQ,GAAoC,YAAe,SACpD,EAAiC,WAAa,IAC/C,KACJ,EAGI,KAAK,IAFX,IAAe,KAEA,EAAe,IAAM,EAAU,GAD/B,EACmC,CAAQ,EAC9D,IAAU,CAAE,UAAS,QAAO,OAAM,CAAC,EACnC,MAAM,EAAK,EAAO,CAAM,CAC5B,CACJ,CAEA,MAAM,CACV"}
|
package/dist/http/retry.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { isApiError as e, isRetriableStatus as t } from "./errors.js";
|
|
1
2
|
//#region src/http/retry.ts
|
|
2
|
-
function
|
|
3
|
+
function n(n) {
|
|
4
|
+
return !e(n) || t(n.status);
|
|
5
|
+
}
|
|
6
|
+
function r(e, t) {
|
|
3
7
|
return new Promise((n, r) => {
|
|
4
8
|
if (t?.aborted) {
|
|
5
9
|
r(new DOMException("Aborted", "AbortError"));
|
|
@@ -11,25 +15,25 @@ function e(e, t) {
|
|
|
11
15
|
}, { once: !0 });
|
|
12
16
|
});
|
|
13
17
|
}
|
|
14
|
-
async function
|
|
15
|
-
let { retries:
|
|
16
|
-
for (;
|
|
17
|
-
if (
|
|
18
|
+
async function i(e, t = {}) {
|
|
19
|
+
let { retries: i = 3, initialDelay: a = 300, maxDelay: o = 1e4, respectRetryAfter: s = !0, shouldRetry: c = n, onRetry: l, signal: u } = t, d = 0, f;
|
|
20
|
+
for (; d < i;) {
|
|
21
|
+
if (u?.aborted) throw new DOMException("Aborted", "AbortError");
|
|
18
22
|
try {
|
|
19
|
-
return await
|
|
20
|
-
} catch (
|
|
21
|
-
if (
|
|
22
|
-
let
|
|
23
|
-
|
|
24
|
-
attempt:
|
|
25
|
-
delay:
|
|
26
|
-
error:
|
|
27
|
-
}), await
|
|
23
|
+
return await e();
|
|
24
|
+
} catch (e) {
|
|
25
|
+
if (f = e, d += 1, d >= i || !c(e, d)) throw e;
|
|
26
|
+
let t = s && typeof e?.retryAfter == "number" ? e.retryAfter * 1e3 : null, n = Math.min(t === null ? a * 2 ** (d - 1) : t, o);
|
|
27
|
+
l?.({
|
|
28
|
+
attempt: d,
|
|
29
|
+
delay: n,
|
|
30
|
+
error: e
|
|
31
|
+
}), await r(n, u);
|
|
28
32
|
}
|
|
29
33
|
}
|
|
30
|
-
throw
|
|
34
|
+
throw f;
|
|
31
35
|
}
|
|
32
36
|
//#endregion
|
|
33
|
-
export {
|
|
37
|
+
export { i as retry };
|
|
34
38
|
|
|
35
39
|
//# sourceMappingURL=retry.js.map
|
package/dist/http/retry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"retry.js","names":[],"sources":["../../src/http/retry.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"./errors\";\n\nexport interface RetryOptions {\n /** Max attempts (including the first). Default: 3. */\n retries?: number;\n /** Initial backoff in ms. Doubles each attempt, capped at `maxDelay`. Default: 300. */\n initialDelay?: number;\n /** Maximum delay between attempts. Default: 10_000. */\n maxDelay?: number;\n /**\n * Honor a `Retry-After` hint on the thrown error (`error.retryAfter`, in\n * seconds — populated by {@link createApiClient} on `429`/`503`). When\n * present it overrides the exponential backoff for that attempt. The value\n * is capped at `maxDelay`. Default: true.\n */\n respectRetryAfter?: boolean;\n /**\n * Return false to stop retrying for a specific error.\n *\n * Default: replay anything that is not a recognisable API error — a\n * transport failure has no status to judge — and, for one that is, only the\n * statuses {@link isRetriableStatus} accepts. A `403` on an admin-only\n * endpoint and a `404` for a deleted record are the server's final answer;\n * repeating them spends the caller's time to show the same error twice.\n */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n /** Called before each retry with the upcoming delay. */\n onRetry?: (info: { attempt: number; delay: number; error: unknown }) => void;\n /** Cancel pending retries. */\n signal?: AbortSignal;\n}\n\n/**\n * The default {@link RetryOptions.shouldRetry}.\n *\n * Permissive about what it cannot classify and strict about what it can: an\n * error with no API shape may well be a transport failure, while an API error\n * carrying a deliberate refusal will answer the same on every attempt.\n *\n * @param error - Whatever the attempt threw.\n * @returns Whether the helper should try again.\n */\nfunction defaultShouldRetry(error: unknown): boolean {\n return !isApiError(error) || isRetriableStatus(error.status);\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n },\n { once: true },\n );\n });\n}\n\n/**\n * Run `factory()` with exponential backoff. Each attempt awaits an\n * increasing delay capped at `maxDelay`. Throws the last error if every\n * attempt fails.\n *\n * @example\n * const data = await retry(() => api.get(\"/flaky\"), { retries: 5 });\n */\nexport async function retry<T>(factory: () => Promise<T>, options: RetryOptions = {}): Promise<T> {\n const {\n retries = 3,\n initialDelay = 300,\n maxDelay = 10_000,\n respectRetryAfter = true,\n shouldRetry = defaultShouldRetry,\n onRetry,\n signal,\n } = options;\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt < retries) {\n if (signal?.aborted) throw new DOMException(\"Aborted\", \"AbortError\");\n try {\n return await factory();\n } catch (error) {\n lastError = error;\n attempt += 1;\n if (attempt >= retries || !shouldRetry(error, attempt)) {\n throw error;\n }\n const retryAfter =\n respectRetryAfter &&\n typeof (error as { retryAfter?: unknown })?.retryAfter === \"number\"\n ? (error as { retryAfter: number }).retryAfter * 1000\n : null;\n const delay =\n retryAfter !== null\n ? Math.min(retryAfter, maxDelay)\n : Math.min(initialDelay * 2 ** (attempt - 1), maxDelay);\n onRetry?.({ attempt, delay, error });\n await wait(delay, signal);\n }\n }\n\n throw lastError;\n}\n"],"mappings":";;AA0CA,SAAS,EAAmB,GAAyB;CACjD,OAAO,CAAC,EAAW,CAAK,KAAK,EAAkB,EAAM,MAAM;AAC/D;AAEA,SAAS,EAAK,GAAY,GAAqC;CAC3D,OAAO,IAAI,SAAe,GAAS,MAAW;EAC1C,IAAI,GAAQ,SAAS;GACjB,EAAO,IAAI,aAAa,WAAW,YAAY,CAAC;GAChD;EACJ;EACA,IAAM,IAAQ,WAAW,GAAS,CAAE;EACpC,GAAQ,iBACJ,eACM;GAEF,AADA,aAAa,CAAK,GAClB,EAAO,IAAI,aAAa,WAAW,YAAY,CAAC;EACpD,GACA,EAAE,MAAM,GAAK,CACjB;CACJ,CAAC;AACL;AAUA,eAAsB,EAAS,GAA2B,IAAwB,CAAC,GAAe;CAC9F,IAAM,EACF,aAAU,GACV,kBAAe,KACf,cAAW,KACX,uBAAoB,IACpB,iBAAc,GACd,YACA,cACA,GAEA,IAAU,GACV;CAEJ,OAAO,IAAU,IAAS;EACtB,IAAI,GAAQ,SAAS,MAAM,IAAI,aAAa,WAAW,YAAY;EACnE,IAAI;GACA,OAAO,MAAM,EAAQ;EACzB,SAAS,GAAO;GAGZ,IAFA,IAAY,GACZ,KAAW,GACP,KAAW,KAAW,CAAC,EAAY,GAAO,CAAO,GACjD,MAAM;GAEV,IAAM,IACF,KACA,OAAQ,GAAoC,cAAe,WACpD,EAAiC,aAAa,MAC/C,MACJ,IAGI,KAAK,IAFX,MAAe,OAEA,IAAe,MAAM,IAAU,KAD/B,GACmC,CAAQ;GAE9D,AADA,IAAU;IAAE;IAAS;IAAO;GAAM,CAAC,GACnC,MAAM,EAAK,GAAO,CAAM;EAC5B;CACJ;CAEA,MAAM;AACV"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./describe-api-error.cjs"),t=require("../i18n/I18nProvider.cjs");let n=require("react");function r(t,n,r){let i=t?.(n
|
|
1
|
+
const e=require("./describe-api-error.cjs"),t=require("../i18n/I18nProvider.cjs");let n=require("react");function r(t,n,r){let i=e.DEFAULT_API_ERROR_STRINGS[r];return t?.(n,void 0,{default:i})??i}function i(){let i=t.useOptionalI18n()?.t;return(0,n.useCallback)((t,n)=>e.describeApiError(t,n,{offline:r(i,e.API_ERROR_OFFLINE_KEY,`offline`),validation:r(i,e.API_ERROR_VALIDATION_KEY,`validation`)}),[i])}exports.useDescribeApiError=i;
|
|
2
2
|
//# sourceMappingURL=use-describe-api-error.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-describe-api-error.cjs","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * `t`
|
|
1
|
+
{"version":3,"file":"use-describe-api-error.cjs","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (error: unknown, fallback: string) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n });\n },\n [translate],\n );\n}\n"],"mappings":"yGAkDA,SAAS,EACL,EACA,EACA,EACM,CACN,IAAM,EAAW,EAAA,0BAA0B,GAC3C,OAAO,IAAY,EAAK,IAAA,GAAW,CAAE,QAAS,CAAS,CAAC,GAAK,CACjE,CAEA,SAAgB,GAAoE,CAEhF,IAAM,EADO,EAAA,gBACK,CAAA,EAAM,EAExB,OAAA,EAAO,EAAA,YAAA,EACF,EAAgB,IACN,EAAA,iBAAiB,EAAO,EAAU,CACrC,QAAS,EAAQ,EAAW,EAAA,sBAAuB,SAAS,EAC5D,WAAY,EAAQ,EAAW,EAAA,yBAA0B,YAAY,CACzE,CAAC,EAEL,CAAC,CAAS,CACd,CACJ"}
|
|
@@ -3,8 +3,8 @@ import { useOptionalI18n as i } from "../i18n/I18nProvider.js";
|
|
|
3
3
|
import { useCallback as a } from "react";
|
|
4
4
|
//#region src/http/use-describe-api-error.ts
|
|
5
5
|
function o(e, t, r) {
|
|
6
|
-
let i =
|
|
7
|
-
return
|
|
6
|
+
let i = n[r];
|
|
7
|
+
return e?.(t, void 0, { default: i }) ?? i;
|
|
8
8
|
}
|
|
9
9
|
function s() {
|
|
10
10
|
let n = i()?.t;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-describe-api-error.js","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * `t`
|
|
1
|
+
{"version":3,"file":"use-describe-api-error.js","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (error: unknown, fallback: string) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n });\n },\n [translate],\n );\n}\n"],"mappings":";;;;AAkDA,SAAS,EACL,GACA,GACA,GACM;CACN,IAAM,IAAW,EAA0B;CAC3C,OAAO,IAAY,GAAK,KAAA,GAAW,EAAE,SAAS,EAAS,CAAC,KAAK;AACjE;AAEA,SAAgB,IAAoE;CAEhF,IAAM,IADO,EACK,CAAA,EAAM;CAExB,OAAO,GACF,GAAgB,MACN,EAAiB,GAAO,GAAU;EACrC,SAAS,EAAQ,GAAW,GAAuB,SAAS;EAC5D,YAAY,EAAQ,GAAW,GAA0B,YAAY;CACzE,CAAC,GAEL,CAAC,CAAS,CACd;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>{let r=t[n];return r===void 0?`{${n}}`:String(r)}):e}function t(e,t,n,r){let i=e[t]?.[r];if(i!==void 0)return i;if(n){let t=e[n]?.[r];if(t!==void 0)return t}return null}function n(r){let{locale:i,fallbackLocale:a=null,messages:o}=r;function s(n,r){let
|
|
1
|
+
function e(e,t){return t?e.replace(/\{(\w+)\}/g,(e,n)=>{let r=t[n];return r===void 0?`{${n}}`:String(r)}):e}function t(e,t,n,r){let i=e[t]?.[r];if(i!==void 0)return i;if(n){let t=e[n]?.[r];if(t!==void 0)return t}return null}function n(r){let{locale:i,fallbackLocale:a=null,messages:o}=r;function s(n,r,s){let c=t(o,i,a,n)??s?.default;return c===void 0?n:e(c,r)}function c(n,r,s,c){let l=t(o,i,a,`${n}${r===1?`_one`:`_other`}`)??t(o,i,a,n)??c?.default;return l===void 0?n:e(l,{count:r,...s??{}})}function l(e,t){return new Intl.NumberFormat(i,t).format(e)}function u(e,t){let n=typeof e==`string`?new Date(e):e;return Number.isNaN(n.getTime())?``:new Intl.DateTimeFormat(i,t).format(n)}return{locale:i,fallbackLocale:a,t:s,plural:c,formatNumber:l,formatDate:u,withLocale:e=>n({locale:e,fallbackLocale:a??void 0,messages:o})}}exports.createI18n=n;
|
|
2
2
|
//# sourceMappingURL=create-i18n.cjs.map
|