@yaks/api 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 (152) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +956 -2
  3. package/_dist/actor.d.ts +59 -0
  4. package/_dist/actor.d.ts.map +1 -0
  5. package/_dist/address.d.ts +33 -0
  6. package/_dist/address.d.ts.map +1 -0
  7. package/_dist/asset.d.ts +15 -0
  8. package/_dist/asset.d.ts.map +1 -0
  9. package/_dist/batches.d.ts +4 -0
  10. package/_dist/batches.d.ts.map +1 -0
  11. package/_dist/body.d.ts +7 -0
  12. package/_dist/body.d.ts.map +1 -0
  13. package/_dist/deno.d.ts +38 -0
  14. package/_dist/deno.d.ts.map +1 -0
  15. package/_dist/doors.d.ts +134 -0
  16. package/_dist/doors.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +17 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/headers.d.ts +5 -0
  20. package/_dist/headers.d.ts.map +1 -0
  21. package/_dist/log.d.ts +253 -0
  22. package/_dist/log.d.ts.map +1 -0
  23. package/_dist/mod.d.ts +71 -0
  24. package/_dist/mod.d.ts.map +1 -0
  25. package/_dist/publish.d.ts +7 -0
  26. package/_dist/publish.d.ts.map +1 -0
  27. package/_dist/reached.d.ts +145 -0
  28. package/_dist/reached.d.ts.map +1 -0
  29. package/_dist/receipts.d.ts +153 -0
  30. package/_dist/receipts.d.ts.map +1 -0
  31. package/_dist/refuse.d.ts +51 -0
  32. package/_dist/refuse.d.ts.map +1 -0
  33. package/_dist/relay.d.ts +3 -0
  34. package/_dist/relay.d.ts.map +1 -0
  35. package/_dist/request.d.ts +79 -0
  36. package/_dist/request.d.ts.map +1 -0
  37. package/_dist/requests.d.ts +7 -0
  38. package/_dist/requests.d.ts.map +1 -0
  39. package/_dist/route.d.ts +71 -0
  40. package/_dist/route.d.ts.map +1 -0
  41. package/_dist/routed.d.ts +33 -0
  42. package/_dist/routed.d.ts.map +1 -0
  43. package/_dist/routes.d.ts +46 -0
  44. package/_dist/routes.d.ts.map +1 -0
  45. package/_dist/save.d.ts +6 -0
  46. package/_dist/save.d.ts.map +1 -0
  47. package/_dist/socket.d.ts +73 -0
  48. package/_dist/socket.d.ts.map +1 -0
  49. package/_dist/subs.d.ts +134 -0
  50. package/_dist/subs.d.ts.map +1 -0
  51. package/_dist/timing.d.ts +8 -0
  52. package/_dist/timing.d.ts.map +1 -0
  53. package/_dist/tools.d.ts +80 -0
  54. package/_dist/tools.d.ts.map +1 -0
  55. package/_dist/vocab.d.ts +6 -0
  56. package/_dist/vocab.d.ts.map +1 -0
  57. package/access.js +32 -0
  58. package/access.js.map +1 -0
  59. package/access.ts +42 -0
  60. package/actor.js +75 -0
  61. package/actor.js.map +1 -0
  62. package/actor.ts +106 -0
  63. package/address.js +42 -0
  64. package/address.js.map +1 -0
  65. package/address.ts +49 -0
  66. package/admission.js +71 -0
  67. package/admission.js.map +1 -0
  68. package/admission.ts +64 -0
  69. package/asset.js +37 -0
  70. package/asset.js.map +1 -0
  71. package/asset.ts +47 -0
  72. package/batches.js +92 -0
  73. package/batches.js.map +1 -0
  74. package/batches.ts +96 -0
  75. package/body.js +51 -0
  76. package/body.js.map +1 -0
  77. package/body.ts +82 -0
  78. package/deno.js +88 -0
  79. package/deno.js.map +1 -0
  80. package/deno.json +1 -0
  81. package/deno.ts +150 -0
  82. package/doors.js +435 -0
  83. package/doors.js.map +1 -0
  84. package/doors.ts +570 -0
  85. package/graph.js +12 -0
  86. package/graph.js.map +1 -0
  87. package/graph.ts +23 -0
  88. package/headers.js +5 -0
  89. package/headers.js.map +1 -0
  90. package/headers.ts +9 -0
  91. package/interest.js +224 -0
  92. package/interest.js.map +1 -0
  93. package/interest.ts +264 -0
  94. package/log.js +1011 -0
  95. package/log.js.map +1 -0
  96. package/log.ts +1035 -0
  97. package/mod.js +69 -0
  98. package/mod.js.map +1 -0
  99. package/mod.ts +142 -0
  100. package/package.json +75 -4
  101. package/peer_query.js +164 -0
  102. package/peer_query.js.map +1 -0
  103. package/peer_query.ts +158 -0
  104. package/publish.js +7 -0
  105. package/publish.js.map +1 -0
  106. package/publish.ts +16 -0
  107. package/reached.js +456 -0
  108. package/reached.js.map +1 -0
  109. package/reached.ts +549 -0
  110. package/receipts.js +543 -0
  111. package/receipts.js.map +1 -0
  112. package/receipts.ts +749 -0
  113. package/refuse.js +120 -0
  114. package/refuse.js.map +1 -0
  115. package/refuse.ts +179 -0
  116. package/relay.js +249 -0
  117. package/relay.js.map +1 -0
  118. package/relay.ts +284 -0
  119. package/request.js +218 -0
  120. package/request.js.map +1 -0
  121. package/request.ts +235 -0
  122. package/requests.js +250 -0
  123. package/requests.js.map +1 -0
  124. package/requests.ts +257 -0
  125. package/route.js +139 -0
  126. package/route.js.map +1 -0
  127. package/route.ts +228 -0
  128. package/routed.js +25 -0
  129. package/routed.js.map +1 -0
  130. package/routed.ts +53 -0
  131. package/routes.js +154 -0
  132. package/routes.js.map +1 -0
  133. package/routes.ts +201 -0
  134. package/save.js +341 -0
  135. package/save.js.map +1 -0
  136. package/save.ts +393 -0
  137. package/socket.js +398 -0
  138. package/socket.js.map +1 -0
  139. package/socket.ts +496 -0
  140. package/subs.js +2295 -0
  141. package/subs.js.map +1 -0
  142. package/subs.ts +2979 -0
  143. package/timing.js +17 -0
  144. package/timing.js.map +1 -0
  145. package/timing.ts +26 -0
  146. package/tools.js +251 -0
  147. package/tools.js.map +1 -0
  148. package/tools.ts +315 -0
  149. package/vocab.js +18 -0
  150. package/vocab.js.map +1 -0
  151. package/vocab.json +93 -0
  152. package/vocab.ts +18 -0
