ranuts 0.3.0-alpha.1 → 0.4.0-alpha.1

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/CLAUDE.md CHANGED
@@ -27,14 +27,15 @@ from the **subpath that owns it** (below) — not from a deep source path.
27
27
  Each subpath is an independent, tree-shakeable barrel. Import from the subpath, never from
28
28
  `ranuts/dist/...` or `@/...` (that alias is internal to the source).
29
29
 
30
- | Import from | Source | What | Runtime |
31
- | --------------- | --------------------------- | --------------------------------------------------- | ---------------- |
32
- | `ranuts` | `index.ts` | Root barrel — re-exports the utils + visual surface | browser + node |
33
- | `ranuts/utils` | `src/utils/index.ts` | DOM/BOM, string, object, number, color, time, etc. | browser + node\* |
34
- | `ranuts/node` | `src/node/index.ts` | HTTP server, router, ws, fs, streams, middleware | **node only** |
35
- | `ranuts/visual` | `src/utils/visual/index.ts` | 2D rendering engine (Canvas / WebGL / WebGPU) | **browser only** |
36
- | `ranuts/i18n` | `src/utils/i18n.ts` | `I18nCore` / `createI18n` / `useI18n` — DOM-free | browser + node |
37
- | `ranuts/vnode` | `src/vnode/index.ts` | Snabbdom-style virtual DOM (`h`, `init`, modules) | browser |
30
+ | Import from | Source | What | Runtime |
31
+ | --------------- | --------------------------- | --------------------------------------------------- | ------------------ |
32
+ | `ranuts` | `index.ts` | Root barrel — re-exports the utils + visual surface | browser + node |
33
+ | `ranuts/utils` | `src/utils/index.ts` | DOM/BOM, string, object, number, color, time, etc. | browser + node\* |
34
+ | `ranuts/node` | `src/node/index.ts` | HTTP server, router, ws, fs, streams, middleware | **node only** |
35
+ | `ranuts/visual` | `src/utils/visual/index.ts` | 2D rendering engine (Canvas / WebGL / WebGPU) | **browser only** |
36
+ | `ranuts/i18n` | `src/utils/i18n.ts` | `I18nCore` / `createI18n` / `useI18n` — DOM-free | browser + node |
37
+ | `ranuts/sw` | `src/sw/index.ts` | Cache strategies + the precache protocol's SW half | **service worker** |
38
+ | `ranuts/vnode` | `src/vnode/index.ts` | Snabbdom-style virtual DOM (`h`, `init`, modules) | browser |
38
39
 
39
40
  \* `ranuts/utils` is broad: most functions are browser-oriented (touch `window`/`document`),
40
41
  but pure helpers (`str`, `obj`, `number`, `compose`, `cloneDeep`, …) run anywhere. Functions
@@ -153,15 +154,25 @@ Then `npm run doc:api`.
153
154
  - Never call `window.setTimeout` / `window.setInterval`. The bare globals work in Node, Web
154
155
  Workers and the browser alike; the `window.`-prefixed ones throw `ReferenceError` outside a
155
156
  document. (This is what made `throttle` unusable in SSR before 0.3.)
156
- - Keep `ranuts/node` server-only; never import it from browser-facing modules.
157
+ - Keep `ranuts/node` server-only; never import it from browser-facing modules. Same for
158
+ `ranuts/sw`: it runs in a `ServiceWorkerGlobalScope` with no `window`/`document`, which is
159
+ why it is its own entry rather than part of the utils barrel.
160
+
161
+ ### Ship both halves of a protocol, or neither
162
+
163
+ `WorkerClient` without `serveWorker` meant every worker re-implemented the same id echo and
164
+ error envelope — and each got to invent its own bug (a sync throw escaping the handler, a
165
+ rejection with no id so the caller waits forever). Same for `prefetchUrls({ serviceWorkerMessage })`
166
+ without `servePrecache`. When a helper defines a message shape, the counterpart that answers
167
+ it belongs in the library too; a JSDoc block saying "just echo the id back" is not a substitute.
157
168
 
158
169
  ### Anything that installs something must return how to uninstall it
159
170
 
160
171
  `debounce`, `throttle`, `watchMediaQuery`, `whenIdle`, `WorkerClient`, `QuestQueue` hand back
161
172
  something holding a timer, a listener or a worker. `replaceOld`, `handleConsole`,
162
- `handleFetchHook`, `handleXhrHook`, `handleError`, `handleClick` and `Monitor.start()` patch a
163
- global or register a listener. **All of them return a teardown function**, and callers are
164
- expected to use it.
173
+ `handleFetchHook`, `handleXhrHook`, `handleError`, `handleClick`, `serveWorker`,
174
+ `servePrecache` and `Monitor.start()` patch a global or register a listener. **All of them
175
+ return a teardown function**, and callers are expected to use it.
165
176
 
166
177
  A utility of this shape without a teardown path is incomplete. The failure modes are concrete:
