@vielzeug/tandem 26.10.0 → 26.10.3
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 +3 -3
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +2 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/tandem.cjs +1 -1
- package/dist/tandem.cjs.map +1 -1
- package/dist/tandem.d.ts +1 -1
- package/dist/tandem.d.ts.map +1 -1
- package/dist/tandem.iife.js +1 -1
- package/dist/tandem.iife.js.map +1 -1
- package/dist/tandem.js +1 -1
- package/dist/tandem.js.map +1 -1
- package/dist/types.d.ts +23 -14
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ yarn add @vielzeug/tandem
|
|
|
12
12
|
|
|
13
13
|
## Quick Start
|
|
14
14
|
|
|
15
|
-
Tandem drives sync between your storage and your server through two interfaces you implement: a `SyncPort` (the server) and a `SyncGateway` (the device). Records are opaque
|
|
15
|
+
Tandem drives sync between your storage and your server through two interfaces you implement: a `SyncPort` (the server) and a `SyncGateway` (the device). Records are opaque: the engine reads only `id` and a `rev` write counter.
|
|
16
16
|
|
|
17
17
|
```ts
|
|
18
18
|
import { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';
|
|
@@ -36,7 +36,7 @@ const gateway: SyncGateway = {
|
|
|
36
36
|
};
|
|
37
37
|
|
|
38
38
|
const sync = createSync({ gateway, port });
|
|
39
|
-
myStore.subscribe(() => sync.changed()); // a local write
|
|
39
|
+
myStore.subscribe(() => sync.changed()); // a local write: the engine batches and pushes
|
|
40
40
|
await sync.flush(); // pulls remote changes, then pushes dirty records; rejects on failure
|
|
41
41
|
sync.dispose(); // on account switch or teardown
|
|
42
42
|
```
|
|
@@ -50,4 +50,4 @@ sync.dispose(); // on account switch or teardown
|
|
|
50
50
|
|
|
51
51
|
## License
|
|
52
52
|
|
|
53
|
-
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu)
|
|
53
|
+
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu): part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{};exports.TandemDisposedError=TandemDisposedError,exports.TandemError=TandemError;
|
|
2
|
+
//# sourceMappingURL=errors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n"],"mappings":"AAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base class for all tandem errors.
|
|
3
|
+
* Use `instanceof TandemError` to catch any tandem-originated error in one branch.
|
|
4
|
+
*/
|
|
5
|
+
export declare class TandemError extends Error {
|
|
6
|
+
constructor(message: string, opts?: ErrorOptions);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Thrown when a disposed sync handle is used again. A scheduler that stops
|
|
10
|
+
* silently is a sync engine's worst failure: the device keeps editing while
|
|
11
|
+
* nothing uploads, and the divergence looks like working software.
|
|
12
|
+
*/
|
|
13
|
+
export declare class TandemDisposedError extends TandemError {
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,WAAY,SAAQ,KAAK;gBACxB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAKjD;AAED;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,WAAW;CAAG"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n"],"mappings":"AAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./tandem.cjs");exports.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./tandem.cjs");exports.TandemDisposedError=e.TandemDisposedError,exports.TandemError=e.TandemError,exports.createSync=t.createSync;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { TandemDisposedError, TandemError } from './errors';
|
|
1
2
|
export { createSync } from './tandem';
|
|
2
3
|
export type { SyncDeletion, SyncEnvelope, SyncGateway, SyncHandle, SyncOptions, SyncPort, SyncPullResult, SyncRecordBase, SyncState, TandemEvent, } from './types';
|
|
3
4
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,cAAc,EACd,cAAc,EACd,SAAS,EACT,WAAW,GACZ,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{TandemDisposedError as e,TandemError as t}from"./errors.js";import{createSync as n}from"./tandem.js";export{e as TandemDisposedError,t as TandemError,n as createSync};
|
package/dist/tandem.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=3e3,baseline=(e=null)=>({cursor:e,revs:{}});function createSync(t){let{gateway:n,port:r}=t,i=t.idleDelayMs??e,a=new AbortController,o=new Set,emit=e=>{for(let t of o)try{t(e)}catch{}},warn=e=>{emit({message:e instanceof Error?e.message:String(e),type:`warning`})},s=baseline(),c=null,l=Promise.resolve(),key=e=>`${e
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},e=3e3,baseline=(e=null)=>({cursor:e,revs:{}}),cloneState=e=>({cursor:e.cursor,revs:{...e.revs}});function createSync(t){let{gateway:n,port:r}=t,i=t.idleDelayMs??e,a=new AbortController,o=new Set,emit=e=>{if(o.size!==0)for(let t of o)try{t(e)}catch{}},warn=e=>{o.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},s=baseline(),c=null,l=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(s.revs[envelopeKey(e)]??-1),save=()=>n.saveState(cloneState(s)),pull=async()=>{if(a.signal.aborted)return;let{cursor:e,deletions:t,records:i}=await r.pull(s.cursor),o=new Map((await n.records()).map(e=>[envelopeKey(e),e.record.rev])),c=new Set((await n.pendingDeletions()).map(e=>key(e.entity,e.id))),l=new Set(t.map(e=>key(e.entity,e.id))),u=i.filter(e=>!c.has(envelopeKey(e))&&!l.has(envelopeKey(e))&&(o.get(envelopeKey(e))??-1)<e.record.rev),d=await n.applyRecords(u);d.length&&emit({message:`Skipped invalid remote records: ${d.join(`, `)}.`,skipped:d,type:`invalid`});let f=t.filter(e=>{let t=key(e.entity,e.id);return(o.get(t)??-1)<=(s.revs[t]??-1)});await n.applyDeletions(f);for(let e of i)s.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete s.revs[key(e.entity,e.id)];s.cursor=e,await save(),emit({records:u.length,type:`pull`})},push=async e=>{if(a.signal.aborted)return;let t=(await n.records()).filter(isDirty),i=await n.pendingDeletions();if(t.length||i.length){await r.push(t,i,e?{keepalive:!0}:void 0);for(let e of t)s.revs[envelopeKey(e)]=e.record.rev;await n.clearDeletions(i);for(let e of i)delete s.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=l.then(e);return l=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{c&&clearTimeout(c),c=setTimeout(()=>void enqueue(pushJob(!1)),i)},u=globalThis.document,onVisibility=()=>{u.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));u?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide),enqueue(async()=>{a.signal.aborted||(s=cloneState(await n.loadState()??baseline()),await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(a.signal.aborted)throw disposedError();flushSoon()},disposalSignal:a.signal,dispose(){a.signal.aborted||(emit({type:`dispose`}),a.abort(),c&&clearTimeout(c),u?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),o.clear())},get disposed(){return a.signal.aborted},flush:()=>a.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(a.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{o.delete(e)};return o.add(e),a.signal.addEventListener(`abort`,detach,{once:!0}),t?.signal?.addEventListener(`abort`,detach,{once:!0}),detach},[Symbol.dispose](){this.dispose()}}}exports.TandemDisposedError=TandemDisposedError,exports.TandemError=TandemError,exports.createSync=createSync;
|
|
2
2
|
//# sourceMappingURL=tandem.cjs.map
|
package/dist/tandem.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.cjs","names":[],"sources":["../src/tandem.ts"],"sourcesContent":["import type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline — a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n emit({ message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (envelope: SyncEnvelope<TRecord>): string => `${envelope.entity}:${envelope.record.id}`;\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean => envelope.record.rev > (state.revs[key(envelope)] ?? -1);\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(gateway.records().map((envelope) => [key(envelope), envelope.record.rev] as const));\n const entombed = new Set((await gateway.pendingDeletions()).map((d) => `${d.entity}:${d.id}`));\n const deleted = new Set(deletions.map((d) => `${d.entity}:${d.id}`));\n // Apply only records the server is ahead on — a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(key(envelope)) &&\n !deleted.has(key(envelope)) &&\n (localRevs.get(key(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = `${deletion.entity}:${deletion.id}`;\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n state.cursor = cursor;\n await gateway.saveState(state);\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = gateway.records().filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried — new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n await gateway.saveState(state);\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on — pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (controller.signal.aborted) return;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle — pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = (await gateway.loadState()) ?? baseline();\n await cycle();\n });\n\n return {\n changed: flushSoon,\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => enqueue(cycle),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"mEAEA,IAAM,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAelF,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAAS,EACpB,EAAY,EAAQ,aAAe,EAEnC,EAAa,IAAI,gBACjB,EAAU,IAAI,IACd,KAAQ,GAA6B,CACzC,IAAK,IAAM,KAAU,EACnB,GAAI,CACF,EAAO,CAAK,CACd,MAAQ,CAER,CAEJ,EACM,KAAQ,GAAyB,CACrC,KAAK,CAAE,QAAS,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D,OAXA,GAAK,iBAAiB,mBAAoB,YAAY,EACtD,WAAW,mBAAmB,WAAY,UAAU,EAIpD,QAAa,SAAY,CACnB,EAAW,OAAO,UACtB,EAAS,MAAM,EAAQ,UAAU,GAAM,SAAS,EAChD,MAAM,MAAM,EACd,CAAC,EAEM,CACL,QAAS,UACT,eAAgB,EAAW,OAC3B,SAAgB,CACV,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxB,EAAW,MAAM,EACb,GAAO,aAAa,CAAK,EAC7B,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvD,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAO,EAAW,OAAO,OAC3B,EACA,UAAa,QAAQ,KAAK,EAC1B,IAAI,EAAS,EAAwB,CACnC,GAAI,EAAW,OAAO,SAAW,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"tandem.cjs","names":[],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"mEAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECdhD,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAG5E,WAAc,IAAiC,CAAE,OAAQ,EAAM,OAAQ,KAAM,CAAE,GAAG,EAAM,IAAK,CAAE,GAerG,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAAS,EACpB,EAAY,EAAQ,aAAe,EAEnC,EAAa,IAAI,gBACjB,EAAU,IAAI,IACd,KAAQ,GAA6B,CACrC,KAAQ,OAAS,EACrB,IAAK,IAAM,KAAU,EACnB,GAAI,CACF,EAAO,CAAK,CACd,MAAQ,CAER,CAEJ,EACM,KAAQ,GAAyB,CACjC,EAAQ,OAAS,GACrB,KAAK,CAAE,QAAO,QAAS,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAAG,KAAM,SAAU,CAAC,CAClG,EAEI,EAAmB,SAAS,EAC5B,EAA8C,KAC9C,EAAuB,QAAQ,QAAQ,EAErC,KAAO,EAAgB,IAAuB,GAAG,EAAO,GAAG,IAC3D,YAAe,GAA4C,IAAI,EAAS,OAAQ,EAAS,OAAO,EAAE,EAClG,QAAW,GACf,EAAS,OAAO,KAAO,EAAM,KAAK,YAAY,CAAQ,IAAM,IACxD,SAA4B,EAAQ,UAAU,WAAW,CAAK,CAAC,EAE/D,KAAO,SAA2B,CACt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EAC5D,MAAM,MAAM,EACd,CAAC,EAED,IAAM,kBAA2C,IAAI,oBAAoB,qCAAqC,EAE9G,MAAO,CACL,SAAgB,CACd,GAAI,EAAW,OAAO,QAAS,MAAM,cAAc,EAEnD,UAAU,CACZ,EACA,eAAgB,EAAW,OAC3B,SAAgB,CACV,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxB,EAAW,MAAM,EACb,GAAO,aAAa,CAAK,EAC7B,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvD,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAO,EAAW,OAAO,OAC3B,EACA,UAAc,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAI,EAAW,OAAO,SAAW,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
package/dist/tandem.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { SyncHandle, SyncOptions, SyncRecordBase } from './types';
|
|
|
2
2
|
/**
|
|
3
3
|
* Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees
|
|
4
4
|
* individual commands or record shapes: it reads the device's records, and after a
|
|
5
|
-
* quiet period pushes every record whose `rev` is above the last-synced baseline
|
|
5
|
+
* quiet period pushes every record whose `rev` is above the last-synced baseline: a
|
|
6
6
|
* burst of edits becomes one batched upload instead of one per edit. Every rev
|
|
7
7
|
* comparison is the engine's: the gateway upserts what it is given and tombstones
|
|
8
8
|
* what it deletes. Flushes serialize (one push in flight), fire immediately when
|
package/dist/tandem.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.d.ts","sourceRoot":"","sources":["../src/tandem.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tandem.d.ts","sourceRoot":"","sources":["../src/tandem.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAgB,UAAU,EAAE,WAAW,EAAE,cAAc,EAA0B,MAAM,SAAS,CAAC;AAS7G;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,UAAU,CAgKrH"}
|
package/dist/tandem.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Tandem=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=3e3,baseline=(e=null)=>({cursor:e,revs:{}});function createSync(e){let{gateway:n,port:r}=e,i=e.idleDelayMs??t,a=new AbortController,o=new Set,emit=e=>{for(let t of o)try{t(e)}catch{}},warn=e=>{emit({message:e instanceof Error?e.message:String(e),type:`warning`})},s=baseline(),c=null,l=Promise.resolve(),key=e=>`${e
|
|
1
|
+
var Tandem=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},t=3e3,baseline=(e=null)=>({cursor:e,revs:{}}),cloneState=e=>({cursor:e.cursor,revs:{...e.revs}});function createSync(e){let{gateway:n,port:r}=e,i=e.idleDelayMs??t,a=new AbortController,o=new Set,emit=e=>{if(o.size!==0)for(let t of o)try{t(e)}catch{}},warn=e=>{o.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},s=baseline(),c=null,l=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(s.revs[envelopeKey(e)]??-1),save=()=>n.saveState(cloneState(s)),pull=async()=>{if(a.signal.aborted)return;let{cursor:e,deletions:t,records:i}=await r.pull(s.cursor),o=new Map((await n.records()).map(e=>[envelopeKey(e),e.record.rev])),c=new Set((await n.pendingDeletions()).map(e=>key(e.entity,e.id))),l=new Set(t.map(e=>key(e.entity,e.id))),u=i.filter(e=>!c.has(envelopeKey(e))&&!l.has(envelopeKey(e))&&(o.get(envelopeKey(e))??-1)<e.record.rev),d=await n.applyRecords(u);d.length&&emit({message:`Skipped invalid remote records: ${d.join(`, `)}.`,skipped:d,type:`invalid`});let f=t.filter(e=>{let t=key(e.entity,e.id);return(o.get(t)??-1)<=(s.revs[t]??-1)});await n.applyDeletions(f);for(let e of i)s.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete s.revs[key(e.entity,e.id)];s.cursor=e,await save(),emit({records:u.length,type:`pull`})},push=async e=>{if(a.signal.aborted)return;let t=(await n.records()).filter(isDirty),i=await n.pendingDeletions();if(t.length||i.length){await r.push(t,i,e?{keepalive:!0}:void 0);for(let e of t)s.revs[envelopeKey(e)]=e.record.rev;await n.clearDeletions(i);for(let e of i)delete s.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=l.then(e);return l=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{c&&clearTimeout(c),c=setTimeout(()=>void enqueue(pushJob(!1)),i)},u=globalThis.document,onVisibility=()=>{u.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));u?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide),enqueue(async()=>{a.signal.aborted||(s=cloneState(await n.loadState()??baseline()),await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(a.signal.aborted)throw disposedError();flushSoon()},disposalSignal:a.signal,dispose(){a.signal.aborted||(emit({type:`dispose`}),a.abort(),c&&clearTimeout(c),u?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),o.clear())},get disposed(){return a.signal.aborted},flush:()=>a.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(a.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{o.delete(e)};return o.add(e),a.signal.addEventListener(`abort`,detach,{once:!0}),t?.signal?.addEventListener(`abort`,detach,{once:!0}),detach},[Symbol.dispose](){this.dispose()}}}return e.TandemDisposedError=TandemDisposedError,e.TandemError=TandemError,e.createSync=createSync,e})({});
|
|
2
2
|
//# sourceMappingURL=tandem.iife.js.map
|
package/dist/tandem.iife.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.iife.js","names":[],"sources":["../src/tandem.ts"],"sourcesContent":["import type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline — a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n emit({ message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (envelope: SyncEnvelope<TRecord>): string => `${envelope.entity}:${envelope.record.id}`;\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean => envelope.record.rev > (state.revs[key(envelope)] ?? -1);\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(gateway.records().map((envelope) => [key(envelope), envelope.record.rev] as const));\n const entombed = new Set((await gateway.pendingDeletions()).map((d) => `${d.entity}:${d.id}`));\n const deleted = new Set(deletions.map((d) => `${d.entity}:${d.id}`));\n // Apply only records the server is ahead on — a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(key(envelope)) &&\n !deleted.has(key(envelope)) &&\n (localRevs.get(key(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = `${deletion.entity}:${deletion.id}`;\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n state.cursor = cursor;\n await gateway.saveState(state);\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = gateway.records().filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried — new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n await gateway.saveState(state);\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on — pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (controller.signal.aborted) return;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle — pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = (await gateway.loadState()) ?? baseline();\n await cycle();\n });\n\n return {\n changed: flushSoon,\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => enqueue(cycle),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"qFAEA,IAAM,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAelF,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAAS,EACpB,EAAY,EAAQ,aAAe,EAEnC,EAAa,IAAI,gBACjB,EAAU,IAAI,IACd,KAAQ,GAA6B,CACzC,IAAK,IAAM,KAAU,EACnB,GAAI,CACF,EAAO,CAAK,CACd,MAAQ,CAER,CAEJ,EACM,KAAQ,GAAyB,CACrC,KAAK,CAAE,QAAS,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAAG,KAAM,SAAU,CAAC,CAC3F,EAEI,EAAmB,SAAS,EAC5B,EAA8C,KAC9C,EAAuB,QAAQ,QAAQ,EAErC,IAAO,GAA4C,GAAG,EAAS,OAAO,GAAG,EAAS,OAAO,KACzF,QAAW,GAA6C,EAAS,OAAO,KAAO,EAAM,KAAK,IAAI,CAAQ,IAAM,IAE5G,KAAO,SAA2B,CACtC,GAAI,EAAW,OAAO,QAAS,OAC/B,GAAM,CAAE,SAAQ,YAAW,WAAY,MAAM,EAAK,KAAK,EAAM,MAAM,EAE7D,EAAY,IAAI,IAAI,EAAQ,QAAQ,CAAC,CAAC,IAAK,GAAa,CAAC,IAAI,CAAQ,EAAG,EAAS,OAAO,GAAG,CAAU,CAAC,EACtG,EAAW,IAAI,KAAK,MAAM,EAAQ,iBAAiB,EAAA,CA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AY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"tandem.iife.js","names":[],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"qFAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECdhD,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAG5E,WAAc,IAAiC,CAAE,OAAQ,EAAM,OAAQ,KAAM,CAAE,GAAG,EAAM,I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O,SAAW,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
package/dist/tandem.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var baseline=(e=null)=>({cursor:e,revs:{}});function createSync(
|
|
1
|
+
var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},e=3e3,baseline=(e=null)=>({cursor:e,revs:{}}),cloneState=e=>({cursor:e.cursor,revs:{...e.revs}});function createSync(t){let{gateway:n,port:r}=t,i=t.idleDelayMs??e,a=new AbortController,o=new Set,emit=e=>{if(o.size!==0)for(let t of o)try{t(e)}catch{}},warn=e=>{o.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},s=baseline(),c=null,l=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(s.revs[envelopeKey(e)]??-1),save=()=>n.saveState(cloneState(s)),pull=async()=>{if(a.signal.aborted)return;let{cursor:e,deletions:t,records:i}=await r.pull(s.cursor),o=new Map((await n.records()).map(e=>[envelopeKey(e),e.record.rev])),c=new Set((await n.pendingDeletions()).map(e=>key(e.entity,e.id))),l=new Set(t.map(e=>key(e.entity,e.id))),u=i.filter(e=>!c.has(envelopeKey(e))&&!l.has(envelopeKey(e))&&(o.get(envelopeKey(e))??-1)<e.record.rev),d=await n.applyRecords(u);d.length&&emit({message:`Skipped invalid remote records: ${d.join(`, `)}.`,skipped:d,type:`invalid`});let f=t.filter(e=>{let t=key(e.entity,e.id);return(o.get(t)??-1)<=(s.revs[t]??-1)});await n.applyDeletions(f);for(let e of i)s.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete s.revs[key(e.entity,e.id)];s.cursor=e,await save(),emit({records:u.length,type:`pull`})},push=async e=>{if(a.signal.aborted)return;let t=(await n.records()).filter(isDirty),i=await n.pendingDeletions();if(t.length||i.length){await r.push(t,i,e?{keepalive:!0}:void 0);for(let e of t)s.revs[envelopeKey(e)]=e.record.rev;await n.clearDeletions(i);for(let e of i)delete s.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=l.then(e);return l=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{c&&clearTimeout(c),c=setTimeout(()=>void enqueue(pushJob(!1)),i)},u=globalThis.document,onVisibility=()=>{u.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));u?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide),enqueue(async()=>{a.signal.aborted||(s=cloneState(await n.loadState()??baseline()),await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(a.signal.aborted)throw disposedError();flushSoon()},disposalSignal:a.signal,dispose(){a.signal.aborted||(emit({type:`dispose`}),a.abort(),c&&clearTimeout(c),u?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),o.clear())},get disposed(){return a.signal.aborted},flush:()=>a.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(a.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{o.delete(e)};return o.add(e),a.signal.addEventListener(`abort`,detach,{once:!0}),t?.signal?.addEventListener(`abort`,detach,{once:!0}),detach},[Symbol.dispose](){this.dispose()}}}export{TandemDisposedError,TandemError,createSync};
|
|
2
2
|
//# sourceMappingURL=tandem.js.map
|
package/dist/tandem.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.js","names":[],"sources":["../src/tandem.ts"],"sourcesContent":["import type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline — a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n emit({ message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (envelope: SyncEnvelope<TRecord>): string => `${envelope.entity}:${envelope.record.id}`;\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean => envelope.record.rev > (state.revs[key(envelope)] ?? -1);\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(gateway.records().map((envelope) => [key(envelope), envelope.record.rev] as const));\n const entombed = new Set((await gateway.pendingDeletions()).map((d) => `${d.entity}:${d.id}`));\n const deleted = new Set(deletions.map((d) => `${d.entity}:${d.id}`));\n // Apply only records the server is ahead on — a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(key(envelope)) &&\n !deleted.has(key(envelope)) &&\n (localRevs.get(key(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = `${deletion.entity}:${deletion.id}`;\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n state.cursor = cursor;\n await gateway.saveState(state);\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = gateway.records().filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[key(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried — new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n await gateway.saveState(state);\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on — pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (controller.signal.aborted) return;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle — pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = (await gateway.loadState()) ?? baseline();\n await cycle();\n });\n\n return {\n changed: flushSoon,\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => enqueue(cycle),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"AAEA,IAEM,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAelF,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAAS,EACpB,EAAY,EAAQ,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CAAC,EAAG,CAAS,EAClE,EAEM,EAAM,WAAW,SACjB,iBAA2B,CAC3B,EAAI,kBAAoB,SAAU,QAAa,QAAQ,EAAI,CAAC,EAC3D,QAAa,KAAK,CACzB,EACM,eAAyB,KAAK,QAAQ,QAAQ,EAAI,CAAC,EAYzD,OAXA,GAAK,iBAAiB,mBAAoB,YAAY,EACtD,WAAW,mBAAmB,WAAY,UAAU,EAIpD,QAAa,SAAY,CACnB,EAAW,OAAO,UACtB,EAAS,MAAM,EAAQ,UAAU,GAAM,SAAS,EAChD,MAAM,MAAM,EACd,CAAC,EAEM,CACL,QAAS,UACT,eAAgB,EAAW,OAC3B,SAAgB,CACV,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxB,EAAW,MAAM,EACb,GAAO,aAAa,CAAK,EAC7B,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvD,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAO,EAAW,OAAO,OAC3B,EACA,UAAa,QAAQ,KAAK,EAC1B,IAAI,EAAS,EAAwB,CACnC,GAAI,EAAW,OAAO,SAAW,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"tandem.js","names":[],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"AAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECdhD,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAG5E,WAAc,IAAiC,CAAE,OAAQ,EAAM,OAAQ,KAAM,CAAE,GAAG,EAAM,IAAK,CAAE,GAerG,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAAS,EACpB,EAAY,EAAQ,aAAe,EAEnC,EAAa,IAAI,gBACjB,EAAU,IAAI,IACd,KAAQ,GAA6B,CACrC,KAAQ,OAAS,EACrB,IAAK,IAAM,KAAU,EACnB,GAAI,CACF,EAAO,CAAK,CACd,MAAQ,CAER,CAEJ,EACM,KAAQ,GAAyB,CACjC,EAAQ,OAAS,GACrB,KAAK,CAAE,QAAO,QAAS,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAAG,KAAM,SAAU,CAAC,CAClG,EAEI,EAAmB,SAAS,EAC5B,EAA8C,KAC9C,EAAuB,QAAQ,QAAQ,EAErC,KAAO,EAAgB,IAAuB,GAAG,EAAO,GAAG,IAC3D,YAAe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QAAQ,EAAI,CAAC,EACzD,GAAK,iBAAiB,mBAAoB,YAAY,EACtD,WAAW,mBAAmB,WAAY,UAAU,EAIpD,QAAa,SAAY,CACnB,EAAW,OAAO,UACtB,EAAQ,WAAY,MAAM,EAAQ,UAAU,GAAM,SAAS,CAAC,EAC5D,MAAM,MAAM,EACd,CAAC,EAED,IAAM,kBAA2C,IAAI,oBAAoB,qCAAqC,EAE9G,MAAO,CACL,SAAgB,CACd,GAAI,EAAW,OAAO,QAAS,MAAM,cAAc,EAEnD,UAAU,CACZ,EACA,eAAgB,EAAW,OAC3B,SAAgB,CACV,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxB,EAAW,MAAM,EACb,GAAO,aAAa,CAAK,EAC7B,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvD,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAO,EAAW,OAAO,OAC3B,EACA,UAAc,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAI,EAAW,OAAO,SAAW,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB,EAAQ,OAAO,CAAO,CACxB,EAIA,OAHA,EAAQ,IAAI,CAAO,EACnB,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The two seams Tandem drives: a {@link SyncPort} that reaches the server, and a
|
|
3
3
|
* {@link SyncGateway} that reaches the device's own storage. The engine never
|
|
4
|
-
* sees a database, a transport, or a record shape
|
|
4
|
+
* sees a database, a transport, or a record shape: records travel as opaque
|
|
5
5
|
* envelopes carrying only an `id` and a write-counter `rev`. Every rev
|
|
6
6
|
* comparison is the engine's: the gateway upserts, validates, and tombstones
|
|
7
7
|
* without re-deriving the sync policy.
|
|
@@ -20,13 +20,16 @@ export interface SyncEnvelope<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
|
20
20
|
}
|
|
21
21
|
/** A deletion that travels: stored locally as a tombstone, propagated on the next push. */
|
|
22
22
|
export interface SyncDeletion {
|
|
23
|
-
|
|
23
|
+
/** When the deletion happened, set by whoever recorded it. The engine never reads
|
|
24
|
+
* it: a device may stamp its own tombstones, a server that needs the timestamp
|
|
25
|
+
* for conflict policy may send one, and either may omit it. */
|
|
26
|
+
readonly deletedAt?: string;
|
|
24
27
|
readonly entity: string;
|
|
25
28
|
readonly id: string;
|
|
26
29
|
}
|
|
27
30
|
/** Per-account sync bookkeeping the gateway persists: the pull cursor and the newest
|
|
28
31
|
* rev the server has seen per record (`"${entity}:${id}"` → rev). A record is dirty
|
|
29
|
-
* exactly when its current rev is above that baseline
|
|
32
|
+
* exactly when its current rev is above that baseline: across reloads, not just
|
|
30
33
|
* this session. */
|
|
31
34
|
export interface SyncState {
|
|
32
35
|
cursor: string | null;
|
|
@@ -46,7 +49,7 @@ export interface SyncPort<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
|
46
49
|
/**
|
|
47
50
|
* Push local records and deletions. Reject when the server diverged (it is ahead
|
|
48
51
|
* of the pushed lineage) so the engine can pull and reconcile. `keepalive` marks
|
|
49
|
-
* a flush that must survive the tab closing
|
|
52
|
+
* a flush that must survive the tab closing: serve it with `navigator.sendBeacon`
|
|
50
53
|
* or a `keepalive` fetch.
|
|
51
54
|
*/
|
|
52
55
|
push(records: readonly SyncEnvelope<TRecord>[], deletions: readonly SyncDeletion[], options?: {
|
|
@@ -55,26 +58,28 @@ export interface SyncPort<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
|
55
58
|
}
|
|
56
59
|
/**
|
|
57
60
|
* The device side of sync: the app's storage, expressed as the handful of reads
|
|
58
|
-
* and writes the engine needs. The engine does the rev math
|
|
61
|
+
* and writes the engine needs. The engine does the rev math: `applyRecords`
|
|
59
62
|
* receives only records the server is ahead on, already filtered against
|
|
60
63
|
* same-or-ahead locals and locally tombstoned ids, so the gateway upserts and
|
|
61
|
-
* validates without comparing revs itself. Remote records are untrusted
|
|
64
|
+
* validates without comparing revs itself. Remote records are untrusted :
|
|
62
65
|
* `applyRecords` is the app's validation boundary and reports the ids it refused.
|
|
63
66
|
*/
|
|
64
67
|
export interface SyncGateway<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
65
|
-
/** Applies pulled deletions
|
|
68
|
+
/** Applies pulled deletions: no tombstone: the deletion came from the server. */
|
|
66
69
|
applyDeletions(deletions: readonly SyncDeletion[]): Promise<void>;
|
|
67
70
|
/** Upserts the given pulled records; returns the ids of records that failed validation. */
|
|
68
71
|
applyRecords(records: readonly SyncEnvelope<TRecord>[]): Promise<string[]>;
|
|
69
|
-
/** Removes the tombstones a successful push carried
|
|
72
|
+
/** Removes the tombstones a successful push carried: only those, since new
|
|
70
73
|
* deletions may have been recorded while the push was in flight. */
|
|
71
74
|
clearDeletions(deletions: readonly SyncDeletion[]): Promise<void>;
|
|
72
75
|
/** The persisted baseline, or `null` on a fresh device. */
|
|
73
76
|
loadState(): Promise<SyncState | null>;
|
|
74
77
|
/** Tombstones not yet acknowledged by the server. */
|
|
75
78
|
pendingDeletions(): Promise<SyncDeletion[]>;
|
|
76
|
-
/** The device's own records
|
|
77
|
-
|
|
79
|
+
/** The device's own records: no remote mirrors. Sync or async, so an in-memory
|
|
80
|
+
* gateway can return them directly while a disk-backed one reads them from
|
|
81
|
+
* storage instead of holding a mirror of every synced record in memory. */
|
|
82
|
+
records(): Promise<SyncEnvelope<TRecord>[]> | SyncEnvelope<TRecord>[];
|
|
78
83
|
/** Persists the baseline after a completed pull or push. */
|
|
79
84
|
saveState(state: SyncState): Promise<void>;
|
|
80
85
|
}
|
|
@@ -90,6 +95,7 @@ export type TandemEvent = {
|
|
|
90
95
|
readonly skipped: readonly string[];
|
|
91
96
|
readonly type: 'invalid';
|
|
92
97
|
} | {
|
|
98
|
+
readonly error: unknown;
|
|
93
99
|
readonly message: string;
|
|
94
100
|
readonly type: 'warning';
|
|
95
101
|
} | {
|
|
@@ -107,18 +113,21 @@ export interface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
|
107
113
|
/** The running sync scheduler returned by {@link createSync}. */
|
|
108
114
|
export interface SyncHandle {
|
|
109
115
|
/** Records that a local change happened; (re)starts the idle timer that flushes
|
|
110
|
-
* dirty records. Wire this to the app's write path or reactive layer.
|
|
116
|
+
* dirty records. Wire this to the app's write path or reactive layer.
|
|
117
|
+
* Throws `TandemDisposedError` after {@link dispose}: a leaked scheduler must
|
|
118
|
+
* fail loudly rather than stop syncing in silence. */
|
|
111
119
|
changed(): void;
|
|
112
120
|
/** Aborted when the handle is disposed. */
|
|
113
121
|
readonly disposalSignal: AbortSignal;
|
|
114
|
-
/** Stops the scheduler. Dispose before switching accounts
|
|
122
|
+
/** Stops the scheduler. Dispose before switching accounts: the baseline is
|
|
115
123
|
* per-account state and a running scheduler would push into the wrong port. */
|
|
116
124
|
dispose(): void;
|
|
117
125
|
/** True once {@link dispose} has run. */
|
|
118
126
|
readonly disposed: boolean;
|
|
119
|
-
/** Runs a full sync cycle now
|
|
127
|
+
/** Runs a full sync cycle now: pulls remote changes, then pushes dirty records.
|
|
120
128
|
* Resolves when the cycle completes; rejects when it fails (dirty records stay
|
|
121
|
-
* dirty and the next cycle retries them).
|
|
129
|
+
* dirty and the next cycle retries them). Rejects with `TandemDisposedError`
|
|
130
|
+
* after {@link dispose}. */
|
|
122
131
|
flush(): Promise<void>;
|
|
123
132
|
/** Subscribes to {@link TandemEvent}s. Handler errors are swallowed; the
|
|
124
133
|
* subscription detaches when `signal` aborts or the handle is disposed. */
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,+FAA+F;IAC/F,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED,qEAAqE;AACrE,MAAM,WAAW,YAAY,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED,2FAA2F;AAC3F,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,+FAA+F;IAC/F,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED,qEAAqE;AACrE,MAAM,WAAW,YAAY,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED,2FAA2F;AAC3F,MAAM,WAAW,YAAY;IAC3B;;oEAEgE;IAChE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB;AAED;;;oBAGoB;AACpB,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,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