@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/relay.ts ADDED
@@ -0,0 +1,284 @@
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
+
32
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
33
+ import { comps } from '@yaks/graph/bundle'
34
+ import { durableOf, ms, syncOf, type Vocab } from '@yaks/vocab'
35
+
36
+ /** How a timer is set, so a test can control the clock. Returns the function
37
+ * that cancels it. */
38
+ export type Timer = (fn: () => void, after: number) => () => void
39
+
40
+ let clock: Timer = (fn, after) => {
41
+ let t = setTimeout(fn, after)
42
+ return () => clearTimeout(t)
43
+ }
44
+
45
+ /** One value the relay is holding: which entity, which component, and the
46
+ * patch last sent for it. */
47
+ export type Holding = { eid: Eid; comp: string; patch: Comp }
48
+
49
+ /** The relay over one graph's vocabulary. */
50
+ export type Relay<C> = {
51
+ /**
52
+ * Relayed bundles from one connection: held under it, taking over any value
53
+ * another connection said of the same component, and returned as the
54
+ * bundles to forward. A clear clears the value whoever said it. Components
55
+ * that do not declare `sync: peers` are dropped — the relay forwards, it
56
+ * does not store, so a durable component sent here would silently vanish.
57
+ */
58
+ write: (conn: C, bundles: Bundle[]) => Bundle[]
59
+ /** What one connection is holding, as `"<eid> <comp>"` keys — small enough
60
+ * to store somewhere that survives losing this process's memory. */
61
+ holds: (conn: C) => string[]
62
+ /** Take those keys back, without their values, so a close can still clear
63
+ * them. A key another connection holds stays with it. */
64
+ adopt: (conn: C, keys: string[]) => void
65
+ /** What a subscriber connecting now should be sent: every value another
66
+ * connection holds, for the entities it can see. What it holds itself, it
67
+ * already has. */
68
+ snapshot: (mine: C, sees: (eid: Eid) => boolean) => Bundle[]
69
+ /** Values currently said by all connections, for query membership. Pass
70
+ * entity ids when only those rows can affect the answer. */
71
+ values: (ids?: Iterable<Eid>) => Bundle[]
72
+ /** Held rows whose reference names one of these entities. */
73
+ referencing: (comp: string, prop: string, targets: Iterable<Eid>) => Bundle[]
74
+ /** A connection went away: clear its connection-lifetime values. Timed
75
+ * values remain available until expiry or takeover. Return the clears. */
76
+ drop: (conn: C) => Bundle[]
77
+ /** Cancel every timer — for a shutdown, so nothing is left running. */
78
+ close: () => void
79
+ }
80
+
81
+ let KEY = ' ' // the one character a component name cannot hold
82
+ let key = (eid: Eid, comp: string) => eid + KEY + comp
83
+ let split = (k: string): [Eid, string] => {
84
+ let at = k.indexOf(KEY)
85
+ return [k.slice(0, at), k.slice(at + 1)]
86
+ }
87
+
88
+ /** One bundle clearing a component — the same bundle a clear, a close and an
89
+ * expiry all produce. */
90
+ let cleared = (eid: Eid, comp: string): Bundle => ({
91
+ entity: { eid },
92
+ [comp]: null,
93
+ })
94
+
95
+ /**
96
+ * A relay. `expire` is how a value that ran out of time reaches the
97
+ * subscribers — the registry passes its own broadcast function, so an expiry
98
+ * looks to a client exactly like the writer clearing the value.
99
+ */
100
+ export let relay = <C>(
101
+ vocab: Vocab,
102
+ expire: (bundles: Bundle[]) => void,
103
+ timer: Timer = clock,
104
+ ): Relay<C> => {
105
+ // key → the connection that said it last, and the value as it now stands:
106
+ // null when it was adopted after a lost memory, and only its key is known.
107
+ let held = new Map<string, { conn?: C; patch: Comp | null }>()
108
+ let byEntity = new Map<Eid, Set<string>>()
109
+ // A reference kept by peers needs the same reverse lookup as a stored one.
110
+ let refs = new Map<string, Set<Eid>>()
111
+ // conn → the keys it holds, in the order it first said them.
112
+ let saying = new Map<C, Set<string>>()
113
+ // key → cancel. Separate because most values have no timer at all.
114
+ let timers = new Map<string, () => void>()
115
+ let refKey = (comp: string, prop: string, target: Eid) =>
116
+ JSON.stringify([comp, prop, target])
117
+ let index = (eid: Eid, comp: string, patch: Comp, add: boolean) => {
118
+ for (let [prop, target] of Object.entries(patch)) {
119
+ if (
120
+ typeof target != 'string' ||
121
+ vocab.prop(comp, prop)?.category != 'ref'
122
+ ) continue
123
+ let k = refKey(comp, prop, target)
124
+ let ids = refs.get(k) ?? new Set<Eid>()
125
+ if (add) ids.add(eid)
126
+ else ids.delete(eid)
127
+ if (ids.size) refs.set(k, ids)
128
+ else refs.delete(k)
129
+ }
130
+ }
131
+
132
+ let cancel = (k: string) => {
133
+ timers.get(k)?.()
134
+ timers.delete(k)
135
+ }
136
+
137
+ let forget = (k: string) => {
138
+ cancel(k)
139
+ let was = held.get(k)
140
+ if (was?.conn !== undefined) saying.get(was.conn)?.delete(k)
141
+ held.delete(k)
142
+ let [eid, comp] = split(k)
143
+ if (was?.patch) index(eid, comp, was.patch, false)
144
+ let keys = byEntity.get(eid)
145
+ keys?.delete(k)
146
+ if (!keys?.size) byEntity.delete(eid)
147
+ }
148
+
149
+ let hold = (conn: C, k: string, patch: Comp | null) => {
150
+ let was = held.get(k)
151
+ if (was?.conn !== undefined && was.conn !== conn) {
152
+ saying.get(was.conn)?.delete(k)
153
+ }
154
+ let [eid, comp] = split(k)
155
+ if (was?.patch) index(eid, comp, was.patch, false)
156
+ let keys = byEntity.get(eid) ?? new Set<string>()
157
+ keys.add(k)
158
+ byEntity.set(eid, keys)
159
+ held.set(k, { conn, patch })
160
+ if (patch) index(eid, comp, patch, true)
161
+ let mine = saying.get(conn) ?? new Set<string>()
162
+ saying.set(conn, mine)
163
+ mine.add(k)
164
+ }
165
+
166
+ let write = (conn: C, bundles: Bundle[]): Bundle[] => {
167
+ let out: Bundle[] = []
168
+ for (let b of bundles) {
169
+ let eid = b.entity?.eid
170
+ if (!eid) continue
171
+ let sent: Bundle = { entity: { eid } }
172
+ let said = false
173
+ for (let [name, patch] of comps(b)) {
174
+ if (syncOf(vocab, name) != 'peers') continue
175
+ let k = key(eid, name)
176
+ said = true
177
+ if (patch == null) {
178
+ forget(k)
179
+ sent[name] = null
180
+ continue
181
+ }
182
+ // A relayed value is a PATCH like any other: what is held is the
183
+ // merge onto the value as it stands, whoever said it, as every client
184
+ // merges it; what is forwarded is only what this write carried.
185
+ hold(conn, k, { ...held.get(k)?.patch, ...patch })
186
+ sent[name] = patch
187
+ // The timer restarts on every write: a cursor that keeps moving keeps
188
+ // its value alive, and one that stops is cleared after the declared
189
+ // duration.
190
+ cancel(k)
191
+ let span = ms(durableOf(vocab, name))
192
+ if (span == null) continue
193
+ timers.set(
194
+ k,
195
+ timer(() => {
196
+ forget(k)
197
+ expire([cleared(eid, name)])
198
+ }, span),
199
+ )
200
+ }
201
+ if (said) out.push(sent)
202
+ }
203
+ return out
204
+ }
205
+
206
+ let values = (
207
+ keys: Iterable<string>,
208
+ mine?: C,
209
+ sees: (eid: Eid) => boolean = () => true,
210
+ ): Bundle[] => {
211
+ let out = new Map<Eid, Bundle>()
212
+ for (let k of keys) {
213
+ let value = held.get(k)
214
+ if (!value) continue
215
+ let { conn, patch } = value
216
+ if ((mine !== undefined && mine === conn) || patch == null) continue
217
+ let [eid, comp] = split(k)
218
+ if (!sees(eid)) continue
219
+ let b = out.get(eid) ?? { entity: { eid } }
220
+ b[comp] = patch
221
+ out.set(eid, b)
222
+ }
223
+ return [...out.values()]
224
+ }
225
+ function* keysFor(ids: Iterable<Eid>): Generator<string> {
226
+ for (let eid of ids) yield* byEntity.get(eid) ?? []
227
+ }
228
+
229
+ return {
230
+ write,
231
+ holds: (conn) => [...saying.get(conn) ?? []],
232
+ adopt: (conn, keys) => {
233
+ // Stored without values on purpose: this is what is left after the
234
+ // process forgot what it was holding, and clearing a component needs no
235
+ // value.
236
+ for (let k of keys) if (!held.has(k)) hold(conn, k, null)
237
+ },
238
+ snapshot: (mine, sees) => values(held.keys(), mine, sees),
239
+ values: (ids) => values(ids ? keysFor(ids) : held.keys()),
240
+ referencing: (comp, prop, targets) => {
241
+ let ids = new Set<Eid>()
242
+ for (let target of targets) {
243
+ for (let eid of refs.get(refKey(comp, prop, target)) ?? []) {
244
+ ids.add(eid)
245
+ }
246
+ }
247
+ return values(keysFor(ids))
248
+ },
249
+ drop: (conn) => {
250
+ let mine = [...saying.get(conn) ?? []]
251
+ saying.delete(conn)
252
+ let out: Bundle[] = []
253
+ for (let k of mine) {
254
+ let [, comp] = split(k)
255
+ // A duration owns its lifetime, not its writer's socket. Retain no
256
+ // reference to the closed connection while its existing timer runs.
257
+ if (ms(durableOf(vocab, comp)) != null && timers.has(k)) {
258
+ let value = held.get(k)
259
+ if (value) delete value.conn
260
+ } else {
261
+ forget(k)
262
+ out.push(cleared(...split(k)))
263
+ }
264
+ }
265
+ return out
266
+ },
267
+ close: () => {
268
+ for (let off of timers.values()) off()
269
+ timers.clear()
270
+ held.clear()
271
+ byEntity.clear()
272
+ refs.clear()
273
+ saying.clear()
274
+ },
275
+ }
276
+ }
277
+
278
+ /** Every value one connection is holding, as one record per (entity,
279
+ * component) — {@link Relay.holds}'s keys, split back apart for a reader. */
280
+ export let holding = <C>(r: Relay<C>, conn: C): Holding[] =>
281
+ r.holds(conn).map((k) => {
282
+ let [eid, comp] = split(k)
283
+ return { eid, comp, patch: {} }
284
+ })
package/request.js ADDED
@@ -0,0 +1,218 @@
1
+ // An HTTP request as an entity, `request{method, url, route, status, ms,
2
+ // agent}` (./vocab.json), and the one place an answer is watched for breaking.
3
+ //
4
+ // The server that answered is the only one that knows how it answered, so it
5
+ // is the writer, and it writes only a request that broke (D-45640): an answer
6
+ // at 500 or over, whether a handler threw it or returned it. The entity's eid
7
+ // is a fresh uuid, and the caller is answered with the same id in
8
+ // `x-request-id`, so the person holding a failed answer and the record of it
9
+ // name one thing.
10
+ //
11
+ // Where the bundle goes is not this package's word. {@link served} hands it to
12
+ // the `report` its host supplies, with the error when one was thrown or
13
+ // `refuse` answered one; a host that supplies none has the failure go where
14
+ // every other failure here goes (./refuse.ts `fault`).
15
+ import { status } from "@yaks/graph/errors";
16
+ import { during, link, parent, peek, unlink } from "@yaks/trace";
17
+ import { cause, fault, FILED, json, refusal, reporting, watch } from "./refuse.js";
18
+ import { receive } from "./requests.js";
19
+ // The browsers first, since each also says `Safari` and `Mozilla`; Edge and
20
+ // Opera before Chrome, whose token they carry too.
21
+ let BROWSERS = [
22
+ [
23
+ /Edg(?:e|A|iOS)?\/(\d+)/,
24
+ 'Edge'
25
+ ],
26
+ [
27
+ /OPR\/(\d+)/,
28
+ 'Opera'
29
+ ],
30
+ [
31
+ /(?:Chrome|CriOS)\/(\d+)/,
32
+ 'Chrome'
33
+ ],
34
+ [
35
+ /(?:Firefox|FxiOS)\/(\d+)/,
36
+ 'Firefox'
37
+ ],
38
+ [
39
+ /Version\/(\d+).*Safari\//,
40
+ 'Safari'
41
+ ]
42
+ ];
43
+ // iOS and Android before the desktops whose names their agents also carry.
44
+ let SYSTEMS = [
45
+ [
46
+ /iPhone|iPad|iPod/,
47
+ 'iOS'
48
+ ],
49
+ [
50
+ /Android/,
51
+ 'Android'
52
+ ],
53
+ [
54
+ /CrOS/,
55
+ 'ChromeOS'
56
+ ],
57
+ [
58
+ /Macintosh|Mac OS X/,
59
+ 'macOS'
60
+ ],
61
+ [
62
+ /Windows/,
63
+ 'Windows'
64
+ ],
65
+ [
66
+ /Linux/,
67
+ 'Linux'
68
+ ]
69
+ ];
70
+ /**
71
+ * A `User-Agent` reduced to what a person reading a failure wants: the
72
+ * browser, its major version and the operating system. Anything else is its
73
+ * first product token.
74
+ *
75
+ * ```ts
76
+ * import { assertEquals } from '@std/assert'
77
+ * import { agent } from '@yaks/api'
78
+ *
79
+ * assertEquals(
80
+ * agent(
81
+ * 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
82
+ * '(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
83
+ * ),
84
+ * 'Chrome 141 on macOS',
85
+ * )
86
+ * assertEquals(
87
+ * agent(
88
+ * 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) ' +
89
+ * 'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 ' +
90
+ * 'Mobile/15E148 Safari/604.1',
91
+ * ),
92
+ * 'Safari 18 on iOS',
93
+ * )
94
+ * assertEquals(agent('curl/8.5.0'), 'curl 8.5.0')
95
+ * ```
96
+ */ export let agent = (ua)=>{
97
+ let os = SYSTEMS.find(([re])=>re.test(ua))?.[1];
98
+ for (let [re, name] of BROWSERS){
99
+ let m = ua.match(re);
100
+ if (m) return os ? `${name} ${m[1]} on ${os}` : `${name} ${m[1]}`;
101
+ }
102
+ let m = ua.match(/^([^\s/]+)\/(\S+)/);
103
+ return m ? `${m[1]} ${m[2]}` : ua.slice(0, 64);
104
+ };
105
+ /**
106
+ * The `request` bundle for one answered request, under the id its caller was
107
+ * answered with. The address keeps no query string.
108
+ *
109
+ * ```ts
110
+ * import { assertEquals } from '@std/assert'
111
+ * import { requested } from '@yaks/api'
112
+ *
113
+ * let r = new Request('https://shop.test/blob/ab?token=x', { method: 'PUT' })
114
+ * assertEquals(requested('1f0c', r, { status: 503, ms: 12, route: '/blob/*' }), {
115
+ * entity: { eid: '1f0c' },
116
+ * request: {
117
+ * method: 'PUT',
118
+ * url: 'https://shop.test/blob/ab',
119
+ * route: '/blob/*',
120
+ * status: 503,
121
+ * ms: 12,
122
+ * },
123
+ * })
124
+ * ```
125
+ */ export let requested = (id, request, a)=>{
126
+ let url = new URL(request.url);
127
+ let ua = request.headers.get('user-agent');
128
+ return {
129
+ entity: {
130
+ eid: id
131
+ },
132
+ request: {
133
+ method: request.method,
134
+ url: url.origin + (a.redact ? a.route ?? '/' : url.pathname),
135
+ ...a.route ? {
136
+ route: a.route
137
+ } : {},
138
+ status: a.status,
139
+ ms: a.ms,
140
+ ...ua ? {
141
+ agent: agent(ua)
142
+ } : {}
143
+ }
144
+ };
145
+ };
146
+ // The report a host that supplied none gets: a fault, where it names the id
147
+ // its caller holds, with the door's tags. An answer at 500 that no error
148
+ // explains is one too.
149
+ let saying = (tags = {})=>(b, err)=>{
150
+ let r = b.request;
151
+ let where = `${r.method} ${new URL(r.url).pathname} (request ${b.entity.eid})`;
152
+ fault(err === undefined ? `answered ${r.status}` : err, where, tags);
153
+ };
154
+ /**
155
+ * `handle`, watched. Each answer is timed; one at 500 or over, thrown or
156
+ * returned, is answered with an `x-request-id` and reported as a `request`
157
+ * bundle under that id, with the error thrown or the one `refuse` answered.
158
+ * A thrown error is answered as its refusal body. An answer that already
159
+ * carries an `x-request-id` was reported by whoever answered it, so a watched
160
+ * handler inside another is reported once; one reported to a host's reporter
161
+ * says so to its caller ({@link FILED}).
162
+ */ export let served = (handle, o = {})=>async (request)=>{
163
+ watch(request);
164
+ let c = o.graph && peek(o.graph);
165
+ // Nested served handlers share this request's locally trusted parent.
166
+ let span = c && !parent(o.graph, request) ? c.begin({
167
+ kind: 'request',
168
+ name: o.route?.(request) ?? 'http',
169
+ package: '@yaks/api'
170
+ }) : undefined;
171
+ if (span) link(o.graph, request, span.id);
172
+ let began = Date.now();
173
+ // The host's context carrier keeps this request local across awaits, so
174
+ // plugin routes and graph reads without an explicit request parent still
175
+ // belong to the HTTP tree. Nested served handlers reuse the same span.
176
+ let { answer, err } = await during(span, async ()=>{
177
+ let err;
178
+ let answer;
179
+ try {
180
+ answer = await receive(request, ()=>handle(request));
181
+ } catch (e) {
182
+ err = e;
183
+ answer = json(refusal(e), status(e));
184
+ }
185
+ span?.end({
186
+ outcome: answer.status >= 500 ? 'error' : answer.status >= 400 ? 'refused' : 'ok',
187
+ counts: {
188
+ status: answer.status
189
+ }
190
+ });
191
+ return {
192
+ answer,
193
+ err
194
+ };
195
+ });
196
+ if (span) unlink(o.graph, request);
197
+ if (answer.status < 500 || answer.headers.has('x-request-id')) {
198
+ return answer;
199
+ }
200
+ let id = crypto.randomUUID();
201
+ let b = requested(id, request, {
202
+ status: answer.status,
203
+ ms: Date.now() - began,
204
+ route: o.route?.(request),
205
+ redact: o.redact?.(request)
206
+ });
207
+ try {
208
+ ;
209
+ (o.report ?? saying(o.tags?.()))(b, err ?? cause(request));
210
+ } catch (why) {
211
+ fault(why, `report ${id}`);
212
+ }
213
+ let out = new Response(answer.body, answer);
214
+ out.headers.set('x-request-id', id);
215
+ if (o.report || reporting()) out.headers.set(FILED, '1');
216
+ return out;
217
+ };
218
+ //# sourceMappingURL=request.js.map
package/request.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sources":["./request.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,+EAA+E;AAC/E,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,kEAAkE;AAClE,6EAA6E;AAC7E,kBAAkB;AAClB,EAAE;AACF,+EAA+E;AAC/E,wEAAwE;AACxE,4EAA4E;AAC5E,uDAAuD;AAGvD,SAAS,MAAM,kCAAuC;AACtD,SAAS,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,2BAAgC;AAC3E,SACE,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,EACJ,OAAO,EACP,SAAS,EAET,KAAK,sBACa;AAEpB,SAAS,OAAO,wBAAuB;AAmBvC,4EAA4E;AAC5E,mDAAmD;AACnD,IAAI,WAA+B;EACjC;IAAC;IAA0B;GAAO;EAClC;IAAC;IAAc;GAAQ;EACvB;IAAC;IAA2B;GAAS;EACrC;IAAC;IAA4B;GAAU;EACvC;IAAC;IAA4B;GAAS;CACvC;AAED,2EAA2E;AAC3E,IAAI,UAA8B;EACh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