167
178
  a pending timer firing into a destroyed component; a hot reload re-patching an already-patched
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{i as s}from"./enums-BAgbyGdH.js";import{A as a,B as t,C as n,D as o,E as r,F as m,G as i,H as p,I as f,J as j,K as c,L as l,M as u,N as h,O as x,P as b,Q as d,R as e,S as g,T as k,U as v,V as w,W as y,X as z,Y as A,Z as B,_ as C,a as D,b as E,c as F,d as H,f as I,g as L,h as M,i as N,j as O,k as P,l as R,m as S,n as T,o as U,p as V,q as W,r as _,s as q,t as G,u as J,v as K,w as Q,x as X,y as Y,z as Z}from"./color-Dohr9BXX.js";import{$,$t as ss,A as as,At as ts,B as ns,Bt as os,C as rs,Ct as ms,D as is,Dt as ps,E as fs,Et as js,F as cs,Ft as ls,G as us,Gt as hs,H as xs,Ht as bs,I as ds,It as es,J as gs,Jt as ks,K as vs,Kt as ws,L as ys,Lt as zs,M as As,Mt as Bs,N as Cs,Nt as Ds,O as Es,Ot as Fs,P as Hs,Pt as Is,Q as Ls,Qt as Ms,R as Ns,Rt as Os,S as Ps,St as Rs,T as Ss,Tt as Ts,U as Us,Ut as Vs,V as Ws,Vt as _s,W as qs,Wt as Gs,X as Js,Xt as Ks,Y as Qs,Yt as Xs,Z as Ys,Zt as Zs,_ as $s,_t as sa,a as aa,an as ta,at as na,b as oa,bt as ra,c as ma,cn as ia,ct as pa,d as fa,dt as ja,en as ca,et as la,f as ua,ft as ha,g as xa,gt as ba,h as da,ht as ea,i as ga,in as ka,it as va,j as wa,jt as ya,k as za,kt as Aa,l as Ba,lt as Ca,m as Da,mt as Ea,n as Fa,nn as Ha,nt as Ia,o as La,on as Ma,ot as Na,p as Oa,pt as Pa,q as Ra,qt as Sa,r as Ta,rn as Ua,rt as Va,s as Wa,sn as _a,st as qa,t as Ga,tn as Ja,tt as Ka,u as Qa,ut as Xa,v as Ya,vt as Za,w as $a,wt as st,x as at,xt as tt,y as nt,yt as ot,z as rt,zt as mt}from"./utils-BDtXHcK8.js";import{A as it,B as pt,C as ft,D as jt,E as ct,F as lt,H as ut,I as ht,L as xt,M as bt,N as dt,O as et,P as gt,R as kt,S as vt,T as wt,U as yt,V as zt,W as At,_ as Bt,a as Ct,b as Dt,c as Et,d as Ft,f as Ht,g as It,h as Lt,i as Mt,k as Nt,l as Ot,m as Pt,n as Rt,o as St,p as Tt,r as Ut,s as Vt,t as Wt,u as _t,v as qt,w as Gt,x as Jt,y as Kt,z as Qt}from"./i18n-Cf5TtRb4.js";import{n as Xt,t as Yt}from"./chain-CTywmh_H.js";export{vs as ADOPTED_SHEET_MARKER,Ra as ADOPTED_STYLE_MARKER,ya as AudioRecorder,Gs as BRIDGE_MARKER,hs as BridgeManager,Yt as Chain,ws as Client,G as Color,T as ColorScheme,Sa as DEFAULT_CHANNEL,ea as EventManager,_ as FMT,N as HEX_COLOR_REGEX,D as Hsl,U as Hsla,Wt as I18nCore,bt as MOBILE_MEDIA_QUERY,ca as Mathjs,f as MessageCodec,u as MimeType,La as Monitor,ks as Platform,Xs as PostMessageBridge,Ta as QuestQueue,q as RGBA_REGEX,F as RGB_REGEX,R as Rgb,J as Rgba,s as SyncHook,Ts as TOTP,$a as TimeoutError,qs as WebDB,cs as WorkerClient,da as ZIP_DEFLATE,xa as ZIP_STORED,Ks as acceptPortBridge,sa as addClassToElement,Ja as addNumSym,gs as adoptSheetText,Qs as adoptStyles,Ft as appendUrl,l as arrayBufferToString,js as audioVendor,Zs as bridgeManager,Ws as buildOffsets,ps as canvasVendor,e as changeHumpToLowerCase,Z as checkEncoding,pa as circ,t as clearBr,w as clearStr,Bs as cloneDeep,H as componentToHex,st as compose,Ht as connection,Js as convertImageToBase64,$s as crc32,Xt as create,Qa as createData,Za as createDocumentFragment,us as createHandoff,Rt as createI18n,ns as createLocalePath,Tt as createObjectURL,Ms as createPortBridge,Aa as createSignal,Vt as createStore,Ya as createZip,Ca as cubic,dt as currentDevice,Ys as cutRound,Rs as debounce,Ss as deferred,fs as delay,Mt as detectLanguage,Pt as durationHandler,Lt as encodeUrl,ot as escapeHtml,Xa as expo,Ia as fanShapedByArc,Ds as filterObj,pt as formatDate,Is as formatJson,It as getAllQueryString,Va as getAngle,va as getArcPointerByDeg,Bt as getCookie,qt as getCookieByName,h as getExtensions,Kt as getFrame,Ls as getImage,na as getLinearGradient,p as getMatchingSentences,$ as getMatrix,b as getMime,Da as getPerformance,Dt as getPixelRatio,Jt as getQuery,v as getRandomString,fa as getReportUrl,ga as getStatus,Na as getTangentByPointer,vt as getWindow,ms as handleConsole,ba as handleError,ma as handleFetchHook,Ba as handleXhrHook,I as hexToAlpha,V as hexToHsb,S as hexToHsv,M as hexToRgb,L as hsbToHsl,C as hsbToRgb,K as hslToHsb,Y as hslToHsv,E as hslToRgb,X as hsvToHsl,g as hsvToRgb,n as hue2rgb,ft as imageRequest,xs as indexForOffset,nt as inflateRaw,gt as isBangDevice,lt as isClient,ls as isEqual,la as isImageSize,Gt as isInIframe,ht as isMobile,wt as isSafari,y as isString,za as isUrlCached,xt as isWeiXin,Ga as loadScript,Et as localStorageGetItem,Ot as localStorageRemoveItem,_t as localStorageSetItem,kt as matchMediaQuery,Ha as mathjs,i as md5,_s as memoize,es as merge,zs as mergeExports,Ct as navigatorLanguage,as as networkAllowsDownload,ct as networkSpeed,At as noop,bs as once,Ka as opacity,ss as openPortBridge,Ua as parseChineseNumber,ka as parseEnglishNumber,ta as parseRomanNumber,Ma as perToNum,zt as performanceTime,wa as prefetchUrl,As as prefetchUrls,Cs as prefetchWhenIdle,ja as quad,ha as quart,jt as queryFlag,Os as querystring,Pa as quint,Q as randomColor,c as randomString,_a as range,ds as readFileAsArrayBuffer,ys as readFileAsDataURL,Ns as readFileAsText,rt as readFileAsUint8Array,oa as readZipEntries,at as readZipEntry,ra as removeClassToElement,et as removeGhosting,mt as replaceOld,ua as report,Nt as requestUrlToBuffer,St as resolveLocale,it as retain,Ps as rewriteZip,k as rgbToHex,r as rgbToHsb,o as rgbToHsl,x as rgbToHsv,P as rgbaString,a as rgbaToHex,O as rgbaToRgb,qa as roundRectByArc,Fa as scriptOnLoad,Us as segmentByRanges,os as setAttributeByGlobal,tt as setFontSize2html,m as setMime,Oa as setReportUrl,Ea as sine,Vs as singleFlight,aa as status,W as str2Xml,j as strParse,ts as subscribers,Wa as throttle,ut as timeFormat,yt as timestampToTime,A as toFullWidth,z as toHalfWidth,B as toString,ia as transformNumber,d as transformText,Ut as useI18n,Qt as watchMediaQuery,Fs as webglVendor,Hs as whenIdle,is as withTimeout,Es as withTimeoutFallback,rs as zipHasEntry};
1
+ import{i as s}from"./enums-BAgbyGdH.js";import{A as a,B as t,C as n,D as o,E as r,F as m,G as i,H as p,I as f,J as j,K as c,L as l,M as u,N as h,O as x,P as b,Q as d,R as e,S as g,T as k,U as v,V as w,W as y,X as z,Y as A,Z as B,_ as C,a as D,b as E,c as F,d as H,f as I,g as L,h as M,i as N,j as O,k as P,l as R,m as S,n as T,o as U,p as V,q as W,r as _,s as q,t as G,u as J,v as K,w as Q,x as X,y as Y,z as Z}from"./color-Dohr9BXX.js";import{$,$t as ss,A as as,At as ts,B as ns,Bt as os,C as rs,Ct as ms,D as is,Dt as ps,E as fs,Et as js,F as cs,Ft as ls,G as us,Gt as hs,H as xs,Ht as bs,I as ds,It as es,J as gs,Jt as ks,K as vs,Kt as ws,L as ys,Lt as zs,M as As,Mt as Bs,N as Cs,Nt as Ds,O as Es,Ot as Fs,P as Hs,Pt as Is,Q as Ls,Qt as Ms,R as Ns,Rt as Os,S as Ps,St as Rs,T as Ss,Tt as Ts,U as Us,Ut as Vs,V as Ws,Vt as _s,W as qs,Wt as Gs,X as Js,Xt as Ks,Y as Qs,Yt as Xs,Z as Ys,Zt as Zs,_ as $s,_t as sa,a as aa,an as ta,at as na,b as oa,bt as ra,c as ma,cn as ia,ct as pa,d as fa,dt as ja,en as ca,et as la,f as ua,ft as ha,g as xa,gt as ba,h as da,ht as ea,i as ga,in as ka,it as va,j as wa,jt as ya,k as za,kt as Aa,l as Ba,ln as Ca,lt as Da,m as Ea,mt as Fa,n as Ha,nn as Ia,nt as La,o as Ma,on as Na,ot as Oa,p as Pa,pt as Ra,q as Sa,qt as Ta,r as Ua,rn as Va,rt as Wa,s as _a,sn as qa,st as Ga,t as Ja,tn as Ka,tt as Qa,u as Xa,un as Ya,ut as Za,v as $a,vt as st,w as at,wt as tt,x as nt,xt as ot,y as rt,yt as mt,z as it,zt as pt}from"./utils-8TVtLBjA.js";import{A as ft,B as jt,C as ct,D as lt,E as ut,F as ht,H as xt,I as bt,L as dt,M as et,N as gt,O as kt,P as vt,R as wt,S as yt,T as zt,U as At,V as Bt,W as Ct,_ as Dt,a as Et,b as Ft,c as Ht,d as It,f as Lt,g as Mt,h as Nt,i as Ot,k as Pt,l as Rt,m as St,n as Tt,o as Ut,p as Vt,r as Wt,s as _t,t as qt,u as Gt,v as Jt,w as Kt,x as Qt,y as Xt,z as Yt}from"./i18n-Cf5TtRb4.js";import{n as Zt,t as $t}from"./chain-CTywmh_H.js";export{gs as ADOPTED_SHEET_MARKER,Qs as ADOPTED_STYLE_MARKER,Ds as AudioRecorder,ws as BRIDGE_MARKER,Ta as BridgeManager,$t as Chain,ks as Client,G as Color,T as ColorScheme,Xs as DEFAULT_CHANNEL,sa as EventManager,_ as FMT,N as HEX_COLOR_REGEX,D as Hsl,U as Hsla,qt as I18nCore,et as MOBILE_MEDIA_QUERY,Ia as Mathjs,f as MessageCodec,u as MimeType,Ma as Monitor,Ks as Platform,Zs as PostMessageBridge,Ua as QuestQueue,q as RGBA_REGEX,F as RGB_REGEX,R as Rgb,J as Rgba,s as SyncHook,ps as TOTP,at as TimeoutError,vs as WebDB,cs as WorkerClient,da as ZIP_DEFLATE,xa as ZIP_STORED,Ms as acceptPortBridge,mt as addClassToElement,Va as addNumSym,Js as adoptSheetText,Ys as adoptStyles,It as appendUrl,l as arrayBufferToString,Fs as audioVendor,ss as bridgeManager,Us as buildOffsets,Aa as canvasVendor,e as changeHumpToLowerCase,Z as checkEncoding,Za as circ,t as clearBr,w as clearStr,Is as cloneDeep,H as componentToHex,js as compose,Lt as connection,Ls as convertImageToBase64,$s as crc32,Zt as create,Xa as createData,ra as createDocumentFragment,Sa as createHandoff,Tt as createI18n,Ws as createLocalePath,Vt as createObjectURL,ca as createPortBridge,ya as createSignal,_t as createStore,$a as createZip,ja as cubic,gt as currentDevice,$ as cutRound,tt as debounce,Ss as deferred,fs as delay,Ot as detectLanguage,St as durationHandler,Nt as encodeUrl,ot as escapeHtml,ha as expo,va as fanShapedByArc,ls as filterObj,jt as formatDate,es as formatJson,Mt as getAllQueryString,na as getAngle,Oa as getArcPointerByDeg,Dt as getCookie,Jt as getCookieByName,h as getExtensions,Xt as getFrame,la as getImage,Ga as getLinearGradient,p as getMatchingSentences,Qa as getMatrix,b as getMime,Ea as getPerformance,Ft as getPixelRatio,Qt as getQuery,v as getRandomString,fa as getReportUrl,ga as getStatus,pa as getTangentByPointer,yt as getWindow,Ts as handleConsole,st as handleError,ma as handleFetchHook,Ba as handleXhrHook,I as hexToAlpha,V as hexToHsb,S as hexToHsv,M as hexToRgb,L as hsbToHsl,C as hsbToRgb,K as hslToHsb,Y as hslToHsv,E as hslToRgb,X as hsvToHsl,g as hsvToRgb,n as hue2rgb,ct as imageRequest,qs as indexForOffset,rt as inflateRaw,vt as isBangDevice,ht as isClient,zs as isEqual,La as isImageSize,Kt as isInIframe,bt as isMobile,zt as isSafari,y as isString,za as isUrlCached,dt as isWeiXin,Ja as loadScript,Ht as localStorageGetItem,Rt as localStorageRemoveItem,Gt as localStorageSetItem,wt as matchMediaQuery,ka as mathjs,i as md5,Vs as memoize,Os as merge,pt as mergeExports,Et as navigatorLanguage,as as networkAllowsDownload,ut as networkSpeed,Ct as noop,Gs as once,Wa as opacity,Ka as openPortBridge,xs as paginateText,ta as parseChineseNumber,Na as parseEnglishNumber,qa as parseRomanNumber,ia as perToNum,Bt as performanceTime,wa as prefetchUrl,As as prefetchUrls,Cs as prefetchWhenIdle,Ra as quad,Fa as quart,lt as queryFlag,os as querystring,ea as quint,Q as randomColor,c as randomString,Ca as range,ys as readFileAsArrayBuffer,Ns as readFileAsDataURL,it as readFileAsText,ns as readFileAsUint8Array,oa as readZipEntries,nt as readZipEntry,Rs as removeClassToElement,kt as removeGhosting,_s as replaceOld,ua as report,Pt as requestUrlToBuffer,Ut as resolveLocale,ft as retain,Ps as rewriteZip,k as rgbToHex,r as rgbToHsb,o as rgbToHsl,x as rgbToHsv,P as rgbaString,a as rgbaToHex,O as rgbaToRgb,Da as roundRectByArc,Ha as scriptOnLoad,us as segmentByRanges,ds as serveWorker,bs as setAttributeByGlobal,ms as setFontSize2html,m as setMime,Pa as setReportUrl,ba as sine,hs as singleFlight,aa as status,W as str2Xml,j as strParse,Bs as subscribers,_a as throttle,xt as timeFormat,At as timestampToTime,A as toFullWidth,z as toHalfWidth,B as toString,Ya as transformNumber,d as transformText,Wt as useI18n,Yt as watchMediaQuery,ts as webglVendor,Hs as whenIdle,is as withTimeout,Es as withTimeoutFallback,rs as zipHasEntry};
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Service Worker building blocks.
3
+ *
4
+ * A companion to `prefetchUrls` / `prefetchWhenIdle` in `ranuts/utils`: those ship the page
5
+ * side of the "warm the cache in the background" protocol, and {@link servePrecache} is the
6
+ * worker side that answers them. The two caching strategies below are the standard pair every
7
+ * SW ends up writing.
8
+ *
9
+ * Its own entry point (`ranuts/sw`) rather than part of `ranuts/utils`, because this code runs
10
+ * in a `ServiceWorkerGlobalScope` where `window` and `document` do not exist — pulling in the
11
+ * general utils barrel would drag DOM-facing modules into a worker bundle.
12
+ *
13
+ * All of it assumes a bundled service worker. A hand-written `sw.js` served as a static file
14
+ * cannot import from node_modules; either bundle it, or copy the pieces you need.
15
+ */
16
+ /**
17
+ * The bit of `ExtendableMessageEvent` used here, declared locally rather than pulled from
18
+ * `lib.webworker` — that lib conflicts with `lib.dom` in a project that compiles both, and
19
+ * this package must stay importable from either.
20
+ */
21
+ export interface PrecacheMessageEvent {
22
+ data: unknown;
23
+ waitUntil: (promise: Promise<unknown>) => void;
24
+ }
25
+ /** Minimal view of the SW global the helpers touch, so they can be unit-tested with a stub. */
26
+ export interface SWScope {
27
+ caches: CacheStorage;
28
+ fetch: typeof fetch;
29
+ addEventListener: (type: string, listener: (event: never) => void) => void;
30
+ removeEventListener: (type: string, listener: (event: never) => void) => void;
31
+ }
32
+ export interface CacheStrategyOptions {
33
+ /** Cache to read and write. */
34
+ cacheName: string;
35
+ /** Whether a response may be stored. Default: any GET answered with 200. */
36
+ shouldCache?: (request: Request, response: Response) => boolean;
37
+ /** Scope override, for tests or a non-global worker. */
38
+ scope?: SWScope;
39
+ }
40
+ /**
41
+ * @description: Cache-first: serve the stored copy when there is one, otherwise fetch and
42
+ * store. For immutable, content-hashed assets — scripts, styles, fonts, model weights.
43
+ *
44
+ * @param {Request} request
45
+ * @param {CacheStrategyOptions} options
46
+ * @return {Promise<Response>} never rejects; a network failure resolves to a 408
47
+ */
48
+ export declare const cacheFirst: (request: Request, options: CacheStrategyOptions) => Promise<Response>;
49
+ /**
50
+ * @description: Network-first: go to the network, store what comes back, and fall back to the
51
+ * cache when offline. For anything that must reflect a deploy immediately — HTML navigations,
52
+ * a manifest, an API response you also want available offline.
53
+ *
54
+ * @param {Request} request
55
+ * @param {CacheStrategyOptions} options
56
+ * @return {Promise<Response>} never rejects; offline with nothing cached resolves to a 408
57
+ */
58
+ export declare const networkFirst: (request: Request, options: CacheStrategyOptions) => Promise<Response>;
59
+ /**
60
+ * @description: Fill a cache with a list of URLs, skipping what is already there. Failures are
61
+ * per-URL and silent — one 404 in a precache list must not abort the install.
62
+ *
63
+ * @param {string} cacheName
64
+ * @param {string[]} urls
65
+ * @param {object} options
66
+ * @return {Promise<void>}
67
+ */
68
+ export declare const precache: (cacheName: string, urls: readonly string[], options?: {
69
+ scope?: SWScope;
70
+ }) => Promise<void>;
71
+ /**
72
+ * @description: Delete every cache except the ones named. Call it on `activate` so a new
73
+ * build's caches replace the previous build's instead of accumulating.
74
+ *
75
+ * @param {string[]} keep cache names to preserve
76
+ * @param {object} options
77
+ * @return {Promise<string[]>} the names that were deleted
78
+ */
79
+ export declare const dropCachesExcept: (keep: readonly string[], options?: {
80
+ scope?: SWScope;
81
+ }) => Promise<string[]>;
82
+ export interface ServePrecacheOptions {
83
+ /** Cache the URLs land in. */
84
+ cacheName: string;
85
+ /** Message `type` to answer. Must match `prefetchUrls({ serviceWorkerMessage })`. */
86
+ type: string;
87
+ scope?: SWScope;
88
+ }
89
+ /**
90
+ * @description: Answer the precache messages that `prefetchUrls({ serviceWorkerMessage })`
91
+ * posts from the page — the worker half of that protocol.
92
+ *
93
+ * Downloading here rather than on the page is the whole point: the work is wrapped in
94
+ * `event.waitUntil`, so the service worker stays alive through navigations. A page-side fetch
95
+ * is aborted the moment the user clicks away, and a large asset then restarts from zero on the
96
+ * next visit.
97
+ *
98
+ * @param {ServePrecacheOptions} options
99
+ * @return {Function} stop — removes the listener
100
+ * @example
101
+ * ```ts
102
+ * // sw.ts
103
+ * servePrecache({ type: 'precache-models', cacheName: 'models' });
104
+ *
105
+ * // page
106
+ * prefetchUrls(modelFiles, { serviceWorkerMessage: 'precache-models' });
107
+ * ```
108
+ */
109
+ export declare const servePrecache: (options: ServePrecacheOptions) => (() => void);
@@ -0,0 +1 @@
1
+ var e=()=>globalThis,t=()=>new Response("Network error happened",{status:408,headers:{"Content-Type":"text/plain"}}),c=(e,t)=>"GET"===e.method&&200===t.status,a=(e,t,c,a)=>{const s=a.clone();return e.caches.open(t).then(e=>e.put(c.url,s)).catch(()=>{})},s=async(s,n)=>{const r=n.scope??e(),o=n.shouldCache??c;try{const e=await r.caches.match(s.url);if(e)return e;const t=await r.fetch(s);return o(s,t)&&a(r,n.cacheName,s,t),t}catch{return t()}},n=async(s,n)=>{const r=n.scope??e(),o=n.shouldCache??c;try{const e=await r.fetch(s);return o(s,e)&&a(r,n.cacheName,s,e),e}catch{return await r.caches.match(s.url).catch(()=>{})??t()}},r=async(t,c,a={})=>{const s=a.scope??e(),n=await s.caches.open(t);for(const e of c)try{if(await n.match(e))continue;const t=await s.fetch(e,{cache:"force-cache"});t.ok&&await n.put(e,t.clone())}catch{}},o=async(t,c={})=>{const a=c.scope??e(),s=(await a.caches.keys()).filter(e=>!t.includes(e));return await Promise.all(s.map(e=>a.caches.delete(e))),s},h=t=>{const c=t.scope??e(),a=e=>{const a=e.data;a&&a.type===t.type&&Array.isArray(a.urls)&&e.waitUntil(r(t.cacheName,a.urls,{scope:c}))};return c.addEventListener("message",a),()=>c.removeEventListener("message",a)};export{s as cacheFirst,o as dropCachesExcept,n as networkFirst,r as precache,h as servePrecache};
@@ -11,10 +11,15 @@
11
11
  export declare const readFileAsArrayBuffer: (blob: Blob) => Promise<ArrayBuffer>;
