@stacksjs/browser 0.75.669 → 0.75.674

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.
@@ -16,3 +16,4 @@ export * from './retry';
16
16
  export * from './sleep';
17
17
  export * from './throttle';
18
18
  export * from './vendors';
19
+ export * from './uploads';
@@ -1 +1 @@
1
- export*from"./base";export*from"./api-url";export*from"./billable";export*from"./date";export*from"./debounce";export*from"./fetch";export*from"./function";export*from"./guards";export*from"./lazy";export*from"./math";export*from"./plans";export*from"./promise";export*from"./random";export*from"./regex";export*from"./retry";export*from"./sleep";export*from"./throttle";export*from"./vendors";
1
+ export*from"./base";export*from"./api-url";export*from"./billable";export*from"./date";export*from"./debounce";export*from"./fetch";export*from"./function";export*from"./guards";export*from"./lazy";export*from"./math";export*from"./plans";export*from"./promise";export*from"./random";export*from"./regex";export*from"./retry";export*from"./sleep";export*from"./throttle";export*from"./vendors";export*from"./uploads";
@@ -0,0 +1,69 @@
1
+ /** A name for "this very file" that survives a reload: its name, size and last change. */
2
+ export declare function uploadResumeKey(file: Blob & { name?: string, lastModified?: number }, purpose?: string): string;
3
+ /**
4
+ * Uploads `file` in parts and answers its session id once every part is in.
5
+ * Throws `UploadRefused` when the server will not take it, an `AbortError`
6
+ * when cancelled (the session is then removed), and the last network error
7
+ * when a part keeps failing; called again with the same `resumeKey`, it
8
+ * carries on from the parts that made it.
9
+ */
10
+ export declare function uploadInParts(file: Blob, options: UploadInPartsOptions): Promise<UploadSession>;
11
+ /** Forgets a remembered session once the application has taken the upload, so the same file can be sent anew. */
12
+ export declare function forgetUpload(resumeKey: string, storage?: Pick<Storage, 'removeItem'> | null): void;
13
+ /**
14
+ * Sends a file in parts to an application's upload-session routes
15
+ * (`createUploadSessions` in `@stacksjs/storage`), so a large upload survives
16
+ * a dropped connection and fits under any gateway's body limit.
17
+ *
18
+ * Each part is its own request, retried on its own with a growing pause; a
19
+ * part that arrived is never sent again. With `resumeKey`, the session's id
20
+ * is remembered in the browser, so the same file picked again after a reload
21
+ * or a crash continues where it stopped.
22
+ *
23
+ * The routes it speaks to, all under `endpoint`:
24
+ *
25
+ * - `POST {endpoint}` `{ name, size, type, meta }` → the session
26
+ * - `GET {endpoint}/{id}` → the session, with the parts received
27
+ * - `PUT {endpoint}/{id}/parts/{index}` the part's bytes
28
+ * - `DELETE {endpoint}/{id}` when cancelled
29
+ *
30
+ * It answers the session's id. Asking the server to join the parts and attach
31
+ * the file to something is the application's own request, with that id.
32
+ *
33
+ * No dependencies and no globals beyond `fetch`: the transport is passed in,
34
+ * so an application's authenticated fetch (cookies, a bearer token, a native
35
+ * bridge) is the one used.
36
+ */
37
+ export declare interface UploadSession {
38
+ id: string
39
+ size: number
40
+ partBytes: number
41
+ parts: number
42
+ received: number[]
43
+ complete?: boolean
44
+ }
45
+ export declare interface UploadProgress {
46
+ loaded: number
47
+ total: number
48
+ }
49
+ export declare interface UploadInPartsOptions {
50
+ transport?: UploadTransport
51
+ endpoint: string
52
+ name?: string
53
+ meta?: Record<string, string>
54
+ concurrency?: number
55
+ retries?: number
56
+ signal?: AbortSignal
57
+ onProgress?: (progress: UploadProgress) => void
58
+ transportReportsProgress?: boolean
59
+ resumeKey?: string
60
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null
61
+ retryDelay?: number
62
+ }
63
+ export type UploadTransport = (path: string, init: RequestInit & { onUploadProgress?: (progress: UploadProgress) => void }) => Promise<Response>;
64
+ /** A refusal the server gave that sending again would not change. */
65
+ export declare class UploadRefused extends Error {
66
+ readonly status: number;
67
+ readonly body: unknown;
68
+ constructor(message: string, status: number, body: unknown);
69
+ }
@@ -0,0 +1 @@
1
+ export class UploadRefused extends Error{status;body;constructor(message,status,body){super(message);this.status=status;this.body=body;this.name="UploadRefused"}}export function uploadResumeKey(file,purpose=""){return`upload:${purpose}:${file.name??""}:${file.size}:${file.lastModified??""}`}const defaultTransport=(path,init)=>fetch(path,{credentials:"include",...init});function storageOf(options){if(options.storage!==undefined)return options.storage;try{return typeof localStorage==="undefined"?null:localStorage}catch{return null}}const aborted=(signal)=>{if(signal?.aborted)throw signal.reason??new DOMException("The upload was cancelled.","AbortError")};const isAbort=(error)=>error?.name==="AbortError";function pause(ms,signal){return new Promise((resolve,reject)=>{const done=()=>{signal?.removeEventListener("abort",stop);resolve()};const timer=setTimeout(done,ms);const stop=()=>{clearTimeout(timer);reject(signal.reason??new DOMException("The upload was cancelled.","AbortError"))};signal?.addEventListener("abort",stop,{once:true})})}const transient=(status)=>status===408||status===425||status===429||status>=500;async function refusal(response,fallback){const body=await response.json().catch(()=>null);return new UploadRefused(typeof body?.error==="string"&&body.error?body.error:fallback,response.status,body)}function retryAfter(response){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:0}export async function uploadInParts(file,options){const transport=options.transport??defaultTransport;const endpoint=options.endpoint.replace(/\/+$/,"");const retries=Math.max(0,options.retries??5);const delay=Math.max(1,options.retryDelay??500);const store=options.resumeKey?storageOf(options):null;const signal=options.signal;aborted(signal);async function attempt(send){let last;for(let tried=0;tried<=retries;tried++){aborted(signal);let wait=Math.min(15000,delay*2**tried);try{const response=await send();if(!transient(response.status))return response;last=await refusal(response,"The upload could not be sent. Try again.");wait=Math.max(wait,retryAfter(response))}catch(error){if(isAbort(error)||signal?.aborted)throw error;last=error}if(tried<retries)await pause(wait+Math.random()*wait*0.25,signal)}throw last}let session=null;const remembered=store?.getItem(options.resumeKey)||null;if(remembered&&/^[a-f0-9]{32}$/.test(remembered)){const response=await attempt(()=>transport(`${endpoint}/${remembered}`,{method:"GET",signal})).catch(()=>null);const found=response?.ok?await response.json().catch(()=>null):null;if(found?.upload?.id===remembered&&found.upload.size===file.size)session=found.upload;else store?.removeItem(options.resumeKey)}if(!session){const name=options.name??file.name??"upload";const response=await attempt(()=>transport(endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({name,size:file.size,type:file.type||"application/octet-stream",meta:options.meta??{}}),signal}));if(!response.ok)throw await refusal(response,"The upload could not be started.");session=(await response.json().catch(()=>null))?.upload??null;if(!session?.id||!(session.partBytes>0)||!(session.parts>0))throw new UploadRefused("The upload could not be started.",response.status,null);if(options.resumeKey)store?.setItem(options.resumeKey,session.id)}const{id,partBytes,parts}=session;const have=new Set(session.received);const sizeOf=(index)=>Math.min(partBytes,file.size-index*partBytes);const flying=new Map;let settled=0;for(const index of have)settled+=sizeOf(index);let reported=0;const report=()=>{let loaded=settled;for(const bytes of flying.values())loaded+=bytes;reported=Math.max(reported,Math.min(loaded,file.size));options.onProgress?.({loaded:reported,total:file.size})};report();const queue=[];for(let index=0;index<parts;index++){if(!have.has(index))queue.push(index)}async function sendPart(index){const body=file.slice(index*partBytes,index*partBytes+sizeOf(index));const response=await attempt(()=>{flying.set(index,0);return transport(`${endpoint}/${id}/parts/${index}`,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body,signal,...options.transportReportsProgress?{onUploadProgress:(progress)=>{flying.set(index,Math.min(progress.loaded,sizeOf(index)));report()}}:{}})}).catch((error)=>{flying.delete(index);throw error});flying.delete(index);if(!response.ok){if(response.status===404&&options.resumeKey)store?.removeItem(options.resumeKey);throw await refusal(response,"The upload could not be sent. Try again.")}settled+=sizeOf(index);report()}const workers=Array.from({length:Math.max(1,Math.min(options.concurrency??3,queue.length))},async()=>{for(let index=queue.shift();index!==undefined;index=queue.shift())await sendPart(index)});try{await Promise.all(workers)}catch(error){queue.length=0;await Promise.allSettled(workers);if(isAbort(error)||signal?.aborted){if(options.resumeKey)store?.removeItem(options.resumeKey);transport(`${endpoint}/${id}`,{method:"DELETE",keepalive:true}).catch(()=>{})}throw error}return{...session,received:Array.from({length:parts},(_,index)=>index),complete:false}}export function forgetUpload(resumeKey,storage){try{(storage??(typeof localStorage==="undefined"?null:localStorage))?.removeItem(resumeKey)}catch{}}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/browser",
3
3
  "type": "module",
