@sweidos/eidos 1.2.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -32
- package/dist/action.js +208 -152
- package/dist/action.js.map +1 -0
- package/dist/async-storage-adapter.js.map +1 -0
- package/dist/devtools.js +247 -86
- package/dist/eidos-sw.js +8 -5
- package/dist/eidos.cjs +2 -2
- package/dist/eidos.cjs.map +1 -0
- package/dist/idb.js.map +1 -0
- package/dist/index.d.ts +101 -35
- package/dist/index.js +44 -41
- package/dist/push.cjs +8 -5
- package/dist/push.js +8 -5
- package/dist/query.cjs +1 -1
- package/dist/query.d.ts +1 -2
- package/dist/query.js +1 -1
- package/dist/queue-storage.js.map +1 -0
- package/dist/queue-sync.js +34 -0
- package/dist/queue-sync.js.map +1 -0
- package/dist/react/Provider.js.map +1 -0
- package/dist/react/hooks.js +23 -23
- package/dist/react/hooks.js.map +1 -0
- package/dist/replay.js.map +1 -0
- package/dist/resource.js +121 -107
- package/dist/resource.js.map +1 -0
- package/dist/runtime.js +23 -22
- package/dist/runtime.js.map +1 -0
- package/dist/store-slices.js.map +1 -0
- package/dist/store.js.map +1 -0
- package/dist/stores.js +23 -31
- package/dist/stores.js.map +1 -0
- package/dist/sw-bridge.js.map +1 -0
- package/dist/types.js +15 -0
- package/dist/types.js.map +1 -0
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -0
- package/package.json +2 -3
package/dist/runtime.js
CHANGED
|
@@ -1,49 +1,50 @@
|
|
|
1
1
|
import { useEidosStore as a } from "./store.js";
|
|
2
|
-
import { registerBgSyncHandler as
|
|
3
|
-
import { idbGetQueue as
|
|
4
|
-
import { _getQueueStorage as
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
2
|
+
import { registerBgSyncHandler as c, registerServiceWorker as m } from "./sw-bridge.js";
|
|
3
|
+
import { idbGetQueue as y, idbQueueStorage as d } from "./idb.js";
|
|
4
|
+
import { _getQueueStorage as p } from "./queue-storage.js";
|
|
5
|
+
import { subscribeQueueSync as l } from "./queue-sync.js";
|
|
6
|
+
import { replayQueue as f } from "./action.js";
|
|
7
|
+
import { subscribeReplayOnReconnect as g } from "./replay.js";
|
|
8
|
+
async function h(e) {
|
|
8
9
|
if (e.schemaVersion === 2 && e.idempotencyKey) return e;
|
|
9
10
|
const t = {
|
|
10
11
|
...e,
|
|
11
12
|
schemaVersion: 2,
|
|
12
13
|
idempotencyKey: e.idempotencyKey ?? crypto.randomUUID()
|
|
13
14
|
};
|
|
14
|
-
return await (
|
|
15
|
+
return await (p() ?? d).update(t.id, {
|
|
15
16
|
schemaVersion: t.schemaVersion,
|
|
16
17
|
idempotencyKey: t.idempotencyKey
|
|
17
18
|
}).catch(() => {
|
|
18
19
|
}), t;
|
|
19
20
|
}
|
|
20
|
-
var r = !1, i = null;
|
|
21
|
-
async function
|
|
21
|
+
var r = !1, i = null, o = null;
|
|
22
|
+
async function R(e = {}) {
|
|
22
23
|
if (typeof window > "u" || r) return;
|
|
23
24
|
r = !0;
|
|
24
|
-
const t = e.swPath ?? "/eidos-sw.js",
|
|
25
|
+
const t = e.swPath ?? "/eidos-sw.js", s = e.autoReplay ?? !0;
|
|
25
26
|
try {
|
|
26
|
-
const
|
|
27
|
-
if (
|
|
28
|
-
const
|
|
29
|
-
a.getState().hydrateQueue(
|
|
27
|
+
const n = await y();
|
|
28
|
+
if (n.length > 0) {
|
|
29
|
+
const u = await Promise.all(n.map(h));
|
|
30
|
+
a.getState().hydrateQueue(u);
|
|
30
31
|
}
|
|
31
32
|
} catch {
|
|
32
33
|
}
|
|
33
34
|
try {
|
|
34
|
-
await
|
|
35
|
+
await m(t);
|
|
35
36
|
} catch {
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
-
a.getState().isOnline && setTimeout(
|
|
39
|
-
}),
|
|
38
|
+
c(() => {
|
|
39
|
+
a.getState().isOnline && setTimeout(f, 200);
|
|
40
|
+
}), s && (i = g()), o = l();
|
|
40
41
|
}
|
|
41
|
-
function
|
|
42
|
-
i?.(), i = null, r = !1;
|
|
42
|
+
function V() {
|
|
43
|
+
i?.(), i = null, o?.(), o = null, r = !1;
|
|
43
44
|
}
|
|
44
45
|
export {
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
V as _resetEidos,
|
|
47
|
+
R as initEidos
|
|
47
48
|
};
|
|
48
49
|
|
|
49
50
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import { registerServiceWorker, registerBgSyncHandler } from './sw-bridge';\nimport { replayQueue } from './action';\nimport { useEidosStore } from './store';\nimport { idbGetQueue, idbQueueStorage } from './idb';\nimport { _getQueueStorage } from './queue-storage';\nimport { subscribeReplayOnReconnect } from './replay';\nimport { subscribeQueueSync } from './queue-sync';\nimport { CURRENT_QUEUE_SCHEMA_VERSION } from './types';\nimport type { ActionQueueItem } from './types';\n\n// Items persisted before idempotencyKey/schemaVersion existed (v1) are migrated\n// in place: assign a fresh idempotencyKey and bump schemaVersion. A fresh key on\n// first replay after upgrade is correct — these items were never sent with one.\nasync function migrateQueueItem(item: ActionQueueItem): Promise<ActionQueueItem> {\n if (item.schemaVersion === CURRENT_QUEUE_SCHEMA_VERSION && item.idempotencyKey) {\n return item;\n }\n const migrated: ActionQueueItem = {\n ...item,\n schemaVersion: CURRENT_QUEUE_SCHEMA_VERSION,\n idempotencyKey: item.idempotencyKey ?? crypto.randomUUID(),\n };\n const storage = _getQueueStorage() ?? idbQueueStorage;\n await storage\n .update(migrated.id, {\n schemaVersion: migrated.schemaVersion,\n idempotencyKey: migrated.idempotencyKey,\n })\n .catch(() => {\n // Best-effort persist — item still gets the migrated shape in memory this session\n });\n return migrated;\n}\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;\nlet _unsubscribeQueueSync: (() => 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 const migrated = await Promise.all(persisted.map(migrateQueueItem));\n useEidosStore.getState().hydrateQueue(migrated);\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 _unsubscribe = subscribeReplayOnReconnect();\n }\n\n // Apply queue-item status changes broadcast by the replay-lock holder so\n // non-leader tabs reflect live status without waiting for re-hydration.\n _unsubscribeQueueSync = subscribeQueueSync();\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 _unsubscribeQueueSync?.();\n _unsubscribeQueueSync = null;\n _initialized = false;\n}\n"],"mappings":";;;;;;;AAaA,eAAe,EAAiB,GAAiD;AAC/E,MAAI,EAAK,kBAAA,KAAkD,EAAK,eAC9D,QAAO;AAET,QAAM,IAA4B;AAAA,IAChC,GAAG;AAAA,IACH,eAAA;AAAA,IACA,gBAAgB,EAAK,kBAAkB,OAAO,WAAW;AAAA,EAC3D;AAEA,gBADgB,EAAiB,KAAK,GAEnC,OAAO,EAAS,IAAI;AAAA,IACnB,eAAe,EAAS;AAAA,IACxB,gBAAgB,EAAS;AAAA,EAC3B,CAAC,EACA,MAAA,MAAY;AAAA,EAEb,CAAC,GACI;AACT;AASA,IAAI,IAAe,IACf,IAAoC,MACpC,IAA6C;AAEjD,eAAsB,EAAU,IAAsB,CAAC,GAAkB;AAGvE,MADI,OAAO,SAAW,OAClB,EAAc;AAClB,EAAA,IAAe;AAEf,QAAM,IAAS,EAAO,UAAU,gBAC1B,IAAa,EAAO,cAAc;AAGxC,MAAI;AACF,UAAM,IAAY,MAAM,EAAY;AACpC,QAAI,EAAU,SAAS,GAAG;AACxB,YAAM,IAAW,MAAM,QAAQ,IAAI,EAAU,IAAI,CAAgB,CAAC;AAClE,MAAA,EAAc,SAAS,EAAE,aAAa,CAAQ;AAAA,IAChD;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,MAAI;AACF,UAAM,EAAsB,CAAM;AAAA,EACpC,QAAQ;AAAA,EAER;AAKA,EAAA,EAAA,MAA4B;AAC1B,IAAI,EAAc,SAAS,EAAE,YAC3B,WAAW,GAAa,GAAG;AAAA,EAE/B,CAAC,GAEG,MACF,IAAe,EAA2B,IAK5C,IAAwB,EAAmB;AAU7C;AAEA,SAAgB,IAAc;AAC5B,EAAA,IAAe,GACf,IAAe,MACf,IAAwB,GACxB,IAAwB,MACxB,IAAe;AACjB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-slices.js","names":[],"sources":["../src/store-slices.ts"],"sourcesContent":["import type { ResourceEntry, ActionQueueItem } from './types';\nimport type { EidosStore } from './store';\n\ntype Setter = (updater: (prev: EidosStore) => Partial<EidosStore>) => void;\n\n// ── Resource slice ────────────────────────────────────────────────────────────\n\nexport interface ResourceActions {\n registerResource: (url: string, entry: ResourceEntry) => void;\n updateResource: (url: string, update: Partial<ResourceEntry>) => void;\n unregisterResource: (url: string) => void;\n}\n\nexport function createResourceActions(set: Setter): ResourceActions {\n return {\n registerResource: (url, entry) => 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(Object.entries(s.resources).filter(([k]) => k !== url)),\n })),\n };\n}\n\n// ── Queue slice ───────────────────────────────────────────────────────────────\n\nexport interface QueueActions {\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\nexport function createQueueActions(set: Setter): QueueActions {\n return {\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}\n"],"mappings":"AAaA,SAAgB,EAAsB,GAA8B;AAClE,SAAO;AAAA,IACL,kBAAA,CAAmB,GAAK,MAAU,EAAA,CAAK,OAAO,EAAE,WAAW;AAAA,MAAE,GAAG,EAAE;AAAA,OAAY,CAAA,GAAM;AAAA,IAAM,EAAE,EAAE;AAAA,IAE9F,gBAAA,CAAiB,GAAK,MACpB,EAAA,CAAK,OAAO,EACV,W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,OAAO,EAAM,EAAE;AAAA,EACvD;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../src/store.ts"],"sourcesContent":["import type { EidosState } from './types';\nimport { createResourceActions, createQueueActions } from './store-slices';\nimport type { ResourceActions, QueueActions } from './store-slices';\n\nexport interface EidosStore extends EidosState, ResourceActions, QueueActions {\n // Online\n setOnline: (online: boolean) => void;\n // SW\n setSwStatus: (status: EidosState['swStatus'], error?: string) => 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 ...createResourceActions(_set),\n ...createQueueActions(_set),\n};\n\nfunction _getState() {\n return _state;\n}\n\nfunction _subscribe(listener: Listener) {\n _listeners.add(listener);\n return () => {\n _listeners.delete(listener);\n };\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"],"mappings":";AAaA,IAAI,GACE,IAAa,oBAAI,IAAc;AAErC,SAAS,IAAU;AACjB,EAAA,EAAW,QAAA,CAAS,MAAO,EAAG,CAAC;AACjC;AAEA,SAAS,EAAK,GAAoD;AAChE,EAAA,IAAS;AAAA,IAAE,GAAG;AAAA,IAAQ,GAAG,EAAQ,CAAM;AAAA,EAAE,GACzC,EAAQ;AACV;AAEA,IAAS;AAAA,EAEP,UAAU,OAAO,YAAc,OAAe,UAAU,WAAW;AAAA,EACnE,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW,CAAC;AAAA,EACZ,OAAO,CAAC;AAAA,EAER,WAAA,CAAY,MAAa,EAAA,OAAY,EAAE,UAAA,EAAS,EAAE;AAAA,EAElD,aAAA,CAAc,GAAU,MAAY,EAAA,OAAY;AAAA,IAAE,UAAA;AAAA,IAAU,SAAA;AAAA,EAAQ,EAAE;AAAA,EAEtE,GAAG,EAAsB,CAAI;AAAA,EAC7B,GAAG,EAAmB,CAAI;AAC5B;AAEA,SAAS,IAAY;AACnB,SAAO;AACT;AAEA,SAAS,EAAW,GAAoB;AACtC,SAAA,EAAW,IAAI,CAAQ,GACvB,MAAa;AACX,IAAA,EAAW,OAAO,CAAQ;AAAA,EAC5B;AACF;AAEA,IAAa,IAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,WAAW;AAAA,EAEX,UAAA,CAAW,MAA4E;AACrF,UAAM,IAAS,OAAO,KAAY,aAAa,EAAQ,CAAM,IAAI;AACjE,IAAA,IAAS;AAAA,MAAE,GAAG;AAAA,MAAQ,GAAG;AAAA,IAAO,GAChC,EAAQ;AAAA,EACV;AACF"}
|
package/dist/stores.js
CHANGED
|
@@ -1,54 +1,46 @@
|
|
|
1
|
-
import { useEidosStore as
|
|
2
|
-
|
|
1
|
+
import { useEidosStore as n } from "./store.js";
|
|
2
|
+
import { countQueueByStatus as a } from "./types.js";
|
|
3
|
+
function c(e, t) {
|
|
3
4
|
const r = Object.keys(e);
|
|
4
5
|
if (r.length !== Object.keys(t).length) return !1;
|
|
5
|
-
for (const
|
|
6
|
+
for (const u of r) if (e[u] !== t[u]) return !1;
|
|
6
7
|
return !0;
|
|
7
8
|
}
|
|
8
|
-
function
|
|
9
|
-
return
|
|
9
|
+
function i(e, t) {
|
|
10
|
+
return c(e, t);
|
|
10
11
|
}
|
|
11
|
-
function
|
|
12
|
+
function s(e, t = Object.is) {
|
|
12
13
|
return {
|
|
13
14
|
subscribe(r) {
|
|
14
|
-
let
|
|
15
|
-
return r(
|
|
16
|
-
const
|
|
17
|
-
t(
|
|
15
|
+
let u = e(n.getState());
|
|
16
|
+
return r(u), n.subscribe(() => {
|
|
17
|
+
const o = e(n.getState());
|
|
18
|
+
t(u, o) || (u = o, r(o));
|
|
18
19
|
});
|
|
19
20
|
},
|
|
20
21
|
getState() {
|
|
21
|
-
return e(
|
|
22
|
+
return e(n.getState());
|
|
22
23
|
}
|
|
23
24
|
};
|
|
24
25
|
}
|
|
25
|
-
var
|
|
26
|
+
var S = s((e) => e), d = s((e) => e.queue), b = s((e) => ({
|
|
26
27
|
isOnline: e.isOnline,
|
|
27
28
|
swStatus: e.swStatus,
|
|
28
29
|
swError: e.swError
|
|
29
|
-
}),
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return {
|
|
33
|
-
pending: t,
|
|
34
|
-
failed: r,
|
|
35
|
-
replaying: s,
|
|
36
|
-
total: e.queue.length
|
|
37
|
-
};
|
|
38
|
-
}, o);
|
|
39
|
-
function S(e) {
|
|
40
|
-
return u((t) => t.resources[e]);
|
|
30
|
+
}), i), g = s((e) => a(e.queue), i);
|
|
31
|
+
function w(e) {
|
|
32
|
+
return s((t) => t.resources[e]);
|
|
41
33
|
}
|
|
42
|
-
function
|
|
43
|
-
return
|
|
34
|
+
function q(e) {
|
|
35
|
+
return s((t) => t.queue.find((r) => r.id === e));
|
|
44
36
|
}
|
|
45
37
|
export {
|
|
46
|
-
|
|
47
|
-
|
|
38
|
+
q as eidosAction,
|
|
39
|
+
d as eidosQueue,
|
|
48
40
|
g as eidosQueueStats,
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
41
|
+
w as eidosResource,
|
|
42
|
+
b as eidosStatus,
|
|
43
|
+
S as eidosStore
|
|
52
44
|
};
|
|
53
45
|
|
|
54
46
|
//# sourceMappingURL=stores.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stores.js","names":[],"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 { countQueueByStatus } from './types';\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((s) => countQueueByStatus(s.queue), shallowEq);\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"],"mappings":";;AA2BA,SAAS,EAAgD,GAAM,GAAe;AAC5E,QAAM,IAAO,OAAO,KAAK,CAAC;AAC1B,MAAI,EAAK,WAAW,OAAO,KAAK,CAAC,EAAE,OAAQ,QAAO;AAClD,aAAW,KAAK,EAAM,KAAI,EAAE,CAAA,MAAO,EAAE,CAAA,EAAI,QAAO;AAChD,SAAO;AACT;AAGA,SAAS,EAA6C,GAAM,GAAe;AACzE,SAAO,EAAa,GAAG,CAAC;AAC1B;AAEA,SAAS,EACP,GACA,IAAiC,OAAO,IACtB;AAClB,SAAO;AAAA,IACL,UAAU,GAAK;AAEb,UAAI,IAAO,EAAS,EAAc,SAAS,CAAC;AAC5C,aAAA,EAAI,CAAI,GACD,EAAc,UAAA,MAAgB;AACnC,cAAM,IAAO,EAAS,EAAc,SAAS,CAAC;AAC9C,QAAK,EAAM,GAAM,CAAI,MACnB,IAAO,GACP,EAAI,CAAI;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,IACA,WAAW;AACT,aAAO,EAAS,EAAc,SAAS,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;AAKA,IAAa,IAAwC,EAAA,CAAU,MAAM,CAAC,GAGzD,IAA+C,EAAA,CAAU,MAAM,EAAE,KAAK,GAMtE,IAIR,EAAA,CACF,OAAO;AAAA,EAAE,UAAU,EAAE;AAAA,EAAU,UAAU,EAAE;AAAA,EAAU,SAAS,EAAE;AAAQ,IACzE,CACF,GAMa,IAKR,EAAA,CAAU,MAAM,EAAmB,EAAE,KAAK,GAAG,CAAS;AAW3D,SAAgB,EAAc,GAAuD;AACnF,SAAO,EAAA,CAAU,MAAM,EAAE,UAAU,CAAA,CAAI;AACzC;AAUA,SAAgB,EAAY,GAAwD;AAClF,SAAO,EAAA,CAAU,MAAM,EAAE,MAAM,KAAA,CAAM,MAAS,EAAK,OAAO,CAAE,CAAC;AAC/D"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sw-bridge.js","names":[],"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) {\n resolve();\n return;\n }\n const sw = reg.installing ?? reg.waiting;\n if (!sw) {\n resolve();\n return;\n }\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\ninterface PushHandlers {\n onNotificationClick?: (data: unknown) => void;\n onSubscriptionExpired?: (sub: PushSubscriptionJSON) => void;\n}\n\nlet _pushHandlers: PushHandlers = {};\n\nexport function registerPushCallbacks(handlers: PushHandlers): void {\n _pushHandlers = handlers;\n}\n\nfunction onSwMessage(event: MessageEvent): void {\n const data = event.data as {\n type: string;\n url?: string;\n strategy?: string;\n data?: unknown;\n subscription?: unknown;\n };\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 (type === 'EIDOS_NOTIFICATION_CLICK') {\n _pushHandlers.onNotificationClick?.(data.data);\n return;\n }\n\n if (type === 'EIDOS_SUBSCRIPTION_EXPIRED') {\n _pushHandlers.onSubscriptionExpired?.(data.subscription as PushSubscriptionJSON);\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\n/** Test-only: resets module-level state between test cases. */\nexport function _resetSwBridgeForTests(): void {\n _registration = null;\n _pendingMessages = [];\n _bgSyncHandler = null;\n _pushHandlers = {};\n}\n"],"mappings":";AAEA,IAAI,IAAkD,MAIlD,IAA8C,CAAC;AAEnD,SAAgB,IAAoB;AAClC,SAAO;AACT;AAEA,eAAsB,EAAsB,GAA+B;AACzE,MAAI,OAAO,YAAc,OAAe,EAAE,mBAAmB,YAAY;AACvE,IAAA,EAAc,SAAS,EAAE,YAAY,aAAa;AAClD;AAAA,EACF;AAEA,QAAM,IAAQ,EAAc,SAAS;AACr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|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
function a(e) {
|
|
2
|
+
let n = 0, i = 0, s = 0;
|
|
3
|
+
for (const t of e) t.status === "pending" ? n++ : t.status === "failed" ? i++ : t.status === "replaying" && s++;
|
|
4
|
+
return {
|
|
5
|
+
pending: n,
|
|
6
|
+
failed: i,
|
|
7
|
+
replaying: s,
|
|
8
|
+
total: e.length
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export {
|
|
12
|
+
a as countQueueByStatus
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["// ─────────────────────────────────────────────────────────────────────────────\n// Eidos Core Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type CacheStrategy = 'cache-first' | 'stale-while-revalidate' | 'network-first';\n\n// ── Resource ─────────────────────────────────────────────────────────────────\n\nexport interface ResourceConfig {\n /** Make this resource available when the device is offline. */\n offline: boolean;\n /** Override the auto-selected caching strategy. */\n strategy?: CacheStrategy;\n /** Custom cache bucket name. Defaults to 'eidos-resources-v1'. */\n cacheName?: string;\n /**\n * Cache schema version. Bump when the response shape changes so old\n * cached entries (a different shape) aren't served from a stale bucket.\n * Appended to `cacheName` as a suffix (e.g. `eidos-resources-v1-v2`).\n * Old-versioned buckets are left in Cache Storage — clear them via\n * `caches.delete()` if needed.\n */\n version?: string | number;\n /** Max age of cached response in milliseconds. Expired entries trigger a network fetch. */\n maxAge?: number;\n}\n\nexport interface GeneratedStrategy {\n name: string;\n swStrategy: CacheStrategy;\n cacheName: string;\n /** One-line rationale for why this strategy was chosen. */\n reasoning: string;\n /** Human-readable description of each behavioral step. */\n behavior: string[];\n /** Pseudocode showing the equivalent Workbox config. */\n equivalentCode: string;\n}\n\nexport interface ResourceEntry {\n url: string;\n config: ResourceConfig;\n strategy: GeneratedStrategy;\n status: 'idle' | 'fetching' | 'fresh' | 'stale' | 'error' | 'offline';\n cachedAt?: number;\n fetchedAt?: number;\n cacheHits: number;\n cacheMisses: number;\n lastEvent?: 'cache-hit' | 'cache-updated' | 'network-error' | 'cache-cleared';\n}\n\nexport interface ResourceHandle<T = unknown> {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n fetch: () => Promise<Response>;\n json: () => Promise<T>;\n /** Returns a TanStack Query-compatible options object. */\n query: () => { queryKey: [string, string]; queryFn: () => Promise<T> };\n prefetch: () => Promise<void>;\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same URL with different config. */\n unregister: () => void;\n}\n\n/**\n * Handle for a URL pattern (`/api/products/*`, `/api/users/:id`, `**`).\n * The SW intercepts all matching requests automatically — there is no single\n * URL to fetch/cache directly, so only cache-management methods are exposed.\n * Returned by `resourcePattern()`.\n */\nexport interface PatternResourceHandle {\n readonly url: string;\n readonly config: ResourceConfig;\n readonly strategy: GeneratedStrategy;\n /** Clears all cache entries matching this pattern. */\n invalidate: () => Promise<void>;\n /** Remove from registry and SW. Required before re-registering the same pattern with different config. */\n unregister: () => void;\n}\n\n/** A handle returned by either `resource()` or `resourcePattern()`. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyResourceHandle = ResourceHandle<any> | PatternResourceHandle;\n\n/** Summary returned by warmCache(). */\nexport interface WarmCacheResult {\n /** Resources that were prefetched successfully. */\n warmed: number;\n /** Resources whose prefetch threw (network error, offline, etc.). */\n failed: number;\n /** The raw errors, in input order, for failed handles. */\n errors: unknown[];\n}\n\n// ── Action ───────────────────────────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ActionConfigBase<TArgs extends any[] = any[]> {\n /** Max retry attempts before marking as failed. Default: 3. */\n maxRetries?: number;\n /** Human-readable name for the action (used in devtools). */\n name?: string;\n /**\n * Prefixes the registered action id (`namespace::name`). Use to avoid\n * collisions when two actions share a name (e.g. across micro-frontends,\n * or two `createOrder` actions in different modules) — without a\n * namespace, the second registration silently overwrites the first.\n */\n namespace?: string;\n /**\n * Replay order when multiple queued actions are pending.\n * `'high'` items replay before `'normal'`, which replay before `'low'`.\n * Each tier completes fully before the next tier begins.\n * Default: `'normal'`.\n */\n priority?: 'high' | 'normal' | 'low';\n /**\n * Called immediately before the async function executes, with the same args\n * plus a trailing `ActionContext`. Use to apply an optimistic UI update (add\n * item, mark as pending, etc.) and to capture `idempotencyKey` for later\n * `handle.cancel(idempotencyKey)` calls. Called on every invocation —\n * online, offline, and during queue replay.\n */\n onOptimistic?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Called when the action permanently fails and will not be retried.\n * - `best-effort`: called on first throw.\n * - `neverLose`: called when `maxRetries` is exhausted (status → `'failed'`).\n * Use to revert the optimistic update.\n */\n onRollback?: (...args: [...TArgs, ActionContext]) => void;\n /**\n * Declarative conflict-resolution strategy used during queue replay when\n * the server responds with a 4xx status (conflict, gone, unprocessable,\n * etc.). If not provided, 4xx errors are treated identically to other\n * errors (retried until `maxRetries` is exhausted, then `onRollback` is\n * called). See `ConflictConfig`.\n */\n conflict?: ConflictConfig;\n /**\n * When `true`, each invocation gets an `AbortController` whose `signal` is\n * passed via `ActionContext.signal`. Forward it to `fetch`/etc. so\n * `handle.cancel(idempotencyKey)` can abort an in-flight call, or remove a\n * not-yet-replayed queued item.\n */\n cancellable?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ActionConfig<TArgs extends any[] = any[]> =\n | (ActionConfigBase<TArgs> & {\n /** Call directly, no persistence on failure. */\n reliability: 'best-effort';\n })\n | (ActionConfigBase<TArgs> & {\n /** Persist to IndexedDB before executing; replay on reconnect. */\n reliability: 'neverLose';\n /**\n * Required for `neverLose` — queued items must survive a page reload\n * and be matched back to this action on replay. `fn.name` is not\n * reliable (minifiers rename it, arrow functions may be anonymous).\n */\n name: string;\n });\n\n/**\n * Passed to `ConflictConfig.resolve` (for `'merge'`/`'custom'` strategies)\n * when a queued action's replay receives a 4xx response.\n */\nexport interface ConflictContext {\n /** Whatever `fn` threw — typically a `Response` or an error with `.status`. */\n error: unknown;\n /** The original arguments the action was queued with. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[];\n /** Number of replay attempts so far (0 on first replay). */\n attempt: number;\n idempotencyKey: string;\n}\n\n/**\n * Outcome of `ConflictConfig.resolve`:\n * - `'retry'`: keep the item queued, retry per normal backoff.\n * - `'skip'`: silently remove the item (no `onRollback`).\n * - `{ resolved: args }`: replace the queued args and retry immediately\n * on the next replay pass.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ConflictResolution = 'retry' | 'skip' | { resolved: any[] };\n\nexport interface ConflictConfig {\n /**\n * - `'serverWins'`: drop the queued item, keeping the server's state.\n * - `'clientWins'`: keep retrying — the client's write should eventually\n * be accepted (e.g. once the server-side conflict is cleared).\n * - `'merge'` / `'custom'`: call `resolve` to decide.\n */\n strategy: 'serverWins' | 'clientWins' | 'merge' | 'custom';\n /** Required for `'merge'` and `'custom'`. */\n resolve?: (ctx: ConflictContext) => ConflictResolution;\n}\n\n/** Bump when ActionQueueItem's shape changes. Used to migrate items persisted by older versions. */\nexport const CURRENT_QUEUE_SCHEMA_VERSION = 2;\n\nexport interface ActionQueueItem {\n /** Shape version this item was persisted with. Items from before v2 are migrated on load. */\n schemaVersion: number;\n id: string;\n /** ID of the registered action (maps to the function in the registry). */\n actionId: string;\n actionName: string;\n /**\n * Stable per-invocation key, generated once and reused across every retry/replay\n * of this item. Pass to your server as an idempotency key so retries that reach\n * the server after a dropped response don't double-execute.\n */\n idempotencyKey: string;\n args: unknown[];\n queuedAt: number;\n retryCount: number;\n maxRetries: number;\n status: 'pending' | 'replaying' | 'succeeded' | 'failed';\n /** Replay priority. High items replay before normal, normal before low. Default: 'normal'. */\n priority?: 'high' | 'normal' | 'low';\n error?: string;\n completedAt?: number;\n /** Earliest timestamp at which this item should be retried (exponential backoff). */\n nextRetryAt?: number;\n}\n\nexport interface QueuedResult {\n readonly queued: true;\n readonly id: string;\n readonly message: string;\n}\n\n/** Summary returned by replayQueue(). */\nexport interface ReplayResult {\n /** Items where the registered function was found and called. */\n attempted: number;\n /** Items that resolved successfully. */\n succeeded: number;\n /** Items that failed and have no retries remaining (status: 'failed'). */\n failed: number;\n /** Items that failed but will be retried later (nextRetryAt set). */\n retrying: number;\n /** Items whose actionId had no registered function — likely not yet imported. */\n skipped: number;\n /** Items that received a 4xx response and were dropped via `conflict: { strategy: 'serverWins' }` (or `resolve()` returning `'skip'`). */\n conflicted: number;\n /** Items removed via `handle.cancel(idempotencyKey)` before/during replay. */\n cancelled: number;\n}\n\n/**\n * Passed as an extra argument after the declared params to `neverLose` actions,\n * on every invocation (initial call, offline queue, and replay). The same\n * `idempotencyKey` is reused across all retries of one logical invocation —\n * forward it to your server (e.g. as an `Idempotency-Key` header) so a retry\n * that reaches the server after a dropped response doesn't double-execute.\n */\nexport interface ActionContext {\n idempotencyKey: string;\n /** 0 on the first attempt, incremented on each replay retry. */\n attempt: number;\n /** Set when `config.cancellable` is true. Forward to `fetch`/etc. for cancellation support. */\n signal?: AbortSignal;\n}\n\n/**\n * Every action function receives its declared args plus a trailing\n * `ActionContext` — on every invocation (online, offline, and replay).\n */\nexport type ActionFn<TArgs extends unknown[], TReturn> = (\n ...args: [...TArgs, ActionContext]\n) => Promise<TReturn>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface ActionHandle<TArgs extends any[], TReturn> {\n (...args: TArgs): Promise<TReturn | QueuedResult>;\n readonly id: string;\n readonly config: ActionConfig;\n /**\n * Cancel an invocation by its `idempotencyKey` (from `ActionContext` /\n * `onOptimistic`). Aborts the in-flight call if `cancellable: true` and\n * still running, otherwise removes a not-yet-replayed queued item.\n * Returns `true` if something was cancelled/removed.\n */\n cancel: (idempotencyKey: string) => Promise<boolean>;\n}\n\n// ── Global State ─────────────────────────────────────────────────────────────\n\nexport interface EidosState {\n isOnline: boolean;\n swStatus: 'idle' | 'registering' | 'active' | 'error' | 'unsupported';\n swError?: string;\n resources: Record<string, ResourceEntry>;\n queue: ActionQueueItem[];\n}\n\nexport interface QueueStatusCounts {\n [key: string]: number;\n pending: number;\n failed: number;\n replaying: number;\n total: number;\n}\n\n/** Single pass over the queue — avoids separate .filter() calls per status. */\nexport function countQueueByStatus(queue: ActionQueueItem[]): QueueStatusCounts {\n let pending = 0,\n failed = 0,\n replaying = 0;\n for (const q of 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: queue.length };\n}\n"],"mappings":"AAwTA,SAAgB,EAAmB,GAA6C;AAC9E,MAAI,IAAU,GACZ,IAAS,GACT,IAAY;AACd,aAAW,KAAK,EACd,CAAI,EAAE,WAAW,YAAW,MACnB,EAAE,WAAW,WAAU,MACvB,EAAE,WAAW,eAAa;AAErC,SAAO;AAAA,IAAE,SAAA;AAAA,IAAS,QAAA;AAAA,IAAQ,WAAA;AAAA,IAAW,OAAO,EAAM;AAAA,EAAO;AAC3D"}
|
package/dist/version.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const VERSION = '2.1.0';\n"],"mappings":"AAAA,IAAa,IAAU"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sweidos/eidos",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
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",
|
|
@@ -93,14 +93,13 @@
|
|
|
93
93
|
},
|
|
94
94
|
"files": [
|
|
95
95
|
"dist",
|
|
96
|
-
"!dist/**/*.map",
|
|
97
96
|
"README.md"
|
|
98
97
|
],
|
|
99
98
|
"size-limit": [
|
|
100
99
|
{
|
|
101
100
|
"name": "core (resource + action + store)",
|
|
102
101
|
"path": "dist/index.js",
|
|
103
|
-
"limit": "
|
|
102
|
+
"limit": "7 KB"
|
|
104
103
|
},
|
|
105
104
|
{
|
|
106
105
|
"name": "react hooks",
|