12
12
  /**
13
13
  * @description: Read a File / Blob as a Uint8Array (pair with checkEncoding / arrayBufferToString for encoding sniffing)
14
+ *
15
+ * Typed as `Uint8Array<ArrayBuffer>`, not the default `Uint8Array<ArrayBufferLike>`: a
16
+ * FileReader never yields a SharedArrayBuffer, and the loose form does not satisfy APIs that
17
+ * ask for an ArrayBuffer-backed view, forcing callers into a pointless cast.
18
+ *
14
19
  * @param {Blob} blob
15
- * @return {Promise<Uint8Array>}
20
+ * @return {Promise<Uint8Array<ArrayBuffer>>}
16
21
  */
17
- export declare const readFileAsUint8Array: (blob: Blob) => Promise<Uint8Array>;
22
+ export declare const readFileAsUint8Array: (blob: Blob) => Promise<Uint8Array<ArrayBuffer>>;
18
23
  /**
19
24
  * @description: Read a File / Blob as text
20
25
  * @param {Blob} blob
@@ -132,6 +132,46 @@ export declare class WebDB {
132
132
  clear: ({ storeName }: {
133
133
  storeName: string;
134
134
  }) => Promise<IDBResult>;
135
+ /**
136
+ * @description: A typed, forgiving handle on one object store. Binds the store name once
137
+ * instead of repeating it at every call, and returns plain values rather than `IDBResult`.
138
+ *
139
+ * **Every method swallows failures** and answers with the empty case (`null` / `[]` /
140
+ * `false` / `0`). That is the right default for the storage most apps put in IndexedDB —
141
+ * reading progress, drafts, caches — where a failed read should degrade the feature, not
142
+ * take down the screen. It is the wrong default when the write *is* the user's action
143
+ * (saving a document, completing a purchase): there, call the `IDBResult` methods above and
144
+ * handle the error.
145
+ *
146
+ * @param {string} name object store name (must be declared in `stores`)
147
+ * @return {IDBCollection<T>}
148
+ * @example
149
+ * ```ts
150
+ * const notes = db.collection<BookNote>('books_notes');
151
+ * await notes.put(note); // false if it failed
152
+ * const all = await notes.all(); // [] if it failed
153
+ * const one = await notes.get(id); // null if missing or failed
154
+ * ```
155
+ */
156
+ collection: <T = unknown>(name: string) => IDBCollection<T>;
157
+ }
158
+ /** A store name bound once, values unwrapped, failures folded into the empty case */
159
+ export interface IDBCollection<T> {
160
+ readonly name: string;
161
+ /** The record, or `null` when missing or unreadable */
162
+ get: (key: IDBValidKey) => Promise<T | null>;
163
+ /** Every record, or `[]` on failure */
164
+ all: () => Promise<T[]>;
165
+ /** Record count, or `0` on failure */
166
+ count: () => Promise<number>;
167
+ /** Insert; `false` if the key already exists or the write failed */
168
+ add: (value: T) => Promise<boolean>;
169
+ /** Insert or overwrite; `false` on failure */
170
+ put: (value: T) => Promise<boolean>;
171
+ /** Delete one record; `false` on failure */
172
+ remove: (key: IDBValidKey) => Promise<boolean>;
173
+ /** Empty the store; `false` on failure */
174
+ clear: () => Promise<boolean>;
135
175
  }
