@plitzi/sdk-actions 0.0.0-stage → 0.39.2

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 (168) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +54 -2
  3. package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
  4. package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
  5. package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
  6. package/dist/chunks/load-DBWRZn7G.mjs +48 -0
  7. package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
  8. package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
  9. package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
  10. package/dist/chunks/remote-DopPgCMK.mjs +404 -0
  11. package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
  12. package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
  13. package/dist/connectors/connectors.d.ts +7 -0
  14. package/dist/connectors/engine.d.ts +47 -0
  15. package/dist/connectors/getByPath.d.ts +8 -0
  16. package/dist/connectors/projection.d.ts +18 -0
  17. package/dist/connectors/resolver.d.ts +27 -0
  18. package/dist/connectors/types.d.ts +19 -0
  19. package/dist/engine/configSeam.d.ts +10 -0
  20. package/dist/engine/connectorWrite.d.ts +12 -0
  21. package/dist/engine/fileStore.d.ts +60 -0
  22. package/dist/engine/fleet.d.ts +20 -0
  23. package/dist/engine/jobs/calls.d.ts +49 -0
  24. package/dist/engine/jobs/claimSpaces.d.ts +10 -0
  25. package/dist/engine/jobs/codeMarks.d.ts +10 -0
  26. package/dist/engine/jobs/endings.d.ts +42 -0
  27. package/dist/engine/jobs/failureStreak.d.ts +15 -0
  28. package/dist/engine/jobs/fileQueue.d.ts +34 -0
  29. package/dist/engine/jobs/flow.d.ts +11 -0
  30. package/dist/engine/jobs/jobs.d.ts +36 -0
  31. package/dist/engine/jobs/later.d.ts +27 -0
  32. package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
  33. package/dist/engine/jobs/memoryQueue.d.ts +33 -0
  34. package/dist/engine/jobs/memoryWatch.d.ts +21 -0
  35. package/dist/engine/jobs/notNow.d.ts +39 -0
  36. package/dist/engine/jobs/queueDocument.d.ts +15 -0
  37. package/dist/engine/jobs/queueRules.d.ts +64 -0
  38. package/dist/engine/jobs/scheduler.d.ts +70 -0
  39. package/dist/engine/jobs/schedules.d.ts +24 -0
  40. package/dist/engine/jobs/storeClock.d.ts +16 -0
  41. package/dist/engine/jobs/wake.d.ts +6 -0
  42. package/dist/engine/jobs/worker.d.ts +99 -0
  43. package/dist/engine/module.d.ts +96 -0
  44. package/dist/engine/moduleFor.d.ts +3 -0
  45. package/dist/engine/runtime/check.d.ts +24 -0
  46. package/dist/engine/runtime/credentials.d.ts +8 -0
  47. package/dist/engine/runtime/deadline.d.ts +19 -0
  48. package/dist/engine/runtime/email.d.ts +38 -0
  49. package/dist/engine/runtime/errors.d.ts +28 -0
  50. package/dist/engine/runtime/fileKv.d.ts +35 -0
  51. package/dist/engine/runtime/flags.d.ts +16 -0
  52. package/dist/engine/runtime/guards.d.ts +190 -0
  53. package/dist/engine/runtime/kvList.d.ts +28 -0
  54. package/dist/engine/runtime/kvStore.d.ts +36 -0
  55. package/dist/engine/runtime/limits.d.ts +12 -0
  56. package/dist/engine/runtime/memoryKv.d.ts +28 -0
  57. package/dist/engine/runtime/namespaceKv.d.ts +9 -0
  58. package/dist/engine/runtime/precheck.d.ts +28 -0
  59. package/dist/engine/runtime/rateLimit.d.ts +9 -0
  60. package/dist/engine/runtime/redisKv.d.ts +27 -0
  61. package/dist/engine/runtime/renderFailure.d.ts +24 -0
  62. package/dist/engine/runtime/renderResolver.d.ts +16 -0
  63. package/dist/engine/runtime/renderShare.d.ts +12 -0
  64. package/dist/engine/runtime/report.d.ts +15 -0
  65. package/dist/engine/runtime/runAction.d.ts +26 -0
  66. package/dist/engine/runtime/runLogger.d.ts +37 -0
  67. package/dist/engine/runtime/runStats.d.ts +8 -0
  68. package/dist/engine/runtime/scope.d.ts +40 -0
  69. package/dist/engine/runtime/signing.d.ts +27 -0
  70. package/dist/engine/runtime/taskContext.d.ts +54 -0
  71. package/dist/engine/runtime/triggers.d.ts +12 -0
  72. package/dist/engine/taskCatalog.d.ts +28 -0
  73. package/dist/engine/tasks/auth.d.ts +2 -0
  74. package/dist/engine/tasks/builtins.d.ts +10 -0
  75. package/dist/engine/tasks/connector.d.ts +2 -0
  76. package/dist/engine/tasks/db.d.ts +2 -0
  77. package/dist/engine/tasks/email.d.ts +2 -0
  78. package/dist/engine/tasks/flow.d.ts +3 -0
  79. package/dist/engine/tasks/helpers.d.ts +16 -0
  80. package/dist/engine/tasks/http.d.ts +2 -0
  81. package/dist/engine/tasks/kv.d.ts +2 -0
  82. package/dist/engine/tasks/list.d.ts +2 -0
  83. package/dist/engine/tasks/names.d.ts +8 -0
  84. package/dist/engine/tasks/realtime.d.ts +3 -0
  85. package/dist/engine/tasks/registry.d.ts +19 -0
  86. package/dist/engine/tasks/transform.d.ts +2 -0
  87. package/dist/engine/transport/callHandler.d.ts +34 -0
  88. package/dist/engine/transport/cancelHandler.d.ts +23 -0
  89. package/dist/engine/transport/catalogHandler.d.ts +22 -0
  90. package/dist/engine/transport/stream.d.ts +22 -0
  91. package/dist/engine/transport/verifySignature.d.ts +16 -0
  92. package/dist/engine/transport/webhookHandler.d.ts +26 -0
  93. package/dist/engine/types.d.ts +442 -0
  94. package/dist/functions/build.d.ts +27 -0
  95. package/dist/functions/capabilities.d.ts +11 -0
  96. package/dist/functions/config.d.ts +111 -0
  97. package/dist/functions/context.d.ts +15 -0
  98. package/dist/functions/index.d.ts +17 -0
  99. package/dist/functions/index.mjs +461 -0
  100. package/dist/functions/jobControl.d.ts +22 -0
  101. package/dist/functions/jobs.d.ts +104 -0
  102. package/dist/functions/load.d.ts +22 -0
  103. package/dist/functions/local.d.ts +36 -0
  104. package/dist/functions/manifest.d.ts +32 -0
  105. package/dist/functions/native.d.ts +13 -0
  106. package/dist/functions/oauth.d.ts +33 -0
  107. package/dist/functions/routes.d.ts +50 -0
  108. package/dist/functions/runner/remote.d.ts +26 -0
  109. package/dist/functions/scope.d.ts +28 -0
  110. package/dist/functions/space.d.ts +41 -0
  111. package/dist/functions/tryEntry.d.ts +9 -0
  112. package/dist/index.d.ts +47 -0
  113. package/dist/index.mjs +545 -0
  114. package/dist/mongo/claimable.d.ts +5 -0
  115. package/dist/mongo/index.d.ts +4 -0
  116. package/dist/mongo/index.mjs +779 -0
  117. package/dist/mongo/jobQueue.d.ts +38 -0
  118. package/dist/mongo/kv.d.ts +15 -0
  119. package/dist/mysql/index.d.ts +5 -0
  120. package/dist/mysql/index.mjs +808 -0
  121. package/dist/mysql/jobQueue.d.ts +40 -0
  122. package/dist/mysql/kv.d.ts +18 -0
  123. package/dist/mysql/rows.d.ts +64 -0
  124. package/dist/mysql/schema.d.ts +28 -0
  125. package/dist/mysql/summary.d.ts +7 -0
  126. package/dist/realtime/declarations.d.ts +11 -0
  127. package/dist/realtime/failure.d.ts +6 -0
  128. package/dist/realtime/grants.d.ts +22 -0
  129. package/dist/realtime/handlers.d.ts +86 -0
  130. package/dist/realtime/hub.d.ts +71 -0
  131. package/dist/realtime/index.d.ts +105 -0
  132. package/dist/realtime/index.mjs +824 -0
  133. package/dist/realtime/jobs.d.ts +18 -0
  134. package/dist/realtime/message.d.ts +3 -0
  135. package/dist/realtime/presence.d.ts +33 -0
  136. package/dist/realtime/retained.d.ts +21 -0
  137. package/dist/realtime/socket.d.ts +30 -0
  138. package/dist/render/index.d.ts +10 -0
  139. package/dist/render/index.mjs +1 -0
  140. package/dist/render/protocol.d.ts +47 -0
  141. package/dist/render/remote.d.ts +16 -0
  142. package/dist/runtimes/bundle.d.ts +29 -0
  143. package/dist/runtimes/index.d.ts +3 -0
  144. package/dist/runtimes/index.mjs +229 -0
  145. package/dist/runtimes/stages.d.ts +52 -0
  146. package/dist/sqlite/index.d.ts +4 -0
  147. package/dist/sqlite/index.mjs +160 -0
  148. package/dist/sqlite/jobQueue.d.ts +35 -0
  149. package/dist/sqlite/kv.d.ts +34 -0
  150. package/dist/sqlite/open.d.ts +3 -0
  151. package/dist/types/config.d.ts +293 -0
  152. package/dist/types/index.d.ts +2 -0
  153. package/dist/types/index.mjs +1 -0
  154. package/dist/types/jobs.d.ts +317 -0
  155. package/dist/worker/elsewhere.d.ts +16 -0
  156. package/dist/worker/index.d.ts +5 -0
  157. package/dist/worker/index.mjs +1703 -0
  158. package/dist/worker/origin.d.ts +12 -0
  159. package/dist/worker/pageEngine.d.ts +11 -0
  160. package/dist/worker/stages/action.d.ts +24 -0
  161. package/dist/worker/stages/cors.d.ts +9 -0
  162. package/dist/worker/stages/forward.d.ts +12 -0
  163. package/dist/worker/stages/functionRoutes.d.ts +10 -0
  164. package/dist/worker/stages/queuedCalls.d.ts +15 -0
  165. package/dist/worker/stages/realtime.d.ts +9 -0
  166. package/dist/worker/stages/render.d.ts +9 -0
  167. package/dist/worker/worker.d.ts +39 -0
  168. package/package.json +76 -3
