@qooal/vault 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1028 @@
1
+ import {
2
+ VAULT_API_BASE,
3
+ VaultApiError,
4
+ abortError,
5
+ apiErrorFrom,
6
+ backoffMs,
7
+ idempotencyKey,
8
+ isRetryableStatus,
9
+ seg,
10
+ sleep
11
+ } from "./chunk-Z5XT6XS2.js";
12
+
13
+ // src/upload/perform.ts
14
+ var FORBIDDEN = /* @__PURE__ */ new Set(["host", "content-length", "connection", "expect", "transfer-encoding"]);
15
+ var xhrPut = (req) => new Promise((resolve, reject) => {
16
+ if (req.signal.aborted) return reject(abortError(req.signal));
17
+ const x = new XMLHttpRequest();
18
+ const onAbort = () => x.abort();
19
+ const answer = (status) => {
20
+ req.signal.removeEventListener("abort", onAbort);
21
+ resolve({
22
+ status,
23
+ etag: status ? x.getResponseHeader("ETag") : null,
24
+ text: status ? x.responseText : "",
25
+ retryAfter: status ? x.getResponseHeader("Retry-After") : null
26
+ });
27
+ };
28
+ x.open("PUT", req.url);
29
+ for (const [k, v] of Object.entries(req.headers)) x.setRequestHeader(k, v);
30
+ x.upload.addEventListener("progress", (e) => req.onProgress(e.loaded));
31
+ x.addEventListener("load", () => answer(x.status));
32
+ x.addEventListener("error", () => answer(0));
33
+ x.addEventListener("timeout", () => answer(0));
34
+ x.addEventListener("abort", () => {
35
+ req.signal.removeEventListener("abort", onAbort);
36
+ reject(abortError(req.signal));
37
+ });
38
+ req.signal.addEventListener("abort", onAbort, { once: true });
39
+ x.send(req.body);
40
+ });
41
+ function fetchPut(f = globalThis.fetch) {
42
+ return async (req) => {
43
+ try {
44
+ const r = await f(req.url, { method: "PUT", body: req.body, headers: req.headers, signal: req.signal });
45
+ const text = await r.text();
46
+ req.onProgress(req.body.size);
47
+ return { status: r.status, etag: r.headers.get("etag"), text, retryAfter: r.headers.get("retry-after") };
48
+ } catch {
49
+ if (req.signal.aborted) throw abortError(req.signal);
50
+ return { status: 0, etag: null, text: "", retryAfter: null };
51
+ }
52
+ };
53
+ }
54
+ function pickPut(opts) {
55
+ if (opts.put) return opts.put;
56
+ if (!opts.fetch && typeof XMLHttpRequest === "function") return xhrPut;
57
+ return fetchPut(opts.fetch);
58
+ }
59
+ function bounded(v, dflt, lo, hi, name) {
60
+ if (v === void 0) return dflt;
61
+ if (!Number.isInteger(v) || v < lo || v > hi) throw new RangeError(`${name} must be an integer ${lo}-${hi}`);
62
+ return v;
63
+ }
64
+ function putError(res) {
65
+ if (res.text.trimStart().startsWith("<")) {
66
+ const code = /<Code>([A-Za-z]+)<\/Code>/.exec(res.text)?.[1] ?? null;
67
+ return new VaultApiError({ status: res.status, code: "storage_error", reason: code });
68
+ }
69
+ return apiErrorFrom(res.status, res.text, res.retryAfter);
70
+ }
71
+ function retryable(res) {
72
+ return isRetryableStatus(res.status) || res.status === 400 && res.text.includes("<Code>RequestTimeout</Code>");
73
+ }
74
+ function headerMap(list) {
75
+ const out = {};
76
+ for (const h2 of list) {
77
+ const k = h2.name.toLowerCase();
78
+ if (!FORBIDDEN.has(k)) out[k] = h2.value;
79
+ }
80
+ return out;
81
+ }
82
+ async function performUpload(file, instructions, opts = {}) {
83
+ if (instructions.method === "simulated")
84
+ throw new VaultApiError({
85
+ status: 0,
86
+ code: "invalid",
87
+ reason: "simulated_upload",
88
+ message: "Simulated uploads are sample data: there is nowhere to send the bytes."
89
+ });
90
+ const concurrency = bounded(opts.concurrency, 4, 1, 16, "concurrency");
91
+ const retries = bounded(opts.retries, 3, 0, 10, "retries");
92
+ const put = pickPut(opts);
93
+ const outer = opts.signal;
94
+ if (outer?.aborted) throw abortError(outer);
95
+ const delay = opts.retryDelay ?? ((attempt, after) => after !== null ? Math.min(after, 30) * 1e3 : backoffMs(attempt));
96
+ const total = file.size;
97
+ const ctl = new AbortController();
98
+ const relay = () => ctl.abort(abortError(outer));
99
+ outer?.addEventListener("abort", relay, { once: true });
100
+ const loaded = /* @__PURE__ */ new Map();
101
+ const emit = () => {
102
+ if (!opts.onProgress) return;
103
+ let sum = 0;
104
+ for (const v of loaded.values()) sum += v;
105
+ opts.onProgress({ loaded: Math.min(sum, total), total });
106
+ };
107
+ const send = async (key, body, headers, url, refresh) => {
108
+ let target = await url();
109
+ for (let attempt = 0; ; attempt++) {
110
+ if (ctl.signal.aborted) throw abortError(ctl.signal);
111
+ loaded.set(key, 0);
112
+ const res = await put({
113
+ url: target,
114
+ body,
115
+ headers,
116
+ signal: ctl.signal,
117
+ onProgress: (n) => {
118
+ loaded.set(key, Math.min(n, body.size));
119
+ emit();
120
+ }
121
+ });
122
+ if (res.status >= 200 && res.status < 300) {
123
+ loaded.set(key, body.size);
124
+ emit();
125
+ return res;
126
+ }
127
+ loaded.set(key, 0);
128
+ emit();
129
+ const again = attempt < retries;
130
+ if (again && res.status === 403 && refresh) {
131
+ target = await refresh();
132
+ continue;
133
+ }
134
+ if (!again || !retryable(res)) throw putError(res);
135
+ const after = res.retryAfter !== null && /^\d+$/.test(res.retryAfter) ? Number(res.retryAfter) : null;
136
+ await sleep(delay(attempt, after), ctl.signal);
137
+ }
138
+ };
139
+ try {
140
+ if (instructions.method === "proxy" || instructions.method === "single") {
141
+ const headers = headerMap(instructions.headers);
142
+ const token = instructions.uploadToken ?? opts.uploadToken;
143
+ if (instructions.method === "proxy" && !headers.authorization && token)
144
+ headers.authorization = `VaultUpload ${token}`;
145
+ const body = file.slice(0, total, headers["content-type"] ?? "");
146
+ const res = await send(1, body, headers, async () => instructions.url, null);
147
+ const result = { uploadId: instructions.uploadId, method: instructions.method };
148
+ if (instructions.method === "proxy" && res.text) {
149
+ try {
150
+ result.asset = JSON.parse(res.text);
151
+ } catch {
152
+ }
153
+ }
154
+ return result;
155
+ }
156
+ const { partSize, partCount } = instructions;
157
+ if (!Number.isInteger(partSize) || partSize < 1 || partCount !== Math.max(1, Math.ceil(total / partSize)))
158
+ throw new VaultApiError({
159
+ status: 0,
160
+ code: "invalid",
161
+ reason: "size_mismatch",
162
+ message: `The file is ${total} bytes, which does not make ${partCount} parts of ${partSize} bytes.`
163
+ });
164
+ const partLength = (n) => Math.min(partSize, total - (n - 1) * partSize);
165
+ const urls = /* @__PURE__ */ new Map();
166
+ for (const p of instructions.parts) urls.set(p.n, p.url);
167
+ const done = /* @__PURE__ */ new Map();
168
+ for (const p of opts.done ?? [])
169
+ if (Number.isInteger(p.n) && p.n >= 1 && p.n <= partCount && p.etag) {
170
+ done.set(p.n, p.etag);
171
+ loaded.set(p.n, partLength(p.n));
172
+ }
173
+ emit();
174
+ const queue = [];
175
+ for (let n = 1; n <= partCount; n++) if (!done.has(n)) queue.push(n);
176
+ let next = 0;
177
+ let batch = null;
178
+ const urlFor = async (n) => {
179
+ for (; ; ) {
180
+ const have = urls.get(n);
181
+ if (have !== void 0) return have;
182
+ if (batch) {
183
+ await batch;
184
+ continue;
185
+ }
186
+ if (!opts.requestParts)
187
+ throw new VaultApiError({
188
+ status: 0,
189
+ code: "invalid",
190
+ reason: "missing_part_url",
191
+ message: `No URL for part ${n}, and no requestParts callback to ask for one.`
192
+ });
193
+ const want = [n];
194
+ for (let i = next; i < queue.length && want.length < 100; i++) {
195
+ const m = queue[i];
196
+ if (m !== n && !urls.has(m)) want.push(m);
197
+ }
198
+ const mine = opts.requestParts(want).then((parts2) => {
199
+ for (const p of parts2) urls.set(p.n, p.url);
200
+ });
201
+ batch = mine;
202
+ try {
203
+ await mine;
204
+ } finally {
205
+ batch = null;
206
+ }
207
+ if (ctl.signal.aborted) throw abortError(ctl.signal);
208
+ if (!urls.has(n))
209
+ throw new VaultApiError({
210
+ status: 0,
211
+ code: "invalid",
212
+ reason: "missing_part_url",
213
+ message: `requestParts did not return part ${n}.`
214
+ });
215
+ }
216
+ };
217
+ const state = { failure: null };
218
+ const worker = async () => {
219
+ while (state.failure === null && next < queue.length) {
220
+ const n = queue[next++];
221
+ const start = (n - 1) * partSize;
222
+ const res = await send(
223
+ n,
224
+ file.slice(start, start + partLength(n), ""),
225
+ {},
226
+ () => urlFor(n),
227
+ () => {
228
+ urls.delete(n);
229
+ return urlFor(n);
230
+ }
231
+ );
232
+ if (!res.etag)
233
+ throw new VaultApiError({
234
+ status: res.status,
235
+ code: "storage_error",
236
+ reason: "etag_missing",
237
+ message: "S3 answered without an ETag header (the bucket's CORS rules must expose ETag)."
238
+ });
239
+ done.set(n, res.etag);
240
+ opts.onPartDone?.({ n, etag: res.etag });
241
+ }
242
+ };
243
+ await Promise.all(
244
+ Array.from(
245
+ { length: Math.min(concurrency, Math.max(queue.length, 1)) },
246
+ () => worker().catch((error) => {
247
+ if (state.failure === null) {
248
+ state.failure = { error };
249
+ ctl.abort(error);
250
+ }
251
+ })
252
+ )
253
+ );
254
+ if (outer?.aborted) throw abortError(outer);
255
+ if (state.failure !== null) throw state.failure.error;
256
+ const parts = [];
257
+ for (let n = 1; n <= partCount; n++) parts.push({ n, etag: done.get(n) });
258
+ return { uploadId: instructions.uploadId, method: "multipart", parts };
259
+ } finally {
260
+ outer?.removeEventListener("abort", relay);
261
+ }
262
+ }
263
+
264
+ // src/upload/uploader.ts
265
+ var TICKET_REFUSALS = /* @__PURE__ */ new Set(["ticket_exhausted", "ticket_expired", "ticket_revoked"]);
266
+ function defaultStorage() {
267
+ try {
268
+ const s = globalThis.localStorage;
269
+ return s ?? null;
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+ function fileKey(library, file, filename) {
275
+ const modified = file.lastModified ?? 0;
276
+ return `qooal-vault:upload:${library}:${filename}:${file.size}:${modified}`;
277
+ }
278
+ var tokenAuth = (token) => `VaultUpload ${token}`;
279
+ function createUploader(options) {
280
+ if (!options.library) throw new TypeError("createUploader: `library` is required");
281
+ if (options.ticket === void 0 === (options.preset === void 0))
282
+ throw new TypeError("createUploader: give exactly one of `ticket` and `preset`");
283
+ if (options.preset !== void 0 && options.turnstile === void 0)
284
+ throw new TypeError("createUploader: an unsigned preset needs a `turnstile` token provider");
285
+ const base = (options.apiBase ?? VAULT_API_BASE).replace(/\/+$/, "");
286
+ const f = options.fetch ?? globalThis.fetch.bind(globalThis);
287
+ const retries = options.retries ?? 3;
288
+ const delay = options.retryDelay ?? ((attempt, after) => after !== null ? Math.min(after, 30) * 1e3 : backoffMs(attempt));
289
+ const storage = options.storage === void 0 ? defaultStorage() : options.storage;
290
+ const lib = seg(options.library);
291
+ let ticket = null;
292
+ const getTicket = async (fresh) => {
293
+ if (typeof options.ticket === "string") return options.ticket;
294
+ if (ticket === null || fresh) ticket = await options.ticket();
295
+ return ticket;
296
+ };
297
+ const getTurnstile = async () => typeof options.turnstile === "function" ? await options.turnstile() : options.turnstile;
298
+ const call = async (method, path, init) => {
299
+ const headers = { accept: "application/json" };
300
+ if (init.auth) headers.authorization = init.auth;
301
+ if (init.body !== void 0) headers["content-type"] = "application/json";
302
+ if (init.idem) headers["idempotency-key"] = init.idem;
303
+ for (let attempt = 0; ; attempt++) {
304
+ if (init.signal?.aborted) throw abortError(init.signal);
305
+ let err;
306
+ try {
307
+ const r = await f(`${base}${path}`, {
308
+ method,
309
+ headers,
310
+ body: init.body === void 0 ? null : JSON.stringify(init.body),
311
+ credentials: "omit",
312
+ signal: init.signal ?? null
313
+ });
314
+ const text = await r.text();
315
+ if (r.ok) return text ? JSON.parse(text) : void 0;
316
+ err = apiErrorFrom(r.status, text, r.headers.get("retry-after"));
317
+ } catch (e) {
318
+ if (init.signal?.aborted) throw abortError(init.signal);
319
+ if (e instanceof SyntaxError) throw e;
320
+ err = new VaultApiError({ status: 0, code: "network", message: e instanceof Error ? e.message : String(e) });
321
+ }
322
+ const again = init.retry === "unprocessed" ? err.status === 429 || err.status === 503 : isRetryableStatus(err.status);
323
+ if (init.retry === false || attempt >= retries || !again) throw err;
324
+ await sleep(delay(attempt, err.retryAfter), init.signal);
325
+ }
326
+ };
327
+ const uploadPath = (id) => `/libraries/${lib}/uploads/${seg(id)}`;
328
+ const abort = async (uploadId, uploadToken) => {
329
+ try {
330
+ await call("DELETE", uploadPath(uploadId), { auth: tokenAuth(uploadToken), retry: false });
331
+ } catch {
332
+ }
333
+ };
334
+ const create = async (file, o, filename) => {
335
+ const contentType = o.contentType || file.type || "application/octet-stream";
336
+ const idem = o.idempotencyKey ?? idempotencyKey();
337
+ const path = `/libraries/${lib}/uploads`;
338
+ if (options.preset !== void 0) {
339
+ if (o.folderId !== void 0 || o.publicId !== void 0 || o.overwrite !== void 0 || o.access !== void 0 || o.tags !== void 0)
340
+ throw new TypeError("An unsigned preset fixes folder, public ID, overwrite, access and tags; use a ticket.");
341
+ const body2 = {
342
+ uploadPreset: options.preset,
343
+ turnstileToken: await getTurnstile(),
344
+ filename,
345
+ bytes: file.size,
346
+ contentType
347
+ };
348
+ return call("POST", path, { body: body2, idem, signal: o.signal });
349
+ }
350
+ const body = { filename, bytes: file.size, contentType };
351
+ if (o.folderId !== void 0) body.folderId = o.folderId;
352
+ if (o.publicId !== void 0) body.publicId = o.publicId;
353
+ if (o.overwrite !== void 0) body.overwrite = o.overwrite;
354
+ if (o.access !== void 0) body.access = o.access;
355
+ if (o.tags !== void 0) body.tags = o.tags;
356
+ try {
357
+ return await call("POST", path, {
358
+ auth: `VaultTicket ${await getTicket(false)}`,
359
+ body,
360
+ idem,
361
+ signal: o.signal
362
+ });
363
+ } catch (e) {
364
+ const refused = e instanceof VaultApiError && (e.status === 401 || e.reason !== null && TICKET_REFUSALS.has(e.reason));
365
+ if (!refused || typeof options.ticket !== "function") throw e;
366
+ return call("POST", path, {
367
+ auth: `VaultTicket ${await getTicket(true)}`,
368
+ body,
369
+ idem: idempotencyKey(),
370
+ signal: o.signal
371
+ });
372
+ }
373
+ };
374
+ const resumable = async (key, size, signal) => {
375
+ if (!storage) return null;
376
+ let saved = null;
377
+ try {
378
+ const raw = storage.getItem(key);
379
+ saved = raw ? JSON.parse(raw) : null;
380
+ } catch {
381
+ saved = null;
382
+ }
383
+ if (!saved || !(Date.parse(saved.expiresAt) > Date.now()) || !(saved.partSize > 0) || saved.partCount !== Math.max(1, Math.ceil(size / saved.partSize))) {
384
+ if (saved) storage.removeItem(key);
385
+ return null;
386
+ }
387
+ try {
388
+ const status = await call("GET", uploadPath(saved.uploadId), {
389
+ auth: tokenAuth(saved.uploadToken),
390
+ signal
391
+ });
392
+ if (status.state !== "open" || status.method !== "multipart") throw new Error("not resumable");
393
+ const { partSize, partCount } = saved;
394
+ const done = status.parts.filter((p) => p.n >= 1 && p.n <= partCount && p.etag).filter((p) => p.size === Math.min(partSize, size - (p.n - 1) * partSize)).map((p) => ({ n: p.n, etag: p.etag }));
395
+ return {
396
+ token: saved.uploadToken,
397
+ done,
398
+ ins: {
399
+ uploadId: saved.uploadId,
400
+ method: "multipart",
401
+ partSize: saved.partSize,
402
+ partCount: saved.partCount,
403
+ parts: [],
404
+ expiresAt: saved.expiresAt,
405
+ // performUpload never reads the asset; a resumed upload learns it from `complete`.
406
+ asset: void 0,
407
+ uploadToken: saved.uploadToken
408
+ }
409
+ };
410
+ } catch {
411
+ if (signal?.aborted) throw abortError(signal);
412
+ storage.removeItem(key);
413
+ return null;
414
+ }
415
+ };
416
+ const upload = async (file, o = {}) => {
417
+ const filename = o.filename ?? file.name ?? "upload";
418
+ const key = fileKey(options.library, file, filename);
419
+ if (o.signal?.aborted) throw abortError(o.signal);
420
+ const resumed = o.resume === false ? null : await resumable(key, file.size, o.signal);
421
+ let ins;
422
+ let token;
423
+ if (resumed) {
424
+ ins = resumed.ins;
425
+ token = resumed.token;
426
+ } else {
427
+ ins = await create(file, o, filename);
428
+ if (ins.method === "simulated")
429
+ throw new VaultApiError({
430
+ status: 0,
431
+ code: "invalid",
432
+ reason: "simulated_upload",
433
+ message: "Simulated uploads are sample data: there is nowhere to send the bytes."
434
+ });
435
+ if (!ins.uploadToken) throw new VaultApiError({ status: 0, code: "invalid", reason: "missing_upload_token" });
436
+ token = ins.uploadToken;
437
+ if (ins.method === "multipart" && storage)
438
+ try {
439
+ const r = {
440
+ uploadId: ins.uploadId,
441
+ uploadToken: token,
442
+ partSize: ins.partSize,
443
+ partCount: ins.partCount,
444
+ expiresAt: ins.expiresAt
445
+ };
446
+ storage.setItem(key, JSON.stringify(r));
447
+ } catch {
448
+ }
449
+ }
450
+ const auth = tokenAuth(token);
451
+ const forget = () => {
452
+ try {
453
+ storage?.removeItem(key);
454
+ } catch {
455
+ }
456
+ };
457
+ try {
458
+ const sent = await performUpload(file, ins, {
459
+ ...o.onProgress ? { onProgress: o.onProgress } : {},
460
+ ...o.signal ? { signal: o.signal } : {},
461
+ ...options.concurrency !== void 0 ? { concurrency: options.concurrency } : {},
462
+ retries,
463
+ retryDelay: delay,
464
+ uploadToken: token,
465
+ ...options.put ? { put: options.put } : options.fetch ? { fetch: options.fetch } : {},
466
+ ...resumed ? { done: resumed.done } : {},
467
+ requestParts: async (partNumbers) => {
468
+ const r = await call("POST", `${uploadPath(ins.uploadId)}/parts`, {
469
+ auth,
470
+ body: { partNumbers },
471
+ signal: o.signal
472
+ });
473
+ return r.parts;
474
+ }
475
+ });
476
+ if (sent.method === "proxy") {
477
+ forget();
478
+ if (sent.asset) return sent.asset;
479
+ throw new VaultApiError({ status: 0, code: "invalid", reason: "missing_asset" });
480
+ }
481
+ const body = sent.parts ? { parts: sent.parts } : {};
482
+ const asset = await call("POST", `${uploadPath(ins.uploadId)}/complete`, {
483
+ auth,
484
+ body,
485
+ signal: o.signal,
486
+ retry: "unprocessed"
487
+ });
488
+ forget();
489
+ return asset;
490
+ } catch (e) {
491
+ const aborted = o.signal?.aborted === true;
492
+ if (aborted || ins.method !== "multipart") {
493
+ forget();
494
+ await abort(ins.uploadId, token);
495
+ }
496
+ throw aborted ? abortError(o.signal) : e;
497
+ }
498
+ };
499
+ return { upload, abort };
500
+ }
501
+
502
+ // src/upload/element.ts
503
+ var VAULT_UPLOADER_TAG = "qooal-vault-uploader";
504
+ var DEFAULT_LABELS = {
505
+ drop: "Drag and drop files here, or paste them",
506
+ browse: "Choose files",
507
+ camera: "Take a photo",
508
+ list: "Uploads",
509
+ waiting: "Waiting",
510
+ uploading: "Uploading",
511
+ processing: "Processing",
512
+ done: "Uploaded",
513
+ failed: "Failed",
514
+ cancelled: "Cancelled",
515
+ cancel: "Cancel",
516
+ retry: "Retry",
517
+ remove: "Remove",
518
+ tooLarge: "File is too large",
519
+ tooMany: "Too many files",
520
+ wrongType: "This file type is not accepted",
521
+ maxSize: "Up to {size} per file",
522
+ errors: {
523
+ file_too_large: "File is too large",
524
+ type_not_allowed: "This file type is not allowed",
525
+ storage_quota_exceeded: "Storage is full",
526
+ uploads_blocked: "Uploads are paused for this library",
527
+ origin_not_allowed: "Uploads are not allowed from this site",
528
+ turnstile_failed: "Verification failed, please retry",
529
+ ticket_exhausted: "Upload limit reached",
530
+ preset_rate_limited: "Too many uploads, try again shortly",
531
+ preset_cap_reached: "Upload limit reached",
532
+ library_suspended: "Uploads are unavailable",
533
+ network: "Network problem, please retry",
534
+ default: "Upload failed"
535
+ }
536
+ };
537
+ var CREDENTIAL_ATTRIBUTES = ["library", "ticket", "ticket-endpoint", "preset", "turnstile-sitekey", "api-base"];
538
+ var TURNSTILE_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
539
+ var turnstileLoad = null;
540
+ function loadTurnstile() {
541
+ const w = globalThis;
542
+ if (w.turnstile) return Promise.resolve(w.turnstile);
543
+ turnstileLoad ??= new Promise((resolve, reject) => {
544
+ const s = document.createElement("script");
545
+ s.src = TURNSTILE_SRC;
546
+ s.async = true;
547
+ s.addEventListener(
548
+ "load",
549
+ () => w.turnstile ? resolve(w.turnstile) : reject(new Error("Turnstile did not load"))
550
+ );
551
+ s.addEventListener("error", () => {
552
+ turnstileLoad = null;
553
+ reject(new Error("Turnstile did not load"));
554
+ });
555
+ document.head.appendChild(s);
556
+ });
557
+ return turnstileLoad;
558
+ }
559
+ function formatBytes(n) {
560
+ if (n < 1e3) return `${n} B`;
561
+ const units = ["KB", "MB", "GB", "TB"];
562
+ let v = n;
563
+ let i = -1;
564
+ while (v >= 1e3 && i < units.length - 1) {
565
+ v /= 1e3;
566
+ i++;
567
+ }
568
+ return `${v >= 100 ? Math.round(v) : Math.round(v * 10) / 10} ${units[i]}`;
569
+ }
570
+ function acceptsFile(file, accept) {
571
+ if (!accept?.trim()) return true;
572
+ const name = file.name.toLowerCase();
573
+ const type = file.type.toLowerCase();
574
+ return accept.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean).some(
575
+ (a) => a.startsWith(".") ? name.endsWith(a) : a.endsWith("/*") ? type.startsWith(a.slice(0, -1)) : type === a
576
+ );
577
+ }
578
+ var CSS = `
579
+ :host{--qv-bg:#fff;--qv-fg:#020b1f;--qv-muted:#4f566a;--qv-border:rgba(2,11,31,.18);--qv-accent:#1e4dff;--qv-accent-fg:#fff;--qv-soft:#e7ecff;--qv-link:#1e4dff;--qv-track:#eceef7;--qv-danger:#c9252f;--qv-success:#0e7a52;--qv-radius:14px;display:block;font:inherit;color:var(--qv-fg);color-scheme:light}
580
+ :host([hidden]){display:none}
581
+ @media (prefers-color-scheme:dark){:host(:not([theme=light])){--qv-bg:#0a1633;--qv-fg:#ebeef6;--qv-muted:#a3abc4;--qv-border:rgba(255,255,255,.18);--qv-soft:#142154;--qv-link:#a493ff;--qv-track:#0e1c40;--qv-danger:#ff7a7a;--qv-success:#4ade9a;color-scheme:dark}}
582
+ :host([theme=dark]){--qv-bg:#0a1633;--qv-fg:#ebeef6;--qv-muted:#a3abc4;--qv-border:rgba(255,255,255,.18);--qv-soft:#142154;--qv-link:#a493ff;--qv-track:#0e1c40;--qv-danger:#ff7a7a;--qv-success:#4ade9a;color-scheme:dark}
583
+ *{box-sizing:border-box}
584
+ .zone{display:flex;flex-direction:column;align-items:center;gap:12px;padding:28px 20px;text-align:center;background:var(--qv-bg);border:1.5px dashed var(--qv-border);border-radius:var(--qv-radius);transition:border-color .15s,background-color .15s}
585
+ .zone.over{border-color:var(--qv-accent);background:var(--qv-soft)}
586
+ :host([disabled]) .zone{opacity:.55}
587
+ svg{width:28px;height:28px;color:var(--qv-accent)}
588
+ p{margin:0}
589
+ .hint{font-size:.875em;color:var(--qv-muted)}
590
+ .actions{display:flex;flex-wrap:wrap;gap:8px;justify-content:center}
591
+ button{font:inherit;font-size:.875em;font-weight:600;cursor:pointer;border-radius:999px;padding:8px 16px;border:1px solid transparent}
592
+ button:disabled{cursor:not-allowed}
593
+ button:focus-visible{outline:2px solid var(--qv-accent);outline-offset:2px}
594
+ .primary{background:var(--qv-accent);color:var(--qv-accent-fg)}
595
+ .secondary{background:transparent;color:var(--qv-fg);border-color:var(--qv-border)}
596
+ .link{background:none;border:0;padding:4px 6px;color:var(--qv-link);font-weight:600}
597
+ ul{list-style:none;margin:12px 0 0;padding:0;display:grid;gap:8px}
598
+ ul:empty{display:none}
599
+ li{display:grid;grid-template-columns:1fr auto;gap:6px 12px;align-items:center;padding:12px 14px;background:var(--qv-bg);border:1px solid var(--qv-border);border-radius:var(--qv-radius)}
600
+ .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;font-size:.9em}
601
+ .status{font-size:.8em;color:var(--qv-muted)}
602
+ li[data-state=done] .status{color:var(--qv-success)}
603
+ li[data-state=failed] .status{color:var(--qv-danger)}
604
+ .bar{grid-column:1/-1;height:6px;border-radius:999px;background:var(--qv-track);overflow:hidden}
605
+ .bar>span{display:block;height:100%;width:0;background:var(--qv-accent);transition:width .2s}
606
+ li[data-state=done] .bar,li[data-state=failed] .bar,li[data-state=cancelled] .bar{display:none}
607
+ .btns{display:flex;gap:2px}
608
+ .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
609
+ @media (prefers-reduced-motion:reduce){.zone,.bar>span{transition:none}}
610
+ `;
611
+ var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15V4m0 0L8 8m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>';
612
+ function h(tag, props = {}, text) {
613
+ const el = document.createElement(tag);
614
+ for (const [k, v] of Object.entries(props)) el.setAttribute(k, v);
615
+ if (text !== void 0) el.textContent = text;
616
+ return el;
617
+ }
618
+ function createElementClass() {
619
+ return class QooalVaultUploader extends HTMLElement {
620
+ static formAssociated = true;
621
+ static get observedAttributes() {
622
+ return ["accept", "multiple", "disabled", "label", "max-bytes", "camera", ...CREDENTIAL_ATTRIBUTES];
623
+ }
624
+ #root;
625
+ #internals = null;
626
+ #options = {};
627
+ #items = [];
628
+ #running = 0;
629
+ #uploader = null;
630
+ #depth = 0;
631
+ #tsId = null;
632
+ #tsChain = Promise.resolve();
633
+ #tsWait = null;
634
+ #input;
635
+ #camInput;
636
+ #browse;
637
+ #camera;
638
+ #title;
639
+ #hint;
640
+ #list;
641
+ #live;
642
+ #zone;
643
+ constructor() {
644
+ super();
645
+ this.#root = this.attachShadow({ mode: "open" });
646
+ try {
647
+ this.#internals = this.attachInternals();
648
+ } catch {
649
+ this.#internals = null;
650
+ }
651
+ const style = h("style");
652
+ style.textContent = CSS;
653
+ this.#zone = h("div", { class: "zone", part: "dropzone" });
654
+ this.#zone.innerHTML = ICON;
655
+ this.#title = h("p", { class: "title" });
656
+ this.#hint = h("p", { class: "hint" });
657
+ const actions = h("div", { class: "actions" });
658
+ this.#browse = h("button", { type: "button", class: "primary", part: "button" });
659
+ this.#camera = h("button", { type: "button", class: "secondary", part: "button", hidden: "" });
660
+ this.#input = h("input", { type: "file", hidden: "", tabindex: "-1" });
661
+ this.#camInput = h("input", { type: "file", hidden: "", tabindex: "-1", capture: "environment" });
662
+ actions.append(this.#browse, this.#camera);
663
+ this.#zone.append(this.#title, this.#hint, actions, this.#input, this.#camInput);
664
+ this.#list = h("ul", { part: "list" });
665
+ this.#live = h("div", { class: "sr", "aria-live": "polite", role: "status" });
666
+ const slot = h("slot", { name: "turnstile" });
667
+ this.#root.append(style, this.#zone, slot, this.#list, this.#live);
668
+ this.#browse.addEventListener("click", () => this.#input.click());
669
+ this.#camera.addEventListener("click", () => this.#camInput.click());
670
+ for (const input of [this.#input, this.#camInput])
671
+ input.addEventListener("change", () => {
672
+ if (input.files) this.addFiles(input.files);
673
+ input.value = "";
674
+ });
675
+ this.#zone.addEventListener("dragenter", (e) => this.#drag(e, 1));
676
+ this.#zone.addEventListener("dragover", (e) => this.#drag(e, 0));
677
+ this.#zone.addEventListener("dragleave", (e) => this.#drag(e, -1));
678
+ this.#zone.addEventListener("drop", (e) => {
679
+ this.#drag(e, -this.#depth);
680
+ if (e.dataTransfer?.files.length) this.addFiles(e.dataTransfer.files);
681
+ });
682
+ this.#zone.addEventListener("click", (e) => {
683
+ if (e.target === this.#zone && !this.#disabled) this.#input.click();
684
+ });
685
+ this.#root.addEventListener("paste", (e) => {
686
+ if (e instanceof ClipboardEvent) this.#paste(e);
687
+ });
688
+ this.#render();
689
+ }
690
+ connectedCallback() {
691
+ if (this.getAttribute("paste") === "global") document.addEventListener("paste", this.#onGlobalPaste);
692
+ this.#render();
693
+ }
694
+ disconnectedCallback() {
695
+ document.removeEventListener("paste", this.#onGlobalPaste);
696
+ for (const it of this.#items) it.ctl?.abort();
697
+ }
698
+ attributeChangedCallback(name) {
699
+ if (CREDENTIAL_ATTRIBUTES.includes(name)) this.#uploader = null;
700
+ this.#render();
701
+ }
702
+ /** JS-only settings (a ticket function, a Turnstile provider, a custom fetch, labels). */
703
+ get options() {
704
+ return this.#options;
705
+ }
706
+ set options(v) {
707
+ this.#options = v ?? {};
708
+ this.#uploader = null;
709
+ this.#render();
710
+ }
711
+ /** Same as setting `options` (handy where assigning a property is awkward, e.g. from React state). */
712
+ configure(v) {
713
+ this.options = v;
714
+ }
715
+ /** Assets uploaded so far (in order). */
716
+ get assets() {
717
+ return this.#items.flatMap((it) => it.asset ? [it.asset] : []);
718
+ }
719
+ /** Queues files as if dropped. */
720
+ addFiles(files) {
721
+ if (this.#disabled) return;
722
+ const L = this.#labels;
723
+ const list = Array.from(files);
724
+ const max = this.#int("max-files") ?? (this.hasAttribute("multiple") ? Number.POSITIVE_INFINITY : 1);
725
+ const maxBytes = this.#int("max-bytes");
726
+ const accept = this.getAttribute("accept");
727
+ for (const file of list) {
728
+ const active = this.#items.filter((it) => it.state !== "failed" && it.state !== "cancelled").length;
729
+ let problem = null;
730
+ if (active >= max) problem = L.tooMany;
731
+ else if (!acceptsFile(file, accept)) problem = L.wrongType;
732
+ else if (maxBytes !== null && file.size > maxBytes) problem = L.tooLarge;
733
+ const item = this.#add(file);
734
+ if (problem) this.#set(item, "failed", problem, false);
735
+ }
736
+ this.#pump();
737
+ }
738
+ /** Removes every finished, failed or cancelled row. */
739
+ clear() {
740
+ for (const it of this.#items.slice()) if (it.state !== "uploading" && it.state !== "waiting") this.#remove(it);
741
+ }
742
+ get #disabled() {
743
+ return this.hasAttribute("disabled");
744
+ }
745
+ get #labels() {
746
+ const o = this.#options.labels ?? {};
747
+ return { ...DEFAULT_LABELS, ...o, errors: { ...DEFAULT_LABELS.errors, ...o.errors } };
748
+ }
749
+ #int(name) {
750
+ const v = this.getAttribute(name);
751
+ return v !== null && /^\d+$/.test(v.trim()) ? Number(v.trim()) : null;
752
+ }
753
+ #render() {
754
+ const L = this.#labels;
755
+ const accept = this.getAttribute("accept") ?? "";
756
+ const disabled = this.#disabled;
757
+ this.#title.textContent = this.getAttribute("label") ?? L.drop;
758
+ const maxBytes = this.#int("max-bytes");
759
+ this.#hint.textContent = maxBytes !== null ? L.maxSize.replace("{size}", formatBytes(maxBytes)) : "";
760
+ this.#hint.hidden = maxBytes === null;
761
+ this.#browse.textContent = L.browse;
762
+ this.#camera.textContent = L.camera;
763
+ this.#browse.disabled = disabled;
764
+ this.#camera.disabled = disabled;
765
+ this.#input.accept = accept;
766
+ this.#input.multiple = this.hasAttribute("multiple");
767
+ this.#camInput.accept = /video/.test(accept) ? "image/*,video/*" : "image/*";
768
+ const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
769
+ const imagesOk = !accept || /image|\.(jpe?g|png|heic|webp)/i.test(accept);
770
+ this.#camera.hidden = !coarse || !imagesOk || this.getAttribute("camera") === "off";
771
+ this.#list.setAttribute("aria-label", L.list);
772
+ }
773
+ #drag(e, step) {
774
+ if (!e.dataTransfer || this.#disabled) return;
775
+ e.preventDefault();
776
+ e.dataTransfer.dropEffect = "copy";
777
+ this.#depth = Math.max(0, this.#depth + step);
778
+ this.#zone.classList.toggle("over", this.#depth > 0);
779
+ }
780
+ #paste(e) {
781
+ const files = e.clipboardData?.files;
782
+ if (!files?.length || this.#disabled) return;
783
+ e.preventDefault();
784
+ this.addFiles(files);
785
+ }
786
+ #onGlobalPaste = (e) => {
787
+ if (e.composedPath().includes(this)) return;
788
+ this.#paste(e);
789
+ };
790
+ #add(file) {
791
+ const row = h("li", { part: "item" });
792
+ const item = { file, state: "waiting", loaded: 0, message: "", asset: null, ctl: null, row };
793
+ this.#items.push(item);
794
+ this.#list.append(row);
795
+ this.#draw(item);
796
+ return item;
797
+ }
798
+ #remove(item) {
799
+ item.ctl?.abort();
800
+ this.#items = this.#items.filter((it) => it !== item);
801
+ item.row.remove();
802
+ this.#syncForm();
803
+ }
804
+ #draw(item) {
805
+ const L = this.#labels;
806
+ const { file, state, row } = item;
807
+ row.dataset.state = state;
808
+ row.replaceChildren();
809
+ const name = h("span", { class: "name", title: file.name }, file.name);
810
+ const pct = file.size ? Math.floor(item.loaded / file.size * 100) : 0;
811
+ const text = state === "uploading" ? `${L.uploading} ${pct}% · ${formatBytes(file.size)}` : state === "failed" ? `${L.failed}: ${item.message}` : `${L[state]} · ${formatBytes(file.size)}`;
812
+ const status = h("span", { class: "status" }, text);
813
+ const info = h("div");
814
+ info.append(name, h("br"), status);
815
+ const btns = h("div", { class: "btns" });
816
+ const act = (label, fn) => {
817
+ const b = h("button", { type: "button", class: "link", "aria-label": `${label}: ${file.name}` }, label);
818
+ b.addEventListener("click", fn);
819
+ btns.append(b);
820
+ };
821
+ if (state === "uploading" || state === "waiting") act(L.cancel, () => this.#cancel(item));
822
+ if (state === "failed" || state === "cancelled") {
823
+ if (item.message !== L.tooMany && item.message !== L.wrongType && item.message !== L.tooLarge)
824
+ act(L.retry, () => this.#retry(item));
825
+ act(L.remove, () => this.#remove(item));
826
+ }
827
+ if (state === "done" || state === "processing") act(L.remove, () => this.#remove(item));
828
+ row.append(info, btns);
829
+ if (state === "uploading" || state === "waiting") {
830
+ const bar = h("div", {
831
+ class: "bar",
832
+ role: "progressbar",
833
+ "aria-label": `${L.uploading}: ${file.name}`,
834
+ "aria-valuemin": "0",
835
+ "aria-valuemax": "100",
836
+ "aria-valuenow": String(pct)
837
+ });
838
+ const fill = h("span");
839
+ fill.style.width = `${pct}%`;
840
+ bar.append(fill);
841
+ row.append(bar);
842
+ }
843
+ }
844
+ /** Updates a row's progress in place (redrawing it would move keyboard focus off its Cancel button). */
845
+ #progress(item) {
846
+ const L = this.#labels;
847
+ const pct = item.file.size ? Math.floor(item.loaded / item.file.size * 100) : 0;
848
+ const status = item.row.querySelector(".status");
849
+ const bar = item.row.querySelector(".bar");
850
+ const fill = bar?.querySelector("span");
851
+ if (!status || !bar || !fill) return this.#draw(item);
852
+ status.textContent = `${L.uploading} ${pct}% · ${formatBytes(item.file.size)}`;
853
+ bar.setAttribute("aria-valuenow", String(pct));
854
+ fill.style.width = `${pct}%`;
855
+ }
856
+ #set(item, state, message, announce = true) {
857
+ item.state = state;
858
+ item.message = message;
859
+ this.#draw(item);
860
+ if (announce) {
861
+ const L = this.#labels;
862
+ const word = state === "failed" ? `${L.failed}: ${message}` : L[state];
863
+ this.#live.textContent = `${item.file.name}: ${word}`;
864
+ }
865
+ }
866
+ #cancel(item) {
867
+ if (item.state === "waiting") this.#set(item, "cancelled", "");
868
+ else item.ctl?.abort();
869
+ }
870
+ #retry(item) {
871
+ item.loaded = 0;
872
+ this.#set(item, "waiting", "", false);
873
+ this.#pump();
874
+ }
875
+ #emit(type, detail) {
876
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
877
+ }
878
+ #syncForm() {
879
+ const name = this.getAttribute("name");
880
+ if (!this.#internals || !name) return;
881
+ const fd = new FormData();
882
+ for (const a of this.assets) fd.append(name, a.id);
883
+ try {
884
+ this.#internals.setFormValue(fd);
885
+ } catch {
886
+ }
887
+ }
888
+ /** One Turnstile token per call (tokens are single-use); calls queue so one challenge runs at a time. */
889
+ #turnstileToken = () => {
890
+ const run = async () => {
891
+ const sitekey = this.getAttribute("turnstile-sitekey");
892
+ if (!sitekey) throw new VaultApiError({ status: 0, code: "invalid", reason: "turnstile_failed" });
893
+ const ts = await loadTurnstile();
894
+ return new Promise((resolve, reject) => {
895
+ this.#tsWait = { resolve, reject };
896
+ if (this.#tsId === null) {
897
+ const box = h("div", { slot: "turnstile" });
898
+ this.append(box);
899
+ this.#tsId = ts.render(box, {
900
+ sitekey,
901
+ execution: "execute",
902
+ appearance: "interaction-only",
903
+ callback: (t) => this.#tsWait?.resolve(t),
904
+ "error-callback": () => this.#tsWait?.reject(new VaultApiError({ status: 0, code: "forbidden", reason: "turnstile_failed" }))
905
+ });
906
+ } else ts.reset(this.#tsId);
907
+ ts.execute(this.#tsId);
908
+ });
909
+ };
910
+ const next = this.#tsChain.then(run, run);
911
+ this.#tsChain = next.catch(() => void 0);
912
+ return next;
913
+ };
914
+ #getUploader() {
915
+ if (this.#uploader) return this.#uploader;
916
+ const o = this.#options;
917
+ const library = this.getAttribute("library");
918
+ if (!library) throw new VaultApiError({ status: 0, code: "invalid", reason: "missing_library" });
919
+ const preset = this.getAttribute("preset");
920
+ const endpoint = this.getAttribute("ticket-endpoint");
921
+ const fixed = this.getAttribute("ticket");
922
+ const base = { library };
923
+ const apiBase = this.getAttribute("api-base") ?? o.apiBase;
924
+ if (apiBase) base.apiBase = apiBase;
925
+ if (o.fetch) base.fetch = o.fetch;
926
+ if (o.put) base.put = o.put;
927
+ if (o.retryDelay) base.retryDelay = o.retryDelay;
928
+ if (o.concurrency !== void 0) base.concurrency = o.concurrency;
929
+ if (o.retries !== void 0) base.retries = o.retries;
930
+ if (o.storage !== void 0) base.storage = o.storage;
931
+ if (preset) {
932
+ base.preset = preset;
933
+ base.turnstile = o.turnstile ?? this.#turnstileToken;
934
+ } else if (o.ticket !== void 0) base.ticket = o.ticket;
935
+ else if (fixed) base.ticket = fixed;
936
+ else if (endpoint) {
937
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
938
+ base.ticket = async () => {
939
+ const r = await f(endpoint, {
940
+ method: "POST",
941
+ credentials: "same-origin",
942
+ headers: { accept: "application/json" }
943
+ });
944
+ const body = await r.json().catch(() => null);
945
+ if (!r.ok || typeof body?.ticket !== "string")
946
+ throw new VaultApiError({ status: r.status, code: "unauthorized", reason: "ticket_unavailable" });
947
+ return body.ticket;
948
+ };
949
+ } else throw new VaultApiError({ status: 0, code: "invalid", reason: "missing_credentials" });
950
+ this.#uploader = createUploader(base);
951
+ return this.#uploader;
952
+ }
953
+ #pump() {
954
+ const limit = 2;
955
+ for (const item of this.#items) {
956
+ if (this.#running >= limit) break;
957
+ if (item.state !== "waiting") continue;
958
+ this.#running++;
959
+ void this.#run(item).finally(() => {
960
+ this.#running--;
961
+ this.#pump();
962
+ if (this.#running === 0 && !this.#items.some((it) => it.state === "waiting"))
963
+ this.#emit("vault-complete", { assets: this.assets });
964
+ });
965
+ }
966
+ }
967
+ async #run(item) {
968
+ const L = this.#labels;
969
+ const ctl = new AbortController();
970
+ item.ctl = ctl;
971
+ item.loaded = 0;
972
+ this.#set(item, "uploading", "", false);
973
+ this.#emit("vault-start", { file: item.file });
974
+ try {
975
+ const tags = this.getAttribute("tags");
976
+ const opts = {
977
+ signal: ctl.signal,
978
+ onProgress: (p) => {
979
+ item.loaded = p.loaded;
980
+ this.#progress(item);
981
+ this.#emit("vault-progress", { file: item.file, loaded: p.loaded, total: p.total });
982
+ }
983
+ };
984
+ if (!this.hasAttribute("preset")) {
985
+ const folderId = this.getAttribute("folder-id");
986
+ const publicId = this.getAttribute("public-id");
987
+ const access = this.getAttribute("access");
988
+ if (folderId) opts.folderId = folderId;
989
+ if (publicId) opts.publicId = publicId;
990
+ if (access === "public" || access === "private" || access === "authenticated") opts.access = access;
991
+ if (tags)
992
+ opts.tags = tags.split(",").map((t) => t.trim()).filter(Boolean);
993
+ }
994
+ const asset = await this.#getUploader().upload(item.file, opts);
995
+ item.asset = asset;
996
+ this.#set(item, asset.state === "ready" ? "done" : "processing", "");
997
+ this.#syncForm();
998
+ this.#emit("vault-upload", { file: item.file, asset });
999
+ } catch (error) {
1000
+ if (ctl.signal.aborted) {
1001
+ this.#set(item, "cancelled", "");
1002
+ } else {
1003
+ const reason = error instanceof VaultApiError ? error.reason ?? error.code : "default";
1004
+ this.#set(item, "failed", L.errors[reason] ?? L.errors.default ?? L.failed);
1005
+ this.#emit("vault-error", { file: item.file, error });
1006
+ }
1007
+ } finally {
1008
+ item.ctl = null;
1009
+ }
1010
+ }
1011
+ };
1012
+ }
1013
+ function defineVaultUploader(tag = VAULT_UPLOADER_TAG) {
1014
+ if (typeof customElements === "undefined" || customElements.get(tag)) return;
1015
+ customElements.define(tag, createElementClass());
1016
+ }
1017
+
1018
+ export {
1019
+ xhrPut,
1020
+ fetchPut,
1021
+ performUpload,
1022
+ createUploader,
1023
+ VAULT_UPLOADER_TAG,
1024
+ DEFAULT_LABELS,
1025
+ formatBytes,
1026
+ acceptsFile,
1027
+ defineVaultUploader
1028
+ };