136
176
  export interface HandoffOptions {
137
177
  /** Database name. Both sides of the handoff must agree on this. */
@@ -29,8 +29,10 @@ import { ADOPTED_SHEET_MARKER, ADOPTED_STYLE_MARKER, adoptSheetText, adoptStyles
29
29
  import { memoize, once, singleFlight } from './memoize';
30
30
  import type { SingleFlight } from './memoize';
31
31
  import { WebDB, createHandoff } from './idb';
32
- import type { Handoff, HandoffOptions, IDBResult, IDBStoreSchema, WebDBOptions } from './idb';
32
+ import type { Handoff, HandoffOptions, IDBCollection, IDBResult, IDBStoreSchema, WebDBOptions } from './idb';
33
33
  import { buildOffsets, indexForOffset, segmentByRanges } from './segment';
34
+ import { paginateText } from './paginate';
35
+ import type { PaginateOptions, PaginateResult, TextBox, TextGridMetrics, TextPage } from './paginate';
34
36
  import type { OffsetRange, Segment } from './segment';
35
37
  import { detectLanguage, navigatorLanguage, resolveLocale } from './lang';
36
38
  import { I18nCore, createI18n, useI18n } from './i18n';
@@ -39,8 +41,8 @@ import { createLocalePath } from './localePath';
39
41
  import type { LocalePath, LocalePathConfig, LocaleRoute } from './localePath';
40
42
  import type { ResolveLocaleOptions, TextLanguage } from './lang';
41
43
  import { readFileAsArrayBuffer, readFileAsDataURL, readFileAsText, readFileAsUint8Array } from './file';
42
- import { WorkerClient } from './worker';
43
- import type { WorkerClientOptions, WorkerResponseBase } from './worker';
44
+ import { WorkerClient, serveWorker } from './worker';
45
+ import type { ServeWorkerOptions, WorkerClientOptions, WorkerHandlerContext, WorkerRequestBase, WorkerResponseBase } from './worker';
44
46
  import { isUrlCached, networkAllowsDownload, prefetchUrl, prefetchUrls, prefetchWhenIdle, whenIdle } from './prefetch';
45
47
  import type { NetworkAllowanceOptions, PrefetchOptions, WhenIdleOptions } from './prefetch';
46
48
  import { TimeoutError, deferred, delay, withTimeout, withTimeoutFallback } from './async';
@@ -63,5 +65,5 @@ import { formatDate, performanceTime, timeFormat, timestampToTime } from './time
63
65
  import type { CurrentDevice } from './device';
64
66
  import { MOBILE_MEDIA_QUERY, currentDevice, isBangDevice, isClient, isMobile, isWeiXin, matchMediaQuery, watchMediaQuery } from './device';
65
67
  import { Color, ColorScheme, FMT, HEX_COLOR_REGEX, Hsl, Hsla, RGBA_REGEX, RGB_REGEX, Rgb, Rgba, componentToHex, hexToAlpha, hexToHsb, hexToHsv, hexToRgb, hsbToHsl, hsbToRgb, hslToHsb, hslToHsv, hslToRgb, hsvToHsl, hsvToRgb, hue2rgb, randomColor, rgbToHex, rgbToHsb, rgbToHsl, rgbToHsv, rgbaString, rgbaToHex, rgbaToRgb } from '@/utils/color';
66
- export { performanceTime, timeFormat, timestampToTime, throttle, SyncHook, changeHumpToLowerCase, clearBr, clearStr, isString, randomString, str2Xml, strParse, scriptOnLoad, handleFetchHook, createData, report, QuestQueue, noop, getPerformance, querystring, formatJson, filterObj, merge, replaceOld, mergeExports, perToNum, range, Mathjs, mathjs, getStatus, status, Monitor, MimeType, getExtensions, setMime, getMime, memoize, once, isImageSize, convertImageToBase64, handleError, addClassToElement, removeClassToElement, createDocumentFragment, escapeHtml, isClient, isWeiXin, isMobile, debounce, currentDevice, handleConsole, compose, Color, FMT, Hsl, Hsla, Rgb, Rgba, randomColor, hexToRgb, componentToHex, rgbToHex, rgbToHsl, hue2rgb, hslToRgb, rgbToHsb, hsbToRgb, hsvToRgb, hsvToHsl, ColorScheme, AudioRecorder, webglVendor, canvasVendor, audioVendor, retain, getCookie, requestUrlToBuffer, getPixelRatio, createObjectURL, getFrame, getAllQueryString, queryFlag, isInIframe, appendUrl, removeGhosting, getCookieByName, getWindow, connection, encodeUrl, imageRequest, durationHandler, networkSpeed, TOTP, isBangDevice, localStorageGetItem, localStorageSetItem, localStorageRemoveItem, createStore, setAttributeByGlobal, setFontSize2html, Chain, create, isEqual, cloneDeep, createSignal, subscribers, getMatchingSentences, transformNumber, toString, addNumSym, getQuery, checkEncoding, transformText, isSafari, md5, getRandomString, bridgeManager, Client, BridgeManager, PostMessageBridge, MessageCodec, Platform, openPortBridge, acceptPortBridge, createPortBridge, BRIDGE_MARKER, DEFAULT_CHANNEL, singleFlight, WebDB, createHandoff, buildOffsets, indexForOffset, segmentByRanges, detectLanguage, navigatorLanguage, resolveLocale, readFileAsArrayBuffer, readFileAsUint8Array, readFileAsText, readFileAsDataURL, WorkerClient, whenIdle, networkAllowsDownload, isUrlCached, prefetchUrl, prefetchUrls, prefetchWhenIdle, deferred, withTimeout, withTimeoutFallback, delay, TimeoutError, crc32, inflateRaw, readZipEntries, readZipEntry, zipHasEntry, rewriteZip, createZip, ZIP_STORED, ZIP_DEFLATE, arrayBufferToString, toHalfWidth, toFullWidth, parseChineseNumber, parseRomanNumber, parseEnglishNumber, MOBILE_MEDIA_QUERY, matchMediaQuery, watchMediaQuery, createLocalePath, setReportUrl, getReportUrl, formatDate, handleXhrHook, EventManager, quad, cubic, quart, quint, sine, expo, circ, getImage, cutRound, opacity, getMatrix, getAngle, getArcPointerByDeg, getTangentByPointer, fanShapedByArc, roundRectByArc, getLinearGradient, adoptStyles, adoptSheetText, ADOPTED_STYLE_MARKER, ADOPTED_SHEET_MARKER, rgbToHsv, hexToHsb, hexToHsv, hsbToHsl, hslToHsb, hslToHsv, hexToAlpha, rgbaString, rgbaToRgb, rgbaToHex, HEX_COLOR_REGEX, RGB_REGEX, RGBA_REGEX, loadScript, I18nCore, createI18n, useI18n, };
67
- export type { EasingFn, SpeedType, ImgSource, LoadScriptOptions, I18nConfig, MessageDict, LocaleMessages, TranslateParams, LocaleChangeHandler, Debounced, Throttled, BeaconPayload, ReportConfig, LocalePath, LocalePathConfig, LocaleRoute, SingleFlight, IDBResult, IDBStoreSchema, WebDBOptions, Handoff, HandoffOptions, JsonStore, Deferred, ZipEntry, RewriteZipOptions, ResolveLocaleOptions, OffsetRange, Segment, TextLanguage, WorkerClientOptions, WorkerResponseBase, WhenIdleOptions, NetworkAllowanceOptions, PrefetchOptions, CurrentDevice, TransformText, MessageHandler, MessageData, PendingRequest, BridgeManagerOptions, BroadcastPayload, CallToPayload, PortBridge, OpenPortBridgeOptions, AcceptPortBridgeOptions, };
68
+ export { performanceTime, timeFormat, timestampToTime, throttle, SyncHook, changeHumpToLowerCase, clearBr, clearStr, isString, randomString, str2Xml, strParse, scriptOnLoad, handleFetchHook, createData, report, QuestQueue, noop, getPerformance, querystring, formatJson, filterObj, merge, replaceOld, mergeExports, perToNum, range, Mathjs, mathjs, getStatus, status, Monitor, MimeType, getExtensions, setMime, getMime, memoize, once, isImageSize, convertImageToBase64, handleError, addClassToElement, removeClassToElement, createDocumentFragment, escapeHtml, isClient, isWeiXin, isMobile, debounce, currentDevice, handleConsole, compose, Color, FMT, Hsl, Hsla, Rgb, Rgba, randomColor, hexToRgb, componentToHex, rgbToHex, rgbToHsl, hue2rgb, hslToRgb, rgbToHsb, hsbToRgb, hsvToRgb, hsvToHsl, ColorScheme, AudioRecorder, webglVendor, canvasVendor, audioVendor, retain, getCookie, requestUrlToBuffer, getPixelRatio, createObjectURL, getFrame, getAllQueryString, queryFlag, isInIframe, appendUrl, removeGhosting, getCookieByName, getWindow, connection, encodeUrl, imageRequest, durationHandler, networkSpeed, TOTP, isBangDevice, localStorageGetItem, localStorageSetItem, localStorageRemoveItem, createStore, setAttributeByGlobal, setFontSize2html, Chain, create, isEqual, cloneDeep, createSignal, subscribers, getMatchingSentences, transformNumber, toString, addNumSym, getQuery, checkEncoding, transformText, isSafari, md5, getRandomString, bridgeManager, Client, BridgeManager, PostMessageBridge, MessageCodec, Platform, openPortBridge, acceptPortBridge, createPortBridge, BRIDGE_MARKER, DEFAULT_CHANNEL, singleFlight, WebDB, createHandoff, buildOffsets, paginateText, indexForOffset, segmentByRanges, detectLanguage, navigatorLanguage, resolveLocale, readFileAsArrayBuffer, readFileAsUint8Array, readFileAsText, readFileAsDataURL, WorkerClient, serveWorker, whenIdle, networkAllowsDownload, isUrlCached, prefetchUrl, prefetchUrls, prefetchWhenIdle, deferred, withTimeout, withTimeoutFallback, delay, TimeoutError, crc32, inflateRaw, readZipEntries, readZipEntry, zipHasEntry, rewriteZip, createZip, ZIP_STORED, ZIP_DEFLATE, arrayBufferToString, toHalfWidth, toFullWidth, parseChineseNumber, parseRomanNumber, parseEnglishNumber, MOBILE_MEDIA_QUERY, matchMediaQuery, watchMediaQuery, createLocalePath, setReportUrl, getReportUrl, formatDate, handleXhrHook, EventManager, quad, cubic, quart, quint, sine, expo, circ, getImage, cutRound, opacity, getMatrix, getAngle, getArcPointerByDeg, getTangentByPointer, fanShapedByArc, roundRectByArc, getLinearGradient, adoptStyles, adoptSheetText, ADOPTED_STYLE_MARKER, ADOPTED_SHEET_MARKER, rgbToHsv, hexToHsb, hexToHsv, hsbToHsl, hslToHsb, hslToHsv, hexToAlpha, rgbaString, rgbaToRgb, rgbaToHex, HEX_COLOR_REGEX, RGB_REGEX, RGBA_REGEX, loadScript, I18nCore, createI18n, useI18n, };
69
+ export type { EasingFn, SpeedType, ImgSource, LoadScriptOptions, I18nConfig, MessageDict, LocaleMessages, TranslateParams, LocaleChangeHandler, Debounced, Throttled, BeaconPayload, ReportConfig, LocalePath, LocalePathConfig, LocaleRoute, SingleFlight, IDBCollection, IDBResult, IDBStoreSchema, WebDBOptions, Handoff, HandoffOptions, JsonStore, Deferred, ZipEntry, RewriteZipOptions, ResolveLocaleOptions, OffsetRange, PaginateOptions, PaginateResult, TextBox, TextGridMetrics, TextPage, Segment, TextLanguage, ServeWorkerOptions, WorkerClientOptions, WorkerHandlerContext, WorkerRequestBase, WorkerResponseBase, WhenIdleOptions, NetworkAllowanceOptions, PrefetchOptions, CurrentDevice, TransformText, MessageHandler, MessageData, PendingRequest, BridgeManagerOptions, BroadcastPayload, CallToPayload, PortBridge, OpenPortBridgeOptions, AcceptPortBridgeOptions, };
@@ -1 +1 @@
1
- import{i as s}from"../../enums-BAgbyGdH.js";import{A as a,B as t,C as n,D as o,E as r,F as m,G as i,H as p,I as f,J as j,K as c,L as l,M as u,N as h,O as x,P as b,Q as d,R as e,S as g,T as k,U as v,V as w,W as y,X as z,Y as A,Z as B,_ as C,a as D,b as E,c as F,d as H,f as I,g as L,h as M,i as N,j as O,k as P,l as R,m as S,n as T,o as U,p as V,q as W,r as _,s as q,t as G,u as J,v as K,w as Q,x as X,y as Y,z as Z}from"../../color-Dohr9BXX.js";import{$,$t as ss,A as as,At as ts,B as ns,Bt as os,C as rs,Ct as ms,D as is,Dt as ps,E as fs,Et as js,F as cs,Ft as ls,G as us,Gt as hs,H as xs,Ht as bs,I as ds,It as es,J as gs,Jt as ks,K as vs,Kt as ws,L as ys,Lt as zs,M as As,Mt as Bs,N as Cs,Nt as Ds,O as Es,Ot as Fs,P as Hs,Pt as Is,Q as Ls,Qt as Ms,R as Ns,Rt as Os,S as Ps,St as Rs,T as Ss,Tt as Ts,U as Us,Ut as Vs,V as Ws,Vt as _s,W as qs,Wt as Gs,X as Js,Xt as Ks,Y as Qs,Yt as Xs,Z as Ys,Zt as Zs,_ as $s,_t as sa,a as aa,an as ta,at as na,b as oa,bt as ra,c as ma,cn as ia,ct as pa,d as fa,dt as ja,en as ca,et as la,f as ua,ft as ha,g as xa,gt as ba,h as da,ht as ea,i as ga,in as ka,it as va,j as wa,jt as ya,k as za,kt as Aa,l as Ba,lt as Ca,m as Da,mt as Ea,n as Fa,nn as Ha,nt as Ia,o as La,on as Ma,ot as Na,p as Oa,pt as Pa,q as Ra,qt as Sa,r as Ta,rn as Ua,rt as Va,s as Wa,sn as _a,st as qa,t as Ga,tn as Ja,tt as Ka,u as Qa,ut as Xa,v as Ya,vt as Za,w as $a,wt as st,x as at,xt as tt,y as nt,yt as ot,z as rt,zt as mt}from"../../utils-BDtXHcK8.js";import{A as it,B as pt,C as ft,D as jt,E as ct,F as lt,H as ut,I as ht,L as xt,M as bt,N as dt,O as et,P as gt,R as kt,S as vt,T as wt,U as yt,V as zt,W as At,_ as Bt,a as Ct,b as Dt,c as Et,d as Ft,f as Ht,g as It,h as Lt,i as Mt,k as Nt,l as Ot,m as Pt,n as Rt,o as St,p as Tt,r as Ut,s as Vt,t as Wt,u as _t,v as qt,w as Gt,x as Jt,y as Kt,z as Qt}from"../../i18n-Cf5TtRb4.js";import{n as Xt,t as Yt}from"../../chain-CTywmh_H.js";export{vs as ADOPTED_SHEET_MARKER,Ra as ADOPTED_STYLE_MARKER,ya as AudioRecorder,Gs as BRIDGE_MARKER,hs as BridgeManager,Yt as Chain,ws as Client,G as Color,T as ColorScheme,Sa as DEFAULT_CHANNEL,ea as EventManager,_ as FMT,N as HEX_COLOR_REGEX,D as Hsl,U as Hsla,Wt as I18nCore,bt as MOBILE_MEDIA_QUERY,ca as Mathjs,f as MessageCodec,u as MimeType,La as Monitor,ks as Platform,Xs as PostMessageBridge,Ta as QuestQueue,q as RGBA_REGEX,F as RGB_REGEX,R as Rgb,J as Rgba,s as SyncHook,Ts as TOTP,$a as TimeoutError,qs as WebDB,cs as WorkerClient,da as ZIP_DEFLATE,xa as ZIP_STORED,Ks as acceptPortBridge,sa as addClassToElement,Ja as addNumSym,gs as adoptSheetText,Qs as adoptStyles,Ft as appendUrl,l as arrayBufferToString,js as audioVendor,Zs as bridgeManager,Ws as buildOffsets,ps as canvasVendor,e as changeHumpToLowerCase,Z as checkEncoding,pa as circ,t as clearBr,w as clearStr,Bs as cloneDeep,H as componentToHex,st as compose,Ht as connection,Js as convertImageToBase64,$s as crc32,Xt as create,Qa as createData,Za as createDocumentFragment,us as createHandoff,Rt as createI18n,ns as createLocalePath,Tt as createObjectURL,Ms as createPortBridge,Aa as createSignal,Vt as createStore,Ya as createZip,Ca as cubic,dt as currentDevice,Ys as cutRound,Rs as debounce,Ss as deferred,fs as delay,Mt as detectLanguage,Pt as durationHandler,Lt as encodeUrl,ot as escapeHtml,Xa as expo,Ia as fanShapedByArc,Ds as filterObj,pt as formatDate,Is as formatJson,It as getAllQueryString,Va as getAngle,va as getArcPointerByDeg,Bt as getCookie,qt as getCookieByName,h as getExtensions,Kt as getFrame,Ls as getImage,na as getLinearGradient,p as getMatchingSentences,$ as getMatrix,b as getMime,Da as getPerformance,Dt as getPixelRatio,Jt as getQuery,v as getRandomString,fa as getReportUrl,ga as getStatus,Na as getTangentByPointer,vt as getWindow,ms as handleConsole,ba as handleError,ma as handleFetchHook,Ba as handleXhrHook,I as hexToAlpha,V as hexToHsb,S as hexToHsv,M as hexToRgb,L as hsbToHsl,C as hsbToRgb,K as hslToHsb,Y as hslToHsv,E as hslToRgb,X as hsvToHsl,g as hsvToRgb,n as hue2rgb,ft as imageRequest,xs as indexForOffset,nt as inflateRaw,gt as isBangDevice,lt as isClient,ls as isEqual,la as isImageSize,Gt as isInIframe,ht as isMobile,wt as isSafari,y as isString,za as isUrlCached,xt as isWeiXin,Ga as loadScript,Et as localStorageGetItem,Ot as localStorageRemoveItem,_t as localStorageSetItem,kt as matchMediaQuery,Ha as mathjs,i as md5,_s as memoize,es as merge,zs as mergeExports,Ct as navigatorLanguage,as as networkAllowsDownload,ct as networkSpeed,At as noop,bs as once,Ka as opacity,ss as openPortBridge,Ua as parseChineseNumber,ka as parseEnglishNumber,ta as parseRomanNumber,Ma as perToNum,zt as performanceTime,wa as prefetchUrl,As as prefetchUrls,Cs as prefetchWhenIdle,ja as quad,ha as quart,jt as queryFlag,Os as querystring,Pa as quint,Q as randomColor,c as randomString,_a as range,ds as readFileAsArrayBuffer,ys as readFileAsDataURL,Ns as readFileAsText,rt as readFileAsUint8Array,oa as readZipEntries,at as readZipEntry,ra as removeClassToElement,et as removeGhosting,mt as replaceOld,ua as report,Nt as requestUrlToBuffer,St as resolveLocale,it as retain,Ps as rewriteZip,k as rgbToHex,r as rgbToHsb,o as rgbToHsl,x as rgbToHsv,P as rgbaString,a as rgbaToHex,O as rgbaToRgb,qa as roundRectByArc,Fa as scriptOnLoad,Us as segmentByRanges,os as setAttributeByGlobal,tt as setFontSize2html,m as setMime,Oa as setReportUrl,Ea as sine,Vs as singleFlight,aa as status,W as str2Xml,j as strParse,ts as subscribers,Wa as throttle,ut as timeFormat,yt as timestampToTime,A as toFullWidth,z as toHalfWidth,B as toString,ia as transformNumber,d as transformText,Ut as useI18n,Qt as watchMediaQuery,Fs as webglVendor,Hs as whenIdle,is as withTimeout,Es as withTimeoutFallback,rs as zipHasEntry};
1
+ import{i as s}from"../../enums-BAgbyGdH.js";import{A as a,B as t,C as n,D as o,E as r,F as m,G as i,H as p,I as f,J as j,K as c,L as l,M as u,N as h,O as x,P as b,Q as d,R as e,S as g,T as k,U as v,V as w,W as y,X as z,Y as A,Z as B,_ as C,a as D,b as E,c as F,d as H,f as I,g as L,h as M,i as N,j as O,k as P,l as R,m as S,n as T,o as U,p as V,q as W,r as _,s as q,t as G,u as J,v as K,w as Q,x as X,y as Y,z as Z}from"../../color-Dohr9BXX.js";import{$,$t as ss,A as as,At as ts,B as ns,Bt as os,C as rs,Ct as ms,D as is,Dt as ps,E as fs,Et as js,F as cs,Ft as ls,G as us,Gt as hs,H as xs,Ht as bs,I as ds,It as es,J as gs,Jt as ks,K as vs,Kt as ws,L as ys,Lt as zs,M as As,Mt as Bs,N as Cs,Nt as Ds,O as Es,Ot as Fs,P as Hs,Pt as Is,Q as Ls,Qt as Ms,R as Ns,Rt as Os,S as Ps,St as Rs,T as Ss,Tt as Ts,U as Us,Ut as Vs,V as Ws,Vt as _s,W as qs,Wt as Gs,X as Js,Xt as Ks,Y as Qs,Yt as Xs,Z as Ys,Zt as Zs,_ as $s,_t as sa,a as aa,an as ta,at as na,b as oa,bt as ra,c as ma,cn as ia,ct as pa,d as fa,dt as ja,en as ca,et as la,f as ua,ft as ha,g as xa,gt as ba,h as da,ht as ea,i as ga,in as ka,it as va,j as wa,jt as ya,k as za,kt as Aa,l as Ba,ln as Ca,lt as Da,m as Ea,mt as Fa,n as Ha,nn as Ia,nt as La,o as Ma,on as Na,ot as Oa,p as Pa,pt as Ra,q as Sa,qt as Ta,r as Ua,rn as Va,rt as Wa,s as _a,sn as qa,st as Ga,t as Ja,tn as Ka,tt as Qa,u as Xa,un as Ya,ut as Za,v as $a,vt as st,w as at,wt as tt,x as nt,xt as ot,y as rt,yt as mt,z as it,zt as pt}from"../../utils-8TVtLBjA.js";import{A as ft,B as jt,C as ct,D as lt,E as ut,F as ht,H as xt,I as bt,L as dt,M as et,N as gt,O as kt,P as vt,R as wt,S as yt,T as zt,U as At,V as Bt,W as Ct,_ as Dt,a as Et,b as Ft,c as Ht,d as It,f as Lt,g as Mt,h as Nt,i as Ot,k as Pt,l as Rt,m as St,n as Tt,o as Ut,p as Vt,r as Wt,s as _t,t as qt,u as Gt,v as Jt,w as Kt,x as Qt,y as Xt,z as Yt}from"../../i18n-Cf5TtRb4.js";import{n as Zt,t as $t}from"../../chain-CTywmh_H.js";export{gs as ADOPTED_SHEET_MARKER,Qs as ADOPTED_STYLE_MARKER,Ds as AudioRecorder,ws as BRIDGE_MARKER,Ta as BridgeManager,$t as Chain,ks as Client,G as Color,T as ColorScheme,Xs as DEFAULT_CHANNEL,sa as EventManager,_ as FMT,N as HEX_COLOR_REGEX,D as Hsl,U as Hsla,qt as I18nCore,et as MOBILE_MEDIA_QUERY,Ia as Mathjs,f as MessageCodec,u as MimeType,Ma as Monitor,Ks as Platform,Zs as PostMessageBridge,Ua as QuestQueue,q as RGBA_REGEX,F as RGB_REGEX,R as Rgb,J as Rgba,s as SyncHook,ps as TOTP,at as TimeoutError,vs as WebDB,cs as WorkerClient,da as ZIP_DEFLATE,xa as ZIP_STORED,Ms as acceptPortBridge,mt as addClassToElement,Va as addNumSym,Js as adoptSheetText,Ys as adoptStyles,It as appendUrl,l as arrayBufferToString,Fs as audioVendor,ss as bridgeManager,Us as buildOffsets,Aa as canvasVendor,e as changeHumpToLowerCase,Z as checkEncoding,Za as circ,t as clearBr,w as clearStr,Is as cloneDeep,H as componentToHex,js as compose,Lt as connection,Ls as convertImageToBase64,$s as crc32,Zt as create,Xa as createData,ra as createDocumentFragment,Sa as createHandoff,Tt as createI18n,Ws as createLocalePath,Vt as createObjectURL,ca as createPortBridge,ya as createSignal,_t as createStore,$a as createZip,ja as cubic,gt as currentDevice,$ as cutRound,tt as debounce,Ss as deferred,fs as delay,Ot as detectLanguage,St as durationHandler,Nt as encodeUrl,ot as escapeHtml,ha as expo,va as fanShapedByArc,ls as filterObj,jt as formatDate,es as formatJson,Mt as getAllQueryString,na as getAngle,Oa as getArcPointerByDeg,Dt as getCookie,Jt as getCookieByName,h as getExtensions,Xt as getFrame,la as getImage,Ga as getLinearGradient,p as getMatchingSentences,Qa as getMatrix,b as getMime,Ea as getPerformance,Ft as getPixelRatio,Qt as getQuery,v as getRandomString,fa as getReportUrl,ga as getStatus,pa as getTangentByPointer,yt as getWindow,Ts as handleConsole,st as handleError,ma as handleFetchHook,Ba as handleXhrHook,I as hexToAlpha,V as hexToHsb,S as hexToHsv,M as hexToRgb,L as hsbToHsl,C as hsbToRgb,K as hslToHsb,Y as hslToHsv,E as hslToRgb,X as hsvToHsl,g as hsvToRgb,n as hue2rgb,ct as imageRequest,qs as indexForOffset,rt as inflateRaw,vt as isBangDevice,ht as isClient,zs as isEqual,La as isImageSize,Kt as isInIframe,bt as isMobile,zt as isSafari,y as isString,za as isUrlCached,dt as isWeiXin,Ja as loadScript,Ht as localStorageGetItem,Rt as localStorageRemoveItem,Gt as localStorageSetItem,wt as matchMediaQuery,ka as mathjs,i as md5,Vs as memoize,Os as merge,pt as mergeExports,Et as navigatorLanguage,as as networkAllowsDownload,ut as networkSpeed,Ct as noop,Gs as once,Wa as opacity,Ka as openPortBridge,xs as paginateText,ta as parseChineseNumber,Na as parseEnglishNumber,qa as parseRomanNumber,ia as perToNum,Bt as performanceTime,wa as prefetchUrl,As as prefetchUrls,Cs as prefetchWhenIdle,Ra as quad,Fa as quart,lt as queryFlag,os as querystring,ea as quint,Q as randomColor,c as randomString,Ca as range,ys as readFileAsArrayBuffer,Ns as readFileAsDataURL,it as readFileAsText,ns as readFileAsUint8Array,oa as readZipEntries,nt as readZipEntry,Rs as removeClassToElement,kt as removeGhosting,_s as replaceOld,ua as report,Pt as requestUrlToBuffer,Ut as resolveLocale,ft as retain,Ps as rewriteZip,k as rgbToHex,r as rgbToHsb,o as rgbToHsl,x as rgbToHsv,P as rgbaString,a as rgbaToHex,O as rgbaToRgb,Da as roundRectByArc,Ha as scriptOnLoad,us as segmentByRanges,ds as serveWorker,bs as setAttributeByGlobal,ms as setFontSize2html,m as setMime,Pa as setReportUrl,ba as sine,hs as singleFlight,aa as status,W as str2Xml,j as strParse,Bs as subscribers,_a as throttle,xt as timeFormat,At as timestampToTime,A as toFullWidth,z as toHalfWidth,B as toString,Ya as transformNumber,d as transformText,Wt as useI18n,Yt as watchMediaQuery,ts as webglVendor,Hs as whenIdle,is as withTimeout,Es as withTimeoutFallback,rs as zipHasEntry};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Paginate plain text into fixed-size boxes — the layout a reader, a teleprompter or a
3
+ * printable preview needs, where the same text must be cut into pages of a known size.
4
+ *
5
+ * The whole thing is **pure arithmetic**: it takes the box dimensions and the type metrics as
6
+ * numbers and never touches the DOM. That is what lets it run inside a Worker, on the server,
7
+ * or in a test — measure the container once on the main thread, then paginate anywhere.
8
+ *
9
+ * It assumes a **monospaced grid**: every character advances either one cell (CJK, full-width)
10
+ * or `narrowRatio` of one (ASCII). That is exactly true for a monospaced font and close enough
11
+ * for the CJK-dominant body text this was built for; it is *not* a substitute for real shaping
12
+ * on proportional Latin text.
13
+ */
14
+ /** The box each page must fit into, in px. */
15
+ export interface TextBox {
16
+ width: number;
17
+ height: number;
18
+ }
19
+ export interface TextGridMetrics {
20
+ /** Advance width of one full-width character, px (font size + letter spacing). */
21
+ charWidth: number;
22
+ /** Distance between baselines, px. */
23
+ lineHeight: number;
24
+ /**
25
+ * Advance of a narrow (ASCII) character as a fraction of `charWidth`. Default `0.5625`
26
+ * (9/16), the usual half-width-plus-spacing ratio.
27
+ */
28
+ narrowRatio?: number;
29
+ }
30
+ export interface PaginateOptions {
31
+ /**
32
+ * Below this, in either dimension, the box is treated as not yet laid out and pagination
33
+ * returns nothing. Default `30`. Guards against paginating during first paint, when a
34
+ * container still measures 0 and a naive `floor(0 / charWidth)` would loop forever.
35
+ */
36
+ minBox?: number;
37
+ }
38
+ export interface TextPage {
39
+ text: string;
40
+ /** Offset of this page's first character in the source text. */
41
+ start: number;
42
+ /** Offset one past this page's last character. */
43
+ end: number;
44
+ index: number;
45
+ }
46
+ export interface PaginateResult {
47
+ pages: TextPage[];
48
+ /** Length of the normalized source text. */
49
+ total: number;
50
+ charsPerLine: number;
51
+ linesPerPage: number;
52
+ /** `charsPerLine * linesPerPage` — the budget one page spends. */
53
+ charsPerPage: number;
54
+ }
55
+ /**
56
+ * @description: Cut text into pages that fit `box`, given the type metrics.
57
+ *
58
+ * ASCII words are kept whole: a page never ends mid-word unless the word is longer than a
59
+ * line. Newlines start a new line and are charged one character.
60
+ *
61
+ * @param {string} text source text; `\r\n` / `\r` are normalized to `\n` first
62
+ * @param {TextBox} box page box in px — measure the container once, then call this anywhere
63
+ * @param {TextGridMetrics} metrics character advance and line height, px
64
+ * @param {PaginateOptions} options
65
+ * @return {PaginateResult} pages plus the grid it derived
66
+ * @example
67
+ * ```ts
68
+ * const { width, height } = container.getBoundingClientRect();
69
+ * const result = paginateText(book, { width, height }, { charWidth: 18.4, lineHeight: 40 });
70
+ * render(result.pages[0].text);
71
+ * ```
72
+ */
73
+ export declare const paginateText: (text: string, box: TextBox, metrics: TextGridMetrics, options?: PaginateOptions) => PaginateResult;
@@ -74,3 +74,52 @@ export declare class WorkerClient<Req extends object, Res extends WorkerResponse
74
74
  private handleMessage;
75
75
  private rejectAll;
76
76
  }
77
+ /** A request always carries the id the client stamped on it */
78
+ export interface WorkerRequestBase {
79
+ operationId: number;
80
+ type?: string;
81
+ }
82
+ /** Handed to the handler so it can stream progress for the request it is currently serving */
83
+ export interface WorkerHandlerContext<Progress> {
84
+ /** Post a progress update. Does not settle the request; may be called any number of times. */
85
+ progress: (payload: Progress) => void;
86
+ }
87
+ export interface ServeWorkerOptions {
88
+ /**
89
+ * Where to listen. Defaults to `self` — override for a `MessagePort`, a nested worker, or
90
+ * a test double.
91
+ */
92
+ scope?: {
93
+ addEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;
94
+ removeEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void;
95
+ postMessage: (message: unknown, transfer?: Transferable[]) => void;
96
+ };
97
+ /** Response `type` for a successful reply that the handler returned bare (non-object). Default `'result'`. */
98
+ resultType?: string;
99
+ }
100
+ /**
101
+ * @description: Serve requests inside a Web Worker, mirroring {@link WorkerClient} on the
102
+ * other end. Reads `operationId` off each request, awaits your handler, and posts the reply
103
+ * back with that same id.
104
+ *
105
+ * Failures become `{ operationId, type: 'error', message }` — the envelope `WorkerClient`
106
+ * rejects on by default. **Both synchronous throws and rejected promises are caught**: a sync
107
+ * throw inside `onmessage` would otherwise escape to the worker's error handler, which carries
108
+ * no id, so the client could only fail *every* in-flight request instead of the one that broke.
109
+ *
110
+ * @param {Function} handler receives the request and a context whose `progress()` streams updates
111
+ * @param {ServeWorkerOptions} options
112
+ * @return {Function} stop — removes the listener
113
+ * @example
114
+ * ```ts
115
+ * // my.worker.ts
116
+ * serveWorker<MyRequest, MyResponse, ModelProgress>(async (request, { progress }) => {
117
+ * if (request.type === 'load') {
118
+ * const device = await load(request.modelId, (p) => progress(p));
119
+ * return { type: 'loaded', device };
120
+ * }
121
+ * return { type: 'result', scores: await classify(request.lines) };
122
+ * });
123
+ * ```
124
+ */
125
+ export declare const serveWorker: <Req extends WorkerRequestBase, Res extends object = object, Progress = unknown>(handler: (request: Req, context: WorkerHandlerContext<Progress>) => Promise<Res> | Res, options?: ServeWorkerOptions) => (() => void);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};