@webpodjs/sdk 0.2.7 → 0.3.1

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/README.md +93 -15
  2. package/dist/agent/backend.d.ts +18 -1
  3. package/dist/agent/backend.js +275 -76
  4. package/dist/agent/backend.js.map +1 -1
  5. package/dist/agent/fs.d.ts +2 -2
  6. package/dist/agent/fs.js +3 -2
  7. package/dist/agent/fs.js.map +1 -1
  8. package/dist/agent/protocol.d.ts +40 -1
  9. package/dist/agent/protocol.js +39 -3
  10. package/dist/agent/protocol.js.map +1 -1
  11. package/dist/errors.d.ts +1 -1
  12. package/dist/errors.js.map +1 -1
  13. package/dist/exec/client.js +21 -6
  14. package/dist/exec/client.js.map +1 -1
  15. package/dist/exec/frame.js +5 -0
  16. package/dist/exec/frame.js.map +1 -1
  17. package/dist/fs/tar.d.ts +1 -1
  18. package/dist/fs/tar.js +8 -2
  19. package/dist/fs/tar.js.map +1 -1
  20. package/dist/fs/workspace.js +61 -30
  21. package/dist/fs/workspace.js.map +1 -1
  22. package/dist/host/backend.d.ts +11 -0
  23. package/dist/host/backend.js +71 -14
  24. package/dist/host/backend.js.map +1 -1
  25. package/dist/host/channel.js +4 -1
  26. package/dist/host/channel.js.map +1 -1
  27. package/dist/host/controller.d.ts +2 -0
  28. package/dist/host/controller.js +11 -4
  29. package/dist/host/controller.js.map +1 -1
  30. package/dist/host/devices.d.ts +28 -2
  31. package/dist/host/devices.js +55 -7
  32. package/dist/host/devices.js.map +1 -1
  33. package/dist/host/pump-worker.js +12 -4
  34. package/dist/host/pump-worker.js.map +1 -1
  35. package/dist/host-exec/controller.d.ts +161 -4
  36. package/dist/host-exec/controller.js +1041 -70
  37. package/dist/host-exec/controller.js.map +1 -1
  38. package/dist/host-exec/protocol.d.ts +337 -4
  39. package/dist/host-exec/protocol.js +34 -0
  40. package/dist/host-exec/protocol.js.map +1 -1
  41. package/dist/host-exec/route.js +74 -13
  42. package/dist/host-exec/route.js.map +1 -1
  43. package/dist/host-exec/shim.d.ts +8 -2
  44. package/dist/host-exec/shim.js +77 -12
  45. package/dist/host-exec/shim.js.map +1 -1
  46. package/dist/index.d.ts +3 -1
  47. package/dist/index.js +1 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/net/client.d.ts +5 -1
  50. package/dist/net/client.js +8 -4
  51. package/dist/net/client.js.map +1 -1
  52. package/dist/net/options.d.ts +14 -0
  53. package/dist/net/options.js +1 -1
  54. package/dist/net/options.js.map +1 -1
  55. package/dist/net/preview.d.ts +15 -1
  56. package/dist/net/preview.js +24 -4
  57. package/dist/net/preview.js.map +1 -1
  58. package/dist/output.d.ts +23 -0
  59. package/dist/output.js +161 -0
  60. package/dist/output.js.map +1 -0
  61. package/dist/pod.d.ts +21 -7
  62. package/dist/pod.js +165 -29
  63. package/dist/pod.js.map +1 -1
  64. package/dist/preview-relay.js +24 -7
  65. package/dist/preview-relay.js.map +1 -1
  66. package/dist/preview-serviceworker.js +71 -8
  67. package/dist/preview-serviceworker.js.map +1 -1
  68. package/dist/tools.d.ts +79 -0
  69. package/dist/tools.js +47 -0
  70. package/dist/tools.js.map +1 -0
  71. package/dist/types.d.ts +62 -2
  72. package/dist/version.d.ts +1 -1
  73. package/dist/version.js +1 -1
  74. package/package.json +1 -1
package/README.md CHANGED
@@ -51,9 +51,9 @@ p.stdout.pipeTo(terminal.writable); // ReadableStream<Uint8Array>; stderr
51
51
  const w = p.stdin.getWriter(); // WritableStream<Uint8Array>, or pass { stdin: stream | bytes | string }
52
52
  await p.resize({ cols: 120, rows: 40 });
53
53
  await p.kill("SIGINT");
54
- await p.exit; // { code: number | null, signal: Signal | null }
54
+ await p.exit; // { code: number | null, signal: Signal | null }, dropped when some output was ("Output")
55
55
 
