@sweidos/eidos 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/resource.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { useEidosStore as h } from "./store.js";
2
2
  import { sendToWorker as g } from "./sw-bridge.js";
3
- const p = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Map();
3
+ const p = /* @__PURE__ */ new Map(), v = /* @__PURE__ */ new Map();
4
4
  let m = null;
5
- function N(e) {
5
+ function q(e) {
6
6
  m = e;
7
7
  }
8
8
  function l(e) {
9
9
  return e.includes("*") || /:[^/]+/.test(e);
10
10
  }
11
- function k(e) {
11
+ function E(e) {
12
12
  return "^" + e.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, ".+").replace(/\*/g, "[^/]+").replace(/:[^/]+/g, "[^/]+") + "$";
13
13
  }
14
14
  function w(e, a) {
@@ -16,10 +16,10 @@ function w(e, a) {
16
16
  `[eidos] resource('${e}') is a URL pattern — ${a}() is not supported on pattern handles. The SW intercepts matching requests automatically; call fetch(specificUrl) directly in your app code.`
17
17
  );
18
18
  }
19
- function q(e, a) {
19
+ function A(e, a) {
20
20
  if (p.has(e))
21
21
  return p.get(e);
22
- const s = E(e, a), t = l(e) ? k(e) : void 0, o = {
22
+ const s = S(e, a), t = l(e) ? E(e) : void 0, o = {
23
23
  url: e,
24
24
  config: a,
25
25
  strategy: s,
@@ -40,10 +40,10 @@ function q(e, a) {
40
40
  strategy: s,
41
41
  fetch: async () => {
42
42
  if (l(e)) throw w(e, "fetch");
43
- const r = y.get(e);
43
+ const r = v.get(e);
44
44
  if (r) return r.then((n) => n.clone());
45
- const i = S(e, a, s);
46
- return y.set(e, i), i.finally(() => y.delete(e)).catch(() => {
45
+ const i = k(e, a, s);
46
+ return v.set(e, i), i.finally(() => v.delete(e)).catch(() => {
47
47
  }), i.then((n) => n.clone());
48
48
  },
49
49
  json: async () => {
@@ -68,8 +68,8 @@ function q(e, a) {
68
68
  const i = await r.keys(), n = t ? new RegExp(t) : null, u = e.startsWith("http");
69
69
  await Promise.all(
70
70
  i.filter((f) => {
71
- const d = f.url, v = new URL(d).pathname;
72
- return n ? n.test(u ? d : v) : u ? d === e : d === e || v === e;
71
+ const d = f.url, y = new URL(d).pathname;
72
+ return n ? n.test(u ? d : y) : u ? d === e : d === e || y === e;
73
73
  }).map((f) => r.delete(f))
74
74
  );
75
75
  }
@@ -87,7 +87,7 @@ function q(e, a) {
87
87
  };
88
88
  return p.set(e, c), c;
89
89
  }
90
- async function S(e, a, s) {
90
+ async function k(e, a, s) {
91
91
  const t = h.getState();
92
92
  t.updateResource(e, { status: "fetching", fetchedAt: Date.now() });
93
93
  const o = await caches.open(s.cacheName).catch(() => null);
@@ -136,13 +136,16 @@ async function S(e, a, s) {
136
136
  throw t.updateResource(e, { status: "error" }), c;
137
137
  }
138
138
  }
139
- function E(e, a) {
139
+ function S(e, a) {
140
140
  const s = a.strategy;
141
141
  return a.offline ? R(s ?? "stale-while-revalidate", e, a.cacheName) : R(s ?? "network-first", e, a.cacheName);
142
142
  }
143
- const x = {
143
+ const b = {
144
+ "stale-while-revalidate": "StaleWhileRevalidate",
145
+ "cache-first": "CacheFirst",
146
+ "network-first": "NetworkFirst"
147
+ }, x = {
144
148
  "stale-while-revalidate": {
145
- name: "StaleWhileRevalidate",
146
149
  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.",
147
150
  behavior: [
148
151
  "Cache hit → return immediately, kick off background revalidation",
@@ -157,7 +160,6 @@ new StaleWhileRevalidate({
157
160
  })`
158
161
  },
159
162
  "cache-first": {
160
- name: "CacheFirst",
161
163
  reasoning: "cache-first maximises speed and offline availability. Network is consulted only on cache miss. Best for static or infrequently-updated data.",
162
164
  behavior: [
163
165
  "Cache hit → return immediately, no network request made",
@@ -172,7 +174,6 @@ new CacheFirst({
172
174
  })`
173
175
  },
174
176
  "network-first": {
175
- name: "NetworkFirst",
176
177
  reasoning: "network-first prioritises fresh data. Cache acts as a safety net when offline. Best for frequently-updated resources where stale data causes problems.",
177
178
  behavior: [
178
179
  "Always try network first",
@@ -188,13 +189,19 @@ new NetworkFirst({
188
189
  }
189
190
  };
190
191
  function R(e, a, s) {
192
+ const t = x[e];
191
193
  return {
192
- ...x[e],
194
+ name: b[e],
193
195
  swStrategy: e,
194
- cacheName: s ?? "eidos-resources-v1"
196
+ cacheName: s ?? "eidos-resources-v1",
197
+ // reasoning + behavior are rendered by the playground UI from live ResourceEntry objects —
198
+ // keep them in all builds. equivalentCode is a static code block only used in DEV tools.
199
+ reasoning: t.reasoning,
200
+ behavior: t.behavior,
201
+ equivalentCode: ""
195
202
  };
196
203
  }
197
- async function A(e) {
204
+ async function _(e) {
198
205
  const a = await Promise.allSettled(e.map((t) => t.prefetch())), s = a.filter((t) => t.status === "rejected").map((t) => t.reason);
199
206
  return {
200
207
  warmed: a.filter((t) => t.status === "fulfilled").length,
@@ -203,8 +210,8 @@ async function A(e) {
203
210
  };
204
211
  }
205
212
  export {
206
- q as resource,
207
- N as setQueryInvalidator,
208
- A as warmCache
213
+ A as resource,
214
+ q as setQueryInvalidator,
215
+ _ as warmCache
209
216
  };
210
217
  //# sourceMappingURL=resource.js.map
@@ -1 +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 WarmCacheResult,\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 // .catch() silences the unhandled-rejection on the cleanup promise;\n // the error still propagates to callers via task.then() below.\n task.finally(() => _inflightRequests.delete(url)).catch(() => {})\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, { signal: AbortSignal.timeout(5000) })\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 or timed out — 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\n// ── warmCache ─────────────────────────────────────────────────────────────────\n\n/**\n * Bulk-prefetch an array of resource handles concurrently, warming the cache\n * for each one. Useful on login / app init when you know which resources the\n * user will need offline.\n *\n * Pattern handles (containing `*`, `**`, or `:param`) are silently skipped —\n * they match multiple URLs so there is no single URL to prefetch.\n *\n * @example\n * import { warmCache } from '@sweidos/eidos'\n *\n * // In EidosProvider's onReady, or after login:\n * const { warmed, failed } = await warmCache([products, userProfile, settings])\n */\nexport async function warmCache(handles: ResourceHandle[]): Promise<WarmCacheResult> {\n const results = await Promise.allSettled(handles.map((h) => h.prefetch()))\n const errors = results\n .filter((r): r is PromiseRejectedResult => r.status === 'rejected')\n .map((r) => r.reason)\n\n if (import.meta.env.DEV && errors.length > 0) {\n console.warn(`[eidos] warmCache: ${errors.length} handle(s) failed to prefetch`, errors)\n }\n\n return {\n warmed: results.filter((r) => r.status === 'fulfilled').length,\n failed: errors.length,\n errors,\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","warmCache","handles","results","h","errors"],"mappings":";;AAWA,MAAMA,wBAAgB,IAAA,GAMhBC,wBAAwC,IAAA;AAM9C,IAAIC,IAA6C;AAG1C,SAASC,EAAoBC,GAA4B;AAC9D,EAAAF,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AAE,WAAW,UAAU,EACjE,IAAI,CAACA,MAAMA,EAAE,MAAM;AAMtB,SAAO;AAAA,IACL,QAAQ2B,EAAQ,OAAO,CAAC3B,MAAMA,EAAE,WAAW,WAAW,EAAE;AAAA,IACxD,QAAQ6B,EAAO;AAAA,IACf,QAAAA;AAAA,EAAA;AAEJ;"}
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 WarmCacheResult,\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 // .catch() silences the unhandled-rejection on the cleanup promise;\n // the error still propagates to callers via task.then() below.\n task.finally(() => _inflightRequests.delete(url)).catch(() => {})\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, { signal: AbortSignal.timeout(5000) })\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 or timed out — 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\n// Strategy display names — always included (tiny, used by devtools).\nconst STRATEGY_NAMES: Record<CacheStrategy, string> = {\n 'stale-while-revalidate': 'StaleWhileRevalidate',\n 'cache-first': 'CacheFirst',\n 'network-first': 'NetworkFirst',\n}\n\n// Heavy descriptive strings — stripped from production bundles by Vite's\n// import.meta.env.DEV dead-code elimination. Only the names above ship in prod.\ntype StrategyDevInfo = Pick<GeneratedStrategy, 'reasoning' | 'behavior' | 'equivalentCode'>\nconst _STRATEGY_DEV_META: Record<CacheStrategy, StrategyDevInfo> = {\n 'stale-while-revalidate': {\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 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 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 const meta = _STRATEGY_DEV_META[swStrategy]\n return {\n name: STRATEGY_NAMES[swStrategy],\n swStrategy,\n cacheName: cacheName ?? 'eidos-resources-v1',\n // reasoning + behavior are rendered by the playground UI from live ResourceEntry objects —\n // keep them in all builds. equivalentCode is a static code block only used in DEV tools.\n reasoning: meta.reasoning,\n behavior: meta.behavior,\n equivalentCode: import.meta.env.DEV ? meta.equivalentCode : '',\n }\n}\n\n// ── warmCache ─────────────────────────────────────────────────────────────────\n\n/**\n * Bulk-prefetch an array of resource handles concurrently, warming the cache\n * for each one. Useful on login / app init when you know which resources the\n * user will need offline.\n *\n * Pattern handles (containing `*`, `**`, or `:param`) are silently skipped —\n * they match multiple URLs so there is no single URL to prefetch.\n *\n * @example\n * import { warmCache } from '@sweidos/eidos'\n *\n * // In EidosProvider's onReady, or after login:\n * const { warmed, failed } = await warmCache([products, userProfile, settings])\n */\nexport async function warmCache(handles: ResourceHandle[]): Promise<WarmCacheResult> {\n const results = await Promise.allSettled(handles.map((h) => h.prefetch()))\n const errors = results\n .filter((r): r is PromiseRejectedResult => r.status === 'rejected')\n .map((r) => r.reason)\n\n if (import.meta.env.DEV && errors.length > 0) {\n console.warn(`[eidos] warmCache: ${errors.length} handle(s) failed to prefetch`, errors)\n }\n\n return {\n warmed: results.filter((r) => r.status === 'fulfilled').length,\n failed: errors.length,\n errors,\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_NAMES","_STRATEGY_DEV_META","swStrategy","_url","cacheName","meta","warmCache","handles","results","h","errors"],"mappings":";;AAWA,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,SAA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AM;AAMtB,SAAO;AAAA,IACL,QAAQ6B,EAAQ,OAAO,CAAC7B,MAAMA,EAAE,WAAW,WAAW,EAAE;AAAA,IACxD,QAAQ+B,EAAO;AAAA,IACf,QAAAA;AAAA,EAAA;AAEJ;"}
@@ -1 +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 // Skip silently during SSR — SW, IndexedDB, and window are browser-only.\n if (typeof window === 'undefined') return\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;AAGvE,MADI,OAAO,SAAW,OAClBH,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;"}
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 // Skip silently during SSR — SW, IndexedDB, and window are browser-only.\n if (typeof window === 'undefined') return\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:#22C55E;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;AAGvE,MADI,OAAO,SAAW,OAClBH,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 CHANGED
@@ -22,10 +22,11 @@ o = {
22
22
  [e]: t.resources[e] ? { ...t.resources[e], ...u } : t.resources[e]
23
23
  }
24
24
  })),
25
- unregisterResource: (e) => r((u) => {
26
- const { [e]: t, ...s } = u.resources;
27
- return { resources: s };
28
- }),
25
+ unregisterResource: (e) => r((u) => ({
26
+ resources: Object.fromEntries(
27
+ Object.entries(u.resources).filter(([t]) => t !== e)
28
+ )
29
+ })),
29
30
  addQueueItem: (e) => r((u) => ({ queue: [...u.queue, e] })),
30
31
  updateQueueItem: (e, u) => r((t) => ({
31
32
  queue: t.queue.map((s) => s.id === e ? { ...s, ...u } : s)
@@ -42,17 +43,17 @@ o = {
42
43
  removeQueueItem: (e) => r((u) => ({ queue: u.queue.filter((t) => t.id !== e) })),
43
44
  hydrateQueue: (e) => r(() => ({ queue: e }))
44
45
  };
45
- function d() {
46
+ function i() {
46
47
  return o;
47
48
  }
48
- function i(e) {
49
+ function d(e) {
49
50
  return n.add(e), () => {
50
51
  n.delete(e);
51
52
  };
52
53
  }
53
54
  const f = {
54
- getState: d,
55
- subscribe: i,
55
+ getState: i,
56
+ subscribe: d,
56
57
  // Test/devtools helper — merges partial state, preserves action methods.
57
58
  setState: (e) => {
58
59
  const u = typeof e == "function" ? e(o) : e;
package/dist/store.js.map CHANGED
@@ -1 +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 batchUpdateQueueItems: (updates: Array<{ 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 // navigator.onLine is undefined in React Native — default to true unless explicitly false\n isOnline: typeof navigator === 'undefined' || navigator.onLine !== false,\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 batchUpdateQueueItems: (updates) =>\n _set((s) => {\n const map = new Map(updates.map((u) => [u.id, u.update]))\n return {\n queue: s.queue.map((item) => {\n const u = map.get(item.id)\n return u ? { ...item, ...u } : item\n }),\n }\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","updates","map","u","items","_getState","_subscribe","listener","useEidosStore","partial"],"mappings":"AAqBA,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,E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UAAMO,IAAM,IAAI,IAAID,EAAQ,IAAI,CAACE,MAAM,CAACA,EAAE,IAAIA,EAAE,MAAM,CAAC,CAAC;AACxD,WAAO;AAAA,MACL,OAAOR,EAAE,MAAM,IAAI,CAACI,MAAS;AAC3B,cAAMI,IAAID,EAAI,IAAIH,EAAK,EAAE;AACzB,eAAOI,IAAI,EAAE,GAAGJ,GAAM,GAAGI,MAAMJ;AAAA,MACjC,CAAC;AAAA,IAAA;AAAA,EAEL,CAAC;AAAA,EAEH,iBAAiB,CAACC,MAAOZ,EAAK,CAACO,OAAO,EAAE,OAAOA,EAAE,MAAM,OAAO,CAACI,MAASA,EAAK,OAAOC,CAAE,IAAI;AAAA,EAE1F,cAAc,CAACI,MAAUhB,EAAK,OAAO,EAAE,OAAOgB,IAAQ;AACxD;AAEA,SAASC,IAAY;AACnB,SAAOrB;AACT;AAEA,SAASsB,EAAWC,GAAoB;AACtC,SAAAtB,EAAW,IAAIsB,CAAQ,GAChB,MAAM;AAAE,IAAAtB,EAAW,OAAOsB,CAAQ;AAAA,EAAE;AAC7C;AAEO,MAAMC,IAAgB;AAAA,EAC3B,UAAUH;AAAA,EACV,WAAWC;AAAA;AAAA,EAEX,UAAU,CAACG,MAA4E;AACrF,UAAMb,IAAS,OAAOa,KAAY,aAAaA,EAAQzB,CAAM,IAAIyB;AACjE,IAAAzB,IAAS,EAAE,GAAGA,GAAQ,GAAGY,EAAA,GACzBV,EAAA;AAAA,EACF;AACF;"}
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 batchUpdateQueueItems: (updates: Array<{ 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 // navigator.onLine is undefined in React Native — default to true unless explicitly false\n isOnline: typeof navigator === 'undefined' || navigator.onLine !== false,\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 resources: Object.fromEntries(\n Object.entries(s.resources).filter(([k]) => k !== url),\n ),\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 batchUpdateQueueItems: (updates) =>\n _set((s) => {\n const map = new Map(updates.map((u) => [u.id, u.update]))\n return {\n queue: s.queue.map((item) => {\n const u = map.get(item.id)\n return u ? { ...item, ...u } : item\n }),\n }\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","k","item","id","updates","map","u","items","_getState","_subscribe","listener","useEidosStore","partial"],"mappings":"AAqBA,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;AAAA,EAEP,UAAU,OAAO,YAAc,OAAe,UAAU,WAAW;AAAA,EACnE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAA;AAAA,EACX,OAAO,CAAA;AAAA,EAEP,WAAW,CAACM,MAAaF,EAAK,OAAO,EAAE,UAAAE,IAAW;AAAA,EAElD,aAAa,CAACC,GAAUC,MAAYJ,EAAK,OAAO,EAAE,UAAAG,GAAU,SAAAC,EAAA,EAAU;AAAA,EAEtE,kBAAkB,CAACC,GAAKC,MACtBN,EAAK,CAACO,OAAO,EAAE,WAAW,EAAE,GAAGA,EAAE,WAAW,CAACF,CAAG,GAAGC,EAAA,IAAU;AAAA,EAE/D,gBAAgB,CAACD,GAAKG,MACpBR,EAAK,CAACO,OAAO;AAAA,IACX,WAAW;AAAA,MACT,GAAGA,EAAE;AAAA,MACL,CAACF,CAAG,GAAGE,EAAE,UAAUF,CAAG,IAAI,EAAE,GAAGE,EAAE,UAAUF,CAAG,GAAG,GAAGG,MAAWD,EAAE,UAAUF,CAAG;AAAA,IAAA;AAAA,EAChF,EACA;AAAA,EAEJ,oBAAoB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,EACV,WAAWC;AAAA;AAAA,EAEX,UAAU,CAACG,MAA4E;AACrF,UAAMZ,IAAS,OAAOY,KAAY,aAAaA,EAAQxB,CAAM,IAAIwB;AACjE,IAAAxB,IAAS,EAAE,GAAGA,GAAQ,GAAGY,EAAA,GACzBV,EAAA;AAAA,EACF;AACF;"}
package/dist/stores.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { useEidosStore as i } from "./store.js";
2
- function o(e, t) {
2
+ function a(e, t) {
3
3
  const s = Object.keys(e);
4
4
  if (s.length !== Object.keys(t).length) return !1;
5
- for (const n of s)
6
- if (e[n] !== t[n]) return !1;
5
+ for (const n of s) if (e[n] !== t[n]) return !1;
7
6
  return !0;
8
7
  }
8
+ function o(e, t) {
9
+ return a(e, t);
10
+ }
9
11
  function u(e, t = Object.is) {
10
12
  return {
11
13
  subscribe(s) {
@@ -20,10 +22,10 @@ function u(e, t = Object.is) {
20
22
  }
21
23
  };
22
24
  }
23
- const f = u((e) => e), l = u((e) => e.queue), c = u(
25
+ const l = u((e) => e), c = u((e) => e.queue), d = u(
24
26
  (e) => ({ isOnline: e.isOnline, swStatus: e.swStatus, swError: e.swError }),
25
27
  o
26
- ), d = u(
28
+ ), g = u(
27
29
  (e) => {
28
30
  let t = 0, s = 0, n = 0;
29
31
  for (const r of e.queue)
@@ -32,18 +34,18 @@ const f = u((e) => e), l = u((e) => e.queue), c = u(
32
34
  },
33
35
  o
34
36
  );
35
- function g(e) {
37
+ function S(e) {
36
38
  return u((t) => t.resources[e]);
37
39
  }
38
- function S(e) {
40
+ function b(e) {
39
41
  return u((t) => t.queue.find((s) => s.id === e));
40
42
  }
41
43
  export {
42
- S as eidosAction,
43
- l as eidosQueue,
44
- d as eidosQueueStats,
45
- g as eidosResource,
46
- c as eidosStatus,
47
- f as eidosStore
44
+ b as eidosAction,
45
+ c as eidosQueue,
46
+ g as eidosQueueStats,
47
+ S as eidosResource,
48
+ d as eidosStatus,
49
+ l as eidosStore
48
50
  };
49
51
  //# sourceMappingURL=stores.js.map
@@ -1 +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 shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[]\n if (keys.length !== Object.keys(b).length) return false\n for (const k of keys) {\n if (a[k] !== b[k]) return false\n }\n return true\n}\n\nfunction readable<T>(\n selector: (s: EidosStore) => T,\n equal: (a: T, b: T) => boolean = Object.is,\n): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n let last = selector(useEidosStore.getState())\n run(last)\n return useEidosStore.subscribe(() => {\n const next = selector(useEidosStore.getState())\n if (!equal(last, next)) {\n last = next\n run(next)\n }\n })\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 * Only re-emits when isOnline, swStatus, or swError actually changes.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean\n swStatus: EidosStore['swStatus']\n swError: string | undefined\n}> = readable(\n (s) => ({ isOnline: s.isOnline, swStatus: s.swStatus, swError: s.swError }),\n shallowEqual as (a: { isOnline: boolean; swStatus: EidosStore['swStatus']; swError: string | undefined }, b: { isOnline: boolean; swStatus: EidosStore['swStatus']; swError: string | undefined }) => boolean,\n)\n\n/**\n * Queue counts. Re-emits only when a count actually changes, not on every\n * queue mutation (e.g. a status transition that doesn't change counts is skipped).\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number\n failed: number\n replaying: number\n total: number\n}> = readable(\n (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 shallowEqual as (a: { pending: number; failed: number; replaying: number; total: number }, b: { pending: number; failed: number; replaying: number; total: number }) => boolean,\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":["shallowEqual","a","b","keys","k","readable","selector","equal","run","last","useEidosStore","next","eidosStore","s","eidosQueue","eidosStatus","eidosQueueStats","pending","failed","replaying","q","eidosResource","url","eidosAction","id","item"],"mappings":";AA0BA,SAASA,EAAgDC,GAAMC,GAAe;AAC5E,QAAMC,IAAO,OAAO,KAAKF,CAAC;AAC1B,MAAIE,EAAK,WAAW,OAAO,KAAKD,CAAC,EAAE,OAAQ,QAAO;AAClD,aAAWE,KAAKD;AACd,QAAIF,EAAEG,CAAC,MAAMF,EAAEE,CAAC,EAAG,QAAO;AAE5B,SAAO;AACT;AAEA,SAASC,EACPC,GACAC,IAAiC,OAAO,IACtB;AAClB,SAAO;AAAA,IACL,UAAUC,GAAK;AAEb,UAAIC,IAAOH,EAASI,EAAc,SAAA,CAAU;AAC5C,aAAAF,EAAIC,CAAI,GACDC,EAAc,UAAU,MAAM;AACnC,cAAMC,IAAOL,EAASI,EAAc,SAAA,CAAU;AAC9C,QAAKH,EAAME,GAAME,CAAI,MACnBF,IAAOE,GACPH,EAAIG,CAAI;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,IACA,WAAW;AACT,aAAOL,EAASI,EAAc,UAAU;AAAA,IAC1C;AAAA,EAAA;AAEJ;AAKO,MAAME,IAAwCP,EAAS,CAACQ,MAAMA,CAAC,GAGzDC,IAA+CT,EAAS,CAACQ,MAAMA,EAAE,KAAK,GAMtEE,IAIRV;AAAA,EACH,CAACQ,OAAO,EAAE,UAAUA,EAAE,UAAU,UAAUA,EAAE,UAAU,SAASA,EAAE,QAAA;AAAA,EACjEb;AACF,GAMagB,IAKRX;AAAA,EACH,CAACQ,MAAM;AAEL,QAAII,IAAU,GAAGC,IAAS,GAAGC,IAAY;AACzC,eAAWC,KAAKP,EAAE;AAChB,MAAIO,EAAE,WAAW,YAAWH,MACnBG,EAAE,WAAW,WAAUF,MACvBE,EAAE,WAAW,eAAaD;AAErC,WAAO,EAAE,SAAAF,GAAS,QAAAC,GAAQ,WAAAC,GAAW,OAAON,EAAE,MAAM,OAAA;AAAA,EACtD;AAAA,EACAb;AACF;AAWO,SAASqB,EAAcC,GAAuD;AACnF,SAAOjB,EAAS,CAACQ,MAAMA,EAAE,UAAUS,CAAG,CAAC;AACzC;AAUO,SAASC,EAAYC,GAAwD;AAClF,SAAOnB,EAAS,CAACQ,MAAMA,EAAE,MAAM,KAAK,CAACY,MAASA,EAAK,OAAOD,CAAE,CAAC;AAC/D;"}
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 shallowEqual<T extends Record<string, unknown>>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[]\n if (keys.length !== Object.keys(b).length) return false\n for (const k of keys) if (a[k] !== b[k]) return false\n return true\n}\n\n// Typed comparator alias so call sites don't need inline casts.\nfunction shallowEq<T extends Record<string, unknown>>(a: T, b: T): boolean {\n return shallowEqual(a, b)\n}\n\nfunction readable<T>(\n selector: (s: EidosStore) => T,\n equal: (a: T, b: T) => boolean = Object.is,\n): EidosReadable<T> {\n return {\n subscribe(run) {\n // Emit current value immediately (Svelte store contract)\n let last = selector(useEidosStore.getState())\n run(last)\n return useEidosStore.subscribe(() => {\n const next = selector(useEidosStore.getState())\n if (!equal(last, next)) {\n last = next\n run(next)\n }\n })\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 * Only re-emits when isOnline, swStatus, or swError actually changes.\n */\nexport const eidosStatus: EidosReadable<{\n isOnline: boolean\n swStatus: EidosStore['swStatus']\n swError: string | undefined\n}> = readable(\n (s) => ({ isOnline: s.isOnline, swStatus: s.swStatus, swError: s.swError }),\n shallowEq,\n)\n\n/**\n * Queue counts. Re-emits only when a count actually changes, not on every\n * queue mutation (e.g. a status transition that doesn't change counts is skipped).\n */\nexport const eidosQueueStats: EidosReadable<{\n pending: number\n failed: number\n replaying: number\n total: number\n}> = readable(\n (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 shallowEq,\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":["shallowEqual","a","b","keys","k","shallowEq","readable","selector","equal","run","last","useEidosStore","next","eidosStore","s","eidosQueue","eidosStatus","eidosQueueStats","pending","failed","replaying","q","eidosResource","url","eidosAction","id","item"],"mappings":";AA0BA,SAASA,EAAgDC,GAAMC,GAAe;AAC5E,QAAMC,IAAO,OAAO,KAAKF,CAAC;AAC1B,MAAIE,EAAK,WAAW,OAAO,KAAKD,CAAC,EAAE,OAAQ,QAAO;AAClD,aAAWE,KAAKD,EAAM,KAAIF,EAAEG,CAAC,MAAMF,EAAEE,CAAC,EAAG,QAAO;AAChD,SAAO;AACT;AAGA,SAASC,EAA6CJ,GAAMC,GAAe;AACzE,SAAOF,EAAaC,GAAGC,CAAC;AAC1B;AAEA,SAASI,EACPC,GACAC,IAAiC,OAAO,IACtB;AAClB,SAAO;AAAA,IACL,UAAUC,GAAK;AAEb,UAAIC,IAAOH,EAASI,EAAc,SAAA,CAAU;AAC5C,aAAAF,EAAIC,CAAI,GACDC,EAAc,UAAU,MAAM;AACnC,cAAMC,IAAOL,EAASI,EAAc,SAAA,CAAU;AAC9C,QAAKH,EAAME,GAAME,CAAI,MACnBF,IAAOE,GACPH,EAAIG,CAAI;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,IACA,WAAW;AACT,aAAOL,EAASI,EAAc,UAAU;AAAA,IAC1C;AAAA,EAAA;AAEJ;AAKO,MAAME,IAAwCP,EAAS,CAACQ,MAAMA,CAAC,GAGzDC,IAA+CT,EAAS,CAACQ,MAAMA,EAAE,KAAK,GAMtEE,IAIRV;AAAA,EACH,CAACQ,OAAO,EAAE,UAAUA,EAAE,UAAU,UAAUA,EAAE,UAAU,SAASA,EAAE,QAAA;AAAA,EACjET;AACF,GAMaY,IAKRX;AAAA,EACH,CAACQ,MAAM;AAEL,QAAII,IAAU,GAAGC,IAAS,GAAGC,IAAY;AACzC,eAAWC,KAAKP,EAAE;AAChB,MAAIO,EAAE,WAAW,YAAWH,MACnBG,EAAE,WAAW,WAAUF,MACvBE,EAAE,WAAW,eAAaD;AAErC,WAAO,EAAE,SAAAF,GAAS,QAAAC,GAAQ,WAAAC,GAAW,OAAON,EAAE,MAAM,OAAA;AAAA,EACtD;AAAA,EACAT;AACF;AAWO,SAASiB,EAAcC,GAAuD;AACnF,SAAOjB,EAAS,CAACQ,MAAMA,EAAE,UAAUS,CAAG,CAAC;AACzC;AAUO,SAASC,EAAYC,GAAwD;AAClF,SAAOnB,EAAS,CAACQ,MAAMA,EAAE,MAAM,KAAK,CAACY,MAASA,EAAK,OAAOD,CAAE,CAAC;AAC/D;"}
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
- const o = "1.0.31";
1
+ const o = "1.0.33";
2
2
  export {
3
3
  o as VERSION
4
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '1.0.31'\n"],"names":["VERSION"],"mappings":"AAAO,MAAMA,IAAU;"}
1
+ {"version":3,"file":"version.js","sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '1.0.33'\n"],"names":["VERSION"],"mappings":"AAAO,MAAMA,IAAU;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sweidos/eidos",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
4
4
  "description": "Describe intent. The runtime figures out how. An abstraction layer for offline-first web apps.",
5
5
  "author": "Aditya Raj",
6
6
  "license": "MIT",
@@ -9,14 +9,31 @@
9
9
  "keywords": [
10
10
  "service-worker",
11
11
  "offline",
12
+ "offline-first",
12
13
  "pwa",
13
14
  "cache",
15
+ "cache-api",
14
16
  "indexeddb",
15
17
  "background-sync",
16
- "offline-first",
17
- "react"
18
+ "react",
19
+ "svelte",
20
+ "vue",
21
+ "react-native",
22
+ "queue",
23
+ "optimistic-ui",
24
+ "network-resilience"
18
25
  ],
19
- "homepage": "https://github.com/iamadi11/eidos",
26
+ "homepage": "https://sweidos.vercel.app/overview",
27
+ "bugs": {
28
+ "url": "https://github.com/iamadi11/eidos/issues"
29
+ },
30
+ "funding": {
31
+ "type": "github",
32
+ "url": "https://github.com/sponsors/iamadi11"
33
+ },
34
+ "engines": {
35
+ "node": ">=18.0.0"
36
+ },
20
37
  "repository": {
21
38
  "type": "git",
22
39
  "url": "https://github.com/iamadi11/eidos.git",