package/refuse.js ADDED
@@ -0,0 +1,120 @@
1
+ // How a refusal reaches the caller. Every endpoint in this package answers a
2
+ // thrown error the same way: the error's own name, its message, and whatever
3
+ // fields it carries, as JSON — so a client reads the same shape `apply()`
4
+ // threw, not a prose translation of it. A stale precondition still reports
5
+ // which property moved and what the graph holds now; a refused property still
6
+ // names itself, and a write that did not fit the vocabulary says
7
+ // `misfit: true` (@yaks/graph `Misfit`).
8
+ //
9
+ // The HTTP status is derived from the error's `name` alone, by @yaks/graph's
10
+ // `status`: the one table every door reads to tell a caller's refusal from a
11
+ // defect, which any package's error joins by setting its own `name`.
12
+ import { stringify } from "@yaks/vocab/wire";
13
+ import { STATUS, status } from "@yaks/graph/errors";
14
+ import { FILED } from "./headers.js";
15
+ /** A graph precondition conflict carries the value the caller can retry on. */ export let staleRefusal = (code, body)=>code == STATUS.Stale && body?.error == 'Stale';
16
+ /** The request could not be authenticated. Throw this from an
17
+ * {@link https://jsr.io/@yaks/api/doc/~/Authenticate | Authenticate} to answer
18
+ * a request with a 401. */ export class Unauthorized extends Error {
19
+ /** @param message what the caller is missing (default: `not authenticated`) */ constructor(message = 'not authenticated'){
20
+ super(message);
21
+ this.name = 'Unauthorized';
22
+ }
23
+ }
24
+ // What was thrown, as an error: a refusal another door answered, relayed as
25
+ // it was said, is the error it names, with what else it carried.
26
+ let errorOf = (err)=>{
27
+ if (err instanceof Error) return err;
28
+ if (err && typeof err == 'object' && typeof err.error == 'string' && typeof err.message == 'string') {
29
+ let { error, message, ...rest } = err;
30
+ return Object.assign(new Error(message), rest, {
31
+ name: error
32
+ });
33
+ }
34
+ return new Error(String(err));
35
+ };
36
+ /** An error as the body a client reads: its name as `error`, its message, and
37
+ * every other field it carries. A refusal relayed from another door is said
38
+ * as that door said it. */ export let refusal = (err)=>{
39
+ let e = errorOf(err);
40
+ let out = {
41
+ error: e.name,
42
+ message: e.message
43
+ };
44
+ for (let [k, v] of Object.entries(e)){
45
+ if (k != 'name' && k != 'message' && k != 'stack') out[k] = v;
46
+ }
47
+ return out;
48
+ };
49
+ // Where a server failure goes: the reporter its host installed last, else the
50
+ // console, so a failure met before any host installs one is still said.
51
+ let reporters = [];
52
+ let said = (err, where)=>console.error(`${where} failed —`, err);
53
+ /** Report every server failure this package catches to `report`, with where
54
+ * it was caught and its door's tags: the host's own reporter, which tells its
55
+ * tracker. A failure answered to its caller and one with no caller at all (a
56
+ * socket's message, a subscription's refresh, a page body that did not build)
57
+ * go the same way. The newest installed is the one told; the function
58
+ * returned removes it. */ export let faults = (report)=>{
59
+ reporters.push(report);
60
+ return ()=>{
61
+ let at = reporters.lastIndexOf(report);
62
+ if (at >= 0) reporters.splice(at, 1);
63
+ };
64
+ };
65
+ /** The header on an answer whose failure was reported where it was caught:
66
+ * a caller that relays the answer files it no second time. */ export { FILED };
67
+ /** Whether a host's reporter hears this package's failures ({@link faults}). */ export let reporting = ()=>reporters.length > 0;
68
+ /** A server failure, reported with where it happened and its door's tags to
69
+ * the host's reporter ({@link faults}), or said on the console while none is
70
+ * installed; a refusal (below 500) is the caller's and says nothing. A
71
+ * refusal relayed from another door is judged and reported as the error it
72
+ * names. */ export let fault = (err, where, tags = {})=>{
73
+ if (!(err instanceof Error)) err = errorOf(err);
74
+ if (status(err) < 500) return;
75
+ let report = reporters.at(-1) ?? said;
76
+ try {
77
+ report(err, where, tags);
78
+ } catch (why) {
79
+ said(err, where);
80
+ said(why, `reporting ${where}`);
81
+ }
82
+ };
83
+ // The requests a watch is answering (./request.ts `served`), each with the
84
+ // failure `refuse` answered it with: the watch reports that failure once, with
85
+ // its request. A failure answered where nothing watches is reported here.
86
+ let watched = new WeakMap();
87
+ export let watch = (request)=>void watched.set(request, undefined);
88
+ export let cause = (request)=>watched.get(request);
89
+ /** A JSON response. */ export let json = (body, code = 200)=>new Response(stringify(body), {
90
+ status: code,
91
+ headers: {
92
+ 'content-type': 'application/json'
93
+ }
94
+ });
95
+ /** The seconds an error asks its caller to wait (`retry.after`, in
96
+ * milliseconds, as @yaks/effects reads it), for an answer's `retry-after`. */ export let waits = (err)=>{
97
+ let after = err?.retry?.after;
98
+ return typeof after == 'number' && after > 0 ? Math.ceil(after / 1000) : null;
99
+ };
100
+ /** A thrown error as its response: the refusal body, at its HTTP status, with
101
+ * a `retry-after` when the error asks for a wait (`retry.after`). A
102
+ * server failure is reported once: by the watch the request is answered under
103
+ * (`served`), with its request, or else here ({@link fault}), with the method
104
+ * and path when a request is supplied, never the query string, headers or
105
+ * body, and the `tags` of the door that answered it, and its answer says so
106
+ * ({@link FILED}) while a host's reporter hears it. An expected client
107
+ * refusal is not reported at all. */ export let refuse = (err, request, tags)=>{
108
+ let code = status(err);
109
+ let answer = json(refusal(err), code);
110
+ let wait = waits(err);
111
+ if (wait != null) answer.headers.set('retry-after', String(wait));
112
+ if (request && watched.has(request)) {
113
+ if (code >= 500) watched.set(request, err);
114
+ } else {
115
+ fault(err, request ? `${request.method} ${new URL(request.url).pathname}` : 'request', tags);
116
+ if (code >= 500 && reporting()) answer.headers.set(FILED, '1');
117
+ }
118
+ return answer;
119
+ };
120
+ //# sourceMappingURL=refuse.js.map
package/refuse.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refuse.js","sources":["./refuse.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,0EAA0E;AAC1E,2EAA2E;AAC3E,8EAA8E;AAC9E,iEAAiE;AACjE,yCAAyC;AACzC,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,qEAAqE;AAErE,SAAS,SAAS,gCAAqC;AACvD,SAAqB,MAAM,EAAE,MAAM,kCAAuC;AAC1E,SAAS,KAAK,uBAAsB;AAepC,6EAA6E,GAC7E,OAAO,IAAI,eAAe,CACxB,MACA,OAEA,QAAQ,OAAO,KAAK,IAAI,AAAC,MAAkC,SAAS,QAAO;AAE7E;;yBAEyB,GACzB,OAAO,MAAM,qBAAqB;EAChC,6EAA6E,GAC7E,YAAY,UAAU,mBAAmB,CAAE;IACzC,KAAK,CAAC;IACN,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AAEA,4EAA4E;AAC5E,iEAAiE;AACjE,IAAI,UAAU,CAAC;EACb,IAAI,eAAe,OAAO,OAAO;EACjC,IACE,OAAO,OAAO,OAAO,YACrB,OAAO,AAAC,IAAgB,KAAK,IAAI,YACj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;IACZ,KAAK,KAAK;IACV,KAAK,KAAK,CAAC,UAAU,EAAE,OAAO;EAChC;AACF,EAAC;AAED,2EAA2E;AAC3E,+EAA+E;AAC/E,0EAA0E;AAC1E,IAAI,UAAU,IAAI;AAClB,OAAO,IAAI,QAAQ,CAAC,UAClB,KAAK,QAAQ,GAAG,CAAC,SAAS,WAAU;AACtC,OAAO,IAAI,QAAQ,CAAC,UAA8B,QAAQ,GAAG,CAAC,SAAQ;AAEtE,qBAAqB,GACrB,OAAO,IAAI,OAAO,CAAC,MAAe,OAAO,GAAG,GAC1C,IAAI,SAAS,UAAU,OAAO;IAC5B,QAAQ;IACR,SAAS;MAAE,gBAAgB;IAAmB;EAChD,GAAE;AAEJ;4EAC4E,GAC5E,OAAO,IAAI,QAAQ,CAAC;EAClB,IAAI,QAAS,KAAgD,OAAO;EACpE,OAAO,OAAO,SAAS,YAAY,QAAQ,IAAI,KAAK,IAAI,CAAC,QAAQ,QAAQ;AAC3E,EAAC;AAED;;;;;;;mCAOmC,GACnC,OAAO,IAAI,SAAS,CAClB,KACA,SACA;EAEA,IAAI,OAAO,OAAO;EAClB,IAAI,SAAS,KAAK,QAAQ,MAAM;EAChC,IAAI,OAAO,MAAM;EACjB,IAAI,QAAQ,MAAM,OAAO,OAAO,CAAC,GAAG,CAAC,eAAe,OAAO;EAC3D,IAAI,WAAW,QAAQ,GAAG,CAAC,UAAU;IACnC,IAAI,QAAQ,KAAK,QAAQ,GAAG,CAAC,SAAS;EACxC,OAAO;IACL,MACE,KACA,UACI,GAAG,QAAQ,MAAM,CAAC,CAAC,EAAE,IAAI,IAAI,QAAQ,GAAG,EAAE,QAAQ,EAAE,GACpD,WACJ;IAEF,IAAI,QAAQ,OAAO,aAAa,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO;EAC5D;EACA,OAAO;AACT,EAAC"}
package/refuse.ts ADDED
@@ -0,0 +1,179 @@
1
+ // How a refusal reaches the caller. Every endpoint in this package answers a
2
+ // thrown error the same way: the error's own name, its message, and whatever
3
+ // fields it carries, as JSON — so a client reads the same shape `apply()`
4
+ // threw, not a prose translation of it. A stale precondition still reports
5
+ // which property moved and what the graph holds now; a refused property still
6
+ // names itself, and a write that did not fit the vocabulary says
7
+ // `misfit: true` (@yaks/graph `Misfit`).
8
+ //
9
+ // The HTTP status is derived from the error's `name` alone, by @yaks/graph's
10
+ // `status`: the one table every door reads to tell a caller's refusal from a
11
+ // defect, which any package's error joins by setting its own `name`.
12
+
13
+ import { stringify } from '@yaks/vocab/wire'
14
+ import { type Stale, STATUS, status } from '@yaks/graph/errors'
15
+ import { FILED } from './headers.js'
16
+
17
+ /** A refusal, as a client reads it: the error's name, its message, and any
18
+ * fields the error carried (a {@link https://jsr.io/@yaks/graph | Stale}
19
+ * precondition's `eid`, `comp`, `prop` and `current`, say). */
20
+ export type Refusal = {
21
+ /** the error's name — `Refused`, `Stale`, `Unsupported`, `Unknown`,
22
+ * `Unauthorized`, `Denied` */
23
+ error: string
24
+ /** what was wrong, in the error's own words */
25
+ message: string
26
+ /** whatever else the error carried */
27
+ [detail: string]: unknown
28
+ }
29
+
30
+ /** A graph precondition conflict carries the value the caller can retry on. */
31
+ export let staleRefusal = (
32
+ code: number,
33
+ body: unknown,
34
+ ): body is Refusal & Pick<Stale, 'eid' | 'comp' | 'prop' | 'current'> =>
35
+ code == STATUS.Stale && (body as Partial<Refusal> | null)?.error == 'Stale'
36
+
37
+ /** The request could not be authenticated. Throw this from an
38
+ * {@link https://jsr.io/@yaks/api/doc/~/Authenticate | Authenticate} to answer
39
+ * a request with a 401. */
40
+ export class Unauthorized extends Error {
41
+ /** @param message what the caller is missing (default: `not authenticated`) */
42
+ constructor(message = 'not authenticated') {
43
+ super(message)
44
+ this.name = 'Unauthorized'
45
+ }
46
+ }
47
+
48
+ // What was thrown, as an error: a refusal another door answered, relayed as
49
+ // it was said, is the error it names, with what else it carried.
50
+ let errorOf = (err: unknown): Error => {
51
+ if (err instanceof Error) return err
52
+ if (
53
+ err && typeof err == 'object' &&
54
+ typeof (err as Refusal).error == 'string' &&
55
+ typeof (err as Refusal).message == 'string'
56
+ ) {
57
+ let { error, message, ...rest } = err as Refusal
58
+ return Object.assign(new Error(message), rest, { name: error })
59
+ }
60
+ return new Error(String(err))
61
+ }
62
+
63
+ /** An error as the body a client reads: its name as `error`, its message, and
64
+ * every other field it carries. A refusal relayed from another door is said
65
+ * as that door said it. */
66
+ export let refusal = (err: unknown): Refusal => {
67
+ let e = errorOf(err)
68
+ let out: Refusal = { error: e.name, message: e.message }
69
+ for (let [k, v] of Object.entries(e)) {
70
+ if (k != 'name' && k != 'message' && k != 'stack') out[k] = v
71
+ }
72
+ return out
73
+ }
74
+
75
+ /** What a host adds to the failures a door of its reports (`{store: 'x'}`):
76
+ * the door's own words for where they happened, beside `where`. */
77
+ export type Tags = Record<string, string>
78
+
79
+ /** A host's reporter ({@link faults}): a failure, where it was caught, and
80
+ * the tags the door that caught it was given (none: `{}`). */
81
+ export type Reporter = (err: unknown, where: string, tags: Tags) => void
82
+
83
+ // Where a server failure goes: the reporter its host installed last, else the
84
+ // console, so a failure met before any host installs one is still said.
85
+ let reporters: Reporter[] = []
86
+ let said = (err: unknown, where: string) =>
87
+ console.error(`${where} failed —`, err)
88
+
89
+ /** Report every server failure this package catches to `report`, with where
90
+ * it was caught and its door's tags: the host's own reporter, which tells its
91
+ * tracker. A failure answered to its caller and one with no caller at all (a
92
+ * socket's message, a subscription's refresh, a page body that did not build)
93
+ * go the same way. The newest installed is the one told; the function
94
+ * returned removes it. */
95
+ export let faults = (report: Reporter): () => void => {
96
+ reporters.push(report)
97
+ return () => {
98
+ let at = reporters.lastIndexOf(report)
99
+ if (at >= 0) reporters.splice(at, 1)
100
+ }
101
+ }
102
+
103
+ /** The header on an answer whose failure was reported where it was caught:
104
+ * a caller that relays the answer files it no second time. */
105
+ export { FILED }
106
+
107
+ /** Whether a host's reporter hears this package's failures ({@link faults}). */
108
+ export let reporting = (): boolean => reporters.length > 0
109
+
110
+ /** A server failure, reported with where it happened and its door's tags to
111
+ * the host's reporter ({@link faults}), or said on the console while none is
112
+ * installed; a refusal (below 500) is the caller's and says nothing. A
113
+ * refusal relayed from another door is judged and reported as the error it
114
+ * names. */
115
+ export let fault = (err: unknown, where: string, tags: Tags = {}): void => {
116
+ if (!(err instanceof Error)) err = errorOf(err)
117
+ if (status(err) < 500) return
118
+ let report = reporters.at(-1) ?? said
119
+ try {
120
+ report(err, where, tags)
121
+ } catch (why) {
122
+ said(err, where)
123
+ said(why, `reporting ${where}`)
124
+ }
125
+ }
126
+
127
+ // The requests a watch is answering (./request.ts `served`), each with the
128
+ // failure `refuse` answered it with: the watch reports that failure once, with
129
+ // its request. A failure answered where nothing watches is reported here.
130
+ let watched = new WeakMap<Request, unknown>()
131
+ export let watch = (request: Request): void =>
132
+ void watched.set(request, undefined)
133
+ export let cause = (request: Request): unknown => watched.get(request)
134
+
135
+ /** A JSON response. */
136
+ export let json = (body: unknown, code = 200): Response =>
137
+ new Response(stringify(body), {
138
+ status: code,
139
+ headers: { 'content-type': 'application/json' },
140
+ })
141
+
142
+ /** The seconds an error asks its caller to wait (`retry.after`, in
143
+ * milliseconds, as @yaks/effects reads it), for an answer's `retry-after`. */
144
+ export let waits = (err: unknown): number | null => {
145
+ let after = (err as { retry?: { after?: unknown } } | null)?.retry?.after
146
+ return typeof after == 'number' && after > 0 ? Math.ceil(after / 1000) : null
147
+ }
148
+
149
+ /** A thrown error as its response: the refusal body, at its HTTP status, with
150
+ * a `retry-after` when the error asks for a wait (`retry.after`). A
151
+ * server failure is reported once: by the watch the request is answered under
152
+ * (`served`), with its request, or else here ({@link fault}), with the method
153
+ * and path when a request is supplied, never the query string, headers or
154
+ * body, and the `tags` of the door that answered it, and its answer says so
155
+ * ({@link FILED}) while a host's reporter hears it. An expected client
156
+ * refusal is not reported at all. */
157
+ export let refuse = (
158
+ err: unknown,
159
+ request?: Request,
160
+ tags?: Tags,
161
+ ): Response => {
162
+ let code = status(err)
163
+ let answer = json(refusal(err), code)
164
+ let wait = waits(err)
165
+ if (wait != null) answer.headers.set('retry-after', String(wait))
166
+ if (request && watched.has(request)) {
167
+ if (code >= 500) watched.set(request, err)
168
+ } else {
169
+ fault(
170
+ err,
171
+ request
172
+ ? `${request.method} ${new URL(request.url).pathname}`
173
+ : 'request',
174
+ tags,
175
+ )
176
+ if (code >= 500 && reporting()) answer.headers.set(FILED, '1')
177
+ }
178
+ return answer
179
+ }
package/relay.js ADDED
@@ -0,0 +1,249 @@
1
+ // The relay: the values the server forwards without storing.
2
+ //
3
+ // A `sync: peers` component is somebody's cursor, caret or presence dot. The
4
+ // server is not where it belongs — it is only the one place that can see
5
+ // every subscriber, so it forwards. Nothing is written: no row, no journal
6
+ // line, no commit, and therefore no `effect` phase and no subscription
7
+ // running its query again. A relayed value is a message that happens to be
8
+ // shaped like a patch.
9
+ //
10
+ // What makes it more than a broadcast is the lifetime the component declares
11
+ // (@yaks/vocab `durable`). The relay holds one value per (entity, component),
12
+ // the one every client holds too, under the connection that last wrote it, so
13
+ // three things are possible that a plain broadcast cannot do:
14
+ //
15
+ // a subscriber that connects late is sent what is already there
16
+ // a connection that closes clears its connection-lifetime values; a timed
17
+ // value remains available for takeover until its own expiry
18
+ // a value with a duration clears itself, its timer restarted on each write
19
+ //
20
+ // A clear, disconnect or expiry sends the same `{comp: null}` bundle to
21
+ // the other connections when the value ends.
22
+ //
23
+ // A write from another connection takes a value over, so a close clears only
24
+ // what its connection said last. That is what lets a page move to a new
25
+ // connection: it says its values again there, and then the old connection's
26
+ // close, whenever the server hears it, clears none of them, and no answer
27
+ // hands the page back an older copy of its own (@yaks/sync saying.ts).
28
+ //
29
+ // The connection is a type parameter. This module never asks what one IS: the
30
+ // subscription registry keys by its `Sink`, and a test keys by a string.
31
+ import { comps } from "@yaks/graph/bundle";
32
+ import { durableOf, ms, syncOf } from "@yaks/vocab";
33
+ let clock = (fn, after)=>{
34
+ let t = setTimeout(fn, after);
35
+ return ()=>clearTimeout(t);
36
+ };
37
+ let KEY = ' ' // the one character a component name cannot hold
38
+ ;
39
+ let key = (eid, comp)=>eid + KEY + comp;
40
+ let split = (k)=>{
41
+ let at = k.indexOf(KEY);
42
+ return [
43
+ k.slice(0, at),
44
+ k.slice(at + 1)
45
+ ];
46
+ };
47
+ /** One bundle clearing a component — the same bundle a clear, a close and an
48
+ * expiry all produce. */ let cleared = (eid, comp)=>({
49
+ entity: {
50
+ eid
51
+ },
52
+ [comp]: null
53
+ });
54
+ /**
55
+ * A relay. `expire` is how a value that ran out of time reaches the
56
+ * subscribers — the registry passes its own broadcast function, so an expiry
57
+ * looks to a client exactly like the writer clearing the value.
58
+ */ export let relay = (vocab, expire, timer = clock)=>{
59
+ // key → the connection that said it last, and the value as it now stands:
60
+ // null when it was adopted after a lost memory, and only its key is known.
61
+ let held = new Map();
62
+ let byEntity = new Map();
63
+ // A reference kept by peers needs the same reverse lookup as a stored one.
64
+ let refs = new Map();
65
+ // conn → the keys it holds, in the order it first said them.
66
+ let saying = new Map();
67
+ // key → cancel. Separate because most values have no timer at all.
68
+ let timers = new Map();
69
+ let refKey = (comp, prop, target)=>JSON.stringify([
70
+ comp,
71
+ prop,
72
+ target
73
+ ]);
74
+ let index = (eid, comp, patch, add)=>{
75
+ for (let [prop, target] of Object.entries(patch)){
76
+ if (typeof target != 'string' || vocab.prop(comp, prop)?.category != 'ref') continue;
77
+ let k = refKey(comp, prop, target);
78
+ let ids = refs.get(k) ?? new Set();
79
+ if (add) ids.add(eid);
80
+ else ids.delete(eid);
81
+ if (ids.size) refs.set(k, ids);
82
+ else refs.delete(k);
83
+ }
84
+ };
85
+ let cancel = (k)=>{
86
+ timers.get(k)?.();
87
+ timers.delete(k);
88
+ };
89
+ let forget = (k)=>{
90
+ cancel(k);
91
+ let was = held.get(k);
92
+ if (was?.conn !== undefined) saying.get(was.conn)?.delete(k);
93
+ held.delete(k);
94
+ let [eid, comp] = split(k);
95
+ if (was?.patch) index(eid, comp, was.patch, false);
96
+ let keys = byEntity.get(eid);
97
+ keys?.delete(k);
98
+ if (!keys?.size) byEntity.delete(eid);
99
+ };
100
+ let hold = (conn, k, patch)=>{
101
+ let was = held.get(k);
102
+ if (was?.conn !== undefined && was.conn !== conn) {
103
+ saying.get(was.conn)?.delete(k);
104
+ }
105
+ let [eid, comp] = split(k);
106
+ if (was?.patch) index(eid, comp, was.patch, false);
107
+ let keys = byEntity.get(eid) ?? new Set();
108
+ keys.add(k);
109
+ byEntity.set(eid, keys);
110
+ held.set(k, {
111
+ conn,
112
+ patch
113
+ });
114
+ if (patch) index(eid, comp, patch, true);
115
+ let mine = saying.get(conn) ?? new Set();
116
+ saying.set(conn, mine);
117
+ mine.add(k);
118
+ };
119
+ let write = (conn, bundles)=>{
120
+ let out = [];
121
+ for (let b of bundles){
122
+ let eid = b.entity?.eid;
123
+ if (!eid) continue;
124
+ let sent = {
125
+ entity: {
126
+ eid
127
+ }
128
+ };
129
+ let said = false;
130
+ for (let [name, patch] of comps(b)){
131
+ if (syncOf(vocab, name) != 'peers') continue;
132
+ let k = key(eid, name);
133
+ said = true;
134
+ if (patch == null) {
135
+ forget(k);
136
+ sent[name] = null;
137
+ continue;
138
+ }
139
+ // A relayed value is a PATCH like any other: what is held is the
140
+ // merge onto the value as it stands, whoever said it, as every client
141
+ // merges it; what is forwarded is only what this write carried.
142
+ hold(conn, k, {
143
+ ...held.get(k)?.patch,
144
+ ...patch
145
+ });
146
+ sent[name] = patch;
147
+ // The timer restarts on every write: a cursor that keeps moving keeps
148
+ // its value alive, and one that stops is cleared after the declared
149
+ // duration.
150
+ cancel(k);
151
+ let span = ms(durableOf(vocab, name));
152
+ if (span == null) continue;
153
+ timers.set(k, timer(()=>{
154
+ forget(k);
155
+ expire([
156
+ cleared(eid, name)
157
+ ]);
158
+ }, span));
159
+ }
160
+ if (said) out.push(sent);
161
+ }
162
+ return out;
163
+ };
164
+ let values = (keys, mine, sees = ()=>true)=>{
165
+ let out = new Map();
166
+ for (let k of keys){
167
+ let value = held.get(k);
168
+ if (!value) continue;
169
+ let { conn, patch } = value;
170
+ if (mine !== undefined && mine === conn || patch == null) continue;
171
+ let [eid, comp] = split(k);
172
+ if (!sees(eid)) continue;
173
+ let b = out.get(eid) ?? {
174
+ entity: {
175
+ eid
176
+ }
177
+ };
178
+ b[comp] = patch;
179
+ out.set(eid, b);
180
+ }
181
+ return [
182
+ ...out.values()
183
+ ];
184
+ };
185
+ function* keysFor(ids) {
186
+ for (let eid of ids)yield* byEntity.get(eid) ?? [];
187
+ }
188
+ return {
189
+ write,
190
+ holds: (conn)=>[
191
+ ...saying.get(conn) ?? []
192
+ ],
193
+ adopt: (conn, keys)=>{
194
+ // Stored without values on purpose: this is what is left after the
195
+ // process forgot what it was holding, and clearing a component needs no
196
+ // value.
197
+ for (let k of keys)if (!held.has(k)) hold(conn, k, null);
198
+ },
199
+ snapshot: (mine, sees)=>values(held.keys(), mine, sees),
200
+ values: (ids)=>values(ids ? keysFor(ids) : held.keys()),
201
+ referencing: (comp, prop, targets)=>{
202
+ let ids = new Set();
203
+ for (let target of targets){
204
+ for (let eid of refs.get(refKey(comp, prop, target)) ?? []){
205
+ ids.add(eid);
206
+ }
207
+ }
208
+ return values(keysFor(ids));
209
+ },
210
+ drop: (conn)=>{
211
+ let mine = [
212
+ ...saying.get(conn) ?? []
213
+ ];
214
+ saying.delete(conn);
215
+ let out = [];
216
+ for (let k of mine){
217
+ let [, comp] = split(k);
218
+ // A duration owns its lifetime, not its writer's socket. Retain no
219
+ // reference to the closed connection while its existing timer runs.
220
+ if (ms(durableOf(vocab, comp)) != null && timers.has(k)) {
221
+ let value = held.get(k);
222
+ if (value) delete value.conn;
223
+ } else {
224
+ forget(k);
225
+ out.push(cleared(...split(k)));
226
+ }
227
+ }
228
+ return out;
229
+ },
230
+ close: ()=>{
231
+ for (let off of timers.values())off();
232
+ timers.clear();
233
+ held.clear();
234
+ byEntity.clear();
235
+ refs.clear();
236
+ saying.clear();
237
+ }
238
+ };
239
+ };
240
+ /** Every value one connection is holding, as one record per (entity,
241
+ * component) — {@link Relay.holds}'s keys, split back apart for a reader. */ export let holding = (r, conn)=>r.holds(conn).map((k)=>{
242
+ let [eid, comp] = split(k);
243
+ return {
244
+ eid,
245
+ comp,
246
+ patch: {}
247
+ };
248
+ });
249
+ //# sourceMappingURL=relay.js.map
package/relay.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay.js","sources":["./relay.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,2EAA2E;AAC3E,uEAAuE;AACvE,2EAA2E;AAC3E,uBAAuB;AACvB,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,8DAA8D;AAC9D,EAAE;AACF,kEAAkE;AAClE,4EAA4E;AAC5E,8DAA8D;AAC9D,6EAA6E;AAC7E,EAAE;AACF,wEAAwE;AACxE,6CAA6C;AAC7C,EAAE;AACF,6EAA6E;AAC7E,wEAAwE;AACxE,4EAA4E;AAC5E,0EAA0E;AAC1E,uEAAuE;AACvE,EAAE;AACF,8EAA8E;AAC9E,yEAAyE;AAGzE,SAAS,KAAK,kCAAuC;AACrD,SAAS,SAAS,EAAE,EAAE,EAAE,MAAM,2BAA4C;AAM1E,IAAI,QAAe,CAAC,IAAI;EACtB,IAAI,IAAI,WAAW,IAAI;EACvB,OAAO,IAAM,aAAa;AAC5B;AAsCA,IAAI,MAAM,IAAI,iDAAiD;;AAC/D,IAAI,MAAM,CAAC,KAAU,OAAiB,MAAM,MAAM;AAClD,IAAI,QAAQ,CAAC;EACX,IAAI,KAAK,EAAE,OAAO,CAAC;EACnB,OAAO;IAAC,EAAE,KAAK,CAAC,GAAG;IAAK,EAAE,KAAK,CAAC,KAAK;GAAG;AAC1C;AAEA;uBACuB,GACvB,IAAI,UAAU,CAAC,KAAU,OAAyB,CAAC;IACjD,QAAQ;MAAE;IAAI;IACd,CAAC,KAAK,EAAE;EACV,CAAC;AAED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