@yaks/workerd 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 (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +273 -2
  3. package/_dist/cache.d.ts +67 -0
  4. package/_dist/cache.d.ts.map +1 -0
  5. package/_dist/compose.d.ts +69 -0
  6. package/_dist/compose.d.ts.map +1 -0
  7. package/_dist/deferred.d.ts +10 -0
  8. package/_dist/deferred.d.ts.map +1 -0
  9. package/_dist/door.d.ts +36 -0
  10. package/_dist/door.d.ts.map +1 -0
  11. package/_dist/fetch.d.ts +27 -0
  12. package/_dist/fetch.d.ts.map +1 -0
  13. package/_dist/gen.d.ts +65 -0
  14. package/_dist/gen.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +53 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/plugin.d.ts +15 -0
  18. package/_dist/plugin.d.ts.map +1 -0
  19. package/_dist/purge.d.ts +104 -0
  20. package/_dist/purge.d.ts.map +1 -0
  21. package/_dist/rate.d.ts +65 -0
  22. package/_dist/rate.d.ts.map +1 -0
  23. package/_dist/stub.d.ts +20 -0
  24. package/_dist/stub.d.ts.map +1 -0
  25. package/_dist/upgrade.d.ts +25 -0
  26. package/_dist/upgrade.d.ts.map +1 -0
  27. package/_dist/version.d.ts +2 -0
  28. package/_dist/version.d.ts.map +1 -0
  29. package/_dist/worker.d.ts +40 -0
  30. package/_dist/worker.d.ts.map +1 -0
  31. package/cache.js +199 -0
  32. package/cache.js.map +1 -0
  33. package/cache.ts +254 -0
  34. package/compose.js +126 -0
  35. package/compose.js.map +1 -0
  36. package/compose.ts +236 -0
  37. package/deferred.js +39 -0
  38. package/deferred.js.map +1 -0
  39. package/deferred.ts +64 -0
  40. package/deno.json +1 -0
  41. package/door.js +64 -0
  42. package/door.js.map +1 -0
  43. package/door.ts +89 -0
  44. package/fetch.js +228 -0
  45. package/fetch.js.map +1 -0
  46. package/fetch.ts +231 -0
  47. package/gen.js +153 -0
  48. package/gen.js.map +1 -0
  49. package/gen.ts +189 -0
  50. package/mod.js +53 -0
  51. package/mod.js.map +1 -0
  52. package/mod.ts +69 -0
  53. package/package.json +52 -4
  54. package/plugin.js +16 -0
  55. package/plugin.js.map +1 -0
  56. package/plugin.ts +19 -0
  57. package/purge.js +200 -0
  58. package/purge.js.map +1 -0
  59. package/purge.ts +245 -0
  60. package/rate.js +84 -0
  61. package/rate.js.map +1 -0
  62. package/rate.ts +110 -0
  63. package/stub.js +23 -0
  64. package/stub.js.map +1 -0
  65. package/stub.ts +42 -0
  66. package/upgrade.js +82 -0
  67. package/upgrade.js.map +1 -0
  68. package/upgrade.ts +96 -0
  69. package/version.js +24 -0
  70. package/version.js.map +1 -0
  71. package/version.ts +30 -0
  72. package/worker.js +62 -0
  73. package/worker.js.map +1 -0
  74. package/worker.ts +87 -0
package/upgrade.ts ADDED
@@ -0,0 +1,96 @@
1
+ // The one step no web standard covers, in the one file that depends on a
2
+ // specific runtime. Everywhere else a socket is just a `WebSocket`; creating
3
+ // one from a request is runtime-specific, and Cloudflare's way is
4
+ // `WebSocketPair`: a Worker keeps one half and returns the other on a 101
5
+ // response.
6
+ //
7
+ // The global is looked up rather than imported, so this module loads and
8
+ // type-checks anywhere — outside Workers it throws when called, which is the
9
+ // right behaviour for a package named after the runtime it requires.
10
+
11
+ import type { Socket, Upgrade } from 'jsr:@yaks/api@0.2.36'
12
+
13
+ /** A Workers socket: the half a Worker keeps has to be accepted before it
14
+ * carries frames. */
15
+ type Frame = string | Uint8Array
16
+
17
+ export type Accepting = Socket<Frame> & {
18
+ /** start handling frames on this half of the pair */
19
+ accept: () => void
20
+ }
21
+
22
+ /** `new WebSocketPair()` — an object holding two sockets, client first. */
23
+ type Pair = new () => Record<string, Accepting>
24
+
25
+ // This runtime's `WebSocketPair`, or null if it has none.
26
+ let found = (): Pair | null => {
27
+ let host: unknown = globalThis
28
+ if (!host || typeof host != 'object' || !('WebSocketPair' in host)) {
29
+ return null
30
+ }
31
+ let make = host.WebSocketPair
32
+ // A constructor read off the global object: nothing types this for us.
33
+ return typeof make == 'function' ? make as Pair : null
34
+ }
35
+
36
+ // The 101 returns the client half. `webSocket` is Cloudflare's own addition to
37
+ // `ResponseInit` — no standard declares it, and the half this package keeps is
38
+ // typed here only by the few members it uses — so the type is asserted on this
39
+ // one line, and nowhere else.
40
+ let handing = (client: unknown): ResponseInit =>
41
+ ({ status: 101, webSocket: client }) as ResponseInit
42
+
43
+ /**
44
+ * Cloudflare's WebSocket upgrade, as an
45
+ * {@link https://jsr.io/@yaks/api/doc/~/Upgrade | Upgrade}: create a
46
+ * `WebSocketPair`, accept the server half, and answer 101 with the client
47
+ * half. Pass it to `api()` on a Worker, or let {@link worker} pass it for you.
48
+ *
49
+ * ```ts ignore
50
+ * import { api } from '@yaks/api'
51
+ * import { workerUpgrade } from '@yaks/workerd'
52
+ *
53
+ * let handler = api({ graph, upgrade: workerUpgrade })
54
+ * ```
55
+ *
56
+ * It throws outside the Workers runtime, where `WebSocketPair` does not exist.
57
+ */
58
+ export let workerUpgrade: Upgrade<Frame> = (_request) => {
59
+ let Pair = found()
60
+ if (!Pair) {
61
+ throw new Error(
62
+ '@yaks/workerd: no WebSocketPair here — this needs a Worker',
63
+ )
64
+ }
65
+ let [client, server] = Object.values(new Pair())
66
+ server.accept()
67
+ return { socket: server, response: new Response(null, handing(client)) }
68
+ }
69
+
70
+ /** The answer again under other headers, carrying its WebSocket if present. */
71
+ export let headed = (res: Response, headers: Headers): Response => {
72
+ let socket = (res as { webSocket?: unknown }).webSocket
73
+ if (res.status == 101 && !socket) return res
74
+ let out = new Response(res.body, {
75
+ status: res.status,
76
+ statusText: res.statusText,
77
+ headers,
78
+ ...socket ? { webSocket: socket } : {},
79
+ } as ResponseInit)
80
+ // A runtime with no socket of its own keeps it on the object.
81
+ if (socket && !(out as { webSocket?: unknown }).webSocket) {
82
+ Object.assign(out, { webSocket: socket })
83
+ }
84
+ return out
85
+ }
86
+
87
+ /** Forward the socket so the next HTTP hop can generate its own handshake.
88
+ * A container's outbound proxy appends its headers to the ones it gets. */
89
+ export let rehandshake = (response: Response): Response => {
90
+ if (response.status !== 101) return response
91
+ let headers = new Headers(response.headers)
92
+ headers.delete('upgrade')
93
+ headers.delete('connection')
94
+ headers.delete('sec-websocket-accept')
95
+ return headed(response, headers)
96
+ }
package/version.js ADDED
@@ -0,0 +1,24 @@
1
+ // The deploy a Worker is running, said at one path. It is a route of this
2
+ // package's own `./worker` facet (plugin.ts), so it answers before anything a
3
+ // later plugin loads: an old Durable Object or a broken router cannot name
4
+ // the deploy in its place.
5
+ /** The path a Worker says its deploy at. */ export let VERSION = '/_yak/version';
6
+ /** The route answering {@link VERSION} with `{<name>: <id>}`: `options.name`
7
+ * names the Worker (default `worker`) and `options.version` is its
8
+ * `[version_metadata]` binding, whose `id` changes with every deploy. */ export let version = (options)=>({
9
+ method: 'GET',
10
+ path: VERSION,
11
+ handle: (req)=>{
12
+ let name = typeof options.name == 'string' ? options.name : 'worker';
13
+ let id = options.version?.id ?? null;
14
+ return new Response(req.method == 'HEAD' ? null : JSON.stringify({
15
+ [name]: id
16
+ }), {
17
+ headers: {
18
+ 'content-type': 'application/json',
19
+ 'cache-control': 'no-store'
20
+ }
21
+ });
22
+ }
23
+ });
24
+ //# sourceMappingURL=version.js.map
package/version.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sources":["./version.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,2EAA2E;AAC3E,2BAA2B;AAI3B,0CAA0C,GAC1C,OAAO,IAAI,UAAU,gBAAe;AAEpC;;uEAEuE,GACvE,OAAO,IAAI,UAAU,CAAC,UAA4B,CAAC;IACjD,QAAQ;IACR,MAAM;IACN,QAAQ,CAAC;MACP,IAAI,OAAO,OAAO,QAAQ,IAAI,IAAI,WAAW,QAAQ,IAAI,GAAG;MAC5D,IAAI,KAAK,AAAC,QAAQ,OAAO,EAAkC,MAAM;MACjE,OAAO,IAAI,SACT,IAAI,MAAM,IAAI,SAAS,OAAO,KAAK,SAAS,CAAC;QAAE,CAAC,KAAK,EAAE;MAAG,IAC1D;QACE,SAAS;UACP,gBAAgB;UAChB,iBAAiB;QACnB;MACF;IAEJ;EACF,CAAC,EAAC"}
package/version.ts ADDED
@@ -0,0 +1,30 @@
1
+ // The deploy a Worker is running, said at one path. It is a route of this
2
+ // package's own `./worker` facet (plugin.ts), so it answers before anything a
3
+ // later plugin loads: an old Durable Object or a broken router cannot name
4
+ // the deploy in its place.
5
+ import type { Route } from 'jsr:@yaks/api@0.2.36'
6
+ import type { Options } from 'jsr:@yaks/host@0.2.36/config'
7
+
8
+ /** The path a Worker says its deploy at. */
9
+ export let VERSION = '/_yak/version'
10
+
11
+ /** The route answering {@link VERSION} with `{<name>: <id>}`: `options.name`
12
+ * names the Worker (default `worker`) and `options.version` is its
13
+ * `[version_metadata]` binding, whose `id` changes with every deploy. */
14
+ export let version = (options: Options): Route => ({
15
+ method: 'GET',
16
+ path: VERSION,
17
+ handle: (req) => {
18
+ let name = typeof options.name == 'string' ? options.name : 'worker'
19
+ let id = (options.version as { id?: string } | undefined)?.id ?? null
20
+ return new Response(
21
+ req.method == 'HEAD' ? null : JSON.stringify({ [name]: id }),
22
+ {
23
+ headers: {
24
+ 'content-type': 'application/json',
25
+ 'cache-control': 'no-store',
26
+ },
27
+ },
28
+ )
29
+ },
30
+ })
package/worker.js ADDED
@@ -0,0 +1,62 @@
1
+ // The Worker entrypoint. A Worker's module export is an object with a `fetch`,
2
+ // and its bindings — a database, a Durable Object namespace, a secret — arrive
3
+ // as an argument to that call rather than as an environment a module can read
4
+ // at import time. So the graph cannot be built when this file loads: it is
5
+ // built from `env` on the first request and kept for the isolate's life.
6
+ //
7
+ // That cache is why `api` is given only the bindings: building the api per
8
+ // request would create a fresh subscription registry each time, and the sockets
9
+ // already open would be listening to a registry nothing writes through any
10
+ // more.
11
+ import { api, refuse } from "@yaks/api";
12
+ import { workerUpgrade } from "./upgrade.js";
13
+ /**
14
+ * The Worker export for a graph: build the api from the Worker's bindings once
15
+ * per isolate, connect Cloudflare's socket upgrade to it, and serve every
16
+ * request from it.
17
+ *
18
+ * ```ts
19
+ * import type { Authenticate } from '@yaks/api'
20
+ * import type { Graph } from '@yaks/graph'
21
+ * import { worker } from '@yaks/workerd'
22
+ *
23
+ * declare let shopGraph: (db: unknown) => Graph
24
+ * declare let authenticate: Authenticate
25
+ *
26
+ * export default worker({
27
+ * api: (env) => ({ graph: shopGraph(env.DB), authenticate }),
28
+ * })
29
+ * ```
30
+ *
31
+ * The routes are [@yaks/api](https://jsr.io/@yaks/api)'s: `POST /apply`,
32
+ * `GET|POST /query`, and `/ws`. An `upgrade` given in the options is used as
33
+ * is; when none is given, {@link workerUpgrade} is used. A graph that lives in
34
+ * a Durable Object is served differently — the Worker {@link forward}s to the
35
+ * object, and the object is what calls this.
36
+ */ export let worker = (opts)=>{
37
+ // Kept as a value per env once built, never as the build's promise, which
38
+ // settles only in the request that made it (@yaks/fp `Scope`). A build
39
+ // that failed keeps nothing: a binding that was not there is worth trying
40
+ // again rather than answering 500 for the isolate's whole life.
41
+ let built = new WeakMap();
42
+ let handler = async (env)=>{
43
+ let held = built.get(env);
44
+ if (held) return held;
45
+ let made = api({
46
+ upgrade: workerUpgrade,
47
+ ...await opts.api(env)
48
+ });
49
+ if (!built.has(env)) built.set(env, made);
50
+ return built.get(env);
51
+ };
52
+ return {
53
+ fetch: async (request, env)=>{
54
+ try {
55
+ return await (await handler(env))(request);
56
+ } catch (err) {
57
+ return refuse(err);
58
+ }
59
+ }
60
+ };
61
+ };
62
+ //# sourceMappingURL=worker.js.map
package/worker.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sources":["./worker.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,8EAA8E;AAC9E,2EAA2E;AAC3E,yEAAyE;AACzE,EAAE;AACF,2EAA2E;AAC3E,gFAAgF;AAChF,2EAA2E;AAC3E,QAAQ;AAER,SAAS,GAAG,EAAqC,MAAM,yBAA8B;AACrF,SAAS,aAAa,uBAAsB;AA2B5C;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,IAAI,SAAS,CAAsB;EACxC,0EAA0E;EAC1E,uEAAuE;EACvE,0EAA0E;EAC1E,gEAAgE;EAChE,IAAI,QAAQ,IAAI;EAChB,IAAI,UAAU,OAAO;IACnB,IAAI,OAAO,MAAM,GAAG,CAAC;IACrB,IAAI,MAAM,OAAO;IACjB,IAAI,OAAO,IAAI;MAAE,SAAS;MAAe,GAAG,MAAM,KAAK,GAAG,CAAC,IAAI;IAAC;IAChE,IAAI,CAAC,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,CAAC,KAAK;IACpC,OAAO,MAAM,GAAG,CAAC;EACnB;EAEA,OAAO;IACL,OAAO,OAAO,SAAS;MACrB,IAAI;QACF,OAAO,MAAM,CAAC,MAAM,QAAQ,IAAI,EAAE;MACpC,EAAE,OAAO,KAAK;QACZ,OAAO,OAAO;MAChB;IACF;EACF;AACF,EAAC"}
package/worker.ts ADDED
@@ -0,0 +1,87 @@
1
+ // The Worker entrypoint. A Worker's module export is an object with a `fetch`,
2
+ // and its bindings — a database, a Durable Object namespace, a secret — arrive
3
+ // as an argument to that call rather than as an environment a module can read
4
+ // at import time. So the graph cannot be built when this file loads: it is
5
+ // built from `env` on the first request and kept for the isolate's life.
6
+ //
7
+ // That cache is why `api` is given only the bindings: building the api per
8
+ // request would create a fresh subscription registry each time, and the sockets
9
+ // already open would be listening to a registry nothing writes through any
10
+ // more.
11
+
12
+ import { api, type Handler, type Options as Api, refuse } from '@yaks/api'
13
+ import { workerUpgrade } from './upgrade.js'
14
+
15
+ /** A Worker's bindings, as this package reads them: whatever `wrangler.toml`
16
+ * declared, under the names it gave them. */
17
+ export type Env = Record<string, unknown>
18
+
19
+ /** The Workers execution context — the third argument to `fetch`, kept opaque
20
+ * because this package only passes it along. */
21
+ export type Context = {
22
+ /** keep the Worker alive until a promise settles */
23
+ waitUntil: (promise: Promise<unknown>) => void
24
+ }
25
+
26
+ /** A Cloudflare Worker's default export: its `fetch` entrypoint. */
27
+ export type Worker<E extends Env = Env> = {
28
+ /** answer one request, given this Worker's bindings */
29
+ fetch: (request: Request, env: E, ctx?: Context) => Promise<Response>
30
+ }
31
+
32
+ /** How a Worker is built: what the api is, for a given set of bindings. */
33
+ export type Options<E extends Env = Env> = {
34
+ /** the api this Worker serves — its graph, and the authentication callback
35
+ * that identifies the caller — built from the bindings the request arrived
36
+ * with */
37
+ api: (env: E) => Api | Promise<Api>
38
+ }
39
+
40
+ /**
41
+ * The Worker export for a graph: build the api from the Worker's bindings once
42
+ * per isolate, connect Cloudflare's socket upgrade to it, and serve every
43
+ * request from it.
44
+ *
45
+ * ```ts
46
+ * import type { Authenticate } from '@yaks/api'
47
+ * import type { Graph } from '@yaks/graph'
48
+ * import { worker } from '@yaks/workerd'
49
+ *
50
+ * declare let shopGraph: (db: unknown) => Graph
51
+ * declare let authenticate: Authenticate
52
+ *
53
+ * export default worker({
54
+ * api: (env) => ({ graph: shopGraph(env.DB), authenticate }),
55
+ * })
56
+ * ```
57
+ *
58
+ * The routes are [@yaks/api](https://jsr.io/@yaks/api)'s: `POST /apply`,
59
+ * `GET|POST /query`, and `/ws`. An `upgrade` given in the options is used as
60
+ * is; when none is given, {@link workerUpgrade} is used. A graph that lives in
61
+ * a Durable Object is served differently — the Worker {@link forward}s to the
62
+ * object, and the object is what calls this.
63
+ */
64
+ export let worker = <E extends Env = Env>(opts: Options<E>): Worker<E> => {
65
+ // Kept as a value per env once built, never as the build's promise, which
66
+ // settles only in the request that made it (@yaks/fp `Scope`). A build
67
+ // that failed keeps nothing: a binding that was not there is worth trying
68
+ // again rather than answering 500 for the isolate's whole life.
69
+ let built = new WeakMap<object, Handler>()
70
+ let handler = async (env: E) => {
71
+ let held = built.get(env)
72
+ if (held) return held
73
+ let made = api({ upgrade: workerUpgrade, ...await opts.api(env) })
74
+ if (!built.has(env)) built.set(env, made)
75
+ return built.get(env)!
76
+ }
77
+
78
+ return {
79
+ fetch: async (request, env) => {
80
+ try {
81
+ return await (await handler(env))(request)
82
+ } catch (err) {
83
+ return refuse(err)
84
+ }
85
+ },
86
+ }
87
+ }