56
- await pod.exec("ls", ["-l"]); // { code, signal, stdout, stderr } as text
56
+ await pod.exec("ls", ["-l"]); // { code, signal, stdout, stderr } as text, 16 MiB of each at most
57
57
  await pod.fs.writeFile("/workspace/a.txt", "hi");
58
58
  await pod.fs.readFile("/workspace/a.txt", "utf8");
59
59
  await pod.fs.readdir("/"); await pod.fs.mkdir("/x", { recursive: true }); await pod.fs.stat("/x"); await pod.fs.rm("/x", { recursive: true });
@@ -61,13 +61,60 @@ await pod.dispose(); // further calls fail with DISPOSED
61
61
  ```
62
62
 
63
63
  Errors are `WebPodError` with a `code` (`ENOENT`, `EEXIST`, `ENOTDIR`, `EISDIR`, `ENOTEMPTY`, `EINVAL`,
64
- `ENOSPC` (storage full), `ENGINE_UNAVAILABLE`, `UNSUPPORTED`, `DISPOSED`).
64
+ `ENOSPC` (storage full), `ENOBUFS` (`pod.exec` past `maxBuffer`), `ENGINE_UNAVAILABLE`, `UNSUPPORTED`, `DISPOSED`,
65
+ `AGENT_RESTARTED`: the guest agent started a new session, below).
66
+
67
+ **The guest agent restarting.** When the agent in the guest is killed or runs out of memory (pod-init starts it again
68
+ a second later), or its stream breaks, it starts a new session. What it ran has ended: a process's `exit` rejects with
69
+ `AGENT_RESTARTED` (its output streams error with it), and so do the `pod.fs` calls and the other requests that waited
70
+ for it. Retry what you need: the pod goes on with the new session, which gets the pod CA, host mode and the ports host
71
+ processes hold in the guest again; a `pod.fs.watch` of a guest path goes on after an `overflow` event (rescan). The
72
+ shared workspace (`/workspace`, the FS Worker) is not affected.
73
+
74
+ ```js
75
+ pod.on("agent-restart", ({ session, ended, final, reason }) => {
76
+ // session: 2 at the first restart; ended: processes that ended with the last session.
77
+ if (final) console.warn(`pod lost: ${reason}`); // every later call fails with AGENT_RESTARTED: boot it again
78
+ });
79
+ ```
80
+
81
+ `final` is true when the pod does not go on: the agent restarted more than `engine.agentRestarts` times within a
82
+ minute (default 3; 0 ends the pod at the first restart), came back as another agent, or is from before 0.3 (without
83
+ `rejoin`). A host process's guest child ends as killed by SIGKILL; host processes started
84
+ by the guest's `node` shim end as by SIGHUP. A disk snapshot (`pod.snapshot`) the restart came in the middle of fails
85
+ with `AGENT_RESTARTED` and is not kept. A restart while `Pod.boot` runs fails the boot.
65
86
 
66
87
  Isolation: `isolation: "auto"` (default) picks `iso` when `crossOriginIsolated` and `noiso` otherwise
67
88
  (`cpus > 1` requires `iso`); `"require"` fails without isolation. For hosts that cannot send
68
89
  COOP/COEP, call `ensureCrossOriginIsolation({ serviceWorkerUrl: "/coi-serviceworker.js" })` before
69
90
  booting: it registers the worker, reloads once, and resolves `{ isolated, via | reason }`.
70
91
 
92
+ ## Output
93
+
94
+ A process's `stdout` and `stderr` are byte streams. While nothing reads one (no `getReader()`, `for await`, `pipeTo`
95
+ or `new Response(...)` on it, or after its reader's `releaseLock()`), it does not hold the process up: the pod takes
96
+ what the process writes and keeps the last `outputBuffer` bytes of it, 1 MiB per stream by default
97
+ (`SpawnOptions.outputBuffer`, or `Pod.boot({ outputBuffer })` for the pod's processes); older bytes are dropped, and a
98
+ reader that comes later starts with those kept. From a stream something reads nothing is dropped: the process waits while
99
+ `outputBuffer` bytes of it are not read, as a pipe's writer waits for its reader, so a reader that holds the stream and
100
+ does not read holds the process. After `cancel()` the rest goes nowhere and the process goes on. Guest and host
101
+ processes alike, and in an execution origin.
102
+
103
+ `p.dropped` (`{ stdout, stderr }`) counts the bytes dropped so far; `exit` carries it when it is not zero
104
+ (`{ code: 0, signal: null, dropped: { stdout: 2097152, stderr: 0 } }`), and a process's first drop logs a warning. An
105
+ app that waits for `exit` before it reads the output gets the last `outputBuffer` bytes of it: use `pod.exec`, which
106
+ reads both streams as they come, or a larger `outputBuffer` (`Infinity` keeps everything).
107
+
108
+ `pod.exec` collects `maxBuffer` bytes of each stream at most, 16 MiB by default. Past it the process is killed (SIGKILL)
109
+ and `exec` rejects with `ENOBUFS`, as node's `child_process.exec` does; `truncate: "tail"` keeps the last
110
+ `maxBuffer` bytes instead and lets the process run on (the result's `dropped` says how many went).
111
+
112
+ ```js
113
+ const dev = pod.spawn("npm", ["run", "dev"]); // logs nobody reads: the last 1 MiB of each stream is kept
114
+ const test = await pod.exec("npm", ["test"], { maxBuffer: 64 << 20 });
115
+ const build = await pod.exec("make", [], { maxBuffer: 1 << 20, truncate: "tail" }); // build.dropped?.stdout
116
+ ```
117
+
71
118
  ## Execution origin
72
119
 
73
120
  `Pod.boot({ executionOrigin: "<url of dist/exec-frame.html on another site>", engine })` boots the
@@ -85,26 +132,38 @@ Needs a backend with `net` (a `NetPortSink` that hands MessagePorts to the net W
85
132
  webpod-net's `InboundBridge` serves them).
86
133
 
87
134
  ```ts
