foldkit-sync 0.9.0 → 0.10.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 +104 -16
- package/dist/do.d.mts +60 -0
- package/dist/do.d.mts.map +1 -0
- package/dist/do.mjs +59 -0
- package/dist/do.mjs.map +1 -0
- package/dist/entity.d.mts +5 -53
- package/dist/entity.d.mts.map +1 -1
- package/dist/entity.mjs +5 -66
- package/dist/entity.mjs.map +1 -1
- package/dist/index.d.mts +18 -161
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +38 -11
- package/dist/index.mjs.map +1 -1
- package/dist/journal.d.mts +17 -7
- package/dist/journal.d.mts.map +1 -1
- package/dist/journal.mjs +13 -5
- package/dist/journal.mjs.map +1 -1
- package/dist/{sync-CP5UGs4r.d.mts → make-h5yD8STj.d.mts} +169 -2
- package/dist/make-h5yD8STj.d.mts.map +1 -0
- package/dist/remote.d.mts +123 -0
- package/dist/remote.d.mts.map +1 -0
- package/dist/remote.mjs +163 -0
- package/dist/remote.mjs.map +1 -0
- package/dist/{transport-hlEQpHIv.mjs → transport-DiKXy5zx.mjs} +55 -2
- package/dist/transport-DiKXy5zx.mjs.map +1 -0
- package/package.json +27 -10
- package/dist/sync-CP5UGs4r.d.mts.map +0 -1
- package/dist/transport-hlEQpHIv.mjs.map +0 -1
package/dist/remote.mjs
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { Equal, Option, Schema } from "effect";
|
|
2
|
+
import { entityKey, readField } from "foldkit-remote";
|
|
3
|
+
//#region src/remote.ts
|
|
4
|
+
/**
|
|
5
|
+
* `foldkit-sync/remote`: a slice's cell edits shown through Remote, as
|
|
6
|
+
* request-less overlays every read draws, until the row Remote holds has them.
|
|
7
|
+
*
|
|
8
|
+
* ```text
|
|
9
|
+
* cell shown = Remote's row, with each edit over it the row has not reached:
|
|
10
|
+
* one pending, one committed after the row's revision, or one
|
|
11
|
+
* the journal absorbed while the cached row is still below it
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* Remote keeps the overlays; the slice stays the only copy of the edits. An
|
|
15
|
+
* overlay is not stored, so after a reload `reconcile` rebuilds them from the
|
|
16
|
+
* slice the replica restored. What an edit absorbed and dropped from the slice
|
|
17
|
+
* still owes a cached row is held as an overlay, not in the application's
|
|
18
|
+
* Model, so every view of the row (a second list, a filter, an undo's reading
|
|
19
|
+
* of the page) sees what the page shows.
|
|
20
|
+
*
|
|
21
|
+
* Pure, like `foldkit-sync/entity`: it reads and writes the Model it is given
|
|
22
|
+
* and sends nothing.
|
|
23
|
+
*/
|
|
24
|
+
/** An edit as the store holds it: the encoded id, member and value. */
|
|
25
|
+
const Encoded = Schema.Struct({
|
|
26
|
+
id: Schema.Union([Schema.String, Schema.Number]),
|
|
27
|
+
member: Schema.String,
|
|
28
|
+
value: Schema.Unknown
|
|
29
|
+
});
|
|
30
|
+
const make = (data, edits) => {
|
|
31
|
+
const entity = edits.entity.name;
|
|
32
|
+
const encode = Schema.encodeSync(edits.Edit);
|
|
33
|
+
const decode = Schema.decodeUnknownOption(edits.Edit);
|
|
34
|
+
const decodeEncoded = Schema.decodeUnknownSync(Encoded);
|
|
35
|
+
const SHOWN = `sync-edit:${entity}:`;
|
|
36
|
+
const HELD = `sync-held:${entity}:`;
|
|
37
|
+
const keyOf = (edit) => JSON.stringify(encode(edit));
|
|
38
|
+
const encodedOf = (edit) => decodeEncoded(encode(edit));
|
|
39
|
+
const rowKey = (edit) => entityKey(entity, String(encodedOf(edit).id));
|
|
40
|
+
const cellOf = (edit) => `${rowKey(edit)}\u0000${edit.member}`;
|
|
41
|
+
/** The edits this bridge shows, by overlay id, read back from Remote's overlays. */
|
|
42
|
+
const shownIn = (model) => data.overlays(model).flatMap((id) => {
|
|
43
|
+
const held = id.startsWith(HELD);
|
|
44
|
+
if (!held && !id.startsWith(SHOWN)) return [];
|
|
45
|
+
const key = id.slice((held ? HELD : SHOWN).length);
|
|
46
|
+
return Option.match(Option.flatMap(Option.liftThrowable(JSON.parse)(key), decode), {
|
|
47
|
+
onNone: () => [],
|
|
48
|
+
onSome: (edit) => [{
|
|
49
|
+
id,
|
|
50
|
+
key,
|
|
51
|
+
edit,
|
|
52
|
+
held
|
|
53
|
+
}]
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
/** The revision Remote holds for the edit's row; none when the row is not cached. */
|
|
57
|
+
const revisionOf = (remote, edit) => Option.filter(readField(remote.entities, rowKey(edit), "revision"), Schema.is(Schema.Number));
|
|
58
|
+
const reached = (remote, edit) => Option.exists(edit.at, (at) => Option.exists(revisionOf(remote, edit), (revision) => at <= revision));
|
|
59
|
+
let settled;
|
|
60
|
+
/** Whether the row Remote holds has the edit's value in its cell. */
|
|
61
|
+
const holdsValue = (remote, edit) => Equal.equals(readField(remote.entities, rowKey(edit), edit.member), Option.some(encodedOf(edit).value));
|
|
62
|
+
const patchOf = (edit) => {
|
|
63
|
+
const { id, member, value } = encodedOf(edit);
|
|
64
|
+
return {
|
|
65
|
+
entity,
|
|
66
|
+
id: String(id),
|
|
67
|
+
values: { [member]: value }
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
/**
|
|
72
|
+
* Brings Remote's overlays in line with `slice`: each edit its row has not
|
|
73
|
+
* reached is shown, and each overlay whose edit has left the slice is
|
|
74
|
+
* lifted, unless its row is cached below it, in which case it is held
|
|
75
|
+
* until a read of the row reaches it. This replica's edit the row has
|
|
76
|
+
* reached with its own value is kept, landed, until the slice drops it, so
|
|
77
|
+
* a later edit reaching the row live is seen replacing it. Call it from
|
|
78
|
+
* `Sync.mount`'s `afterUpdate`: a read can land in any Remote Message, and
|
|
79
|
+
* a replayed durable Message may not touch Remote. With nothing to change,
|
|
80
|
+
* the Model comes back as it was given.
|
|
81
|
+
*
|
|
82
|
+
* Only a committed edit can be held: its `at` says which revision has it.
|
|
83
|
+
* One that leaves the slice straight from pending, committed and absorbed
|
|
84
|
+
* before this page installed the commit, is lifted, and its row shows the
|
|
85
|
+
* cached read until it is read again.
|
|
86
|
+
*/
|
|
87
|
+
reconcile: (model, slice, replica) => {
|
|
88
|
+
const remote = data.store.get(model);
|
|
89
|
+
if (settled !== void 0 && settled.entities === remote.entities && settled.optimistic === remote.optimistic && settled.slice === slice && settled.replica === replica) return {
|
|
90
|
+
model,
|
|
91
|
+
held: [],
|
|
92
|
+
replaced: []
|
|
93
|
+
};
|
|
94
|
+
const inSlice = new Map(slice.map((edit) => [keyOf(edit), edit]));
|
|
95
|
+
const edited = new Set(slice.map(cellOf));
|
|
96
|
+
const held = [];
|
|
97
|
+
const replaced = [];
|
|
98
|
+
let next = model;
|
|
99
|
+
for (const shown of shownIn(model)) {
|
|
100
|
+
const reachedNow = reached(remote, shown.edit);
|
|
101
|
+
const differs = reachedNow && !holdsValue(remote, shown.edit);
|
|
102
|
+
if (!shown.held && inSlice.has(shown.key)) {
|
|
103
|
+
inSlice.delete(shown.key);
|
|
104
|
+
if (!reachedNow || !differs && edits.mine(shown.edit, replica)) continue;
|
|
105
|
+
next = data.lift(next, shown.id);
|
|
106
|
+
if (differs && edits.mine(shown.edit, replica)) replaced.push(shown.edit);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const holds = !edited.has(cellOf(shown.edit)) && Option.isSome(shown.edit.at) && Option.isSome(revisionOf(remote, shown.edit)) && !reached(remote, shown.edit);
|
|
110
|
+
if (holds && shown.held) continue;
|
|
111
|
+
next = data.lift(next, shown.id);
|
|
112
|
+
if (holds) {
|
|
113
|
+
next = data.overlay(next, `${HELD}${shown.key}`, [patchOf(shown.edit)]);
|
|
114
|
+
held.push(shown.edit);
|
|
115
|
+
} else if (differs && edits.mine(shown.edit, replica)) replaced.push(shown.edit);
|
|
116
|
+
}
|
|
117
|
+
for (const [key, edit] of inSlice) if (!reached(remote, edit)) next = data.overlay(next, `${SHOWN}${key}`, [patchOf(edit)]);
|
|
118
|
+
settled = {
|
|
119
|
+
entities: remote.entities,
|
|
120
|
+
optimistic: data.store.get(next).optimistic,
|
|
121
|
+
slice,
|
|
122
|
+
replica
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
model: next,
|
|
126
|
+
held,
|
|
127
|
+
replaced
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
/**
|
|
131
|
+
* The edits the overlays show over their rows now, in the order they are
|
|
132
|
+
* drawn: for a cell's mark. One the row has reached, kept only to see a
|
|
133
|
+
* later edit replace it, is not among them.
|
|
134
|
+
*/
|
|
135
|
+
shown: (model) => {
|
|
136
|
+
const remote = data.store.get(model);
|
|
137
|
+
return shownIn(model).flatMap(({ edit, held }) => reached(remote, edit) ? [] : [{
|
|
138
|
+
edit,
|
|
139
|
+
held
|
|
140
|
+
}]);
|
|
141
|
+
},
|
|
142
|
+
/**
|
|
143
|
+
* Lifts every overlay this bridge shows: for a server reset, after which
|
|
144
|
+
* the rows' revisions count a history that is gone.
|
|
145
|
+
*/
|
|
146
|
+
clear: (model) => shownIn(model).reduce((next, shown) => data.lift(next, shown.id), model)
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
const RemoteEdits = {
|
|
150
|
+
/**
|
|
151
|
+
* The bridge between a slice of `EditableEntity` edits and a Remote domain
|
|
152
|
+
* that reads the same Entity, with its `revision`.
|
|
153
|
+
*
|
|
154
|
+
* ```ts
|
|
155
|
+
* const Shown = RemoteEdits.make(Data, ProductEdits)
|
|
156
|
+
* const { model: next } = Shown.reconcile(model, model.edits, model.replica)
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
make };
|
|
160
|
+
//#endregion
|
|
161
|
+
export { RemoteEdits };
|
|
162
|
+
|
|
163
|
+
//# sourceMappingURL=remote.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"remote.mjs","names":[],"sources":["../src/remote.ts"],"sourcesContent":["/**\n * `foldkit-sync/remote`: a slice's cell edits shown through Remote, as\n * request-less overlays every read draws, until the row Remote holds has them.\n *\n * ```text\n * cell shown = Remote's row, with each edit over it the row has not reached:\n * one pending, one committed after the row's revision, or one\n * the journal absorbed while the cached row is still below it\n * ```\n *\n * Remote keeps the overlays; the slice stays the only copy of the edits. An\n * overlay is not stored, so after a reload `reconcile` rebuilds them from the\n * slice the replica restored. What an edit absorbed and dropped from the slice\n * still owes a cached row is held as an overlay, not in the application's\n * Model, so every view of the row (a second list, a filter, an undo's reading\n * of the page) sees what the page shows.\n *\n * Pure, like `foldkit-sync/entity`: it reads and writes the Model it is given\n * and sends nothing.\n */\nimport { Equal, Option, Schema } from 'effect'\nimport { entityKey, readField, type OptimisticOperation, type RemoteModel } from 'foldkit-remote'\nimport type { Author } from './entity.js'\n\n/** What `RemoteEdits.make` uses of a Remote domain: `Remote.make`'s value is one. */\nexport interface RemoteOverlays<AppModel> {\n readonly store: { get(model: AppModel): RemoteModel }\n overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel\n lift(model: AppModel, id: string): AppModel\n overlays(model: AppModel): ReadonlyArray<string>\n}\n\n/** What `RemoteEdits.make` uses of `EditableEntity.make`'s value, over a named Entity. */\nexport interface EditsOf<Edit> {\n readonly entity: { readonly name: string }\n readonly Edit: Schema.Codec<Edit, unknown>\n mine(edit: Edit, replica: string): boolean\n}\n\n/** The fields every cell edit has, as `EditableEntity`'s `Edit` declares them. */\ninterface AnyEdit {\n readonly member: string\n readonly at: Option.Option<number>\n readonly by: Option.Option<Author>\n}\n\n/** An edit as the store holds it: the encoded id, member and value. */\nconst Encoded = Schema.Struct({\n id: Schema.Union([Schema.String, Schema.Number]),\n member: Schema.String,\n value: Schema.Unknown,\n})\n\n/** A cell an overlay draws, and whether its edit is still in the slice or only held. */\nexport interface ShownEdit<Edit> {\n readonly edit: Edit\n /** Absorbed from the slice, and shown until a read of its row has it. */\n readonly held: boolean\n}\n\n/** What `reconcile` did besides the Model. */\nexport interface Reconciled<AppModel, Edit> {\n readonly model: AppModel\n /**\n * Edits the journal absorbed that a cached row has not been read since. The\n * row is out of date until it is: ask for it again, unless a live stream\n * brings it.\n */\n readonly held: ReadonlyArray<Edit>\n /**\n * `replica`'s own edits a read of their row reached with another value: the\n * table applies in commit order, so a later edit replaced them. The slice\n * may say whose later, or may not yet; this is the row saying it.\n */\n readonly replaced: ReadonlyArray<Edit>\n}\n\nconst make = <AppModel, Edit extends AnyEdit>(\n data: RemoteOverlays<AppModel>,\n edits: EditsOf<Edit>,\n) => {\n const entity = edits.entity.name\n const encode = Schema.encodeSync(edits.Edit)\n const decode = Schema.decodeUnknownOption(edits.Edit)\n const decodeEncoded = Schema.decodeUnknownSync(Encoded)\n // Named by the Entity, so a bridge over another one never reads these back.\n const SHOWN = `sync-edit:${entity}:`\n const HELD = `sync-held:${entity}:`\n\n // The overlay's id is the edit itself, encoded: the same edit keeps its\n // overlay, and another edit of the cell is another overlay.\n const keyOf = (edit: Edit) => JSON.stringify(encode(edit))\n const encodedOf = (edit: Edit) => decodeEncoded(encode(edit))\n const rowKey = (edit: Edit) => entityKey(entity, String(encodedOf(edit).id))\n const cellOf = (edit: Edit) => `${rowKey(edit)}\\u0000${edit.member}`\n\n /** The edits this bridge shows, by overlay id, read back from Remote's overlays. */\n const shownIn = (model: AppModel) =>\n data.overlays(model).flatMap(id => {\n const held = id.startsWith(HELD)\n if (!held && !id.startsWith(SHOWN)) return []\n const key = id.slice((held ? HELD : SHOWN).length)\n return Option.match(Option.flatMap(Option.liftThrowable(JSON.parse)(key), decode), {\n onNone: () => [],\n onSome: edit => [{ id, key, edit, held }],\n })\n })\n\n /** The revision Remote holds for the edit's row; none when the row is not cached. */\n const revisionOf = (remote: RemoteModel, edit: Edit): Option.Option<number> =>\n Option.filter(readField(remote.entities, rowKey(edit), 'revision'), Schema.is(Schema.Number))\n const reached = (remote: RemoteModel, edit: Edit) =>\n Option.exists(edit.at, at =>\n Option.exists(revisionOf(remote, edit), revision => at <= revision),\n )\n\n // Reconciling runs after every update; what it depends on rarely changes, so\n // the inputs it last left in line are kept by identity and a repeat is free.\n let settled:\n | {\n readonly entities: RemoteModel['entities']\n readonly optimistic: RemoteModel['optimistic']\n readonly slice: ReadonlyArray<Edit>\n readonly replica: string\n }\n | undefined\n\n /** Whether the row Remote holds has the edit's value in its cell. */\n const holdsValue = (remote: RemoteModel, edit: Edit) =>\n Equal.equals(\n readField(remote.entities, rowKey(edit), edit.member),\n Option.some(encodedOf(edit).value),\n )\n\n const patchOf = (edit: Edit): OptimisticOperation => {\n const { id, member, value } = encodedOf(edit)\n return { entity, id: String(id), values: { [member]: value } }\n }\n\n return {\n /**\n * Brings Remote's overlays in line with `slice`: each edit its row has not\n * reached is shown, and each overlay whose edit has left the slice is\n * lifted, unless its row is cached below it, in which case it is held\n * until a read of the row reaches it. This replica's edit the row has\n * reached with its own value is kept, landed, until the slice drops it, so\n * a later edit reaching the row live is seen replacing it. Call it from\n * `Sync.mount`'s `afterUpdate`: a read can land in any Remote Message, and\n * a replayed durable Message may not touch Remote. With nothing to change,\n * the Model comes back as it was given.\n *\n * Only a committed edit can be held: its `at` says which revision has it.\n * One that leaves the slice straight from pending, committed and absorbed\n * before this page installed the commit, is lifted, and its row shows the\n * cached read until it is read again.\n */\n reconcile: (\n model: AppModel,\n slice: ReadonlyArray<Edit>,\n replica: string,\n ): Reconciled<AppModel, Edit> => {\n const remote = data.store.get(model)\n if (\n settled !== undefined &&\n settled.entities === remote.entities &&\n settled.optimistic === remote.optimistic &&\n settled.slice === slice &&\n settled.replica === replica\n ) {\n return { model, held: [], replaced: [] }\n }\n const inSlice = new Map(slice.map(edit => [keyOf(edit), edit]))\n const edited = new Set(slice.map(cellOf))\n const held: Array<Edit> = []\n const replaced: Array<Edit> = []\n let next = model\n for (const shown of shownIn(model)) {\n const reachedNow = reached(remote, shown.edit)\n const differs = reachedNow && !holdsValue(remote, shown.edit)\n if (!shown.held && inSlice.has(shown.key)) {\n inSlice.delete(shown.key)\n // Kept while the row is below it, and, landed, while it is this\n // replica's and the row still holds it: a later edit that reaches the\n // row live is then seen replacing it, though the slice may never say.\n if (!reachedNow || (!differs && edits.mine(shown.edit, replica))) continue\n next = data.lift(next, shown.id)\n if (differs && edits.mine(shown.edit, replica)) replaced.push(shown.edit)\n continue\n }\n // Held only while nothing in the slice edits the cell and the cached\n // row is below the commit; a later edit of the cell takes its place.\n const holds =\n !edited.has(cellOf(shown.edit)) &&\n Option.isSome(shown.edit.at) &&\n Option.isSome(revisionOf(remote, shown.edit)) &&\n !reached(remote, shown.edit)\n if (holds && shown.held) continue\n next = data.lift(next, shown.id)\n if (holds) {\n next = data.overlay(next, `${HELD}${shown.key}`, [patchOf(shown.edit)])\n held.push(shown.edit)\n } else if (differs && edits.mine(shown.edit, replica)) {\n replaced.push(shown.edit)\n }\n }\n for (const [key, edit] of inSlice) {\n if (!reached(remote, edit)) next = data.overlay(next, `${SHOWN}${key}`, [patchOf(edit)])\n }\n settled = {\n entities: remote.entities,\n optimistic: data.store.get(next).optimistic,\n slice,\n replica,\n }\n return { model: next, held, replaced }\n },\n\n /**\n * The edits the overlays show over their rows now, in the order they are\n * drawn: for a cell's mark. One the row has reached, kept only to see a\n * later edit replace it, is not among them.\n */\n shown: (model: AppModel): ReadonlyArray<ShownEdit<Edit>> => {\n const remote = data.store.get(model)\n return shownIn(model).flatMap(({ edit, held }) =>\n reached(remote, edit) ? [] : [{ edit, held }],\n )\n },\n\n /**\n * Lifts every overlay this bridge shows: for a server reset, after which\n * the rows' revisions count a history that is gone.\n */\n clear: (model: AppModel): AppModel =>\n shownIn(model).reduce((next, shown) => data.lift(next, shown.id), model),\n }\n}\n\nexport const RemoteEdits = {\n /**\n * The bridge between a slice of `EditableEntity` edits and a Remote domain\n * that reads the same Entity, with its `revision`.\n *\n * ```ts\n * const Shown = RemoteEdits.make(Data, ProductEdits)\n * const { model: next } = Shown.reconcile(model, model.edits, model.replica)\n * ```\n */\n make,\n}\nexport type RemoteEdits<AppModel, Edit extends AnyEdit> = ReturnType<typeof make<AppModel, Edit>>\n"],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K,KAAK,MAAM,MAAM,EAAE,GAAG,KAAK;CAC3E;AACF;AAEA,MAAa,cAAc;;;;;;;;;;AAUzB,KACF"}
|
|
@@ -177,6 +177,59 @@ const portSocket = (port, options = {}) => {
|
|
|
177
177
|
}
|
|
178
178
|
};
|
|
179
179
|
};
|
|
180
|
+
/**
|
|
181
|
+
* A socket over an existing `WebSocket`: the accepted end of a Cloudflare
|
|
182
|
+
* `WebSocketPair`, or any other socket the platform hands over. Unlike
|
|
183
|
+
* `nativeSocket` it opens nothing — accept the pair first — and unlike
|
|
184
|
+
* `portSocket` there is no signal: the socket closing, erroring, or being
|
|
185
|
+
* closed fires `onClose` once, which is how a host stops serving it.
|
|
186
|
+
*/
|
|
187
|
+
const workerSocket = (socket) => {
|
|
188
|
+
const messageListeners = /* @__PURE__ */ new Set();
|
|
189
|
+
const closeListeners = /* @__PURE__ */ new Set();
|
|
190
|
+
let closed = false;
|
|
191
|
+
const forget = () => {
|
|
192
|
+
socket.removeEventListener("message", onMessageEvent);
|
|
193
|
+
socket.removeEventListener("close", onClosedEvent);
|
|
194
|
+
socket.removeEventListener("error", onClosedEvent);
|
|
195
|
+
};
|
|
196
|
+
const fireClose = () => {
|
|
197
|
+
closed = true;
|
|
198
|
+
forget();
|
|
199
|
+
for (const listener of [...closeListeners]) listener();
|
|
200
|
+
closeListeners.clear();
|
|
201
|
+
};
|
|
202
|
+
const onMessageEvent = (event) => {
|
|
203
|
+
for (const listener of [...messageListeners]) listener(String(event.data));
|
|
204
|
+
};
|
|
205
|
+
const onClosedEvent = () => {
|
|
206
|
+
fireClose();
|
|
207
|
+
};
|
|
208
|
+
socket.addEventListener("message", onMessageEvent);
|
|
209
|
+
socket.addEventListener("close", onClosedEvent);
|
|
210
|
+
socket.addEventListener("error", onClosedEvent);
|
|
211
|
+
return {
|
|
212
|
+
send: (data) => socket.send(data),
|
|
213
|
+
close: () => {
|
|
214
|
+
try {
|
|
215
|
+
socket.close();
|
|
216
|
+
} catch {}
|
|
217
|
+
fireClose();
|
|
218
|
+
},
|
|
219
|
+
onMessage: (listener) => {
|
|
220
|
+
messageListeners.add(listener);
|
|
221
|
+
return () => messageListeners.delete(listener);
|
|
222
|
+
},
|
|
223
|
+
onClose: (listener) => {
|
|
224
|
+
if (closed) {
|
|
225
|
+
listener();
|
|
226
|
+
return () => {};
|
|
227
|
+
}
|
|
228
|
+
closeListeners.add(listener);
|
|
229
|
+
return () => closeListeners.delete(listener);
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
};
|
|
180
233
|
const connector = (options) => {
|
|
181
234
|
if (options.makeSocket !== void 0) return options.makeSocket;
|
|
182
235
|
const { url } = options;
|
|
@@ -354,6 +407,6 @@ const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.la
|
|
|
354
407
|
});
|
|
355
408
|
})());
|
|
356
409
|
//#endregion
|
|
357
|
-
export {
|
|
410
|
+
export { localSequence as _, layerSocket as a, sequence as b, serveSocket as c, DocumentId as d, LocalSequence as f, documentId as g, Sequence as h, layerLoopback as i, toPromise as l, ReplicaId as m, TransportError as n, nativeSocket as o, OpId as p, layerFromPromise as r, portSocket as s, Transport as t, workerSocket as u, opId as v, replicaId as y };
|
|
358
411
|
|
|
359
|
-
//# sourceMappingURL=transport-
|
|
412
|
+
//# sourceMappingURL=transport-DiKXy5zx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport-DiKXy5zx.mjs","names":[],"sources":["../src/ids.ts","../src/transport.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n /**\n * The connection itself, for another protocol to share, such as presence: a send goes to\n * the socket open now and is dropped while none is, and messages from every socket the\n * transport opens arrive here. It is the transport's to close.\n */\n readonly socket?: SocketLike | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<Operation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch {}\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n return Transport.of({\n changes: Stream.fromPubSub(notices),\n socket: shared,\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n })(),\n )\n"],"mappings":";;;AAGA,MAAa,aAAa,OAAO,eAAe,KAAK,OA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BAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,WAAW,cAAc,CAAC,OAAO;IACnC,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;AACH,CAAC,CAAC,CAAC,CACL"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-sync",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -41,6 +41,16 @@
|
|
|
41
41
|
"foldkit-plus:source": "./src/entity.ts",
|
|
42
42
|
"types": "./dist/entity.d.mts",
|
|
43
43
|
"import": "./dist/entity.mjs"
|
|
44
|
+
},
|
|
45
|
+
"./do": {
|
|
46
|
+
"foldkit-plus:source": "./src/do.ts",
|
|
47
|
+
"types": "./dist/do.d.mts",
|
|
48
|
+
"import": "./dist/do.mjs"
|
|
49
|
+
},
|
|
50
|
+
"./remote": {
|
|
51
|
+
"foldkit-plus:source": "./src/remote.ts",
|
|
52
|
+
"types": "./dist/remote.d.mts",
|
|
53
|
+
"import": "./dist/remote.mjs"
|
|
44
54
|
}
|
|
45
55
|
},
|
|
46
56
|
"files": [
|
|
@@ -49,27 +59,34 @@
|
|
|
49
59
|
"LICENSE"
|
|
50
60
|
],
|
|
51
61
|
"dependencies": {
|
|
52
|
-
"foldkit-surface": "0.
|
|
62
|
+
"foldkit-surface": "0.8.0"
|
|
53
63
|
},
|
|
54
64
|
"peerDependencies": {
|
|
55
65
|
"effect": "^4.0.0",
|
|
56
66
|
"foldkit": "^0.165.0",
|
|
57
|
-
"foldkit-durable": "0.
|
|
67
|
+
"foldkit-durable": "0.8.0",
|
|
68
|
+
"foldkit-remote": "0.14.0"
|
|
69
|
+
},
|
|
70
|
+
"peerDependenciesMeta": {
|
|
71
|
+
"foldkit-durable": {
|
|
72
|
+
"optional": true
|
|
73
|
+
}
|
|
58
74
|
},
|
|
59
75
|
"devDependencies": {
|
|
76
|
+
"@cloudflare/workers-types": "5.20261008.1",
|
|
60
77
|
"@effect/platform-browser": "4.0.0",
|
|
78
|
+
"@effect/sql-d1": "4.0.0",
|
|
61
79
|
"effect": "4.0.0",
|
|
80
|
+
"esbuild": "0.28.2",
|
|
62
81
|
"foldkit": "0.165.0",
|
|
63
82
|
"jsdom": "26.1.0",
|
|
83
|
+
"miniflare": "3.20250718.3",
|
|
64
84
|
"tsdown": "^0.23.0",
|
|
65
85
|
"typescript": "5.9.3",
|
|
66
|
-
"foldkit-
|
|
67
|
-
"foldkit-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
"foldkit-durable": {
|
|
71
|
-
"optional": true
|
|
72
|
-
}
|
|
86
|
+
"foldkit-agent": "0.7.0",
|
|
87
|
+
"foldkit-remote": "0.14.0",
|
|
88
|
+
"foldkit-durable": "0.8.0",
|
|
89
|
+
"foldkit-entity": "0.8.0"
|
|
73
90
|
},
|
|
74
91
|
"scripts": {
|
|
75
92
|
"build": "tsdown",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sync-CP5UGs4r.d.mts","names":[],"sources":["../src/ids.ts","../src/errors.ts","../src/indexedDb.ts","../src/transport.ts","../src/sync.ts"],"mappings":";;;cAGa,YAAU,OAAA,MAAA,OAAA;KACX,oBAAoB,WAAW;;cAG9B,WAAS,OAAA,MAAA,OAAA;KACV,mBAAmB,UAAU;;cAG5B,MAAI,OAAA,MAAA,OAAA;KACL,cAAc,KAAK;;;;;cAMlB,UAAQ,OAAA,MAAA,OAAA;KAKT,kBAAkB,SAAS;;cAG1B,eAAa,OAAA,MAAA,OAAA;KAKd,uBAAuB,cAAc;;;;;;cAOpC,aAAc,kBAAgB;cAC9B,YAAa,kBAAgB;cAC7B,OAAQ,kBAAgB;cACxB,WAAY,kBAAgB;cAC5B,gBAAiB,kBAAgB;;;;;;;;cCvCjC,qBAAqB;;;;;;cAMrB,qCAAqC;;;;;;;cASrC,iCAAiC;;;;;;cAUjC,mCAAmC;;;;;;cASnC,6BAA6B;;;;;cAS7B,2BAA2B;;;;;;;cAQ3B,kCAAkC;;;;;;;cAUlC,4BAA4B;;;;;;cAU5B,8BAA8B;;;;;;;;;;cAa9B,oCAAoC;;;;;cASpC,2BAA2B;;;;;;;cAQ3B,uCAAuC;;;;;;;;;cAavC,oBAAoB;KAKrB,eACR,eACA,cACA,2BACA,6BACA,uBACA,iCACA,qBACA,4BACA,sBACA,wBACA,8BACA;;;;UClIa;;WAEN;WACA;;;;;WAKA;;WAEA;;;UAIM;;;;;EAKf,YAAY,OAAO,gBAAgB;;EAEnC,OAAO,gBAAgB,oCAAoC,OAAO,aAAa;;;;;;EAM/E,UAAU,OAAO,aAAa,6BAA6B,OAAO,aAAa;;EAE/E,OAAO,OAAO;;;cAwCH,YAAS,eAAA,OAAA,gBAAA,UAAA,2BAAA,OAAA,OAAA,SAAA,UAAA,qCAAA;;;;;;;cCpET,uBAAuB;;UAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;UAGM;WACN;WACA;WACA;;;;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AEjC,YAAY,WAAW;;WAEvB,kBAAkB;WAClB;;aAEE,SAAS,WAAW,cAAc;aAClC,SAAS,mBAAmB;;WAE9B;aACE,SAAS,UAAU;aACnB,SAAS,mBAAmB;;WAE9B,aAAa;WACb,SAAS,UAAU,QAAQ,WAAW,cAAc;;WAEpD,SACP,WAAW,WACX;aAAmB;aAA2B;QAC3C;;;;;;;;;cAUM,aAAc,SAAS,QAAQ,gBAAgB,eAC1D,YAAY,eAAe,SAAS,QAAQ,gBAAgB,mBAC3D,KAAK,SAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transport-hlEQpHIv.mjs","names":[],"sources":["../src/ids.ts","../src/transport.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n /**\n * The connection itself, for another protocol to share, such as presence: a send goes to\n * the socket open now and is dropped while none is, and messages from every socket the\n * transport opens arrive here. It is the transport's to close.\n */\n readonly socket?: SocketLike | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<Operation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<Operation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch {}\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n return Transport.of({\n changes: Stream.fromPubSub(notices),\n socket: shared,\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n })(),\n )\n"],"mappings":";;;AAGA,MAAa,aAAa,OAAO,eAAe,KAAK,OAAO,MAAM,0BAA0B,CAAC;;AAI7F,MAAa,YAAY,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAA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