@yaks/sync 0.0.0-stage → 0.2.36

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.
Files changed (75) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +729 -2
  3. package/_dist/coverage.d.ts +7 -0
  4. package/_dist/coverage.d.ts.map +1 -0
  5. package/_dist/inbound.d.ts +43 -0
  6. package/_dist/inbound.d.ts.map +1 -0
  7. package/_dist/mark.d.ts +29 -0
  8. package/_dist/mark.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +78 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/outbound.d.ts +55 -0
  12. package/_dist/outbound.d.ts.map +1 -0
  13. package/_dist/outbox.d.ts +48 -0
  14. package/_dist/outbox.d.ts.map +1 -0
  15. package/_dist/pace.d.ts +9 -0
  16. package/_dist/pace.d.ts.map +1 -0
  17. package/_dist/port.d.ts +31 -0
  18. package/_dist/port.d.ts.map +1 -0
  19. package/_dist/revision.d.ts +60 -0
  20. package/_dist/revision.d.ts.map +1 -0
  21. package/_dist/saying.d.ts +12 -0
  22. package/_dist/saying.d.ts.map +1 -0
  23. package/_dist/socket.d.ts +151 -0
  24. package/_dist/socket.d.ts.map +1 -0
  25. package/_dist/sync.d.ts +97 -0
  26. package/_dist/sync.d.ts.map +1 -0
  27. package/_dist/tier.d.ts +62 -0
  28. package/_dist/tier.d.ts.map +1 -0
  29. package/clock.js +43 -0
  30. package/clock.js.map +1 -0
  31. package/clock.ts +56 -0
  32. package/coverage.js +13 -0
  33. package/coverage.js.map +1 -0
  34. package/coverage.ts +26 -0
  35. package/deno.json +1 -0
  36. package/inbound.js +217 -0
  37. package/inbound.js.map +1 -0
  38. package/inbound.ts +251 -0
  39. package/mark.js +87 -0
  40. package/mark.js.map +1 -0
  41. package/mark.ts +108 -0
  42. package/mod.js +78 -0
  43. package/mod.js.map +1 -0
  44. package/mod.ts +153 -0
  45. package/outbound.js +170 -0
  46. package/outbound.js.map +1 -0
  47. package/outbound.ts +221 -0
  48. package/outbox.js +281 -0
  49. package/outbox.js.map +1 -0
  50. package/outbox.ts +343 -0
  51. package/pace.js +96 -0
  52. package/pace.js.map +1 -0
  53. package/pace.ts +91 -0
  54. package/package.json +32 -4
  55. package/port.js +128 -0
  56. package/port.js.map +1 -0
  57. package/port.ts +176 -0
  58. package/rebase.js +93 -0
  59. package/rebase.js.map +1 -0
  60. package/rebase.ts +77 -0
  61. package/revision.js +104 -0
  62. package/revision.js.map +1 -0
  63. package/revision.ts +146 -0
  64. package/saying.js +62 -0
  65. package/saying.js.map +1 -0
  66. package/saying.ts +69 -0
  67. package/socket.js +694 -0
  68. package/socket.js.map +1 -0
  69. package/socket.ts +927 -0
  70. package/sync.js +542 -0
  71. package/sync.js.map +1 -0
  72. package/sync.ts +705 -0
  73. package/tier.js +176 -0
  74. package/tier.js.map +1 -0
  75. package/tier.ts +211 -0