88
- const url = await pod.net.expose(5173); // https://app.example/__webpod/<pod.id>/5173/
135
+ const url = await pod.net.expose(5173); // https://<id>.webpodsandbox.top/ (Pod.defaultPreviewRelay)
89
136
  iframe.src = url; // served by the preview service worker
90
- // On a preview origin of its own: the guest's pages cannot reach the app.
91
- const isolated = await pod.net.expose(5173, { relay: "https://{id}.preview.example-usercontent.com/preview-relay.html" });
137
+ // On a preview origin of your own, one per preview: https://<id>.preview.example-usercontent.com/
138
+ const own = await pod.net.expose(5173, { relay: "https://{id}.preview.example-usercontent.com/preview-relay.html" });
139
+ // On the app's origin: https://app.example/__webpod/<pod.id>/5173/ (only preview code you trust)
140
+ const here = await pod.net.expose(5173, { relay: false });
92
141
  const r = await pod.fetch("http://localhost:8000/api", { method: "POST", body: "{}" });
93
142
  const sock = await pod.net.connect(6379); // { readable, writable, abort() }; ECONNREFUSED if closed
94
143
  ```
95
144
 
145
+ `pod.fetch("https://localhost:PORT/...")` sends the same request, plaintext as all the page's connections are: a
146
+ host process's TLS server takes it (host mode, `docs/host-exec.md` "TLS servers"), a TLS server in the guest does not.
147
+
96
148
  Preview worker behaviour: absolute-path subresources and links of a preview document are routed to
97
149
  the same pod/port (by client id, then Referer); `Location` headers pointing at the guest are
98
150
  rewritten; requests ask the guest for identity encoding (synthetic responses are not decoded);
99
151
  `Set-Cookie` cannot be set on synthetic responses and is dropped; responses carry
100
152
  `Cross-Origin-Embedder-Policy` (`?coep=require-corp|credentialless|none`) so they load inside
101
153
  isolated pages. When the page that owns the pod is gone, previews answer 503 `Pod not running`.
102
- By default previews run on the app's origin, with the app's privileges: only preview code you
103
- trust there. With `relay` they run on a preview origin of its own, which serves
104
- `preview-relay.html`, `preview-relay.js` and `preview-serviceworker.js` from this package's `dist`
105
- and a `webpod-preview.json` listing the app's origins (`{ "hosts": [...] }`); the SDK embeds the
106
- relay in a hidden iframe and serves the previews' requests through it, and `{id}` in the URL
107
- gives each preview (pod and port) an origin of its own (`docs/deploy.md`, "Previews and isolation").
154
+ A navigation (a GET of a page) that the server answers with 502, 503 or 504 within 20 s of its port's first answer
155
+ (a dev server that is starting) is retried after 0.5, 1, 2 and then every 4 s, the preview showing that the server is
156
+ starting meanwhile; then the server's own response is shown. Subresources, other methods and `pod.fetch` are not
157
+ retried; `expose(port, { startRetry: false })` turns it off, a number sets the seconds.
158
+ With `relay: false` previews run on the app's origin, with the app's privileges: only preview code
159
+ you trust there. With a `relay` (by default the SDK's own, `Pod.defaultPreviewRelay`) they run on a
160
+ preview origin, which serves `preview-relay.html`, `preview-relay.js` and `preview-serviceworker.js`
161
+ from this package's `dist` and a `webpod-preview.json` listing the app's origins
162
+ (`{ "hosts": [...] }`); the SDK embeds the relay in a hidden iframe and serves the previews' requests
163
+ through it. `{id}` in the relay's host name gives each preview (pod and port) an origin of its own,
164
+ whose root it is: the guest's pages see the paths the guest serves, as client-side routers need.
165
+ Otherwise previews are under `__webpod/<podId>/<port>/` and their pages see that prefix in
166
+ `location` (`docs/deploy.md`, "Previews and isolation", "Paths in a preview").
108
167
  Only one service worker can control a scope: with `coi-sw`, register
109
168
  `coi-serviceworker.js?preview` instead of two workers, e.g.
110
169
  `navigator.serviceWorker.register("/coi-serviceworker.js?preview&coep=require-corp")`.
@@ -117,9 +176,9 @@ that sends WebSockets aimed at the preview origin (absolute paths such as Vite's
117
176
 
118
177
  `createAgentBackend({ transport: { readable, writable }, mounts? })` speaks the guest agent protocol
119
178
  (docs/agent-protocol.md) over any byte stream, e.g. the `org.webpod.agent` channel webpod-host
120
- exposes, and returns a `PodBackend` for `Pod.boot({ backend })`. Output is acknowledged only as the
121
- page reads it, so a slow consumer backpressures the guest process; stdin writes wait for agent
122
- credit. Spawn failures reject `exit`/`pid` with `ENOENT`, `EACCES`, ... or `SPAWN_FAILED`.
179
+ exposes, and returns a `PodBackend` for `Pod.boot({ backend })`. Output is acknowledged only as it is
180
+ read, so a slow consumer backpressures the guest process (`pod.spawn`'s streams read it as "Output" says); stdin writes
181
+ wait for agent credit. Spawn failures reject `exit`/`pid` with `ENOENT`, `EACCES`, ... or `SPAWN_FAILED`.
123
182
 
124
183
  Pass `caCertificate` (the Pod CA PEM from webpod-net, never the key) to have the agent append it to
125
184
  every guest trust store and CA env var before the backend resolves (fast path, milliseconds);
@@ -167,8 +226,14 @@ another pod:
167
226
  import { exportTar, importTar } from "@webpodjs/sdk";
168
227
  const tar = await new Response(exportTar(pod.fs, "/workspace")).blob(); // files read as it streams
169
228
  await importTar(other.fs, tar, "/workspace"); // -> { files, dirs, symlinks, skipped }; skips ".."
229
+ await exportTar(pod.fs, "/workspace").pipeTo(await handle.createWritable()); // an OPFS file, Safari too
170
230
  ```
