@plitzi/sdk-server 0.38.23 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/README.md +55 -9
  3. package/dist/actions.d.ts +4 -1
  4. package/dist/actions.js +3 -2
  5. package/dist/auth.d.ts +2 -2
  6. package/dist/auth.js +5 -4
  7. package/dist/core/auth/api/accounts.d.ts +11 -0
  8. package/dist/core/auth/api/accounts.js +175 -0
  9. package/dist/core/auth/api/admin.d.ts +41 -0
  10. package/dist/core/auth/api/admin.js +146 -0
  11. package/dist/core/auth/api/context.d.ts +119 -0
  12. package/dist/core/auth/api/context.js +262 -0
  13. package/dist/core/auth/api/factors.d.ts +31 -0
  14. package/dist/core/auth/api/factors.js +209 -0
  15. package/dist/core/auth/api/index.d.ts +94 -0
  16. package/dist/core/auth/api/index.js +43 -0
  17. package/dist/core/auth/api/profile.d.ts +43 -0
  18. package/dist/core/auth/api/profile.js +243 -0
  19. package/dist/core/auth/api/session.d.ts +62 -0
  20. package/dist/core/auth/api/session.js +312 -0
  21. package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
  22. package/dist/core/auth/api/values.d.ts +67 -0
  23. package/dist/core/auth/api/values.js +90 -0
  24. package/dist/core/auth/createAuth.d.ts +49 -39
  25. package/dist/core/auth/createAuth.js +21 -1
  26. package/dist/core/auth/oauth/client.d.ts +2 -2
  27. package/dist/core/auth/oauth/client.js +6 -1
  28. package/dist/core/auth/oauth/index.d.ts +30 -7
  29. package/dist/core/auth/oauth/index.js +33 -14
  30. package/dist/core/auth/oauth/providers/github.js +1 -1
  31. package/dist/core/auth/oauth/providers/google.js +1 -1
  32. package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
  33. package/dist/core/auth/oauth/providers/oidc.js +197 -0
  34. package/dist/core/auth/oauth/state.d.ts +2 -0
  35. package/dist/core/auth/oauth/state.js +2 -0
  36. package/dist/core/auth/oauth/types.d.ts +21 -3
  37. package/dist/core/auth/oauth/types.js +4 -1
  38. package/dist/core/auth/routes.js +1 -1
  39. package/dist/core/auth/tokens.d.ts +3 -1
  40. package/dist/core/auth/tokens.js +2 -1
  41. package/dist/core/configSeam.d.ts +0 -4
  42. package/dist/core/configSeam.js +12 -1
  43. package/dist/core/createServer.js +16 -4
  44. package/dist/core/freePort.d.ts +10 -0
  45. package/dist/core/freePort.js +39 -1
  46. package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
  47. package/dist/core/handlers/socialRouteHandlers.js +46 -12
  48. package/dist/core/health.d.ts +1 -0
  49. package/dist/core/health.js +2 -1
  50. package/dist/core/http/stages/authRoutes.d.ts +6 -0
  51. package/dist/core/http/stages/authRoutes.js +42 -1
  52. package/dist/core/http/stages/images.js +5 -3
  53. package/dist/core/http/stages/livePages.js +1 -1
  54. package/dist/core/server/fleet/relay.js +9 -1
  55. package/dist/core/server/fleet/stores.d.ts +7 -0
  56. package/dist/core/server/fleet/stores.js +15 -2
  57. package/dist/core/server/pageServer.js +5 -1
  58. package/dist/core/services/realtime.js +4 -2
  59. package/dist/core/services/registry.js +7 -1
  60. package/dist/core/services/robotsTxt.d.ts +16 -0
  61. package/dist/core/services/robotsTxt.js +50 -0
  62. package/dist/core/services/servedSpace.d.ts +8 -0
  63. package/dist/core/services/servedSpace.js +16 -0
  64. package/dist/core/services/sitemapXml.d.ts +7 -0
  65. package/dist/core/services/sitemapXml.js +37 -0
  66. package/dist/functions-api.d.ts +75 -2
  67. package/dist/helpers/fileStore.d.ts +60 -0
  68. package/dist/helpers/fileStore.js +127 -0
  69. package/dist/helpers/outboundGuard.d.ts +32 -3
  70. package/dist/helpers/outboundGuard.js +50 -5
  71. package/dist/hosts/project/agentRuns.d.ts +24 -0
  72. package/dist/hosts/project/agentRuns.js +107 -0
  73. package/dist/hosts/project/laterAsks.d.ts +41 -0
  74. package/dist/hosts/project/laterAsks.js +117 -0
  75. package/dist/hosts/project/plugins.js +11 -4
  76. package/dist/hosts/project/serveProject.d.ts +11 -3
  77. package/dist/hosts/project/serveProject.js +94 -36
  78. package/dist/hosts/project/spaceFailure.d.ts +4 -0
  79. package/dist/hosts/project/spaceFailure.js +10 -0
  80. package/dist/hosts/project/watchSpace.d.ts +5 -5
  81. package/dist/hosts/project/watchSpace.js +15 -6
  82. package/dist/index.js +2 -2
  83. package/dist/kernel.js +1 -1
  84. package/dist/modules/actions/connectorWrite.js +3 -1
  85. package/dist/modules/actions/index.js +1 -1
  86. package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
  87. package/dist/modules/actions/jobs/fileQueue.js +72 -0
  88. package/dist/modules/actions/jobs/index.js +3 -3
  89. package/dist/modules/actions/jobs/memoryQueue.js +6 -215
  90. package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
  91. package/dist/modules/actions/jobs/queueDocument.js +22 -0
  92. package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
  93. package/dist/modules/actions/jobs/queueRules.js +270 -0
  94. package/dist/modules/actions/moduleFor.js +2 -0
  95. package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
  96. package/dist/modules/actions/runtime/fileKv.js +12 -98
  97. package/dist/modules/actions/runtime/guards.d.ts +19 -1
  98. package/dist/modules/actions/runtime/guards.js +10 -1
  99. package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
  100. package/dist/modules/actions/runtime/kvChange.js +23 -1
  101. package/dist/modules/actions/runtime/kvList.d.ts +4 -0
  102. package/dist/modules/actions/runtime/kvList.js +5 -1
  103. package/dist/modules/actions/runtime/kvStore.js +15 -1
  104. package/dist/modules/actions/runtime/namespaceKv.js +2 -0
  105. package/dist/modules/actions/runtime/renderResolver.js +31 -5
  106. package/dist/modules/actions/runtime/runAction.js +16 -6
  107. package/dist/modules/actions/runtime/scope.js +11 -0
  108. package/dist/modules/actions/runtime/taskContext.js +11 -32
  109. package/dist/modules/actions/tasks/auth.js +2 -0
  110. package/dist/modules/actions/tasks/connector.js +6 -2
  111. package/dist/modules/actions/tasks/flow.js +5 -0
  112. package/dist/modules/actions/tasks/http.js +2 -1
  113. package/dist/modules/actions/tasks/kv.js +5 -0
  114. package/dist/modules/actions/tasks/list.js +11 -2
  115. package/dist/modules/actions/tasks/transform.js +2 -0
  116. package/dist/modules/actions/transport/callHandler.js +25 -4
  117. package/dist/modules/actions/types.d.ts +46 -1
  118. package/dist/modules/connectors/engine.d.ts +7 -2
  119. package/dist/modules/connectors/engine.js +4 -4
  120. package/dist/modules/connectors/resolver.d.ts +2 -1
  121. package/dist/modules/connectors/resolver.js +3 -2
  122. package/dist/modules/functions/build.d.ts +7 -2
  123. package/dist/modules/functions/build.js +90 -6
  124. package/dist/modules/functions/capabilities.js +21 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +45 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +39 -0
  129. package/dist/modules/functions/load.d.ts +1 -1
  130. package/dist/modules/functions/load.js +2 -2
  131. package/dist/modules/functions/manifest.js +7 -1
  132. package/dist/modules/functions/oauth.d.ts +3 -1
  133. package/dist/modules/functions/oauth.js +20 -7
  134. package/dist/modules/functions/protocol.d.ts +9 -0
  135. package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
  136. package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
  137. package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
  138. package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
  139. package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
  140. package/dist/modules/functions/sandbox/guest/events.js +143 -0
  141. package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
  142. package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
  143. package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
  144. package/dist/modules/functions/sandbox/guest/index.js +130 -0
  145. package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
  146. package/dist/modules/functions/sandbox/isolate.js +20 -6
  147. package/dist/modules/functions/space.js +2 -8
  148. package/dist/modules/images/imageProxy.d.ts +3 -2
  149. package/dist/modules/images/imageProxy.js +2 -2
  150. package/dist/modules/mongo/jobQueue.js +0 -19
  151. package/dist/modules/mysql/accounts.js +12 -5
  152. package/dist/modules/mysql/jobs/index.d.ts +1 -1
  153. package/dist/modules/mysql/jobs/schema.d.ts +0 -6
  154. package/dist/modules/mysql/jobs/schema.js +2 -46
  155. package/dist/modules/mysql/schema.js +26 -1
  156. package/dist/modules/mysql/sessions.js +2 -1
  157. package/dist/modules/realtime/handlers.d.ts +9 -4
  158. package/dist/modules/realtime/handlers.js +20 -3
  159. package/dist/modules/realtime/hub.d.ts +4 -2
  160. package/dist/modules/realtime/hub.js +36 -4
  161. package/dist/modules/realtime/index.d.ts +14 -0
  162. package/dist/modules/realtime/index.js +14 -1
  163. package/dist/modules/realtime/presence.d.ts +33 -0
  164. package/dist/modules/realtime/presence.js +56 -0
  165. package/dist/modules/realtime/socket.d.ts +3 -1
  166. package/dist/modules/realtime/socket.js +2 -2
  167. package/dist/modules/rsc/connectorRscData.d.ts +6 -1
  168. package/dist/modules/rsc/connectorRscData.js +27 -6
  169. package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
  170. package/dist/modules/rsc/externalQueryReader.js +43 -0
  171. package/dist/modules/rsc/handler.js +1 -1
  172. package/dist/modules/rsc/resolveRscData.d.ts +11 -1
  173. package/dist/modules/rsc/resolveRscData.js +86 -16
  174. package/dist/modules/runtime/inside.js +1 -1
  175. package/dist/modules/runtime/runner.js +2 -1
  176. package/dist/modules/sqlite/jobQueue.d.ts +35 -0
  177. package/dist/modules/sqlite/jobQueue.js +56 -0
  178. package/dist/modules/sqlite/kv.d.ts +1 -1
  179. package/dist/modules/sqlite/kv.js +2 -10
  180. package/dist/modules/sqlite/open.d.ts +3 -0
  181. package/dist/modules/sqlite/open.js +13 -0
  182. package/dist/modules/ssr/Component.d.ts +5 -1
  183. package/dist/modules/ssr/Component.js +3 -1
  184. package/dist/modules/ssr/applySSRResult.d.ts +8 -1
  185. package/dist/modules/ssr/applySSRResult.js +23 -3
  186. package/dist/modules/ssr/handler.js +30 -5
  187. package/dist/modules/ssr/prepareRender.js +27 -5
  188. package/dist/modules/ssr/preview.d.ts +2 -0
  189. package/dist/modules/ssr/preview.js +6 -3
  190. package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
  191. package/dist/modules/ssr/registerExternalPlugins.js +2 -2
  192. package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
  193. package/dist/modules/ssr/resolvePageSeo.js +13 -2
  194. package/dist/modules/ssr/streamBody.js +2 -2
  195. package/dist/modules/ssr/views/template.ejs +21 -17
  196. package/dist/mysql.d.ts +1 -1
  197. package/dist/mysql.js +2 -2
  198. package/dist/plugins/manager.d.ts +5 -0
  199. package/dist/plugins/manager.js +9 -0
  200. package/dist/sqlite.d.ts +8 -1
  201. package/dist/sqlite.js +3 -1
  202. package/package.json +5 -5
  203. package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
  204. package/skills/plitzi-authoring/SKILL.md +4 -2
  205. package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
  206. package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
  207. package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
  208. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
  209. package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
  210. package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
  211. package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
  212. package/skills/plitzi-authoring/reference/accessibility.md +7 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
  215. package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
  216. package/skills/plitzi-authoring/reference/components.md +4 -1
  217. package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
  218. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  219. package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
  220. package/skills/plitzi-authoring/reference/flows.md +20 -8
  221. package/skills/plitzi-authoring/reference/kept-state.md +8 -0
  222. package/skills/plitzi-authoring/reference/layouts.md +18 -2
  223. package/skills/plitzi-authoring/reference/lists.md +20 -4
  224. package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
  225. package/skills/plitzi-authoring/reference/plugins.md +13 -2
  226. package/skills/plitzi-authoring/reference/realtime.md +8 -5
  227. package/skills/plitzi-authoring/reference/structure.md +17 -1
  228. package/skills/plitzi-authoring/reference/templates.md +11 -3
  229. package/skills/plitzi-authoring/reference/testing.md +82 -5
  230. package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
  231. package/skills/plitzi-authoring/reference/validation.md +1 -1
  232. package/dist/core/auth/api.js +0 -1323
  233. package/dist/modules/functions/sandbox/guest.js +0 -662