4
- "version": "0.75.669",
4
+ "version": "0.75.674",
5
5
  "description": "Stacks core frontend/browser functionalities.",
6
6
  "author": "Chris Breuer",
7
7
  "contributors": [
@@ -74,10 +74,10 @@
74
74
  "prepublishOnly": "bun run build"
75
75
  },
76
76
  "dependencies": {
77
- "@stacksjs/composables": "0.75.669",
78
- "@stacksjs/datetime": "0.75.669",
79
- "@stacksjs/strings": "0.75.669",
80
- "@stacksjs/stx": "^0.2.930",
77
+ "@stacksjs/composables": "0.75.674",
78
+ "@stacksjs/datetime": "0.75.674",
79
+ "@stacksjs/strings": "0.75.674",
80
+ "@stacksjs/stx": "^0.2.931",
81
81
  "bun-query-builder": "^0.6.4"
82
82
  },
83
83
  "peerDependencies": {
@@ -89,7 +89,7 @@
89
89
  }
90
90
  },
91
91
  "devDependencies": {
92
- "@stacksjs/utils": "0.75.669",
92
+ "@stacksjs/utils": "0.75.674",
93
93
  "@stripe/stripe-js": "^10.0.0",
94
94
  "better-dx": "^0.2.39"
95
95
  }