171
231
 
232
+ Each chunk `exportTar` gives is a buffer of its own (a view of a larger one is copied): WebKit's
233
+ `FileSystemWritableFileStream.write(view)` writes a view's whole buffer, not the view. The chunks of
234
+ `fs.createReadStream` and of a process's `stdout` and `stderr` are buffers of their own too (the agent's
235
+ protocol and host processes copy them); a stream of views of your own needs `chunk.slice()` before such a write.
236
+
172
237
  ## Engine (webpod-host)
173
238
 
174
239
  `Pod.boot({ engine: { manifestUrl } })` starts the engine Worker named by the manifest, attaches the
@@ -210,6 +275,18 @@ snapshot's import (27 MB for the node image; one cut short leaves what it stored
210
275
  visit) and for the image's chunks a cold boot reads before the agent says hello
211
276
  (`engine.bootTimeoutMs` waits on while the FS Worker downloads).
212
277
 
278
+ A boot that fails says how far it got: `engine did not report its channels (its last step: engine main,
279
+ at 4.2 s)`, `guest agent did not say hello (its last step: console: webpod: formatting /dev/vdb, at
280
+ 12.3 s)`; the FS Worker's `no reply to init` names its step (`init: workspace`). Once the agent said
281
+ hello, the last steps (the pod CA, the shares' mounts) have 60 s.
282
+
283
+ A site's storage left inconsistent (Safari's website data of the site deleted in part) may stop
284
+ answering. The FS Worker gives a first call 10 s, then opens the pod in memory in this tab (the data
285
+ disk and the workspace: `pod.backend.storage` is `{ data: "stalled", workspace: "stalled" }`, nothing
286
+ is kept, no snapshots) with a warning that names the call and says to clear the site's data. A call
287
+ that stops answering later (20 s) fails a boot in progress: `EIO: the site's storage did not answer:
288
+ OPFS getFileHandle("…") pending for 20 s; …`, and is a warning after it.
289
+
213
290
  ## Guest networking (egress)