@@ -0,0 +1,18 @@
1
+ import { RealtimeHub, RealtimeSpace } from './hub';
2
+ import { RealtimeRetained } from './retained';
3
+ import { Job, ChannelDeclaration, FunctionJobView, SSRUser } from '@plitzi/sdk-shared';
4
+ /** How the realtime reaches a job, once the actions module hands it the way (`watchJobs`). */
5
+ export type JobLookup = (spaceId: number, jobId: string) => Promise<Job | undefined>;
6
+ /** A job's topic, as a channel: the server alone says how the job goes, and a page that joins hears the latest. */
7
+ export declare const JOB_CHANNEL: ChannelDeclaration;
8
+ /**
9
+ * Why a page may not watch a job, or nothing when it may: whoever started it always does, and anyone else as the
10
+ * job's `watch` says — a channel's access, read against the visitor's permissions in the space. A job of another space,
11
+ * or none by that id, is no topic at all.
12
+ */
13
+ export declare const jobRefusal: (lookup: JobLookup | undefined, spaceId: number, jobId: string, user: SSRUser | undefined) => Promise<"undeclared" | "unauthenticated" | "forbidden" | undefined>;
14
+ /**
15
+ * Says a job as it is now on its topic, kept for a page that joins later — the one way it is said, by the page server's
16
+ * realtime and by an operator's panel in a process of its own alike.
17
+ */
18
+ export declare const publishJobView: (hub: Pick<RealtimeHub, "publish">, retained: RealtimeRetained, space: RealtimeSpace, jobId: string, view: FunctionJobView) => Promise<void>;
@@ -0,0 +1,3 @@
1
+ import { RealtimeMessage } from '@plitzi/sdk-shared';
2
+ /** A message as a transport or a store carried it — written by this module, but read from something that is not. */
3
+ export declare const isMessage: (value: unknown) => value is RealtimeMessage;
@@ -0,0 +1,33 @@
1
+ import { RealtimeSpace } from './hub';
2
+ import { ActionKvAdapter } from '../engine/types';
3
+ import { RealtimeSender } from '@plitzi/sdk-shared';
4
+ /** How often a replica says its members are still there: a connection open for hours is seen every this often. */
5
+ export declare const PRESENCE_HEARTBEAT_MS = 30000;
6
+ /** A member not seen this long is gone — its replica went down without saying it: three heartbeats missed. */
7
+ export declare const PRESENCE_STALE_MS: number;
8
+ /** One page on a presence channel, as every replica sees it. */
9
+ export type RealtimePresenceMember = {
10
+ /** Its public name on the channel — the `from` of what it says. */
11
+ from: string;
12
+ /** Who is signed in on it, when someone is. */
13
+ user?: RealtimeSender['user'];
14
+ /** When it arrived, ms. */
15
+ since: number;
16
+ };
17
+ export type RealtimePresence = {
18
+ /** Records the pages that arrived on `topic` here — or are still on it, at a heartbeat: their `seenAt` moves on. */
19
+ touch: (space: RealtimeSpace, topic: string, members: readonly RealtimePresenceMember[]) => Promise<void>;
20
+ /** The page left `topic`. */
21
+ depart: (space: RealtimeSpace, topic: string, from: string) => Promise<void>;
22
+ /** Who is on `topic` now, on every replica, the earliest first — those not seen within {@link PRESENCE_STALE_MS} not. */
23
+ of: (space: RealtimeSpace, topic: string) => Promise<RealtimePresenceMember[]>;
24
+ };
25
+ /**
26
+ * Who is on each presence channel, kept where the actions keep their `kv` — beside the grants and what `retain` keeps —
27
+ * so a function on one replica counts the pages connected to all of them (`ctx.presence`). A page counted by its own
28
+ * replica alone answered a room of three as one (a run's listeners, counted by the pages' own heartbeats in kv).
29
+ *
30
+ * One value per topic, written by compare-and-swap; each member carries when its replica last saw it, so one that went
31
+ * down without a word stops counting within {@link PRESENCE_STALE_MS}, and is dropped at the next write.
32
+ */
33
+ export declare const createRealtimePresence: (store: ActionKvAdapter, now?: () => number) => RealtimePresence;
@@ -0,0 +1,21 @@
1
+ import { RealtimeSpace } from './hub';
2
+ import { ActionKvAdapter } from '../engine/types';
3
+ import { RealtimeMessage } from '@plitzi/sdk-shared';
4
+ export type RealtimeRetained = {
5
+ /**
6
+ * Keeps `message` as its topic's latest of its type — or, with `null` data, forgets the type. Refused, before anything
7
+ * is sent, past {@link MAX_RETAINED_TYPES} types or {@link MAX_RETAINED_BYTES} for the topic. With `ttlSeconds`, the
8
+ * topic is forgotten that long after it last changed — a job's, which ends.
9
+ */
10
+ keep: (space: RealtimeSpace, message: RealtimeMessage, ttlSeconds?: number) => Promise<void>;
11
+ /** What a topic keeps: the latest message of each type, oldest first. */
12
+ of: (space: RealtimeSpace, topic: string) => Promise<RealtimeMessage[]>;
13
+ };
14
+ /**
15
+ * The messages of `retain: true` channels, kept in the store the actions' `kv` uses — beside the grants, so one replica
16
+ * keeps what another hands a page that joins, and nothing new has to be configured for it.
17
+ *
18
+ * One value per topic, written by compare-and-swap: two types said at once on one topic are both kept, never one
19
+ * written over the other. Keyed under `realtime-retained:`, which no key a flow writes can reach.
20
+ */
21
+ export declare const createRealtimeRetained: (store: ActionKvAdapter) => RealtimeRetained;
@@ -0,0 +1,30 @@
1
+ import { ChannelResolver } from './declarations';
2
+ import { RealtimeGrants } from './grants';
3
+ import { RealtimeHub } from './hub';
4
+ import { JobLookup } from './jobs';
5
+ import { UpgradeRequest } from '@plitzi/sdk-kernel/http';
6
+ import { SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-kernel/types';
7
+ import { IncomingMessage } from 'node:http';
8
+ export type SocketDeps = {
9
+ req: SSRRequest;
10
+ res: SSRResponseHelpers;
11
+ raw: IncomingMessage;
12
+ upgrade: UpgradeRequest;
13
+ hub: RealtimeHub;
14
+ resolveChannels: ChannelResolver;
15
+ grants: RealtimeGrants;
16
+ allowedOrigins: readonly string[];
17
+ /** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
18
+ jobs?: JobLookup;
19
+ /** The deployment's say on whether a space opens its channels (`realtime.admitSpace`). */
20
+ admitSpace?: (spaceId: number) => Promise<string | undefined>;
21
+ };
22
+ /**
23
+ * A page's realtime connection as a WebSocket: the same topics, rules and messages as the Server-Sent Events one, in
24
+ * both directions over one socket. A publish is a frame, not a request — no headers, no second connection, no token
25
+ * to present: the socket is the credential. Its answer arrives as an `ack` carrying the publish's `id`.
26
+ *
27
+ * Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
28
+ * reports it exactly as it would there.
29
+ */
30
+ export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs, admitSpace }: SocketDeps) => Promise<void>;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Resolving a page's server element that names an action or a connector (RFC 0032, §4.3): in this process, over the
3
+ * engine (`createActionResolver`, what `createPageEngine` hands a page server), or on a worker (`createRemoteRenderResolver`,
4
+ * what `engineOnWorker({ render })` hands one that runs nothing).
5
+ */
6
+ export { createActionResolver } from '../engine/runtime/renderResolver';
7
+ export { createRemoteRenderResolver } from './remote';
8
+ export { RENDER_PATH, RENDER_PROTOCOL } from './protocol';
9
+ export type { RemoteRenderOptions } from './remote';
10
+ export type { RenderAnswer, RenderAsk } from './protocol';
@@ -0,0 +1 @@
1
+ export { n as RENDER_PATH, r as RENDER_PROTOCOL, a as createActionResolver, t as createRemoteRenderResolver } from "../chunks/remote-DopPgCMK.mjs";
@@ -0,0 +1,47 @@
1
+ import { ActionRunSummary, Element, Environment, SSRUser } from '@plitzi/sdk-shared';
2
+ import { ServerTemplateData } from '@plitzi/sdk-shared/schema';
3
+ /** Where a worker answers a page server's server elements (`render.secret`): never a browser's, never routed to it. */
4
+ export declare const RENDER_PATH = "/_render";
5
+ /**
6
+ * The version of what a page server and a worker say to each other at {@link RENDER_PATH}, `major.minor` as the
7
+ * functions protocol's (D14): a minor adds what the other may ignore, a major is refused both ways, naming which side
8
+ * to upgrade — so a rolling deploy says why its sections are empty instead of rendering them wrong.
9
+ */
10
+ export declare const RENDER_PROTOCOL = "1.0";
11
+ /**
12
+ * One server element, as the page server asks the worker for its data: the element and the subtree that reads it, what
13
+ * its input resolved to, the visit as a template reads it, the space and version being rendered, and who is looking —
14
+ * already resolved by the page server, which the worker trusts through the secret.
15
+ */
16
+ export type RenderAsk = {
17
+ protocol: string;
18
+ spaceId: number;
19
+ environment: Environment;
20
+ revision: number;
21
+ element: Element;
22
+ /** The element and every element under it: what a connector's projection reads to send only the bound fields. */
23
+ subtree: Record<string, Element>;
24
+ input?: unknown;
25
+ routeParams: Record<string, string | undefined>;
26
+ queryParams: Record<string, string>;
27
+ /** What a refresh asked for beside the page's address (`/_rsc?…`). */
28
+ rscParams?: Record<string, string>;
29
+ templateData: Omit<ServerTemplateData, 'paintedKeys'> & {
30
+ paintedKeys: string[];
31
+ };
32
+ user?: SSRUser;
33
+ };
34
+ /** The worker's answer: the element's data, or why there is none — and the runs that fed it, for a page that debugs. */
35
+ export type RenderAnswer = {
36
+ ok: true;
37
+ data: unknown;
38
+ runs: ActionRunSummary[];
39
+ } | {
40
+ ok: false;
41
+ error: string;
42
+ refused: boolean;
43
+ said?: string;
44
+ runs: ActionRunSummary[];
45
+ };
46
+ /** A body read as an ask, or what is wrong with it — said to the page server, which wrote it. */
47
+ export declare const readRenderAsk: (body: unknown) => RenderAsk | string;
@@ -0,0 +1,16 @@
1
+ import { RscElementResolver } from '@plitzi/sdk-kernel/engine';
2
+ export type RemoteRenderOptions = {
3
+ /** Where the worker listens, as this page server reaches it — `http://worker:8892`. Never the browser's address. */
4
+ url: string;
5
+ /** The worker's `render.secret`. */
6
+ secret: string;
7
+ };
8
+ /**
9
+ * A page's server elements resolved on a worker (RFC 0032, §4.3): each one asked at `/_render`, so this page server runs
10
+ * no action and no connector, and imports nothing of the engine to run. Handed to it with `engineOnWorker({ render })`.
11
+ *
12
+ * What fed the element comes back with its data — the runs, for a page that debugs — and a failure comes back as one:
13
+ * the element shows its error state, a refusal in the action's own words. A worker that does not answer is that
14
+ * element's failure, said with where it was asked.
15
+ */
16
+ export declare const createRemoteRenderResolver: ({ url, secret }: RemoteRenderOptions) => RscElementResolver;
@@ -0,0 +1,29 @@
1
+ import { SpaceRuntime } from '@plitzi/sdk-shared/functions';
2
+ /** A packed runtime at most this big: its code and every dependency, not its data. */
3
+ export declare const MAX_RUNTIME_BUNDLE_BYTES: number;
4
+ /** A bundle's id: what its bytes are, so the same code packed twice is one bundle. */
5
+ export declare const runtimeBundleId: (bytes: Uint8Array) => string;
6
+ /**
7
+ * A runtime's module packed to travel: bundled for Node with every dependency it imports — but the platform's packages
8
+ * and React, which the host provides, so there is one copy of each — and gzipped. `entry` is the module whose default
9
+ * export is `defineRuntime(…)`.
10
+ */
11
+ export declare const packRuntime: (entry: string) => Promise<Uint8Array>;
12
+ /**
13
+ * What a packed runtime holds, read without running any of it — what a platform checks a bundle with before keeping it.
14
+ * Throws, saying why, for bytes that are not one.
15
+ */
16
+ export declare const inspectRuntime: (bytes: Uint8Array) => {
17
+ entry: string;
18
+ files: string[];
19
+ };
20
+ /**
21
+ * A project's runtime module, as a server of its own runs it — `src/runtime/index.ts`, or what `build` compiled it to —
22
+ * or nothing when the project has none: a project starts one by writing it (`plitzi runtime add`), with nothing to wire.
23
+ */
24
+ export declare const loadRuntimeModule: (file: string) => Promise<SpaceRuntime | undefined>;
25
+ /**
26
+ * A packed runtime written into `dir` and imported: its module's default export. `dir` must be inside the host's own
27
+ * project, so the packages the bundle leaves to the host resolve to the host's — one copy of each.
28
+ */
29
+ export declare const loadRuntime: (bytes: Uint8Array, dir: string) => Promise<SpaceRuntime>;
@@ -0,0 +1,3 @@
1
+ export { inspectRuntime, loadRuntime, loadRuntimeModule, MAX_RUNTIME_BUNDLE_BYTES, packRuntime, runtimeBundleId } from './bundle';
2
+ export { createRuntimeProxyStage, runtimeEndpointsStage, serveRuntime } from './stages';
3
+ export type { RuntimeProxyConfig, RuntimeTarget, ServedRuntime } from './stages';
@@ -0,0 +1,229 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
3
+ import path from "node:path";
4
+ import { PLATFORM_HEADERS, endpointFor, endpointProblem } from "@plitzi/sdk-shared/functions";
5
+ import { clientIp, requestOrigin, webRequestOf, writeWebResponse } from "@plitzi/sdk-kernel/http";
6
+ import { esbuildBuild } from "@plitzi/sdk-kernel/build";
7
+ import fs from "node:fs/promises";
8
+ import { pathToFileURL } from "node:url";
9
+ import { gunzipSync, gzipSync } from "node:zlib";
10
+ import http from "node:http";
11
+ import https from "node:https";
12
+ // src/runtimes/bundle.ts
13
+ /** What the runtime's host provides, and a bundle must not carry a copy of: the platform's packages and React. */
14
+ var PROVIDED = [
15
+ "@plitzi/*",
16
+ "react",
17
+ "react-dom",
18
+ "react/*",
19
+ "react-dom/*"
20
+ ];
21
+ /** A packed runtime at most this big: its code and every dependency, not its data. */
22
+ var MAX_RUNTIME_BUNDLE_BYTES = 33554432;
23
+ var FORMAT = 1;
24
+ var ENTRY = "runtime.mjs";
25
+ /** A bundle's id: what its bytes are, so the same code packed twice is one bundle. */
26
+ var runtimeBundleId = (bytes) => createHash("sha256").update(bytes).digest("hex");
27
+ /**
28
+ * A runtime's module packed to travel: bundled for Node with every dependency it imports — but the platform's packages
29
+ * and React, which the host provides, so there is one copy of each — and gzipped. `entry` is the module whose default
30
+ * export is `defineRuntime(…)`.
31
+ */
32
+ var packRuntime = async (entry) => {
33
+ const result = await esbuildBuild({
34
+ entryPoints: [entry],
35
+ bundle: true,
36
+ platform: "node",
37
+ format: "esm",
38
+ target: "node22",
39
+ external: PROVIDED,
40
+ outdir: "runtime",
41
+ entryNames: "runtime",
42
+ outExtension: { ".js": ".mjs" },
43
+ banner: { js: "import { createRequire as __plitziRequire } from \"node:module\"; const require = __plitziRequire(import.meta.url);" },
44
+ splitting: false,
45
+ logLevel: "warning",
46
+ write: false
47
+ });
48
+ const files = Object.fromEntries(result.outputFiles.map((output) => [path.basename(output.path), Buffer.from(output.contents).toString("base64")]));
49
+ if (!(ENTRY in files)) throw new Error(`Packing ${entry} produced no ${ENTRY}`);
50
+ const bytes = gzipSync(JSON.stringify({
51
+ format: FORMAT,
52
+ entry: ENTRY,
53
+ files
54
+ }));
55
+ if (bytes.byteLength > 33554432) throw new Error(`A runtime is at most ${String(MAX_RUNTIME_BUNDLE_BYTES / 1024 / 1024)} MB packed; this one is ${(bytes.byteLength / 1024 / 1024).toFixed(1)} MB`);
56
+ return new Uint8Array(bytes);
57
+ };
58
+ /** A packed runtime read back — refused whole when it is not one. */
59
+ var unpack = (bytes) => {
60
+ let parsed;
61
+ try {
62
+ parsed = JSON.parse(gunzipSync(bytes).toString("utf8"));
63
+ } catch {
64
+ throw new Error("Not a packed runtime: it is not gzipped JSON");
65
+ }
66
+ if (!isRecord(parsed) || parsed.format !== FORMAT || typeof parsed.entry !== "string" || !isRecord(parsed.files)) throw new Error(`Not a packed runtime of format ${String(FORMAT)}`);
67
+ const files = {};
68
+ Object.entries(parsed.files).forEach(([name, content]) => {
69
+ if (typeof content !== "string" || name !== path.basename(name) || name.startsWith(".")) throw new Error(`"${name}" is not a file a packed runtime can hold`);
70
+ files[name] = content;
71
+ });
72
+ if (!(parsed.entry in files)) throw new Error(`A packed runtime's entry, ${parsed.entry}, is not among its files`);
73
+ return {
74
+ format: FORMAT,
75
+ entry: parsed.entry,
76
+ files
77
+ };
78
+ };
79
+ /**
80
+ * What a packed runtime holds, read without running any of it — what a platform checks a bundle with before keeping it.
81
+ * Throws, saying why, for bytes that are not one.
82
+ */
83
+ var inspectRuntime = (bytes) => {
84
+ if (bytes.byteLength > 33554432) throw new Error(`A runtime is at most ${String(MAX_RUNTIME_BUNDLE_BYTES / 1024 / 1024)} MB packed`);
85
+ const { entry, files } = unpack(bytes);
86
+ return {
87
+ entry,
88
+ files: Object.keys(files)
89
+ };
90
+ };
91
+ var isRuntime = (value) => isRecord(value) && typeof value.start === "function";
92
+ /** A module's default export, held to what a runtime is — or refused, saying how to write one. */
93
+ var runtimeOf = (loaded) => {
94
+ const runtime = isRecord(loaded) ? loaded.default : void 0;
95
+ if (!isRuntime(runtime)) throw new Error("A runtime module exports its runtime by default: export default defineRuntime({ start: … })");
96
+ return runtime;
97
+ };
98
+ /**
99
+ * A project's runtime module, as a server of its own runs it — `src/runtime/index.ts`, or what `build` compiled it to —
100
+ * or nothing when the project has none: a project starts one by writing it (`plitzi runtime add`), with nothing to wire.
101
+ */
102
+ var loadRuntimeModule = async (file) => {
103
+ try {
104
+ await fs.access(file);
105
+ } catch {
106
+ return;
107
+ }
108
+ return runtimeOf(await import(pathToFileURL(file).href));
109
+ };
110
+ /**
111
+ * A packed runtime written into `dir` and imported: its module's default export. `dir` must be inside the host's own
112
+ * project, so the packages the bundle leaves to the host resolve to the host's — one copy of each.
113
+ */
114
+ var loadRuntime = async (bytes, dir) => {
115
+ const { entry, files } = unpack(bytes);
116
+ await fs.mkdir(dir, { recursive: true });
117
+ await Promise.all(Object.entries(files).map(([name, content]) => fs.writeFile(path.join(dir, name), Buffer.from(content, "base64"))));
118
+ return runtimeOf(await import(pathToFileURL(path.join(dir, entry)).href));
119
+ };
120
+ // src/runtimes/stages.ts
121
+ var originOf = (ctx) => requestOrigin(ctx.req) || `${ctx.req.protocol}://${ctx.req.hostname}`;
122
+ /** A runtime's endpoints answered in this process — self-hosting — exactly as the platform forwards them to its own. */
123
+ var runtimeEndpointsStage = (endpoints) => {
124
+ const paths = Object.keys(endpoints);
125
+ const problems = paths.flatMap((path) => endpointProblem(path) ?? []);
126
+ if (problems.length > 0) throw new Error(problems.join("; "));
127
+ return async (ctx) => {
128
+ const endpoint = endpointFor(paths, ctx.req.path);
129
+ const answer = endpoint ? endpoints[endpoint] : void 0;
130
+ if (!endpoint || !answer) return false;
131
+ ctx.operation = `endpoint ${endpoint}`;
132
+ const request = await webRequestOf(ctx.raw, `${originOf(ctx)}${ctx.raw.url ?? ctx.req.path}`, PLATFORM_HEADERS);
133
+ await writeWebResponse(ctx.rawRes, await answer(request), ctx.signal);
134
+ return true;
135
+ };
136
+ };
137
+ /**
138
+ * A space runtime served by a self-hosted server instead of the platform: started here, its functions loaded natively
139
+ * and its endpoints answered by a stage — the same module the platform runs as a runtime of the space.
140
+ */
141
+ var serveRuntime = async (runtime, context) => {
142
+ const parts = await runtime.start(context);
143
+ return {
144
+ native: parts.functions ? [parts.functions] : [],
145
+ stage: runtimeEndpointsStage(parts.endpoints ?? {}),
146
+ close: async () => {
147
+ await parts.close?.();
148
+ }
149
+ };
150
+ };
151
+ var HOP_BY_HOP = [
152
+ "connection",
153
+ "keep-alive",
154
+ "transfer-encoding",
155
+ "upgrade"
156
+ ];
157
+ /** The query parameter a platform credential rides in (`credentials.ts`): never forwarded either. */
158
+ var PLATFORM_QUERY_CREDENTIAL = "access-token";
159
+ /** Never forwarded to a runtime: one hop's, and the platform's — the visitor's session is not the runtime's to hold. */
160
+ var NOT_FORWARDED = /* @__PURE__ */ new Set([
161
+ ...HOP_BY_HOP,
162
+ ...PLATFORM_HEADERS,
163
+ "host"
164
+ ]);
165
+ /** Never answered from one: the host's cookies are the platform's, as a function route's are. */
166
+ var NOT_ANSWERED = /* @__PURE__ */ new Set([...HOP_BY_HOP, "set-cookie"]);
167
+ /**
168
+ * The page server forwarding a space's endpoints to its runtime: the request as it came, streamed both ways — an agent's
169
+ * event stream included — without the visitor's cookies or `Authorization`, and with who asked in `X-Forwarded-*`.
170
+ *
171
+ * A data stage: after the auth chain, so the space is known, and before the space's `/fn/` routes and its pages.
172
+ */
173
+ var createRuntimeProxyStage = ({ lookup, onForward }) => async (ctx) => {
174
+ const { spaceId, environment = "main" } = ctx.req.ctx.spaceDeployment ?? {};
175
+ if (typeof spaceId !== "number") return false;
176
+ const target = await lookup({
177
+ spaceId,
178
+ environment
179
+ });
180
+ const endpoint = target ? endpointFor(target.endpoints, ctx.req.path) : void 0;
181
+ if (!target || !endpoint) return false;
182
+ ctx.operation = `runtime ${endpoint}`;
183
+ onForward?.({
184
+ spaceId,
185
+ environment,
186
+ endpoint
187
+ });
188
+ const headers = {};
189
+ Object.entries(ctx.raw.headers).forEach(([name, value]) => {
190
+ if (!name.startsWith(":") && !NOT_FORWARDED.has(name) && value !== void 0) headers[name] = value;
191
+ });
192
+ headers.authorization = `Bearer ${target.secret}`;
193
+ headers["x-forwarded-host"] = ctx.req.hostname;
194
+ headers["x-forwarded-proto"] = ctx.req.protocol;
195
+ headers["x-forwarded-for"] = clientIp(ctx.raw, ctx.req);
196
+ const url = new URL(ctx.raw.url ?? ctx.req.path, target.url);
197
+ url.searchParams.delete(PLATFORM_QUERY_CREDENTIAL);
198
+ await new Promise((resolve) => {
199
+ const upstream = (url.protocol === "https:" ? https : http).request(url, {
200
+ method: ctx.raw.method,
201
+ headers
202
+ });
203
+ const unreachable = () => {
204
+ if (!ctx.rawRes.headersSent) {
205
+ ctx.rawRes.writeHead(502, { "content-type": "application/json" });
206
+ ctx.rawRes.end(JSON.stringify({ error: "This space’s runtime is not answering" }));
207
+ } else ctx.rawRes.end();
208
+ resolve();
209
+ };
210
+ ctx.signal.addEventListener("abort", () => upstream.destroy(), { once: true });
211
+ upstream.on("error", unreachable);
212
+ upstream.on("response", (answer) => {
213
+ const answered = {};
214
+ Object.entries(answer.headers).forEach(([name, value]) => {
215
+ if (!NOT_ANSWERED.has(name) && value !== void 0) answered[name] = value;
216
+ });
217
+ ctx.rawRes.writeHead(answer.statusCode ?? 502, answered);
218
+ answer.on("data", (chunk) => ctx.rawRes.write(chunk));
219
+ answer.on("end", () => {
220
+ ctx.rawRes.end();
221
+ resolve();
222
+ });
223
+ answer.on("error", unreachable);
224
+ });
225
+ ctx.raw.pipe(upstream);
226
+ });
227
+ return true;
228
+ };
229
+ export { MAX_RUNTIME_BUNDLE_BYTES, createRuntimeProxyStage, inspectRuntime, loadRuntime, loadRuntimeModule, packRuntime, runtimeBundleId, runtimeEndpointsStage, serveRuntime };
@@ -0,0 +1,52 @@
1
+ import { BaseContext, Stage } from '@plitzi/sdk-kernel/http';
2
+ import { SpaceRuntime, SpaceRuntimeContext, SpaceRuntimeEndpoint, FunctionsDefinition } from '@plitzi/sdk-shared/functions';
3
+ /** A runtime's endpoints answered in this process — self-hosting — exactly as the platform forwards them to its own. */
4
+ export declare const runtimeEndpointsStage: (endpoints: Record<string, SpaceRuntimeEndpoint>) => Stage<BaseContext>;
5
+ /** A runtime on a server of its own: what `createServer` is handed of it, and how to stop it. */
6
+ export type ServedRuntime = {
7
+ /** Its tasks and routes, for `functions.native`. */
8
+ native: FunctionsDefinition[];
9
+ /**
10
+ * Its endpoints, for `data` — where the platform forwards a space's: behind the auth chain and the cross-site guard,
11
+ * gating who may call them themselves.
12
+ */
13
+ stage: Stage<BaseContext>;
14
+ close: () => Promise<void>;
15
+ };
16
+ /**
17
+ * A space runtime served by a self-hosted server instead of the platform: started here, its functions loaded natively
18
+ * and its endpoints answered by a stage — the same module the platform runs as a runtime of the space.
19
+ */
20
+ export declare const serveRuntime: (runtime: SpaceRuntime, context: SpaceRuntimeContext) => Promise<ServedRuntime>;
21
+ /** Where a space's runtime is, for the page server to forward its endpoints to. */
22
+ export type RuntimeTarget = {
23
+ /** Its base URL — `http://10.0.4.7:8791`. */
24
+ url: string;
25
+ /** What it is presented, as `Authorization: Bearer <secret>`. */
26
+ secret: string;
27
+ /** The paths it answers — what it described when it started. */
28
+ endpoints: readonly string[];
29
+ };
30
+ export type RuntimeProxyConfig = {
31
+ /** The runtime serving a space and environment — or none, for a space the platform serves alone. */
32
+ lookup: (space: {
33
+ spaceId: number;
34
+ environment: string;
35
+ }) => Promise<RuntimeTarget | undefined>;
36
+ /**
37
+ * Told each time a request is forwarded to a space's runtime — not for every request of the space, most of which are
38
+ * its pages: what counts as a runtime being used, for a deployment that stops the ones nobody uses.
39
+ */
40
+ onForward?: (space: {
41
+ spaceId: number;
42
+ environment: string;
43
+ endpoint: string;
44
+ }) => void;
45
+ };
46
+ /**
47
+ * The page server forwarding a space's endpoints to its runtime: the request as it came, streamed both ways — an agent's
48
+ * event stream included — without the visitor's cookies or `Authorization`, and with who asked in `X-Forwarded-*`.
49
+ *
50
+ * A data stage: after the auth chain, so the space is known, and before the space's `/fn/` routes and its pages.
51
+ */
52
+ export declare const createRuntimeProxyStage: ({ lookup, onForward }: RuntimeProxyConfig) => Stage<BaseContext>;
@@ -0,0 +1,4 @@
1
+ export { createSqliteJobQueue } from './jobQueue';
2
+ export { createSqliteKv } from './kv';
3
+ export type { SqliteJobQueueOptions } from './jobQueue';
4
+ export type { SqliteKvOptions } from './kv';