package/mod.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * @yaks/sync — connects a client {@link https://jsr.io/@yaks/graph |
3
+ * @yaks/graph} to a server: a plugin that sends a local graph's writes to the
4
+ * server over HTTP and applies the server's writes back over a WebSocket.
5
+ *
6
+ * A graph in a page over {@link https://jsr.io/@yaks/ram | @yaks/ram} is
7
+ * a complete graph — same `apply()`, same queries, same bundles — but it is
8
+ * the only participant. This package adds the other one.
9
+ *
10
+ * ```ts
11
+ * import { graph } from '@yaks/graph'
12
+ * import { ram } from '@yaks/ram'
13
+ * import { sync } from '@yaks/sync'
14
+ *
15
+ * // let g = graph({ storage: ram(vocab, { adopt: true }), vocab })
16
+ * // let link = sync(g, { url: 'https://recipes.example' })
17
+ * // link.subscribe('.recipe.course=dinner&.recipe.serves>4')
18
+ * ```
19
+ *
20
+ * ## Writes are optimistic A write commits locally first — the page renders it
21
+ * before anything crosses the network — and is then sent as `POST /apply`. The
22
+ * list of bundles the server responds with is applied back through the same
23
+ * local graph, which is how the numbers it assigned, the properties it stamped
24
+ * and the entities it deleted reach the client. If the server refuses the
25
+ * write, the optimistic batch is undone from the copy {@link sync} took of
26
+ * those entities beforehand, along with whatever the write's rules added, and
27
+ * the refusal is reported. A rule the page ran itself is a guess the server's
28
+ * answer replaces: what it added is undone as the answer lands. If the server
29
+ * is merely unreachable, nothing is undone: the write may have been applied
30
+ * there and only the response lost.
31
+ *
32
+ * ## Two keywords, one apply()
33
+ * A client holds state the server owns, state this browser owns, and state
34
+ * that dies with the tab. Each component declares which it is, using the two
35
+ * core vocabulary keywords:
36
+ *
37
+ * ```json
38
+ * { "$defs": { "draft": { "type": "object", "sync": "none",
39
+ * "properties": { "text": { "type": "string" } } } } }
40
+ * ```
41
+ *
42
+ * `sync` declares who is told about a write — `server` (the default) and
43
+ * `peers` are sent, `none` stays here — and `durable` declares how long the
44
+ * value lives: `forever` (the default) is the vault, `connection` or a
45
+ * duration is memory. All of them go through the same `apply()`. A `peers`
46
+ * component may also declare a `pace` (`"100ms"`): each write lands here at
47
+ * once, and the latest leaves at most once a pace, the last one always.
48
+ *
49
+ * ## Reading is a subscription
50
+ * {@link Sync.subscribe} opens a stored query on the server's `/ws`. Its
51
+ * answer — and every later change to it, including what left the set — is
52
+ * applied to the local graph, so a render reads the local store and never
53
+ * awaits. A dropped socket reconnects with a widening backoff, sends every
54
+ * subscription again, and treats the first frame after a reopen as the whole
55
+ * set. A drop the wire resumes from (open again, every query answered again)
56
+ * missed nothing and says nothing; an outage still unresumed `most` after it
57
+ * began is reported once as a {@link Dropped}.
58
+ *
59
+ * ## Both transports are injected
60
+ * {@link SyncOpts.fetch} and {@link SyncOpts.connect} default to the
61
+ * platform's `fetch` and `WebSocket`, and either can be passed in — which is
62
+ * how this package is tested against an in-process handler with no network at
63
+ * all.
64
+ *
65
+ * @module
66
+ */
67
+
68
+ export {
69
+ type Replica,
70
+ type SubscribeOpts,
71
+ type Sync,
72
+ sync,
73
+ type SyncOpts,
74
+ } from './sync.js'
75
+ export {
76
+ type Fetch,
77
+ MOVED,
78
+ post,
79
+ type PostOpts,
80
+ type Refusal,
81
+ type Report,
82
+ type Trouble,
83
+ WriteRefused,
84
+ WriteUnknown,
85
+ } from './outbound.js'
86
+ export { changes, hear, land, snapshot, strip } from './inbound.js'
87
+ export { pacer } from './pace.js'
88
+ export { type Mine, saying } from './saying.js'
89
+ export {
90
+ type Ask,
91
+ backoff,
92
+ type Connect,
93
+ Dropped,
94
+ type Frame,
95
+ type Network,
96
+ type Socket,
97
+ type Tab,
98
+ type Timer,
99
+ type Wire,
100
+ wire,
101
+ type WireOpts,
102
+ } from './socket.js'
103
+ export {
104
+ durableOf,
105
+ guessed,
106
+ inverse,
107
+ local,
108
+ outbound,
109
+ outward,
110
+ stays,
111
+ stored,
112
+ syncOf,
113
+ } from './tier.js'
114
+ export {
115
+ asked,
116
+ asking,
117
+ before,
118
+ clean,
119
+ ECHO,
120
+ echo,
121
+ echoed,
122
+ marks,
123
+ replicate,
124
+ RULED,
125
+ ruled,
126
+ ruling,
127
+ SENT,
128
+ } from './mark.js'
129
+ export {
130
+ type Port,
131
+ type PortLink,
132
+ portLink,
133
+ type RequestOptions,
134
+ } from './port.js'
135
+
136
+ export { type Coverage, covers, delivered } from './coverage.js'
137
+ export {
138
+ older,
139
+ type Revision,
140
+ REVISIONS,
141
+ type Revisions,
142
+ revisions,
143
+ type Stamped,
144
+ type Verdict,
145
+ } from './revision.js'
146
+
147
+ export {
148
+ durableOutbox,
149
+ type Outbox,
150
+ outboxIdb,
151
+ type OutboxStore,
152
+ type Pending,
153
+ } from './outbox.js'
package/outbound.js ADDED
@@ -0,0 +1,170 @@
1
+ // A committed write on its way to the server as `POST /apply`, and the
2
+ // response.
3
+ //
4
+ // The local commit has already happened — this runs in the `effect` phase, and
5
+ // an effect is by definition post-commit — so every write here is optimistic:
6
+ // the page has already rendered it, and the server's response reconciles it
7
+ // rather than permitting it. Three responses are possible:
8
+ //
9
+ // applied the bundles come back as the server applied them — assigned
10
+ // numbers, stamped properties, cascade deletions, what its rules
11
+ // added — and they are applied locally in turn, marked as an echo
12
+ // so they are not sent back again. What the page's own run of
13
+ // those rules guessed is undone in the same batch, so the
14
+ // server's answer replaces it.
15
+ // refused the server would not take it. The optimistic batch is undone
16
+ // from the copy taken before it, with everything its rules added,
17
+ // and the refusal is reported. A write that was held (a delete —
18
+ // see sync.ts) was never applied locally, so there is nothing to
19
+ // undo.
20
+ // unreachable nothing is undone. The write may have been applied on the
21
+ // server with only the response lost, and a client that guesses
22
+ // wrong about that turns a network blip into data loss.
23
+ import { decode, stringify } from "@yaks/vocab/wire";
24
+ import { formed } from "@yaks/graph/bundle";
25
+ import { replicate } from "./mark.js";
26
+ import { guessed, inverse, outward } from "./tier.js";
27
+ /** The server deliberately refused the batch; none of it was accepted. */ export class WriteRefused extends Error {
28
+ sent;
29
+ refusal;
30
+ outcome;
31
+ constructor(sent, refusal){
32
+ super(refusal.message), this.sent = sent, this.refusal = refusal, this.outcome = 'refused';
33
+ this.name = refusal.error;
34
+ }
35
+ }
36
+ /** No usable acceptance or refusal arrived. Reconcile or retry `sent`;
37
+ * the server may already have committed it. */ export class WriteUnknown extends Error {
38
+ sent;
39
+ outcome;
40
+ retry;
41
+ constructor(sent, cause){
42
+ super(`write outcome unknown: ${cause instanceof Error ? cause.message : String(cause)}`, {
43
+ cause
44
+ }), this.sent = sent, this.outcome = 'unknown';
45
+ this.name = 'WriteUnknown';
46
+ this.retry = cause?.retry;
47
+ }
48
+ }
49
+ /** The header on a write's answer saying the address now reaches another
50
+ * store: a server that gave this browser a store of its own at this write
51
+ * says it, and the client opens its socket again. */ export let MOVED = 'x-yak-moved';
52
+ // The refusal body, however the server phrased it. An endpoint that responded
53
+ // with plain text rather than JSON still produces a named error.
54
+ let refusalOf = async (res)=>{
55
+ let text = await res.text();
56
+ try {
57
+ let body = JSON.parse(text);
58
+ if (body && typeof body == 'object' && typeof body.error == 'string') {
59
+ return body;
60
+ }
61
+ } catch {}
62
+ return {
63
+ error: `HTTP ${res.status}`,
64
+ message: text || res.statusText
65
+ };
66
+ };
67
+ /**
68
+ * Send one write to the server and reconcile the response. The result carries
69
+ * the applied bundles for a caller that waited for the server to choose an eid.
70
+ * `settled` is false only when the request outcome is unknown; an optimistic
71
+ * caller then keeps its rows pinned.
72
+ */ export let exchange = async (bundles, opts)=>{
73
+ let { graph } = opts;
74
+ let sent = opts.sent ?? outward(bundles, graph.vocab);
75
+ if (!sent.length) return {
76
+ settled: true
77
+ };
78
+ let unknown = (cause)=>{
79
+ let error = new WriteUnknown(sent, cause);
80
+ opts.report({
81
+ sent,
82
+ error,
83
+ reverted: false
84
+ });
85
+ return {
86
+ settled: false,
87
+ error
88
+ };
89
+ };
90
+ let land = opts.land ?? ((patches)=>replicate(graph, patches));
91
+ let refuse = async (refused)=>{
92
+ let back = opts.held ? [] : inverse(bundles, graph.vocab);
93
+ if (back.length) await land(back);
94
+ opts.report({
95
+ sent,
96
+ refused,
97
+ reverted: back.length > 0
98
+ });
99
+ return {
100
+ settled: true,
101
+ refused
102
+ };
103
+ };
104
+ let accept = async (applied)=>{
105
+ let landing = [
106
+ ...opts.held ? [] : guessed(bundles, graph.vocab),
107
+ ...applied
108
+ ];
109
+ if (landing.length) await land(landing);
110
+ return {
111
+ settled: true,
112
+ applied
113
+ };
114
+ };
115
+ if (opts.request) {
116
+ let applied;
117
+ try {
118
+ applied = await opts.request(opts.key, sent);
119
+ } catch (error) {
120
+ if (error instanceof WriteRefused) return await refuse(error.refusal);
121
+ return unknown(error);
122
+ }
123
+ return await accept(applied);
124
+ }
125
+ let res;
126
+ try {
127
+ res = await opts.fetch(new Request(`${opts.url.replace(/\/$/, '')}/apply`, {
128
+ method: 'POST',
129
+ headers: {
130
+ 'content-type': 'application/json',
131
+ ...opts.headers,
132
+ ...opts.key ? {
133
+ 'idempotency-key': opts.key
134
+ } : {}
135
+ },
136
+ body: stringify(sent)
137
+ }));
138
+ } catch (error) {
139
+ // Undelivered is not refused: the write may have been applied.
140
+ return unknown(error);
141
+ }
142
+ // A pending write is not an acceptance.
143
+ if (res.status == 202) {
144
+ return unknown(new Error(`HTTP ${res.status}`));
145
+ }
146
+ if (!res.ok) {
147
+ let refused;
148
+ try {
149
+ refused = await refusalOf(res);
150
+ } catch (error) {
151
+ return unknown(error);
152
+ }
153
+ // The graph's explicit refusal body confirms rollback even at 500. A
154
+ // generic gateway/server fault says nothing about whether it committed.
155
+ if (res.status >= 500 && refused.error == `HTTP ${res.status}`) {
156
+ return unknown(new Error(refused.message));
157
+ }
158
+ return await refuse(refused);
159
+ }
160
+ if (res.headers.has(MOVED)) opts.moved?.();
161
+ let applied;
162
+ try {
163
+ applied = formed(decode(graph.vocab, await res.json()));
164
+ } catch (error) {
165
+ return unknown(error);
166
+ }
167
+ return await accept(applied);
168
+ };
169
+ /** Send an optimistic or held write and say whether its outcome is known. */ export let post = async (bundles, opts)=>(await exchange(bundles, opts)).settled;
170
+ //# sourceMappingURL=outbound.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbound.js","sources":["./outbound.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,YAAY;AACZ,EAAE;AACF,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,2DAA2D;AAC3D,EAAE;AACF,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,2EAA2E;AAC3E,uEAAuE;AACvE,4CAA4C;AAC5C,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,qBAAqB;AACrB,2EAA2E;AAC3E,6EAA6E;AAC7E,qEAAqE;AAGrE,SAAS,MAAM,EAAE,SAAS,gCAAqC;AAC/D,SAAS,MAAM,kCAAuC;AACtD,SAAS,SAAS,oBAAmB;AACrC,SAAS,OAAO,EAAE,OAAO,EAAE,OAAO,oBAAmB;AAOrD,wEAAwE,GACxE,OAAO,MAAM,qBAAqB;;;EACvB,QAAmB;EAC5B,YAAY,AAAO,IAAc,EAAE,AAAO,OAAgB,CAAE;IAC1D,KAAK,CA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AI,CAAC,IAAI,EAAE,EAAE;IACX,IAAI;IACJ,IAAI;MACF,UAAU,MAAM,UAAU;IAC5B,EAAE,OAAO,OAAO;MACd,OAAO,QAAQ;IACjB;IACA,qEAAqE;IACrE,wEAAwE;IACxE,IAAI,IAAI,MAAM,IAAI,OAAO,QAAQ,KAAK,IAAI,CAAC,KAAK,EAAE,IAAI,MAAM,EAAE,EAAE;MAC9D,OAAO,QAAQ,IAAI,MAAM,QAAQ,OAAO;IAC1C;IACA,OAAO,MAAM,OAAO;EACtB;EACA,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,KAAK;EACtC,IAAI;EACJ,IAAI;IACF,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE,MAAM,IAAI,IAAI;EACrD,EAAE,OAAO,OAAO;IACd,OAAO,QAAQ;EACjB;EACA,OAAO,MAAM,OAAO;AACtB,EAAC;AAED,2EAA2E,GAC3E,OAAO,IAAI,OAAO,OAAO,SAAmB,OAC1C,CAAC,MAAM,SAAS,SAAS,KAAK,EAAE,OAAO,CAAA"}
package/outbound.ts ADDED
@@ -0,0 +1,221 @@
1
+ // A committed write on its way to the server as `POST /apply`, and the
2
+ // response.
3
+ //
4
+ // The local commit has already happened — this runs in the `effect` phase, and
5
+ // an effect is by definition post-commit — so every write here is optimistic:
6
+ // the page has already rendered it, and the server's response reconciles it
7
+ // rather than permitting it. Three responses are possible:
8
+ //
9
+ // applied the bundles come back as the server applied them — assigned
10
+ // numbers, stamped properties, cascade deletions, what its rules
11
+ // added — and they are applied locally in turn, marked as an echo
12
+ // so they are not sent back again. What the page's own run of
13
+ // those rules guessed is undone in the same batch, so the
14
+ // server's answer replaces it.
15
+ // refused the server would not take it. The optimistic batch is undone
16
+ // from the copy taken before it, with everything its rules added,
17
+ // and the refusal is reported. A write that was held (a delete —
18
+ // see sync.ts) was never applied locally, so there is nothing to
19
+ // undo.
20
+ // unreachable nothing is undone. The write may have been applied on the
21
+ // server with only the response lost, and a client that guesses
22
+ // wrong about that turns a network blip into data loss.
23
+
24
+ import type { Bundle, Graph } from 'jsr:@yaks/graph@0.2.36'
25
+ import { decode, stringify } from '@yaks/vocab/wire'
26
+ import { formed } from '@yaks/graph/bundle'
27
+ import { replicate } from './mark.js'
28
+ import { guessed, inverse, outward } from './tier.js'
29
+
30
+ /** The body of a server's refusal: the error's own name, its message, and
31
+ * whatever fields it carried — a `Stale` names the property and the value the
32
+ * graph holds. */
33
+ export type Refusal = { error: string; message: string; [k: string]: unknown }
34
+
35
+ /** The server deliberately refused the batch; none of it was accepted. */
36
+ export class WriteRefused extends Error {
37
+ readonly outcome = 'refused'
38
+ constructor(public sent: Bundle[], public refusal: Refusal) {
39
+ super(refusal.message)
40
+ this.name = refusal.error
41
+ }
42
+ }
43
+
44
+ /** No usable acceptance or refusal arrived. Reconcile or retry `sent`;
45
+ * the server may already have committed it. */
46
+ export class WriteUnknown extends Error {
47
+ readonly outcome = 'unknown'
48
+ retry?: { after: number }
49
+ constructor(public sent: Bundle[], cause: unknown) {
50
+ super(
51
+ `write outcome unknown: ${
52
+ cause instanceof Error ? cause.message : String(cause)
53
+ }`,
54
+ { cause },
55
+ )
56
+ this.name = 'WriteUnknown'
57
+ this.retry = (cause as { retry?: { after: number } } | null)?.retry
58
+ }
59
+ }
60
+
61
+ /** How a request is sent. The global `fetch` satisfies it, and so does an
62
+ * in-process handler, which is how this package is tested with no network. */
63
+ export type Fetch = (request: Request) => Response | Promise<Response>
64
+
65
+ /** One outgoing write, or one subscription, the server did not take. */
66
+ export type Trouble = {
67
+ /** the bundles as they were sent */
68
+ sent: Bundle[]
69
+ /** the server's refusal, when it responded with one */
70
+ refused?: Refusal
71
+ /** a transport or response failure: the server may have committed */
72
+ error?: unknown
73
+ /** whether the optimistic local change was undone */
74
+ reverted: boolean
75
+ /** the subscription whose query the server refused, when what it refused
76
+ * was a subscription rather than a write */
77
+ subscription?: string
78
+ }
79
+
80
+ /** Where a failure is reported: a page shows it, a test collects it. */
81
+ export type Report = (trouble: Trouble) => void
82
+
83
+ /** The header on a write's answer saying the address now reaches another
84
+ * store: a server that gave this browser a store of its own at this write
85
+ * says it, and the client opens its socket again. */
86
+ export let MOVED = 'x-yak-moved'
87
+
88
+ /** What {@link post} needs: where to send, how, and where to put the answer. */
89
+ export type PostOpts = {
90
+ graph: Graph
91
+ url: string
92
+ fetch: Fetch
93
+ headers?: Record<string, string>
94
+ report: Report
95
+ /** A server-authoritative write already split from browser-owned state. */
96
+ sent?: Bundle[]
97
+ /** the write was held out of the local graph, not applied: a refusal has
98
+ * nothing to revert */
99
+ held?: boolean
100
+ /** The write's idempotency key. Sending the same batch again under it is
101
+ * the same write: a server that kept or applied it answers as it did the
102
+ * first time, rather than taking it again. */
103
+ key?: string
104
+ /** told when the answer says the address moved ({@link MOVED}) */
105
+ moved?: () => void
106
+ /** Adapt a host's write envelope and credentials at the transport boundary. */
107
+ request?: (key: string, sent: Bundle[]) => Promise<Bundle[]>
108
+ land?: (bundles: Bundle[]) => Bundle[] | Promise<Bundle[]>
109
+ }
110
+
111
+ export type PostResult = {
112
+ settled: boolean
113
+ applied?: Bundle[]
114
+ refused?: Refusal
115
+ error?: unknown
116
+ }
117
+
118
+ // The refusal body, however the server phrased it. An endpoint that responded
119
+ // with plain text rather than JSON still produces a named error.
120
+ let refusalOf = async (res: Response): Promise<Refusal> => {
121
+ let text = await res.text()
122
+ try {
123
+ let body = JSON.parse(text)
124
+ if (body && typeof body == 'object' && typeof body.error == 'string') {
125
+ return body as Refusal
126
+ }
127
+ } catch { /* not JSON: the text is the message */ }
128
+ return { error: `HTTP ${res.status}`, message: text || res.statusText }
129
+ }
130
+
131
+ /**
132
+ * Send one write to the server and reconcile the response. The result carries
133
+ * the applied bundles for a caller that waited for the server to choose an eid.
134
+ * `settled` is false only when the request outcome is unknown; an optimistic
135
+ * caller then keeps its rows pinned.
136
+ */
137
+ export let exchange = async (
138
+ bundles: Bundle[],
139
+ opts: PostOpts,
140
+ ): Promise<PostResult> => {
141
+ let { graph } = opts
142
+ let sent = opts.sent ?? outward(bundles, graph.vocab)
143
+ if (!sent.length) return { settled: true }
144
+ let unknown = (cause: unknown): PostResult => {
145
+ let error = new WriteUnknown(sent, cause)
146
+ opts.report({ sent, error, reverted: false })
147
+ return { settled: false, error }
148
+ }
149
+ let land = opts.land ?? ((patches) => replicate(graph, patches))
150
+ let refuse = async (refused: Refusal): Promise<PostResult> => {
151
+ let back = opts.held ? [] : inverse(bundles, graph.vocab)
152
+ if (back.length) await land(back)
153
+ opts.report({ sent, refused, reverted: back.length > 0 })
154
+ return { settled: true, refused }
155
+ }
156
+ let accept = async (applied: Bundle[]): Promise<PostResult> => {
157
+ let landing = [
158
+ ...(opts.held ? [] : guessed(bundles, graph.vocab)),
159
+ ...applied,
160
+ ]
161
+ if (landing.length) await land(landing)
162
+ return { settled: true, applied }
163
+ }
164
+ if (opts.request) {
165
+ let applied: Bundle[]
166
+ try {
167
+ applied = await opts.request(opts.key!, sent)
168
+ } catch (error) {
169
+ if (error instanceof WriteRefused) return await refuse(error.refusal)
170
+ return unknown(error)
171
+ }
172
+ return await accept(applied)
173
+ }
174
+ let res: Response
175
+ try {
176
+ res = await opts.fetch(
177
+ new Request(`${opts.url.replace(/\/$/, '')}/apply`, {
178
+ method: 'POST',
179
+ headers: {
180
+ 'content-type': 'application/json',
181
+ ...opts.headers,
182
+ ...(opts.key ? { 'idempotency-key': opts.key } : {}),
183
+ },
184
+ body: stringify(sent),
185
+ }),
186
+ )
187
+ } catch (error) {
188
+ // Undelivered is not refused: the write may have been applied.
189
+ return unknown(error)
190
+ }
191
+ // A pending write is not an acceptance.
192
+ if (res.status == 202) {
193
+ return unknown(new Error(`HTTP ${res.status}`))
194
+ }
195
+ if (!res.ok) {
196
+ let refused: Refusal
197
+ try {
198
+ refused = await refusalOf(res)
199
+ } catch (error) {
200
+ return unknown(error)
201
+ }
202
+ // The graph's explicit refusal body confirms rollback even at 500. A
203
+ // generic gateway/server fault says nothing about whether it committed.
204
+ if (res.status >= 500 && refused.error == `HTTP ${res.status}`) {
205
+ return unknown(new Error(refused.message))
206
+ }
207
+ return await refuse(refused)
208
+ }
209
+ if (res.headers.has(MOVED)) opts.moved?.()
210
+ let applied: Bundle[]
211
+ try {
212
+ applied = formed(decode(graph.vocab, await res.json()))
213
+ } catch (error) {
214
+ return unknown(error)
215
+ }
216
+ return await accept(applied)
217
+ }
218
+
219
+ /** Send an optimistic or held write and say whether its outcome is known. */
220
+ export let post = async (bundles: Bundle[], opts: PostOpts): Promise<boolean> =>
221
+ (await exchange(bundles, opts)).settled