214
291
 
215
292
  `engine.net: netWorker("/net-worker/worker.js")` attaches the net Worker (`packages/net-worker`,
@@ -224,6 +301,7 @@ const pod = await Pod.boot({
224
301
  mode: "browser", // or "none": no egress unless a route allows it
225
302
  corsProxy: "https://cors.example/", // or { url, token } (docs/cors-proxy-protocol.md)
226
303
  relay: { url: "wss://relay.example/v1/connect", getToken: () => myBackend.relayToken() },
304
+ dns: { upstream: "9.9.9.9:53" }, // the default with a relay: SRV, TXT, ... through it; false: none
227
305
  routes: [{ host: "*.pypi.org", via: "cors-proxy" }, { host: "10.0.0.0/8", via: "deny" }],
228
306
  },
229
307
  });
@@ -1,4 +1,4 @@
1
- import type { FsEvent, PodBackend, PodFs } from "../types.js";
1
+ import type { AgentRestart, FsEvent, PodBackend, PodFs } from "../types.js";
2
2
  import { type FsEventMsg, type GuestHostModeMsg, type HostModeMsg } from "./protocol.js";
3
3
  /** A reliable byte stream to the guest agent (e.g. the org.webpod.agent channel from webpod-host). */
4
4
  export interface AgentTransport {
@@ -41,6 +41,13 @@ export interface AgentBackendOptions {
41
41
  * workspace's `settle`: page changes are replayed in the guest first.
42
42
  */
43
43
  beforeSpawn?: () => Promise<unknown> | undefined;
44
+ /** Diagnostics (warnings of the agent, a session's restart, a resynced stream). Default: the console. */
45
+ onLog?: (level: string, text: string) => void;
46
+ /**
47
+ * Restarts of the agent within a minute that the connection goes on after (agents with `rejoin`); at one more it
48
+ * ends (`final`). Default 3; 0: it ends at the first.
49
+ */
50
+ maxRestarts?: number;
44
51
  }
45
52
  export interface CaInstallResult {
46
53
  /** System bundle that now includes the CA; the CA env vars point at it. */
@@ -58,12 +65,20 @@ export interface HostModeChannel {
58
65
  send(msg: HostModeMsg): Promise<void>;
59
66
  /** Where the agent's host mode messages go (one listener; null drops them). */
60
67
  listen(listener: ((msg: GuestHostModeMsg) => void) | null): void;
68
+ /**
69
+ * Called when the agent starts a new session that the connection goes on with: the host-mode processes of the last
70
+ * are gone (their shims with it). Its HostExecInfo, the last one sent, is sent again. Unsubscribes when called.
71
+ */
72
+ onSession?(listener: () => void): () => void;
61
73
  /** Resolves once the connection to the agent is over. */
62
74
  readonly closed: Promise<void>;
63
75
  }
64
76
  export interface AgentBackend extends PodBackend {
65
77
  /** Agent identification from its hello, e.g. `webpod-agent 0.0.0`. */
66
78
  readonly agent: string;
79
+ /** The agent's session: 1, then one more at each restart the connection went on after (agents with `rejoin`). */
80
+ readonly session: number;
81
+ onAgentRestart(listener: (event: AgentRestart) => void): () => void;
67
82
  /** Appends a CA certificate to the guest's trust stores (idempotent). */
68
83
  installCa(pem: string): Promise<CaInstallResult>;
69
84
  /** `settled` of the `caCertificate` install, or null when none was given. */
@@ -87,6 +102,8 @@ export interface AgentBackend extends PodBackend {
87
102
  readonly hostListen: import("../host-exec/controller.js").HostGuestPorts | null;
88
103
  /** Host mode, when the agent has it (`host-exec`), else null. */
89
104
  readonly hostMode: HostModeChannel | null;
105
+ /** kill(2) in the guest with user `uid`'s permission (agents with `kill`): 0 or the errno; else null. */
106
+ readonly killPid: ((pid: number, signal: number, uid: number) => Promise<number>) | null;
90
107
  }
91
108
  /**
92
109
  * A batch of page changes in parts of REPLAY_PART_BYTES at most, in order: one batch of a host process's writes can be