@@ -1,662 +0,0 @@
1
- //#region src/modules/functions/sandbox/guest.ts
2
- /**
3
- * The runtime a space's code finds in an isolate: the web APIs a bare V8 lacks (`Headers`, `Request`, `Response`,
4
- * `TextEncoder`, `AbortSignal`, timers, `crypto`) and the `ctx` its functions are handed.
5
- *
6
- * It is installed by PRINTING this function into the isolate (`installGuest.toString()`), after the prelude that brings
7
- * `URL`, `atob`, `structuredClone` and `DOMException`. So it may use nothing from outside its own body — no import,
8
- * no helper beside it — and all it has of the runner is `host`, and the functions in `shared`. Streams are not
9
- * provided: a body is text or bytes.
10
- */
11
- var installGuest = (scope, host, shared) => {
12
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13
- /**
14
- * A refusal: what the code threw to tell whoever asked — a wrong password, a full board — rather than a fault. It is
15
- * `ActionRefusal` from `@plitzi/sdk-server/functions`, known here by its name: the bundle carries its own copy of the
16
- * class, printed from the platform's (`build.ts`).
17
- */
18
- const REFUSAL = "ActionRefusal";
19
- const isRefusal = (error) => error instanceof Error && error.name === REFUSAL;
20
- const refusal = (message, code) => Object.assign(new Error(message), { name: REFUSAL }, code === void 0 ? {} : { code });
21
- const encodeUtf8 = (text) => {
22
- const out = [];
23
- for (const char of text) {
24
- let code = char.codePointAt(0) ?? 0;
25
- if (code >= 55296 && code <= 57343) code = 65533;
26
- if (code < 128) out.push(code);
27
- else if (code < 2048) out.push(192 | code >> 6, 128 | code & 63);
28
- else if (code < 65536) out.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
29
- else out.push(240 | code >> 18, 128 | code >> 12 & 63, 128 | code >> 6 & 63, 128 | code & 63);
30
- }
31
- return new Uint8Array(out);
32
- };
33
- /** UTF-8, with U+FFFD for every byte that does not belong to a well-formed sequence — what a web `TextDecoder` does. */
34
- const decodeUtf8 = (bytes) => {
35
- const points = [];
36
- let text = "";
37
- let index = 0;
38
- const continuation = (at) => at < bytes.length && ((bytes[at] ?? 0) & 192) === 128;
39
- while (index < bytes.length) {
40
- const lead = bytes[index] ?? 0;
41
- const length = lead < 128 ? 1 : lead >= 194 && lead < 224 ? 2 : lead >= 224 && lead < 240 ? 3 : lead >= 240 && lead < 245 ? 4 : 0;
42
- let code = 65533;
43
- let used = 1;
44
- if (length === 1) code = lead;
45
- else if (length > 1) {
46
- let valid = true;
47
- let value = lead & 255 >> length + 1;
48
- for (let offset = 1; offset < length; offset++) {
49
- if (!continuation(index + offset)) {
50
- valid = false;
51
- used = offset;
52
- break;
53
- }
54
- value = value << 6 | (bytes[index + offset] ?? 0) & 63;
55
- }
56
- if (valid && value >= (length === 3 ? 2048 : length === 4 ? 65536 : 128) && value <= 1114111 && (value < 55296 || value > 57343)) {
57
- code = value;
58
- used = length;
59
- } else if (valid) used = 1;
60
- }
61
- points.push(code);
62
- index += used;
63
- if (points.length >= 4096) {
64
- text += String.fromCodePoint(...points);
65
- points.length = 0;
66
- }
67
- }
68
- return text + String.fromCodePoint(...points);
69
- };
70
- const bytesToBase64 = (bytes) => {
71
- let binary = "";
72
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
73
- return btoa(binary);
74
- };
75
- const base64ToBytes = (base64) => {
76
- const binary = atob(base64);
77
- const bytes = new Uint8Array(binary.length);
78
- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
79
- return bytes;
80
- };
81
- const copyBytes = (view) => {
82
- const source = view instanceof ArrayBuffer ? new Uint8Array(view) : new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
83
- const bytes = new Uint8Array(source.length);
84
- bytes.set(source);
85
- return bytes;
86
- };
87
- class GuestTextEncoder {
88
- encoding = "utf-8";
89
- encode(text = "") {
90
- return encodeUtf8(typeof text === "string" ? text : String(text));
91
- }
92
- }
93
- class GuestTextDecoder {
94
- encoding = "utf-8";
95
- constructor(label = "utf-8") {
96
- if (![
97
- "utf-8",
98
- "utf8",
99
- "unicode-1-1-utf-8"
100
- ].includes(label.toLowerCase())) throw new RangeError(`This runtime decodes UTF-8 only, not "${label}"`);
101
- }
102
- decode(input) {
103
- if (!input) return "";
104
- const text = decodeUtf8(copyBytes(input));
105
- return text.startsWith("") ? text.slice(1) : text;
106
- }
107
- }
108
- class GuestEvent {
109
- type;
110
- constructor(type) {
111
- this.type = type;
112
- }
113
- }
114
- class GuestEventTarget {
115
- #listeners = /* @__PURE__ */ new Map();
116
- addEventListener(type, listener, options) {
117
- if (!listener) return;
118
- const listeners = this.#listeners.get(type) ?? /* @__PURE__ */ new Map();
119
- listeners.set(listener, { once: typeof options === "object" && options.once === true });
120
- this.#listeners.set(type, listeners);
121
- }
122
- removeEventListener(type, listener) {
123
- if (listener) this.#listeners.get(type)?.delete(listener);
124
- }
125
- dispatchEvent(event) {
126
- const listeners = this.#listeners.get(event.type);
127
- [...listeners ?? /* @__PURE__ */ new Map()].forEach(([listener, { once }]) => {
128
- if (once) listeners?.delete(listener);
129
- listener.call(this, event);
130
- });
131
- return true;
132
- }
133
- }
134
- const signals = /* @__PURE__ */ new WeakMap();
135
- const CONSTRUCT = Symbol("AbortSignal");
136
- class GuestAbortSignal extends GuestEventTarget {
137
- onabort = null;
138
- constructor(token) {
139
- super();
140
- if (token !== CONSTRUCT) throw new TypeError("Illegal constructor: an AbortSignal comes from an AbortController");
141
- signals.set(this, {
142
- aborted: false,
143
- reason: void 0
144
- });
145
- }
146
- get aborted() {
147
- return signals.get(this)?.aborted ?? false;
148
- }
149
- get reason() {
150
- return signals.get(this)?.reason;
151
- }
152
- throwIfAborted() {
153
- if (this.aborted) throw this.reason;
154
- }
155
- static abort(reason) {
156
- const signal = new GuestAbortSignal(CONSTRUCT);
157
- abortSignal(signal, reason);
158
- return signal;
159
- }
160
- static timeout(ms) {
161
- const signal = new GuestAbortSignal(CONSTRUCT);
162
- guestSetTimeout(() => {
163
- abortSignal(signal, new DOMException("The operation timed out.", "TimeoutError"));
164
- }, ms);
165
- return signal;
166
- }
167
- static any(sources) {
168
- const signal = new GuestAbortSignal(CONSTRUCT);
169
- const aborted = sources.find((source) => source.aborted);
170
- if (aborted) {
171
- abortSignal(signal, aborted.reason);
172
- return signal;
173
- }
174
- sources.forEach((source) => {
175
- source.addEventListener("abort", () => abortSignal(signal, source.reason), { once: true });
176
- });
177
- return signal;
178
- }
179
- }
180
- const abortSignal = (signal, reason) => {
181
- const state = signals.get(signal);
182
- if (!state || state.aborted) return;
183
- state.aborted = true;
184
- state.reason = reason === void 0 ? new DOMException("This operation was aborted", "AbortError") : reason;
185
- const event = new GuestEvent("abort");
186
- signal.onabort?.call(signal, event);
187
- signal.dispatchEvent(event);
188
- };
189
- class GuestAbortController {
190
- signal = new GuestAbortSignal(CONSTRUCT);
191
- abort(reason) {
192
- abortSignal(this.signal, reason);
193
- }
194
- }
195
- const timers = /* @__PURE__ */ new Set();
196
- let nextTimer = 1;
197
- const delayOf = (ms) => Math.max(0, Number(ms) || 0);
198
- const guestSetTimeout = (callback, ms, ...args) => {
199
- const id = nextTimer++;
200
- timers.add(id);
201
- host.sleep(delayOf(ms)).then(() => {
202
- if (timers.delete(id)) callback(...args);
203
- });
204
- return id;
205
- };
206
- const guestSetInterval = (callback, ms, ...args) => {
207
- const id = nextTimer++;
208
- timers.add(id);
209
- const tick = () => {
210
- host.sleep(Math.max(1, delayOf(ms))).then(() => {
211
- if (timers.has(id)) {
212
- callback(...args);
213
- tick();
214
- }
215
- });
216
- };
217
- tick();
218
- return id;
219
- };
220
- const clearTimer = (id) => {
221
- if (id !== void 0) timers.delete(id);
222
- };
223
- const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
224
- class GuestHeaders {
225
- #values = /* @__PURE__ */ new Map();
226
- constructor(init) {
227
- if (init instanceof GuestHeaders) init.forEach((value, name) => this.append(name, value));
228
- else if (Array.isArray(init)) init.forEach(([name, value]) => this.append(name, value));
229
- else if (init) Object.entries(init).forEach(([name, value]) => this.append(name, value));
230
- }
231
- #name(name) {
232
- if (!TOKEN.test(name)) throw new TypeError(`"${name}" is not a valid header name`);
233
- return name.toLowerCase();
234
- }
235
- append(name, value) {
236
- const key = this.#name(name);
237
- this.#values.set(key, [...this.#values.get(key) ?? [], String(value).trim()]);
238
- }
239
- set(name, value) {
240
- this.#values.set(this.#name(name), [String(value).trim()]);
241
- }
242
- get(name) {
243
- return this.#values.get(this.#name(name))?.join(", ") ?? null;
244
- }
245
- getSetCookie() {
246
- return [...this.#values.get("set-cookie") ?? []];
247
- }
248
- has(name) {
249
- return this.#values.has(this.#name(name));
250
- }
251
- delete(name) {
252
- this.#values.delete(this.#name(name));
253
- }
254
- *entries() {
255
- for (const name of [...this.#values.keys()].sort()) if (name === "set-cookie") for (const value of this.#values.get(name) ?? []) yield [name, value];
256
- else yield [name, this.#values.get(name)?.join(", ") ?? ""];
257
- }
258
- *keys() {
259
- for (const [name] of this.entries()) yield name;
260
- }
261
- *values() {
262
- for (const [, value] of this.entries()) yield value;
263
- }
264
- forEach(callback) {
265
- for (const [name, value] of this.entries()) callback(value, name, this);
266
- }
267
- [Symbol.iterator]() {
268
- return this.entries();
269
- }
270
- }
271
- const sourceOf = (body, headers) => {
272
- const typed = (type) => {
273
- if (!headers.has("content-type")) headers.set("content-type", type);
274
- };
275
- if (body === null || body === void 0) return null;
276
- if (typeof body === "string") {
277
- typed("text/plain;charset=UTF-8");
278
- return { text: body };
279
- }
280
- if (body instanceof URLSearchParams) {
281
- typed("application/x-www-form-urlencoded;charset=UTF-8");
282
- return { text: body.toString() };
283
- }
284
- if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { bytes: copyBytes(body) };
285
- throw new TypeError("A body is a string, bytes or URLSearchParams — this runtime has no streams, Blob or FormData");
286
- };
287
- /** Each body's source and whether it was read, kept out of the objects the code holds. */
288
- const bodies = /* @__PURE__ */ new WeakMap();
289
- const take = (body) => {
290
- const state = bodies.get(body);
291
- if (!state) return null;
292
- if (state.used) throw new TypeError("Body has already been read");
293
- state.used = state.source !== null;
294
- return state.source;
295
- };
296
- /** A body as it was written, to copy it: text stays text and bytes stay bytes. */
297
- const peek = (body) => {
298
- const source = bodies.get(body)?.source ?? null;
299
- if (!source) return null;
300
- return "text" in source ? source.text : source.bytes;
301
- };
302
- class GuestBody {
303
- headers;
304
- constructor(body, headers) {
305
- this.headers = new GuestHeaders(headers);
306
- bodies.set(this, {
307
- source: sourceOf(body, this.headers),
308
- used: false
309
- });
310
- }
311
- get bodyUsed() {
312
- return bodies.get(this)?.used ?? false;
313
- }
314
- get body() {
315
- return null;
316
- }
317
- text() {
318
- try {
319
- const source = take(this);
320
- if (!source) return Promise.resolve("");
321
- return Promise.resolve("text" in source ? source.text : decodeUtf8(source.bytes));
322
- } catch (error) {
323
- return Promise.reject(error instanceof Error ? error : new TypeError(String(error)));
324
- }
325
- }
326
- async json() {
327
- return JSON.parse(await this.text());
328
- }
329
- bytes() {
330
- try {
331
- const source = take(this);
332
- if (!source) return Promise.resolve(/* @__PURE__ */ new Uint8Array(0));
333
- return Promise.resolve("text" in source ? encodeUtf8(source.text) : copyBytes(source.bytes));
334
- } catch (error) {
335
- return Promise.reject(error instanceof Error ? error : new TypeError(String(error)));
336
- }
337
- }
338
- async arrayBuffer() {
339
- return (await this.bytes()).buffer;
340
- }
341
- }
342
- const METHODS = [
343
- "DELETE",
344
- "GET",
345
- "HEAD",
346
- "OPTIONS",
347
- "POST",
348
- "PUT",
349
- "PATCH"
350
- ];
351
- class GuestRequest extends GuestBody {
352
- url;
353
- method;
354
- signal;
355
- constructor(input, init = {}) {
356
- const from = input instanceof GuestRequest ? input : void 0;
357
- const method = init.method ?? from?.method ?? "GET";
358
- const upper = method.toUpperCase();
359
- const normal = METHODS.includes(upper) ? upper : method;
360
- if ((normal === "GET" || normal === "HEAD") && init.body !== void 0 && init.body !== null) throw new TypeError(`A ${normal} request has no body`);
361
- super(init.body, init.headers ?? from?.headers);
362
- this.url = new URL(input instanceof GuestRequest ? input.url : input).href;
363
- this.method = normal;
364
- this.signal = init.signal ?? from?.signal ?? new GuestAbortController().signal;
365
- }
366
- clone() {
367
- return new GuestRequest(this.url, {
368
- method: this.method,
369
- headers: this.headers,
370
- body: peek(this),
371
- signal: this.signal
372
- });
373
- }
374
- }
375
- class GuestResponse extends GuestBody {
376
- status;
377
- statusText;
378
- type = "default";
379
- url = "";
380
- redirected = false;
381
- constructor(body, init = {}) {
382
- super(body, init.headers);
383
- const status = init.status ?? 200;
384
- if (!Number.isInteger(status) || status < 200 || status > 599) throw new RangeError(`A response status is 200–599, not ${String(status)}`);
385
- this.status = status;
386
- this.statusText = init.statusText ?? "";
387
- }
388
- get ok() {
389
- return this.status >= 200 && this.status < 300;
390
- }
391
- clone() {
392
- return new GuestResponse(peek(this), {
393
- status: this.status,
394
- statusText: this.statusText,
395
- headers: this.headers
396
- });
397
- }
398
- static json(data, init = {}) {
399
- const headers = new GuestHeaders(init.headers);
400
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
401
- return new GuestResponse(JSON.stringify(data), {
402
- ...init,
403
- headers
404
- });
405
- }
406
- static redirect(url, status = 302) {
407
- if (![
408
- 301,
409
- 302,
410
- 303,
411
- 307,
412
- 308
413
- ].includes(status)) throw new RangeError(`${String(status)} is not a redirect status`);
414
- return new GuestResponse(null, {
415
- status,
416
- headers: { location: new URL(String(url)).href }
417
- });
418
- }
419
- }
420
- /** Text back as text and bytes as base64: what the code wrote crosses unchanged, and nothing is decided from its type. */
421
- const wireOf = (body) => {
422
- const source = take(body);
423
- if (!source) return null;
424
- return "text" in source ? { text: source.text } : { base64: bytesToBase64(source.bytes) };
425
- };
426
- const headerPairs = (value) => Array.isArray(value) ? value.flatMap((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string" ? [[pair[0], pair[1]]] : []) : [];
427
- const bodyOfWire = (body) => {
428
- if (!isRecord(body)) return null;
429
- if (typeof body.text === "string") return body.text;
430
- return typeof body.base64 === "string" ? base64ToBytes(body.base64) : null;
431
- };
432
- const getRandomValues = (array) => {
433
- if (array.byteLength > 65536) throw new DOMException("At most 65536 bytes at a time", "QuotaExceededError");
434
- new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(host.random(array.byteLength));
435
- return array;
436
- };
437
- const randomUUID = () => {
438
- const bytes = getRandomValues(/* @__PURE__ */ new Uint8Array(16));
439
- bytes[6] = bytes[6] & 15 | 64;
440
- bytes[8] = bytes[8] & 63 | 128;
441
- const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
442
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
443
- };
444
- const HASHES = [
445
- "SHA-1",
446
- "SHA-256",
447
- "SHA-384",
448
- "SHA-512"
449
- ];
450
- const nameOf = (algorithm) => {
451
- const name = typeof algorithm === "string" ? algorithm : isRecord(algorithm) ? algorithm.name : void 0;
452
- return typeof name === "string" ? name.toUpperCase() : "";
453
- };
454
- const hashOf = (algorithm) => {
455
- const upper = nameOf(algorithm);
456
- if (!HASHES.includes(upper)) throw new DOMException(`${upper || String(algorithm)} is not a supported hash (${HASHES.join(", ")})`, "NotSupportedError");
457
- return upper;
458
- };
459
- /** An HMAC key's length when its algorithm names none: the hash's block, as Web Crypto has it. */
460
- const blockBitsOf = (hash) => hash === "SHA-384" || hash === "SHA-512" ? 1024 : 512;
461
- /**
462
- * The two kinds of key this runtime's `crypto.subtle` makes: HMAC, what signing a webhook needs, and PBKDF2, a
463
- * password to derive from — what keeping a password needs.
464
- */
465
- class GuestCryptoKey {
466
- type = "secret";
467
- algorithm;
468
- extractable;
469
- usages;
470
- raw;
471
- constructor(raw, algorithm, extractable, usages) {
472
- this.raw = raw;
473
- this.algorithm = algorithm;
474
- this.extractable = extractable;
475
- this.usages = usages;
476
- }
477
- }
478
- const bytesOf = (data) => {
479
- if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) return copyBytes(data);
480
- throw new TypeError("crypto.subtle takes bytes: an ArrayBuffer or a typed array");
481
- };
482
- const cryptoCall = async (message) => {
483
- const answer = JSON.parse(await host.crypto(JSON.stringify(message)));
484
- if (!isRecord(answer) || answer.ok !== true || typeof answer.value !== "string") throw new DOMException(isRecord(answer) && typeof answer.error === "string" ? answer.error : "The operation failed", "OperationError");
485
- return base64ToBytes(answer.value);
486
- };
487
- const isKeyOf = (key, name) => key instanceof GuestCryptoKey && key.algorithm.name === name;
488
- /** The key an operation was handed, when it is of the kind the operation takes and was imported for it. */
489
- const keyFor = (key, name, usage) => {
490
- if (!isKeyOf(key, name)) throw new DOMException(`${usage} takes a ${name} key, from crypto.subtle.importKey`, "InvalidAccessError");
491
- if (!key.usages.includes(usage)) throw new DOMException(`The key was not imported for ${usage}`, "InvalidAccessError");
492
- return key;
493
- };
494
- const hmacOf = (key, usage, data) => {
495
- const { algorithm, raw } = keyFor(key, "HMAC", usage);
496
- return cryptoCall({
497
- op: "hmac",
498
- hash: algorithm.hash.name,
499
- key: bytesToBase64(raw),
500
- data: bytesToBase64(bytesOf(data))
501
- });
502
- };
503
- /** How many rounds and bits a derivation may take is the runner's to say: it is the one doing the work. */
504
- const pbkdf2Of = (algorithm, baseKey, bits, usage) => {
505
- if (!isRecord(algorithm) || nameOf(algorithm) !== "PBKDF2") throw new DOMException("This runtime derives with PBKDF2 only", "NotSupportedError");
506
- const { raw } = keyFor(baseKey, "PBKDF2", usage);
507
- if (typeof algorithm.iterations !== "number" || typeof bits !== "number") throw new TypeError("PBKDF2 takes { name, hash, salt, iterations } and a length in bits");
508
- return cryptoCall({
509
- op: "pbkdf2",
510
- hash: hashOf(algorithm.hash),
511
- key: bytesToBase64(raw),
512
- salt: bytesToBase64(bytesOf(algorithm.salt)),
513
- iterations: String(algorithm.iterations),
514
- bits: String(bits)
515
- });
516
- };
517
- /** The key `importKey` makes — thrown, not answered, when it is none this runtime has. */
518
- const importedKey = (format, keyData, algorithm, extractable, usages) => {
519
- const name = nameOf(algorithm);
520
- if (format === "raw" && name === "HMAC" && isRecord(algorithm)) return new GuestCryptoKey(bytesOf(keyData), {
521
- name,
522
- hash: { name: hashOf(algorithm.hash) }
523
- }, extractable, usages);
524
- if (format === "raw" && name === "PBKDF2") {
525
- if (extractable) throw new DOMException("A PBKDF2 key is never extractable", "SyntaxError");
526
- return new GuestCryptoKey(bytesOf(keyData), { name }, false, usages);
527
- }
528
- throw new DOMException("This runtime imports raw keys for HMAC and PBKDF2 only (format \"raw\", { name: \"HMAC\", hash } or \"PBKDF2\")", "NotSupportedError");
529
- };
530
- const subtle = {
531
- digest: async (algorithm, data) => (await cryptoCall({
532
- op: "digest",
533
- hash: hashOf(algorithm),
534
- data: bytesToBase64(bytesOf(data))
535
- })).buffer,
536
- importKey: (format, keyData, algorithm, extractable, usages) => new Promise((resolve) => {
537
- resolve(importedKey(format, keyData, algorithm, extractable, usages));
538
- }),
539
- sign: async (_algorithm, key, data) => (await hmacOf(key, "sign", data)).buffer,
540
- verify: async (_algorithm, key, signature, data) => {
541
- const expected = await hmacOf(key, "verify", data);
542
- const given = bytesOf(signature);
543
- let difference = expected.length ^ given.length;
544
- expected.forEach((byte, index) => {
545
- difference |= byte ^ (given[index] ?? 0);
546
- });
547
- return difference === 0;
548
- },
549
- deriveBits: async (algorithm, baseKey, length) => (await pbkdf2Of(algorithm, baseKey, length, "deriveBits")).buffer,
550
- /** Derives an HMAC key — the one other kind this runtime has. */
551
- deriveKey: async (algorithm, baseKey, derivedKeyAlgorithm, extractable, usages) => {
552
- if (!isRecord(derivedKeyAlgorithm) || nameOf(derivedKeyAlgorithm) !== "HMAC") throw new DOMException("This runtime derives HMAC keys only", "NotSupportedError");
553
- const hash = hashOf(derivedKeyAlgorithm.hash);
554
- const length = derivedKeyAlgorithm.length ?? blockBitsOf(hash);
555
- const raw = await pbkdf2Of(algorithm, baseKey, length, "deriveKey");
556
- return new GuestCryptoKey(raw, {
557
- name: "HMAC",
558
- hash: { name: hash }
559
- }, extractable, usages);
560
- }
561
- };
562
- const call = async (message) => {
563
- const answer = JSON.parse(await host.call(JSON.stringify(message)));
564
- if (isRecord(answer) && answer.ok === true) return answer.value;
565
- const said = isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call";
566
- if (isRecord(answer) && answer.refused === true) throw refusal(said, typeof answer.code === "string" ? answer.code : void 0);
567
- throw new Error(said);
568
- };
569
- const run = new GuestAbortController();
570
- const driver = shared.createFunctionsDriver({
571
- call,
572
- signal: run.signal,
573
- responseOf: (wire) => new GuestResponse(bodyOfWire(wire.body), {
574
- status: typeof wire.status === "number" ? wire.status : 502,
575
- statusText: typeof wire.statusText === "string" ? wire.statusText : "",
576
- headers: headerPairs(wire.headers)
577
- }),
578
- requestOf: (wire) => new GuestRequest(String(wire.url), {
579
- method: String(wire.method),
580
- headers: headerPairs(wire.headers),
581
- body: wire.method === "GET" || wire.method === "HEAD" ? null : bodyOfWire(wire.body),
582
- signal: run.signal
583
- }),
584
- wireOfResponse: (response) => Promise.resolve(response instanceof GuestResponse ? {
585
- status: response.status,
586
- statusText: response.statusText,
587
- headers: [...response.headers],
588
- body: wireOf(response)
589
- } : void 0),
590
- changeKv: shared.changeKv,
591
- refusal
592
- });
593
- const { log } = driver;
594
- const refuseFetch = () => Promise.reject(/* @__PURE__ */ new TypeError("Functions reach the network through ctx.fetch, which knows the hosts they may reach"));
595
- Object.assign(scope, {
596
- TextEncoder: GuestTextEncoder,
597
- TextDecoder: GuestTextDecoder,
598
- Event: GuestEvent,
599
- EventTarget: GuestEventTarget,
600
- AbortSignal: GuestAbortSignal,
601
- AbortController: GuestAbortController,
602
- Headers: GuestHeaders,
603
- Request: GuestRequest,
604
- Response: GuestResponse,
605
- setTimeout: guestSetTimeout,
606
- clearTimeout: clearTimer,
607
- setInterval: guestSetInterval,
608
- clearInterval: clearTimer,
609
- queueMicrotask: (callback) => {
610
- Promise.resolve().then(callback);
611
- },
612
- crypto: {
613
- getRandomValues,
614
- randomUUID,
615
- subtle
616
- },
617
- console: {
618
- log,
619
- info: log,
620
- warn: log,
621
- error: log,
622
- debug: log
623
- },
624
- fetch: refuseFetch
625
- });
626
- const describe = (definition) => JSON.stringify({
627
- ok: true,
628
- value: shared.describeFunctions(definition)
629
- });
630
- return {
631
- describe,
632
- invoke: async (definition, invocationText) => {
633
- let answer;
634
- try {
635
- const invocation = JSON.parse(invocationText);
636
- answer = {
637
- ok: true,
638
- value: await driver.invoke(definition, isRecord(invocation) ? invocation : {})
639
- };
640
- } catch (error) {
641
- answer = {
642
- ok: false,
643
- error: error instanceof Error ? error.message : String(error),
644
- ...isRefusal(error) ? { refused: true } : {}
645
- };
646
- }
647
- try {
648
- return JSON.stringify(answer);
649
- } catch (error) {
650
- return JSON.stringify({
651
- ok: false,
652
- error: `What the function answered is not JSON: ${error instanceof Error ? error.message : String(error)}`
653
- });
654
- }
655
- },
656
- abort: (reason) => {
657
- run.abort(new DOMException(reason, "AbortError"));
658
- }
659
- };
660
- };
661
- //#endregion
662
- export { installGuest };