@sweidos/eidos 1.0.20 → 1.0.23
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/README.md +81 -4
- package/dist/action.js +103 -0
- package/dist/action.js.map +1 -0
- package/dist/eidos.cjs.js +2 -2
- package/dist/eidos.cjs.js.map +1 -1
- package/dist/idb.js +87 -0
- package/dist/idb.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +37 -0
- package/dist/index.js.map +1 -0
- package/dist/react/Provider.js +12 -0
- package/dist/react/Provider.js.map +1 -0
- package/dist/react/hooks.js +42 -0
- package/dist/react/hooks.js.map +1 -0
- package/dist/resource.js +200 -0
- package/dist/resource.js.map +1 -0
- package/dist/runtime.js +38 -0
- package/dist/runtime.js.map +1 -0
- package/dist/store.js +55 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.js +36 -0
- package/dist/stores.js.map +1 -0
- package/dist/sw-bridge.js +105 -0
- package/dist/sw-bridge.js.map +1 -0
- package/dist/testing.cjs.js +86 -0
- package/dist/testing.d.ts +98 -0
- package/dist/testing.js +86 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/package.json +9 -4
- package/dist/eidos.es.js +0 -621
- package/dist/eidos.es.js.map +0 -1
package/dist/resource.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { useEidosStore as h } from "./store.js";
|
|
2
|
+
import { sendToWorker as g } from "./sw-bridge.js";
|
|
3
|
+
const p = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map();
|
|
4
|
+
let m = null;
|
|
5
|
+
function N(e) {
|
|
6
|
+
m = e;
|
|
7
|
+
}
|
|
8
|
+
function u(e) {
|
|
9
|
+
return e.includes("*") || /:[^/]+/.test(e);
|
|
10
|
+
}
|
|
11
|
+
function k(e) {
|
|
12
|
+
return "^" + e.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".+").replace(/\*/g, "[^/]+").replace(/:[^/]+/g, "[^/]+") + "$";
|
|
13
|
+
}
|
|
14
|
+
function w(e, t) {
|
|
15
|
+
return new Error(
|
|
16
|
+
`[eidos] resource('${e}') is a URL pattern — ${t}() is not supported on pattern handles. The SW intercepts matching requests automatically; call fetch(specificUrl) directly in your app code.`
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
function q(e, t) {
|
|
20
|
+
if (p.has(e))
|
|
21
|
+
return p.get(e);
|
|
22
|
+
const a = S(e, t), n = u(e) ? k(e) : void 0, o = {
|
|
23
|
+
url: e,
|
|
24
|
+
config: t,
|
|
25
|
+
strategy: a,
|
|
26
|
+
status: "idle",
|
|
27
|
+
cacheHits: 0,
|
|
28
|
+
cacheMisses: 0
|
|
29
|
+
};
|
|
30
|
+
h.getState().registerResource(e, o), g({
|
|
31
|
+
type: "EIDOS_REGISTER_RESOURCE",
|
|
32
|
+
url: e,
|
|
33
|
+
strategy: a.swStrategy,
|
|
34
|
+
cacheName: a.cacheName,
|
|
35
|
+
...n !== void 0 && { pattern: n }
|
|
36
|
+
});
|
|
37
|
+
const s = {
|
|
38
|
+
url: e,
|
|
39
|
+
config: t,
|
|
40
|
+
strategy: a,
|
|
41
|
+
fetch: async () => {
|
|
42
|
+
if (u(e)) throw w(e, "fetch");
|
|
43
|
+
const r = y.get(e);
|
|
44
|
+
if (r) return r.then((c) => c.clone());
|
|
45
|
+
const i = E(e, t, a);
|
|
46
|
+
return y.set(e, i), i.finally(() => y.delete(e)), i.then((c) => c.clone());
|
|
47
|
+
},
|
|
48
|
+
json: async () => {
|
|
49
|
+
if (u(e)) throw w(e, "json");
|
|
50
|
+
return (await s.fetch()).json();
|
|
51
|
+
},
|
|
52
|
+
query: () => {
|
|
53
|
+
if (u(e)) throw w(e, "query");
|
|
54
|
+
return {
|
|
55
|
+
queryKey: ["eidos", e],
|
|
56
|
+
queryFn: () => s.json()
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
prefetch: async () => {
|
|
60
|
+
if (u(e)) throw w(e, "prefetch");
|
|
61
|
+
await s.fetch();
|
|
62
|
+
},
|
|
63
|
+
invalidate: async () => {
|
|
64
|
+
g({ type: "EIDOS_CLEAR_CACHE", url: e });
|
|
65
|
+
const r = await caches.open(a.cacheName).catch(() => null);
|
|
66
|
+
if (r) {
|
|
67
|
+
const i = await r.keys(), c = n ? new RegExp(n) : null, l = e.startsWith("http");
|
|
68
|
+
await Promise.all(
|
|
69
|
+
i.filter((f) => {
|
|
70
|
+
const d = f.url, v = new URL(d).pathname;
|
|
71
|
+
return c ? c.test(l ? d : v) : l ? d === e : d === e || v === e;
|
|
72
|
+
}).map((f) => r.delete(f))
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
u(e) || h.getState().updateResource(e, {
|
|
76
|
+
status: "stale",
|
|
77
|
+
cachedAt: void 0,
|
|
78
|
+
lastEvent: "cache-cleared",
|
|
79
|
+
cacheHits: 0,
|
|
80
|
+
cacheMisses: 0
|
|
81
|
+
}), m == null || m(["eidos", e]);
|
|
82
|
+
},
|
|
83
|
+
unregister: () => {
|
|
84
|
+
p.delete(e), g({ type: "EIDOS_UNREGISTER_RESOURCE", url: e }), h.getState().unregisterResource(e);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
return p.set(e, s), s;
|
|
88
|
+
}
|
|
89
|
+
async function E(e, t, a) {
|
|
90
|
+
const n = h.getState();
|
|
91
|
+
n.updateResource(e, { status: "fetching", fetchedAt: Date.now() });
|
|
92
|
+
const o = await caches.open(a.cacheName).catch(() => null);
|
|
93
|
+
try {
|
|
94
|
+
if (a.swStrategy !== "network-first") {
|
|
95
|
+
const i = o ? await o.match(e).catch(() => null) : null, c = h.getState().resources[e], l = t.maxAge !== void 0 && (c == null ? void 0 : c.cachedAt) !== void 0 && Date.now() - c.cachedAt > t.maxAge;
|
|
96
|
+
if (i && !l)
|
|
97
|
+
return n.updateResource(e, {
|
|
98
|
+
status: "fresh",
|
|
99
|
+
lastEvent: "cache-hit",
|
|
100
|
+
cacheHits: ((c == null ? void 0 : c.cacheHits) ?? 0) + 1
|
|
101
|
+
}), a.swStrategy === "stale-while-revalidate" && fetch(e).then(async (d) => {
|
|
102
|
+
d.ok && o && (await o.put(e, d.clone()), h.getState().updateResource(e, {
|
|
103
|
+
cachedAt: Date.now(),
|
|
104
|
+
lastEvent: "cache-updated"
|
|
105
|
+
}));
|
|
106
|
+
}).catch(() => {
|
|
107
|
+
}), i;
|
|
108
|
+
const f = h.getState().resources[e];
|
|
109
|
+
n.updateResource(e, {
|
|
110
|
+
cacheMisses: ((f == null ? void 0 : f.cacheMisses) ?? 0) + 1
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const s = await fetch(e);
|
|
114
|
+
if (s.ok)
|
|
115
|
+
return o && await o.put(e, s.clone()), n.updateResource(e, {
|
|
116
|
+
status: "fresh",
|
|
117
|
+
cachedAt: Date.now(),
|
|
118
|
+
lastEvent: "cache-updated"
|
|
119
|
+
}), s;
|
|
120
|
+
n.updateResource(e, { status: s.status === 503 ? "offline" : "error" });
|
|
121
|
+
const r = s.headers.get("X-Eidos-Offline") === "true";
|
|
122
|
+
throw new Error(
|
|
123
|
+
r ? `offline: no cached response for ${e}` : `${s.status} ${s.statusText}`
|
|
124
|
+
);
|
|
125
|
+
} catch (s) {
|
|
126
|
+
const r = o ? await o.match(e).catch(() => null) : null;
|
|
127
|
+
if (r) {
|
|
128
|
+
const i = h.getState().resources[e];
|
|
129
|
+
return n.updateResource(e, {
|
|
130
|
+
status: "fresh",
|
|
131
|
+
lastEvent: "cache-hit",
|
|
132
|
+
cacheHits: ((i == null ? void 0 : i.cacheHits) ?? 0) + 1
|
|
133
|
+
}), r;
|
|
134
|
+
}
|
|
135
|
+
throw n.updateResource(e, { status: "error" }), s;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function S(e, t) {
|
|
139
|
+
const a = t.strategy;
|
|
140
|
+
return t.offline ? R(a ?? "stale-while-revalidate", e, t.cacheName) : R(a ?? "network-first", e, t.cacheName);
|
|
141
|
+
}
|
|
142
|
+
const x = {
|
|
143
|
+
"stale-while-revalidate": {
|
|
144
|
+
name: "StaleWhileRevalidate",
|
|
145
|
+
reasoning: "offline: true signals resilience. SWR returns cached data instantly while revalidating in the background — the best tradeoff between speed and freshness for offline-capable resources.",
|
|
146
|
+
behavior: [
|
|
147
|
+
"Cache hit → return immediately, kick off background revalidation",
|
|
148
|
+
"Cache miss → fetch from network, cache the response, return it",
|
|
149
|
+
"Offline → return cached version if available, 503 if not",
|
|
150
|
+
"Reconnect → next request triggers a background refresh"
|
|
151
|
+
],
|
|
152
|
+
equivalentCode: `// Workbox equivalent
|
|
153
|
+
new StaleWhileRevalidate({
|
|
154
|
+
cacheName: 'eidos-resources-v1',
|
|
155
|
+
plugins: [new ExpirationPlugin({ maxEntries: 60 })],
|
|
156
|
+
})`
|
|
157
|
+
},
|
|
158
|
+
"cache-first": {
|
|
159
|
+
name: "CacheFirst",
|
|
160
|
+
reasoning: "cache-first maximises speed and offline availability. Network is consulted only on cache miss. Best for static or infrequently-updated data.",
|
|
161
|
+
behavior: [
|
|
162
|
+
"Cache hit → return immediately, no network request made",
|
|
163
|
+
"Cache miss → fetch from network, cache the response, return it",
|
|
164
|
+
"Offline → return cached version, 503 if cache is empty",
|
|
165
|
+
"Cache never expires unless explicitly invalidated"
|
|
166
|
+
],
|
|
167
|
+
equivalentCode: `// Workbox equivalent
|
|
168
|
+
new CacheFirst({
|
|
169
|
+
cacheName: 'eidos-resources-v1',
|
|
170
|
+
plugins: [new ExpirationPlugin({ maxEntries: 60 })],
|
|
171
|
+
})`
|
|
172
|
+
},
|
|
173
|
+
"network-first": {
|
|
174
|
+
name: "NetworkFirst",
|
|
175
|
+
reasoning: "network-first prioritises fresh data. Cache acts as a safety net when offline. Best for frequently-updated resources where stale data causes problems.",
|
|
176
|
+
behavior: [
|
|
177
|
+
"Always try network first",
|
|
178
|
+
"Network success → update cache, return fresh response",
|
|
179
|
+
"Network failure → fall back to cached version",
|
|
180
|
+
"Offline with empty cache → return 503 error response"
|
|
181
|
+
],
|
|
182
|
+
equivalentCode: `// Workbox equivalent
|
|
183
|
+
new NetworkFirst({
|
|
184
|
+
cacheName: 'eidos-resources-v1',
|
|
185
|
+
networkTimeoutSeconds: 3,
|
|
186
|
+
})`
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function R(e, t, a) {
|
|
190
|
+
return {
|
|
191
|
+
...x[e],
|
|
192
|
+
swStrategy: e,
|
|
193
|
+
cacheName: a ?? "eidos-resources-v1"
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
export {
|
|
197
|
+
q as resource,
|
|
198
|
+
N as setQueryInvalidator
|
|
199
|
+
};
|
|
200
|
+
//# sourceMappingURL=resource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.js","sources":["../src/resource.ts"],"sourcesContent":["import { useEidosStore } from './store'\nimport { sendToWorker } from './sw-bridge'\nimport type {\n ResourceConfig,\n ResourceHandle,\n ResourceEntry,\n GeneratedStrategy,\n CacheStrategy,\n} from './types'\n\nconst _registry = new Map<string, ResourceHandle>()\n\n// ── Request deduplication ─────────────────────────────────────────────────────\n// If multiple callers invoke handle.fetch() simultaneously for the same URL,\n// only one network request is made. Each caller gets its own cloned Response.\n// Keyed by URL; entry is deleted when the request settles.\nconst _inflightRequests = /* @__PURE__ */ new Map<string, Promise<Response>>()\n\n// ── TanStack Query bridge (optional) ─────────────────────────────────────────\n// Set by @sweidos/eidos/query when withEidosQueryClient() is called.\n// Lets handle.invalidate() also invalidate the matching TQ cache entry.\ntype QueryInvalidator = (queryKey: [string, string]) => void\nlet _queryInvalidator: QueryInvalidator | null = null\n\n/** @internal Called by @sweidos/eidos/query. */\nexport function setQueryInvalidator(fn: QueryInvalidator): void {\n _queryInvalidator = fn\n}\n\n// ── URL pattern helpers ───────────────────────────────────────────────────────\n\n/** Returns true if `url` contains wildcard or :param segments. */\nfunction isPattern(url: string): boolean {\n return url.includes('*') || /:[^/]+/.test(url)\n}\n\n/**\n * Converts a URL pattern to a regex source string for SW fetch matching.\n * `**` → multi-segment wildcard (`.+`)\n * `*` → single-segment wildcard (`[^/]+`)\n * `:param` → named single segment (`[^/]+`)\n *\n * Special regex characters in the pattern (e.g. `.`) are escaped first so\n * they match literally.\n *\n * @example\n * patternToRegexStr('/api/products/*') // '^/api/products/[^/]+$'\n * patternToRegexStr('/api/products/**') // '^/api/products/.+$'\n * patternToRegexStr('/api/users/:id') // '^/api/users/[^/]+$'\n */\nfunction patternToRegexStr(pattern: string): string {\n // Escape all regex-special chars except `*`, `/`, `:` (handled below)\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return (\n '^' +\n escaped\n .replace(/\\*\\*/g, '.+') // ** → multi-segment wildcard\n .replace(/\\*/g, '[^/]+') // * → single-segment wildcard\n .replace(/:[^/]+/g, '[^/]+') // :param → single-segment wildcard\n + '$'\n )\n}\n\nfunction _patternError(url: string, method: string): Error {\n return new Error(\n `[eidos] resource('${url}') is a URL pattern — ${method}() is not supported on pattern handles. ` +\n `The SW intercepts matching requests automatically; call fetch(specificUrl) directly in your app code.`,\n )\n}\n\n// ── resource() ────────────────────────────────────────────────────────────────\n\nexport function resource<T = unknown>(\n url: string,\n config: ResourceConfig,\n): ResourceHandle<T> {\n if (_registry.has(url)) {\n if (import.meta.env.DEV) {\n const existing = _registry.get(url)!\n const existingCfg = existing.config\n if (\n existingCfg.offline !== config.offline ||\n existingCfg.strategy !== config.strategy ||\n existingCfg.cacheName !== config.cacheName\n ) {\n console.warn(\n `[eidos] resource('${url}') already registered with a different config — returning cached handle. Call resource.unregister() first to re-register.`,\n { registered: existingCfg, ignored: config },\n )\n }\n }\n return _registry.get(url) as ResourceHandle<T>\n }\n\n const strategy = deriveStrategy(url, config)\n const regexStr = isPattern(url) ? patternToRegexStr(url) : undefined\n\n const entry: ResourceEntry = {\n url,\n config,\n strategy,\n status: 'idle',\n cacheHits: 0,\n cacheMisses: 0,\n }\n\n useEidosStore.getState().registerResource(url, entry)\n\n sendToWorker({\n type: 'EIDOS_REGISTER_RESOURCE',\n url,\n strategy: strategy.swStrategy,\n cacheName: strategy.cacheName,\n ...(regexStr !== undefined && { pattern: regexStr }),\n })\n\n const handle: ResourceHandle<T> = {\n url,\n config,\n strategy,\n\n fetch: async () => {\n if (isPattern(url)) throw _patternError(url, 'fetch')\n\n // ── Deduplication: coalesce concurrent fetches for the same URL ─────\n // If a request is already in-flight, piggyback on it and return a clone\n // so each caller gets an independent readable Response body.\n const existing = _inflightRequests.get(url)\n if (existing) return existing.then((r) => r.clone())\n\n // Store the raw-response promise. All callers (including the primary)\n // receive a clone — the raw response stays unconsumed in the map so\n // any caller arriving while the promise is still pending can clone it.\n const task = _fetchResource(url, config, strategy)\n _inflightRequests.set(url, task)\n task.finally(() => _inflightRequests.delete(url))\n return task.then((r) => r.clone())\n },\n\n json: async () => {\n if (isPattern(url)) throw _patternError(url, 'json')\n const res = await handle.fetch()\n return res.json() as Promise<T>\n },\n\n query: () => {\n if (isPattern(url)) throw _patternError(url, 'query')\n return {\n queryKey: ['eidos', url] as [string, string],\n queryFn: () => handle.json(),\n }\n },\n\n prefetch: async () => {\n if (isPattern(url)) throw _patternError(url, 'prefetch')\n await handle.fetch()\n },\n\n invalidate: async () => {\n sendToWorker({ type: 'EIDOS_CLEAR_CACHE', url })\n const cache = await caches.open(strategy.cacheName).catch(() => null)\n if (cache) {\n const keys = await cache.keys()\n const patternRe = regexStr ? new RegExp(regexStr) : null\n const isCrossOrigin = url.startsWith('http')\n await Promise.all(\n keys\n .filter((r) => {\n const rUrl = r.url\n const p = new URL(rUrl).pathname\n if (patternRe) {\n // Cross-origin patterns were compiled from absolute URLs; test full URL.\n return patternRe.test(isCrossOrigin ? rUrl : p)\n }\n return isCrossOrigin ? rUrl === url : (rUrl === url || p === url)\n })\n .map((r) => cache.delete(r)),\n )\n }\n // For exact-URL resources update the store entry; patterns don't have a\n // single entry to update (individual URLs are not tracked per-pattern).\n if (!isPattern(url)) {\n useEidosStore.getState().updateResource(url, {\n status: 'stale',\n cachedAt: undefined,\n lastEvent: 'cache-cleared',\n cacheHits: 0,\n cacheMisses: 0,\n })\n }\n // Notify TanStack Query bridge if registered.\n _queryInvalidator?.(['eidos', url])\n },\n\n unregister: () => {\n _registry.delete(url)\n sendToWorker({ type: 'EIDOS_UNREGISTER_RESOURCE', url })\n useEidosStore.getState().unregisterResource(url)\n },\n }\n\n _registry.set(url, handle)\n return handle\n}\n\n// ── _fetchResource ─────────────────────────────────────────────────────────────\n// The actual network/cache implementation. Separated from handle.fetch() so the\n// deduplication wrapper can store the Promise and share it across concurrent callers.\n// Returns the raw (unconsumed) Response — callers MUST .clone() before reading body.\nasync function _fetchResource(\n url: string,\n config: ResourceConfig,\n strategy: GeneratedStrategy,\n): Promise<Response> {\n const store = useEidosStore.getState()\n store.updateResource(url, { status: 'fetching', fetchedAt: Date.now() })\n\n // Open cache once and reuse across try/catch — avoids a redundant\n // caches.open() call in the error fallback path.\n const cache = await caches.open(strategy.cacheName).catch(() => null)\n\n try {\n // ── network-first: skip cache check, go straight to network ─────────\n // For cache-first / SWR the cache check below is correct. For\n // network-first, reading cache first and returning early would\n // contradict the strategy — fresh data is the priority.\n if (strategy.swStrategy !== 'network-first') {\n // ── Direct Cache API check ─────────────────────────────────────────\n // We read the cache in the main thread rather than waiting for\n // an async SW postMessage. This gives instant, reliable status\n // updates regardless of SW message timing.\n const cached = cache ? await cache.match(url).catch(() => null) : null\n\n // Treat cache as miss if maxAge exceeded\n const current = useEidosStore.getState().resources[url]\n const expired =\n config.maxAge !== undefined &&\n current?.cachedAt !== undefined &&\n Date.now() - current.cachedAt > config.maxAge\n\n if (cached && !expired) {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n\n // Background revalidation for SWR (stale-while-revalidate)\n if (strategy.swStrategy === 'stale-while-revalidate') {\n fetch(url)\n .then(async (resp) => {\n if (resp.ok && cache) {\n await cache.put(url, resp.clone())\n useEidosStore.getState().updateResource(url, {\n cachedAt: Date.now(),\n lastEvent: 'cache-updated',\n })\n }\n })\n .catch(() => {\n /* offline — cached version stays valid */\n })\n }\n\n return cached\n }\n\n // Cache miss (or expired)\n const storeEntry = useEidosStore.getState().resources[url]\n store.updateResource(url, {\n cacheMisses: (storeEntry?.cacheMisses ?? 0) + 1,\n })\n }\n\n const response = await fetch(url)\n\n if (response.ok) {\n if (cache) await cache.put(url, response.clone())\n store.updateResource(url, {\n status: 'fresh',\n cachedAt: Date.now(),\n lastEvent: 'cache-updated',\n })\n return response\n }\n\n // Non-2xx response (e.g. 503 from offline SW) — update status and throw\n // so callers get a proper error instead of a plain-object body they can't use.\n store.updateResource(url, { status: response.status === 503 ? 'offline' : 'error' })\n\n // Check if the SW tagged this as an offline response\n const isOffline = response.headers.get('X-Eidos-Offline') === 'true'\n throw new Error(\n isOffline ? `offline: no cached response for ${url}` : `${response.status} ${response.statusText}`,\n )\n } catch (err) {\n // Network failure — try cache one more time as fallback\n const fallback = cache ? await cache.match(url).catch(() => null) : null\n\n if (fallback) {\n const current = useEidosStore.getState().resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n return fallback\n }\n\n store.updateResource(url, { status: 'error' })\n throw err\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Strategy derivation — intent → deterministic caching strategy\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction deriveStrategy(url: string, config: ResourceConfig): GeneratedStrategy {\n const explicit = config.strategy\n if (config.offline) return buildStrategy(explicit ?? 'stale-while-revalidate', url, config.cacheName)\n return buildStrategy(explicit ?? 'network-first', url, config.cacheName)\n}\n\nconst STRATEGY_META: Record<CacheStrategy, Omit<GeneratedStrategy, 'swStrategy' | 'cacheName'>> = {\n 'stale-while-revalidate': {\n name: 'StaleWhileRevalidate',\n reasoning:\n 'offline: true signals resilience. SWR returns cached data instantly while revalidating in the background — the best tradeoff between speed and freshness for offline-capable resources.',\n behavior: [\n 'Cache hit → return immediately, kick off background revalidation',\n 'Cache miss → fetch from network, cache the response, return it',\n 'Offline → return cached version if available, 503 if not',\n 'Reconnect → next request triggers a background refresh',\n ],\n equivalentCode: `// Workbox equivalent\nnew StaleWhileRevalidate({\n cacheName: 'eidos-resources-v1',\n plugins: [new ExpirationPlugin({ maxEntries: 60 })],\n})`,\n },\n 'cache-first': {\n name: 'CacheFirst',\n reasoning:\n 'cache-first maximises speed and offline availability. Network is consulted only on cache miss. Best for static or infrequently-updated data.',\n behavior: [\n 'Cache hit → return immediately, no network request made',\n 'Cache miss → fetch from network, cache the response, return it',\n 'Offline → return cached version, 503 if cache is empty',\n 'Cache never expires unless explicitly invalidated',\n ],\n equivalentCode: `// Workbox equivalent\nnew CacheFirst({\n cacheName: 'eidos-resources-v1',\n plugins: [new ExpirationPlugin({ maxEntries: 60 })],\n})`,\n },\n 'network-first': {\n name: 'NetworkFirst',\n reasoning:\n 'network-first prioritises fresh data. Cache acts as a safety net when offline. Best for frequently-updated resources where stale data causes problems.',\n behavior: [\n 'Always try network first',\n 'Network success → update cache, return fresh response',\n 'Network failure → fall back to cached version',\n 'Offline with empty cache → return 503 error response',\n ],\n equivalentCode: `// Workbox equivalent\nnew NetworkFirst({\n cacheName: 'eidos-resources-v1',\n networkTimeoutSeconds: 3,\n})`,\n },\n}\n\nfunction buildStrategy(swStrategy: CacheStrategy, _url: string, cacheName?: string): GeneratedStrategy {\n return {\n ...STRATEGY_META[swStrategy],\n swStrategy,\n cacheName: cacheName ?? 'eidos-resources-v1',\n }\n}\n"],"names":["_registry","_inflightRequests","_queryInvalidator","setQueryInvalidator","fn","isPattern","url","patternToRegexStr","pattern","_patternError","method","resource","config","strategy","deriveStrategy","regexStr","entry","useEidosStore","sendToWorker","handle","existing","r","task","_fetchResource","cache","keys","patternRe","isCrossOrigin","rUrl","p","store","cached","current","expired","resp","storeEntry","response","isOffline","err","fallback","explicit","buildStrategy","STRATEGY_META","swStrategy","_url","cacheName"],"mappings":";;AAUA,MAAMA,wBAAgB,IAAA,GAMhBC,wBAAwC,IAAA;AAM9C,IAAIC,IAA6C;AAG1C,SAASC,EAAoBC,GAA4B;AAC9D,EAAAF,IAAoBE;AACtB;AAKA,SAASC,EAAUC,GAAsB;AACvC,SAAOA,EAAI,SAAS,GAAG,KAAK,SAAS,KAAKA,CAAG;AAC/C;AAgBA,SAASC,EAAkBC,GAAyB;AAGlD,SACE,MAFcA,EAAQ,QAAQ,sBAAsB,MAAM,EAIvD,QAAQ,SAAS,IAAI,EACrB,QAAQ,OAAO,OAAO,EACtB,QAAQ,WAAW,OAAO,IAC3B;AAEN;AAEA,SAASC,EAAcH,GAAaI,GAAuB;AACzD,SAAO,IAAI;AAAA,IACT,qBAAqBJ,CAAG,yBAAyBI,CAAM;AAAA,EAAA;AAG3D;AAIO,SAASC,EACdL,GACAM,GACmB;AACnB,MAAIZ,EAAU,IAAIM,CAAG;AAenB,WAAON,EAAU,IAAIM,CAAG;AAG1B,QAAMO,IAAWC,EAAeR,GAAKM,CAAM,GACrCG,IAAWV,EAAUC,CAAG,IAAIC,EAAkBD,CAAG,IAAI,QAErDU,IAAuB;AAAA,IAC3B,KAAAV;AAAA,IACA,QAAAM;AAAA,IACA,UAAAC;AAAA,IACA,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,aAAa;AAAA,EAAA;AAGf,EAAAI,EAAc,SAAA,EAAW,iBAAiBX,GAAKU,CAAK,GAEpDE,EAAa;AAAA,IACX,MAAM;AAAA,IACN,KAAAZ;AAAA,IACA,UAAUO,EAAS;AAAA,IACnB,WAAWA,EAAS;AAAA,IACpB,GAAIE,MAAa,UAAa,EAAE,SAASA,EAAA;AAAA,EAAS,CACnD;AAED,QAAMI,IAA4B;AAAA,IAChC,KAAAb;AAAA,IACA,QAAAM;AAAA,IACA,UAAAC;AAAA,IAEA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@ -0,0 +1,38 @@
|
|
|
1
|
+
import { registerServiceWorker as m, registerBgSyncHandler as d } from "./sw-bridge.js";
|
|
2
|
+
import { replayQueue as n } from "./action.js";
|
|
3
|
+
import { useEidosStore as e } from "./store.js";
|
|
4
|
+
import { idbGetQueue as p } from "./idb.js";
|
|
5
|
+
let o = !1, s = null;
|
|
6
|
+
async function O(r = {}) {
|
|
7
|
+
if (o) return;
|
|
8
|
+
o = !0;
|
|
9
|
+
const u = r.swPath ?? "/eidos-sw.js", l = r.autoReplay ?? !0;
|
|
10
|
+
try {
|
|
11
|
+
const t = await p();
|
|
12
|
+
t.length > 0 && e.getState().hydrateQueue(t);
|
|
13
|
+
} catch {
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
await m(u);
|
|
17
|
+
} catch {
|
|
18
|
+
}
|
|
19
|
+
if (d(() => {
|
|
20
|
+
e.getState().isOnline && setTimeout(n, 200);
|
|
21
|
+
}), l) {
|
|
22
|
+
let t = e.getState().isOnline;
|
|
23
|
+
s = e.subscribe(() => {
|
|
24
|
+
const { isOnline: i } = e.getState(), f = i && !t;
|
|
25
|
+
t = i, f && setTimeout(n, 600);
|
|
26
|
+
});
|
|
27
|
+
const a = e.getState(), c = a.queue.some((i) => i.status === "pending" || i.status === "failed");
|
|
28
|
+
a.isOnline && c && setTimeout(n, 1200);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function w() {
|
|
32
|
+
s == null || s(), s = null, o = !1;
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
w as _resetEidos,
|
|
36
|
+
O as initEidos
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sources":["../src/runtime.ts"],"sourcesContent":["import { registerServiceWorker, registerBgSyncHandler } from './sw-bridge'\nimport { replayQueue } from './action'\nimport { useEidosStore } from './store'\nimport { idbGetQueue } from './idb'\n\nexport interface EidosConfig {\n /** Path to the eidos service worker. Defaults to '/eidos-sw.js'. */\n swPath?: string\n /** Automatically replay the action queue on reconnect. Default: true. */\n autoReplay?: boolean\n}\n\nlet _initialized = false\nlet _unsubscribe: (() => void) | null = null\n\nexport async function initEidos(config: EidosConfig = {}): Promise<void> {\n if (_initialized) return\n _initialized = true\n\n const swPath = config.swPath ?? '/eidos-sw.js'\n const autoReplay = config.autoReplay ?? true\n\n // Restore persisted queue from IndexedDB on startup\n try {\n const persisted = await idbGetQueue()\n if (persisted.length > 0) {\n useEidosStore.getState().hydrateQueue(persisted)\n }\n } catch {\n // IndexedDB unavailable (Firefox private browsing) — silent fallback\n }\n\n try {\n await registerServiceWorker(swPath)\n } catch {\n // SW registration failed; app continues without offline support\n }\n\n // When the SW fires the Background Sync tag, replay the queue in the main thread.\n // This path runs even if the user briefly navigated away and back — the browser\n // triggers the sync event on the SW, which wakes up all open clients.\n registerBgSyncHandler(() => {\n if (useEidosStore.getState().isOnline) {\n setTimeout(replayQueue, 200)\n }\n })\n\n if (autoReplay) {\n // ── Subscribe to the store instead of window.addEventListener('online')\n //\n // WHY: setOfflineSimulation() updates the store directly but never fires a\n // real browser `online` event. Watching the store catches both:\n // • Real network reconnects (sw-bridge updates store on window.online)\n // • Simulation toggled off (setOfflineSimulation(false) → store.setOnline(true))\n //\n let prevIsOnline = useEidosStore.getState().isOnline\n\n _unsubscribe = useEidosStore.subscribe(() => {\n const { isOnline } = useEidosStore.getState()\n const justCameOnline = isOnline && !prevIsOnline\n prevIsOnline = isOnline\n\n if (justCameOnline) {\n // Small delay so the connection (or simulation reset) settles first\n setTimeout(replayQueue, 600)\n }\n })\n\n // Replay any pending items that survived a page reload\n const store = useEidosStore.getState()\n const hasPending = store.queue.some((q) => q.status === 'pending' || q.status === 'failed')\n if (store.isOnline && hasPending) {\n setTimeout(replayQueue, 1200)\n }\n }\n\n if (import.meta.env.DEV) {\n const store = useEidosStore.getState()\n console.groupCollapsed('%c⚡ Eidos', 'color:#38bdf8;font-weight:bold')\n console.log('SW path :', swPath)\n console.log('Auto-replay:', autoReplay)\n console.log('SW status :', store.swStatus)\n console.groupEnd()\n }\n}\n\nexport function _resetEidos() {\n _unsubscribe?.()\n _unsubscribe = null\n _initialized = false\n}\n"],"names":["_initialized","_unsubscribe","initEidos","config","swPath","autoReplay","persisted","idbGetQueue","useEidosStore","registerServiceWorker","registerBgSyncHandler","replayQueue","prevIsOnline","isOnline","justCameOnline","store","hasPending","q","_resetEidos"],"mappings":";;;;AAYA,IAAIA,IAAe,IACfC,IAAoC;AAExC,eAAsBC,EAAUC,IAAsB,IAAmB;AACvE,MAAIH,EAAc;AAClB,EAAAA,IAAe;AAEf,QAAMI,IAASD,EAAO,UAAU,gBAC1BE,IAAaF,EAAO,cAAc;AAGxC,MAAI;AACF,UAAMG,IAAY,MAAMC,EAAA;AACxB,IAAID,EAAU,SAAS,KACrBE,EAAc,SAAA,EAAW,aAAaF,CAAS;AAAA,EAEnD,QAAQ;AAAA,EAER;AAEA,MAAI;AACF,UAAMG,EAAsBL,CAAM;AAAA,EACpC,QAAQ;AAAA,EAER;AAWA,MANAM,EAAsB,MAAM;AAC1B,IAAIF,EAAc,SAAA,EAAW,YAC3B,WAAWG,GAAa,GAAG;AAAA,EAE/B,CAAC,GAEGN,GAAY;AAQd,QAAIO,IAAeJ,EAAc,SAAA,EAAW;AAE5C,IAAAP,IAAeO,EAAc,UAAU,MAAM;AAC3C,YAAM,EAAE,UAAAK,EAAA,IAAaL,EAAc,SAAA,GAC7BM,IAAiBD,KAAY,CAACD;AACpC,MAAAA,IAAeC,GAEXC,KAEF,WAAWH,GAAa,GAAG;AAAA,IAE/B,CAAC;AAGD,UAAMI,IAAQP,EAAc,SAAA,GACtBQ,IAAaD,EAAM,MAAM,KAAK,CAACE,MAAMA,EAAE,WAAW,aAAaA,EAAE,WAAW,QAAQ;AAC1F,IAAIF,EAAM,YAAYC,KACpB,WAAWL,GAAa,IAAI;AAAA,EAEhC;AAUF;AAEO,SAASO,IAAc;AAC5B,EAAAjB,KAAA,QAAAA,KACAA,IAAe,MACfD,IAAe;AACjB;"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
let s;
|
|
2
|
+
const n = /* @__PURE__ */ new Set();
|
|
3
|
+
function c() {
|
|
4
|
+
n.forEach((e) => e());
|
|
5
|
+
}
|
|
6
|
+
function r(e) {
|
|
7
|
+
s = { ...s, ...e(s) }, c();
|
|
8
|
+
}
|
|
9
|
+
s = {
|
|
10
|
+
isOnline: typeof navigator < "u" ? navigator.onLine : !0,
|
|
11
|
+
swStatus: "idle",
|
|
12
|
+
swError: void 0,
|
|
13
|
+
resources: {},
|
|
14
|
+
queue: [],
|
|
15
|
+
setOnline: (e) => r(() => ({ isOnline: e })),
|
|
16
|
+
setSwStatus: (e, u) => r(() => ({ swStatus: e, swError: u })),
|
|
17
|
+
registerResource: (e, u) => r((t) => ({ resources: { ...t.resources, [e]: u } })),
|
|
18
|
+
updateResource: (e, u) => r((t) => ({
|
|
19
|
+
resources: {
|
|
20
|
+
...t.resources,
|
|
21
|
+
[e]: t.resources[e] ? { ...t.resources[e], ...u } : t.resources[e]
|
|
22
|
+
}
|
|
23
|
+
})),
|
|
24
|
+
unregisterResource: (e) => r((u) => {
|
|
25
|
+
const { [e]: t, ...o } = u.resources;
|
|
26
|
+
return { resources: o };
|
|
27
|
+
}),
|
|
28
|
+
addQueueItem: (e) => r((u) => ({ queue: [...u.queue, e] })),
|
|
29
|
+
updateQueueItem: (e, u) => r((t) => ({
|
|
30
|
+
queue: t.queue.map((o) => o.id === e ? { ...o, ...u } : o)
|
|
31
|
+
})),
|
|
32
|
+
removeQueueItem: (e) => r((u) => ({ queue: u.queue.filter((t) => t.id !== e) })),
|
|
33
|
+
hydrateQueue: (e) => r(() => ({ queue: e }))
|
|
34
|
+
};
|
|
35
|
+
function i() {
|
|
36
|
+
return s;
|
|
37
|
+
}
|
|
38
|
+
function d(e) {
|
|
39
|
+
return n.add(e), () => {
|
|
40
|
+
n.delete(e);
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const a = {
|
|
44
|
+
getState: i,
|
|
45
|
+
subscribe: d,
|
|
46
|
+
// Test/devtools helper — merges partial state, preserves action methods.
|
|
47
|
+
setState: (e) => {
|
|
48
|
+
const u = typeof e == "function" ? e(s) : e;
|
|
49
|
+
s = { ...s, ...u }, c();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
export {
|
|
53
|
+
a as useEidosStore
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sources":["../src/store.ts"],"sourcesContent":["import type { EidosState, ResourceEntry, ActionQueueItem } from './types'\n\nexport interface EidosStore extends EidosState {\n // Online\n setOnline: (online: boolean) => void\n // SW\n setSwStatus: (status: EidosState['swStatus'], error?: string) => void\n // Resources\n registerResource: (url: string, entry: ResourceEntry) => void\n updateResource: (url: string, update: Partial<ResourceEntry>) => void\n unregisterResource: (url: string) => void\n // Queue\n addQueueItem: (item: ActionQueueItem) => void\n updateQueueItem: (id: string, update: Partial<ActionQueueItem>) => void\n removeQueueItem: (id: string) => void\n hydrateQueue: (items: ActionQueueItem[]) => void\n}\n\ntype Listener = () => void\n\nlet _state: EidosStore\nconst _listeners = new Set<Listener>()\n\nfunction _notify() {\n _listeners.forEach((fn) => fn())\n}\n\nfunction _set(updater: (prev: EidosStore) => Partial<EidosStore>) {\n _state = { ..._state, ...updater(_state) }\n _notify()\n}\n\n_state = {\n isOnline: typeof navigator !== 'undefined' ? navigator.onLine : true,\n swStatus: 'idle',\n swError: undefined,\n resources: {},\n queue: [],\n\n setOnline: (isOnline) => _set(() => ({ isOnline })),\n\n setSwStatus: (swStatus, swError) => _set(() => ({ swStatus, swError })),\n\n registerResource: (url, entry) =>\n _set((s) => ({ resources: { ...s.resources, [url]: entry } })),\n\n updateResource: (url, update) =>\n _set((s) => ({\n resources: {\n ...s.resources,\n [url]: s.resources[url] ? { ...s.resources[url], ...update } : s.resources[url],\n },\n })),\n\n unregisterResource: (url) =>\n _set((s) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { [url]: _removed, ...rest } = s.resources\n return { resources: rest }\n }),\n\n addQueueItem: (item) => _set((s) => ({ queue: [...s.queue, item] })),\n\n updateQueueItem: (id, update) =>\n _set((s) => ({\n queue: s.queue.map((item) => (item.id === id ? { ...item, ...update } : item)),\n })),\n\n removeQueueItem: (id) => _set((s) => ({ queue: s.queue.filter((item) => item.id !== id) })),\n\n hydrateQueue: (items) => _set(() => ({ queue: items })),\n}\n\nfunction _getState() {\n return _state\n}\n\nfunction _subscribe(listener: Listener) {\n _listeners.add(listener)\n return () => { _listeners.delete(listener) }\n}\n\nexport const useEidosStore = {\n getState: _getState,\n subscribe: _subscribe,\n // Test/devtools helper — merges partial state, preserves action methods.\n setState: (partial: Partial<EidosStore> | ((s: EidosStore) => Partial<EidosStore>)) => {\n const update = typeof partial === 'function' ? partial(_state) : partial\n _state = { ..._state, ...update }\n _notify()\n },\n}\n"],"names":["_state","_listeners","_notify","fn","_set","updater","isOnline","swStatus","swError","url","entry","s","update","_removed","rest","item","id","items","_getState","_subscribe","listener","useEidosStore","partial"],"mappings":"AAoBA,IAAIA;AACJ,MAAMC,wBAAiB,IAAA;AAEvB,SAASC,IAAU;AACjB,EAAAD,EAAW,QAAQ,CAACE,MAAOA,EAAA,CAAI;AACjC;AAEA,SAASC,EAAKC,GAAoD;AAChE,EAAAL,IAAS,EAAE,GAAGA,GAAQ,GAAGK,EAAQL,CAAM,EAAA,GACvCE,EAAA;AACF;AAEAF,IAAS;AAAA,EACP,UAAU,OAAO,YAAc,MAAc,UAAU,SAAS;AAAA,EAChE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAACM,MAAaF,EAAK,OAAO,EAAE,UAAAE,IAAW;AAAA,EAElD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AM;AAAE,IAAAnB,EAAW,OAAOmB,CAAQ;AAAA,EAAE;AAC7C;AAEO,MAAMC,IAAgB;AAAA,EAC3B,UAAUH;AAAA,EACV,WAAWC;AAAA;AAAA,EAEX,UAAU,CAACG,MAA4E;AACrF,UAAMV,IAAS,OAAOU,KAAY,aAAaA,EAAQtB,CAAM,IAAIsB;AACjE,IAAAtB,IAAS,EAAE,GAAGA,GAAQ,GAAGY,EAAA,GACzBV,EAAA;AAAA,EACF;AACF;"}
|
package/dist/stores.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { useEidosStore as i } from "./store.js";
|
|
2
|
+
function s(e) {
|
|
3
|
+
return {
|
|
4
|
+
subscribe(t) {
|
|
5
|
+
return t(e(i.getState())), i.subscribe(() => t(e(i.getState())));
|
|
6
|
+
},
|
|
7
|
+
getState() {
|
|
8
|
+
return e(i.getState());
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
const a = s((e) => e), d = s((e) => e.queue), f = s((e) => ({
|
|
13
|
+
isOnline: e.isOnline,
|
|
14
|
+
swStatus: e.swStatus,
|
|
15
|
+
swError: e.swError
|
|
16
|
+
})), c = s((e) => {
|
|
17
|
+
let t = 0, u = 0, r = 0;
|
|
18
|
+
for (const n of e.queue)
|
|
19
|
+
n.status === "pending" ? t++ : n.status === "failed" ? u++ : n.status === "replaying" && r++;
|
|
20
|
+
return { pending: t, failed: u, replaying: r, total: e.queue.length };
|
|
21
|
+
});
|
|
22
|
+
function l(e) {
|
|
23
|
+
return s((t) => t.resources[e]);
|
|
24
|
+
}
|
|
25
|
+
function S(e) {
|
|
26
|
+
return s((t) => t.queue.find((u) => u.id === e));
|
|
27
|
+
}
|
|
28
|
+
export {
|
|
29
|
+
S as eidosAction,
|
|
30
|
+
d as eidosQueue,
|
|
31
|
+
c as eidosQueueStats,
|
|
32
|
+
l as eidosResource,
|
|
33
|
+
f as eidosStatus,
|
|
34
|
+
a as eidosStore
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=stores.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores.js","sources":["../src/stores.ts"],"sourcesContent":["/**\n * Framework-agnostic reactive stores — compatible with Svelte's store protocol,\n * Vue's watchEffect, RxJS, and vanilla JS. Zero framework dependencies.\n *\n * Svelte: use the `$` prefix — `$eidosQueue`, `$eidosStatus`, etc.\n * Vue: call `.subscribe()` inside a composable with `onUnmounted` cleanup.\n * Vanilla: call `.subscribe(run)` directly; the return value unsubscribes.\n *\n * Each store calls its subscriber whenever any part of the Eidos state changes.\n * For fine-grained subscriptions, use `.getState()` to read the current snapshot\n * and compare manually in the subscriber callback.\n */\n\nimport { useEidosStore } from './store'\nimport type { EidosStore } from './store'\nimport type { ActionQueueItem, ResourceEntry } from './types'\n\n// ── Readable<T> — compatible with Svelte's Readable interface ─────────────────\n\nexport interface EidosReadable<T> {\n /** Subscribe to value changes. Returns an unsubscribe function. */\n subscribe(run: (value: T) => void): () => void\n /** Read the current value synchronously without subscribing. */\n getState(): T\n}\n\nfunction readable<T>(selector: (s: EidosStore) => T): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n run(selector(useEidosStore.getState()))\n return useEidosStore.subscribe(() => run(selector(useEidosStore.getState())))\n },\n getState() {\n return selector(useEidosStore.getState())\n },\n }\n}\n\n// ── Static stores (created once at module scope) ──────────────────────────────\n\n/** Full Eidos state snapshot. Prefer the narrower stores below. */\nexport const eidosStore: EidosReadable<EidosStore> = readable((s) => s)\n\n/** The action queue. Re-notifies on every queue mutation. */\nexport const eidosQueue: EidosReadable<ActionQueueItem[]> = readable((s) => s.queue)\n\n/**\n * Online status + SW lifecycle.\n * Object identity changes on every notification — destructure or compare fields\n * in the subscriber if you need to avoid unnecessary work.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean\n swStatus: EidosStore['swStatus']\n swError: string | undefined\n}> = readable((s) => ({\n isOnline: s.isOnline,\n swStatus: s.swStatus,\n swError: s.swError,\n}))\n\n/**\n * Queue counts. Re-notifies on any queue mutation — compare values inside the\n * subscriber callback to skip work when counts haven't changed.\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number\n failed: number\n replaying: number\n total: number\n}> = readable((s) => {\n // Single pass over the queue — avoids three separate .filter() calls.\n let pending = 0, failed = 0, replaying = 0\n for (const q of s.queue) {\n if (q.status === 'pending') pending++\n else if (q.status === 'failed') failed++\n else if (q.status === 'replaying') replaying++\n }\n return { pending, failed, replaying, total: s.queue.length }\n})\n\n// ── Dynamic stores (created per URL / ID) ─────────────────────────────────────\n\n/**\n * Live cache state for a single registered resource URL.\n * @example\n * // Svelte\n * const entry = eidosResource('/api/products')\n * $: hits = $entry?.cacheHits ?? 0\n */\nexport function eidosResource(url: string): EidosReadable<ResourceEntry | undefined> {\n return readable((s) => s.resources[url])\n}\n\n/**\n * Live state for a single queue item by ID. Returns `undefined` once the item\n * is removed from the queue (after a successful replay or `clearQueue()`).\n * @example\n * // Svelte\n * const item = eidosAction(queuedResult.id)\n * $: status = $item?.status // 'pending' | 'replaying' | 'succeeded' | 'failed' | undefined\n */\nexport function eidosAction(id: string): EidosReadable<ActionQueueItem | undefined> {\n return readable((s) => s.queue.find((item) => item.id === id))\n}\n"],"names":["readable","selector","run","useEidosStore","eidosStore","s","eidosQueue","eidosStatus","eidosQueueStats","pending","failed","replaying","q","eidosResource","url","eidosAction","id","item"],"mappings":";AA0BA,SAASA,EAAYC,GAAkD;AACrE,SAAO;AAAA,IACL,UAAUC,GAAK;AAEb,aAAAA,EAAID,EAASE,EAAc,SAAA,CAAU,CAAC,GAC/BA,EAAc,UAAU,MAAMD,EAAID,EAASE,EAAc,SAAA,CAAU,CAAC,CAAC;AAAA,IAC9E;AAAA,IACA,WAAW;AACT,aAAOF,EAASE,EAAc,UAAU;AAAA,IAC1C;AAAA,EAAA;AAEJ;AAKO,MAAMC,IAAwCJ,EAAS,CAACK,MAAMA,CAAC,GAGzDC,IAA+CN,EAAS,CAACK,MAAMA,EAAE,KAAK,GAOtEE,IAIRP,EAAS,CAACK,OAAO;AAAA,EACpB,UAAUA,EAAE;AAAA,EACZ,UAAUA,EAAE;AAAA,EACZ,SAASA,EAAE;AACb,EAAE,GAMWG,IAKRR,EAAS,CAACK,MAAM;AAEnB,MAAII,IAAU,GAAGC,IAAS,GAAGC,IAAY;AACzC,aAAWC,KAAKP,EAAE;AAChB,IAAIO,EAAE,WAAW,YAAWH,MACnBG,EAAE,WAAW,WAAUF,MACvBE,EAAE,WAAW,eAAaD;AAErC,SAAO,EAAE,SAAAF,GAAS,QAAAC,GAAQ,WAAAC,GAAW,OAAON,EAAE,MAAM,OAAA;AACtD,CAAC;AAWM,SAASQ,EAAcC,GAAuD;AACnF,SAAOd,EAAS,CAACK,MAAMA,EAAE,UAAUS,CAAG,CAAC;AACzC;AAUO,SAASC,EAAYC,GAAwD;AAClF,SAAOhB,EAAS,CAACK,MAAMA,EAAE,MAAM,KAAK,CAACY,MAASA,EAAK,OAAOD,CAAE,CAAC;AAC/D;"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { useEidosStore as o } from "./store.js";
|
|
2
|
+
let s = null, u = [];
|
|
3
|
+
function v() {
|
|
4
|
+
return s;
|
|
5
|
+
}
|
|
6
|
+
async function w(t) {
|
|
7
|
+
if (typeof navigator > "u" || !("serviceWorker" in navigator)) {
|
|
8
|
+
o.getState().setSwStatus("unsupported");
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const e = o.getState();
|
|
12
|
+
e.setSwStatus("registering");
|
|
13
|
+
try {
|
|
14
|
+
s = await navigator.serviceWorker.register(t, { scope: "/" }), await f(s), e.setSwStatus("active"), navigator.serviceWorker.addEventListener("message", S), window.addEventListener("online", () => e.setOnline(!0)), window.addEventListener("offline", () => e.setOnline(!1)), g();
|
|
15
|
+
} catch (n) {
|
|
16
|
+
e.setSwStatus("error", String(n));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function f(t) {
|
|
20
|
+
return new Promise((e) => {
|
|
21
|
+
if (t.active) {
|
|
22
|
+
e();
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const n = t.installing ?? t.waiting;
|
|
26
|
+
if (!n) {
|
|
27
|
+
e();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const i = setTimeout(e, 1e4);
|
|
31
|
+
n.addEventListener("statechange", function r() {
|
|
32
|
+
n.state === "activated" && (clearTimeout(i), n.removeEventListener("statechange", r), e());
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function d(t) {
|
|
37
|
+
const e = s == null ? void 0 : s.active;
|
|
38
|
+
e ? e.postMessage(t) : u.push(t);
|
|
39
|
+
}
|
|
40
|
+
let a = null;
|
|
41
|
+
function E(t) {
|
|
42
|
+
a = t;
|
|
43
|
+
}
|
|
44
|
+
function p() {
|
|
45
|
+
try {
|
|
46
|
+
return typeof navigator < "u" && "serviceWorker" in navigator && s !== null && "sync" in s;
|
|
47
|
+
} catch {
|
|
48
|
+
return !1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function S(t) {
|
|
52
|
+
const e = t.data;
|
|
53
|
+
if (!(e != null && e.type)) return;
|
|
54
|
+
const n = o.getState(), { type: i, url: r } = e;
|
|
55
|
+
if (i === "EIDOS_BACKGROUND_SYNC") {
|
|
56
|
+
a == null || a();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (r)
|
|
60
|
+
switch (i) {
|
|
61
|
+
case "EIDOS_CACHE_HIT": {
|
|
62
|
+
const c = n.resources[r];
|
|
63
|
+
n.updateResource(r, {
|
|
64
|
+
status: "fresh",
|
|
65
|
+
lastEvent: "cache-hit",
|
|
66
|
+
cacheHits: ((c == null ? void 0 : c.cacheHits) ?? 0) + 1
|
|
67
|
+
});
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case "EIDOS_CACHE_UPDATED": {
|
|
71
|
+
n.updateResource(r, {
|
|
72
|
+
status: "fresh",
|
|
73
|
+
lastEvent: "cache-updated",
|
|
74
|
+
cachedAt: Date.now()
|
|
75
|
+
});
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case "EIDOS_NETWORK_ERROR": {
|
|
79
|
+
n.updateResource(r, {
|
|
80
|
+
status: "error",
|
|
81
|
+
lastEvent: "network-error"
|
|
82
|
+
});
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function h(t) {
|
|
88
|
+
d({ type: "EIDOS_SIMULATE_OFFLINE", enabled: t }), o.getState().setOnline(!t);
|
|
89
|
+
}
|
|
90
|
+
function g() {
|
|
91
|
+
const t = s == null ? void 0 : s.active;
|
|
92
|
+
if (t) {
|
|
93
|
+
for (const e of u) t.postMessage(e);
|
|
94
|
+
u = [];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export {
|
|
98
|
+
v as getSwRegistration,
|
|
99
|
+
p as isBgSyncSupported,
|
|
100
|
+
E as registerBgSyncHandler,
|
|
101
|
+
w as registerServiceWorker,
|
|
102
|
+
d as sendToWorker,
|
|
103
|
+
h as setOfflineSimulation
|
|
104
|
+
};
|
|
105
|
+
//# sourceMappingURL=sw-bridge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sw-bridge.js","sources":["../src/sw-bridge.ts"],"sourcesContent":["import { useEidosStore } from './store'\n\nlet _registration: ServiceWorkerRegistration | null = null\n// Messages sent before the SW activates are buffered here and flushed once\n// the SW is ready. Covers resource registrations, cache clears, offline\n// simulation — anything sent at module scope before EidosProvider mounts.\nlet _pendingMessages: Record<string, unknown>[] = []\n\nexport function getSwRegistration() {\n return _registration\n}\n\nexport async function registerServiceWorker(swPath: string): Promise<void> {\n if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {\n useEidosStore.getState().setSwStatus('unsupported')\n return\n }\n\n const store = useEidosStore.getState()\n store.setSwStatus('registering')\n\n try {\n _registration = await navigator.serviceWorker.register(swPath, { scope: '/' })\n\n await waitForActivation(_registration)\n\n store.setSwStatus('active')\n\n // Receive messages from SW\n navigator.serviceWorker.addEventListener('message', onSwMessage)\n\n // Track online/offline\n window.addEventListener('online', () => store.setOnline(true))\n window.addEventListener('offline', () => store.setOnline(false))\n\n flushPendingMessages()\n } catch (err) {\n store.setSwStatus('error', String(err))\n }\n}\n\nfunction waitForActivation(reg: ServiceWorkerRegistration): Promise<void> {\n return new Promise((resolve) => {\n if (reg.active) { resolve(); return }\n const sw = reg.installing ?? reg.waiting\n if (!sw) { resolve(); return }\n\n // Resolve after 10s regardless — another tab may be blocking activation\n const timer = setTimeout(resolve, 10_000)\n\n sw.addEventListener('statechange', function handler() {\n if (sw.state === 'activated') {\n clearTimeout(timer)\n sw.removeEventListener('statechange', handler)\n resolve()\n }\n })\n })\n}\n\nexport function sendToWorker(message: Record<string, unknown>): void {\n const sw = _registration?.active\n if (sw) {\n sw.postMessage(message)\n } else {\n _pendingMessages.push(message)\n }\n}\n\nlet _bgSyncHandler: (() => void) | null = null\n\nexport function registerBgSyncHandler(fn: () => void): void {\n _bgSyncHandler = fn\n}\n\nexport function isBgSyncSupported(): boolean {\n try {\n return (\n typeof navigator !== 'undefined' &&\n 'serviceWorker' in navigator &&\n _registration !== null &&\n 'sync' in _registration\n )\n } catch {\n return false\n }\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as { type: string; url?: string; strategy?: string }\n if (!data?.type) return\n\n const store = useEidosStore.getState()\n const { type, url } = data\n\n if (type === 'EIDOS_BACKGROUND_SYNC') {\n _bgSyncHandler?.()\n return\n }\n\n if (!url) return\n\n switch (type) {\n case 'EIDOS_CACHE_HIT': {\n const current = store.resources[url]\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-hit',\n cacheHits: (current?.cacheHits ?? 0) + 1,\n })\n break\n }\n case 'EIDOS_CACHE_UPDATED': {\n store.updateResource(url, {\n status: 'fresh',\n lastEvent: 'cache-updated',\n cachedAt: Date.now(),\n })\n break\n }\n case 'EIDOS_NETWORK_ERROR': {\n store.updateResource(url, {\n status: 'error',\n lastEvent: 'network-error',\n })\n break\n }\n }\n}\n\nexport function setOfflineSimulation(enabled: boolean): void {\n sendToWorker({ type: 'EIDOS_SIMULATE_OFFLINE', enabled })\n useEidosStore.getState().setOnline(!enabled)\n}\n\nfunction flushPendingMessages(): void {\n const sw = _registration?.active\n if (!sw) return\n for (const msg of _pendingMessages) sw.postMessage(msg)\n _pendingMessages = []\n}\n"],"names":["_registration","_pendingMessages","getSwRegistration","registerServiceWorker","swPath","useEidosStore","store","waitForActivation","onSwMessage","flushPendingMessages","err","reg","resolve","sw","timer","handler","sendToWorker","message","_bgSyncHandler","registerBgSyncHandler","fn","isBgSyncSupported","event","data","type","url","current","setOfflineSimulation","enabled","msg"],"mappings":";AAEA,IAAIA,IAAkD,MAIlDC,IAA8C,CAAA;AAE3C,SAASC,IAAoB;AAClC,SAAOF;AACT;AAEA,eAAsBG,EAAsBC,GAA+B;AACzE,MAAI,OAAO,YAAc,OAAe,EAAE,mBAAmB,YAAY;AACvE,IAAAC,EAAc,SAAA,EAAW,YAAY,aAAa;AAClD;AAAA,EACF;AAEA,QAAMC,IAAQD,EAAc,SAAA;AAC5B,EAAAC,EAAM,YAAY,aAAa;AAE/B,MAAI;AACF,IAAAN,IAAgB,MAAM,UAAU,cAAc,SAASI,GAAQ,EAAE,OAAO,KAAK,GAE7E,MAAMG,EAAkBP,CAAa,GAErCM,EAAM,YAAY,QAAQ,GAG1B,UAAU,cAAc,iBAAiB,WAAWE,CAAW,GAG/D,OAAO,iBAAiB,UAAU,MAAMF,EAAM,UAAU,EAAI,CAAC,GAC7D,OAAO,iBAAiB,WAAW,MAAMA,EAAM,UAAU,EAAK,CAAC,GAE/DG,EAAA;AAAA,EACF,SAASC,GAAK;AACZ,IAAAJ,EAAM,YAAY,SAAS,OAAOI,CAAG,CAAC;AAAA,EACxC;AACF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,WAAW;AAAA,UACX,aAAYC,KAAA,gBAAAA,EAAS,cAAa,KAAK;AAAA,QAAA,CACxC;AACD;AAAA,MACF;AAAA,MACA,KAAK,uBAAuB;AAC1B,QAAApB,EAAM,eAAemB,GAAK;AAAA,UACxB,QAAQ;AAAA,UACR,WAAW;AAAA,UACX,UAAU,KAAK,IAAA;AAAA,QAAI,CACpB;AACD;AAAA,MACF;AAAA,MACA,KAAK,uBAAuB;AAC1B,QAAAnB,EAAM,eAAemB,GAAK;AAAA,UACxB,QAAQ;AAAA,UACR,WAAW;AAAA,QAAA,CACZ;AACD;AAAA,MACF;AAAA,IAAA;AAEJ;AAEO,SAASE,EAAqBC,GAAwB;AAC3D,EAAAZ,EAAa,EAAE,MAAM,0BAA0B,SAAAY,EAAA,CAAS,GACxDvB,EAAc,SAAA,EAAW,UAAU,CAACuB,CAAO;AAC7C;AAEA,SAASnB,IAA6B;AACpC,QAAMI,IAAKb,KAAA,gBAAAA,EAAe;AAC1B,MAAKa,GACL;AAAA,eAAWgB,KAAO5B,EAAkB,CAAAY,EAAG,YAAYgB,CAAG;AACtD,IAAA5B,IAAmB,CAAA;AAAA;AACrB;"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const eidos = require("@sweidos/eidos");
|
|
4
|
+
let _originalFetch = null;
|
|
5
|
+
function mockOffline(options = {}) {
|
|
6
|
+
eidos.useEidosStore.getState().setOnline(false);
|
|
7
|
+
if (options.stubFetch && _originalFetch === null) {
|
|
8
|
+
_originalFetch = globalThis.fetch;
|
|
9
|
+
globalThis.fetch = () => Promise.reject(
|
|
10
|
+
new TypeError("Network request failed (stubbed by @sweidos/eidos/testing)")
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function mockOnline() {
|
|
15
|
+
eidos.useEidosStore.getState().setOnline(true);
|
|
16
|
+
if (_originalFetch !== null) {
|
|
17
|
+
globalThis.fetch = _originalFetch;
|
|
18
|
+
_originalFetch = null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async function drainQueue() {
|
|
22
|
+
eidos.useEidosStore.getState().setOnline(true);
|
|
23
|
+
return eidos.replayQueue();
|
|
24
|
+
}
|
|
25
|
+
function waitForQueueDrain(options = {}) {
|
|
26
|
+
const timeout = options.timeout ?? 5e3;
|
|
27
|
+
const interval = options.interval ?? 50;
|
|
28
|
+
const deadline = Date.now() + timeout;
|
|
29
|
+
return new Promise((resolve, reject) => {
|
|
30
|
+
function check() {
|
|
31
|
+
const { queue } = eidos.useEidosStore.getState();
|
|
32
|
+
const active = queue.filter(
|
|
33
|
+
(q) => q.status === "pending" || q.status === "replaying"
|
|
34
|
+
);
|
|
35
|
+
if (active.length === 0) {
|
|
36
|
+
resolve();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (Date.now() >= deadline) {
|
|
40
|
+
reject(
|
|
41
|
+
new Error(
|
|
42
|
+
`[eidos/testing] waitForQueueDrain timed out after ${timeout}ms. ${active.length} item(s) still active (statuses: ${active.map((q) => q.status).join(", ")}).`
|
|
43
|
+
)
|
|
44
|
+
);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
setTimeout(check, interval);
|
|
48
|
+
}
|
|
49
|
+
check();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
const EIDOS_CACHE_NAME = "eidos-resources-v1";
|
|
53
|
+
async function getCachedEntry(url, cacheName = EIDOS_CACHE_NAME) {
|
|
54
|
+
if (typeof caches === "undefined") return void 0;
|
|
55
|
+
const cache = await caches.open(cacheName);
|
|
56
|
+
const match = await cache.match(url);
|
|
57
|
+
return match ?? void 0;
|
|
58
|
+
}
|
|
59
|
+
async function clearEidosCache(cacheName = EIDOS_CACHE_NAME) {
|
|
60
|
+
if (typeof caches === "undefined") return;
|
|
61
|
+
await caches.delete(cacheName);
|
|
62
|
+
}
|
|
63
|
+
async function resetEidos() {
|
|
64
|
+
eidos._resetEidos();
|
|
65
|
+
await eidos.clearQueue();
|
|
66
|
+
mockOnline();
|
|
67
|
+
eidos.useEidosStore.setState((s) => ({
|
|
68
|
+
...s,
|
|
69
|
+
resources: {},
|
|
70
|
+
swStatus: "idle",
|
|
71
|
+
swError: void 0
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
74
|
+
function getEidosState() {
|
|
75
|
+
const { isOnline, swStatus, swError, resources, queue } = eidos.useEidosStore.getState();
|
|
76
|
+
return { isOnline, swStatus, swError, resources, queue };
|
|
77
|
+
}
|
|
78
|
+
exports.EIDOS_CACHE_NAME = EIDOS_CACHE_NAME;
|
|
79
|
+
exports.clearEidosCache = clearEidosCache;
|
|
80
|
+
exports.drainQueue = drainQueue;
|
|
81
|
+
exports.getCachedEntry = getCachedEntry;
|
|
82
|
+
exports.getEidosState = getEidosState;
|
|
83
|
+
exports.mockOffline = mockOffline;
|
|
84
|
+
exports.mockOnline = mockOnline;
|
|
85
|
+
exports.resetEidos = resetEidos;
|
|
86
|
+
exports.waitForQueueDrain = waitForQueueDrain;
|