coderaft 0.0.25 → 0.0.27

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.
package/README.md CHANGED
@@ -135,6 +135,34 @@ interface CodeServerHandle {
135
135
  }
136
136
  ```
137
137
 
138
+ ### `spawnCodeServer(options)`
139
+
140
+ Runs the code-server in a forked Node.js child process — useful for isolating VS Code's singletons from the host or restarting the server without taking the host down. Accepts the same options as `startCodeServer`, plus a `spawn` sub-object (`env`, `execArgv`, `stdio`, `startupTimeout`).
141
+
142
+ ```ts
143
+ import { spawnCodeServer } from "coderaft";
144
+
145
+ const instance = await spawnCodeServer({
146
+ port: 6063,
147
+ defaultFolder: "/path/to/workspace",
148
+ });
149
+
150
+ console.log(`Ready at ${instance.url}`);
151
+
152
+ // Notify on unexpected worker exits (not fired during close/reload):
153
+ instance.on("exit", (code, signal) => {
154
+ console.warn(`worker died code=${code} signal=${signal}`);
155
+ });
156
+
157
+ // Restart the worker in place (reads fresh url/port/connectionToken after):
158
+ await instance.reload();
159
+
160
+ // Graceful shutdown — SIGTERM to the worker, then SIGKILL after 5s:
161
+ await instance.close();
162
+ ```
163
+
164
+ Options cross an IPC boundary, so nested values (`vscode`, etc.) must be JSON-compatible.
165
+
138
166
  ## CLI Options
139
167
 
140
168
  ### Server
@@ -375,6 +375,214 @@ DEALINGS IN THE SOFTWARE.
375
375
 
376
376
  ---------------------------------------------------------
377
377
 
378
+ codex
379
+ https://github.com/openai/codex
380
+
381
+ Apache License
382
+ Version 2.0, January 2004
383
+ http://www.apache.org/licenses/
384
+
385
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
386
+
387
+ 1. Definitions.
388
+
389
+ "License" shall mean the terms and conditions for use, reproduction,
390
+ and distribution as defined by Sections 1 through 9 of this document.
391
+
392
+ "Licensor" shall mean the copyright owner or entity authorized by
393
+ the copyright owner that is granting the License.
394
+
395
+ "Legal Entity" shall mean the union of the acting entity and all
396
+ other entities that control, are controlled by, or are under common
397
+ control with that entity. For the purposes of this definition,
398
+ "control" means (i) the power, direct or indirect, to cause the
399
+ direction or management of such entity, whether by contract or
400
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
401
+ outstanding shares, or (iii) beneficial ownership of such entity.
402
+
403
+ "You" (or "Your") shall mean an individual or Legal Entity
404
+ exercising permissions granted by this License.
405
+
406
+ "Source" form shall mean the preferred form for making modifications,
407
+ including but not limited to software source code, documentation
408
+ source, and configuration files.
409
+
410
+ "Object" form shall mean any form resulting from mechanical
411
+ transformation or translation of a Source form, including but
412
+ not limited to compiled object code, generated documentation,
413
+ and conversions to other media types.
414
+
415
+ "Work" shall mean the work of authorship, whether in Source or
416
+ Object form, made available under the License, as indicated by a
417
+ copyright notice that is included in or attached to the work
418
+ (an example is provided in the Appendix below).
419
+
420
+ "Derivative Works" shall mean any work, whether in Source or Object
421
+ form, that is based on (or derived from) the Work and for which the
422
+ editorial revisions, annotations, elaborations, or other modifications
423
+ represent, as a whole, an original work of authorship. For the purposes
424
+ of this License, Derivative Works shall not include works that remain
425
+ separable from, or merely link (or bind by name) to the interfaces of,
426
+ the Work and Derivative Works thereof.
427
+
428
+ "Contribution" shall mean any work of authorship, including
429
+ the original version of the Work and any modifications or additions
430
+ to that Work or Derivative Works thereof, that is intentionally
431
+ submitted to Licensor for inclusion in the Work by the copyright owner
432
+ or by an individual or Legal Entity authorized to submit on behalf of
433
+ the copyright owner. For the purposes of this definition, "submitted"
434
+ means any form of electronic, verbal, or written communication sent
435
+ to the Licensor or its representatives, including but not limited to
436
+ communication on electronic mailing lists, source code control systems,
437
+ and issue tracking systems that are managed by, or on behalf of, the
438
+ Licensor for the purpose of discussing and improving the Work, but
439
+ excluding communication that is conspicuously marked or otherwise
440
+ designated in writing by the copyright owner as "Not a Contribution."
441
+
442
+ "Contributor" shall mean Licensor and any individual or Legal Entity
443
+ on behalf of whom a Contribution has been received by Licensor and
444
+ subsequently incorporated within the Work.
445
+
446
+ 2. Grant of Copyright License. Subject to the terms and conditions of
447
+ this License, each Contributor hereby grants to You a perpetual,
448
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
449
+ copyright license to reproduce, prepare Derivative Works of,
450
+ publicly display, publicly perform, sublicense, and distribute the
451
+ Work and such Derivative Works in Source or Object form.
452
+
453
+ 3. Grant of Patent License. Subject to the terms and conditions of
454
+ this License, each Contributor hereby grants to You a perpetual,
455
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
456
+ (except as stated in this section) patent license to make, have made,
457
+ use, offer to sell, sell, import, and otherwise transfer the Work,
458
+ where such license applies only to those patent claims licensable
459
+ by such Contributor that are necessarily infringed by their
460
+ Contribution(s) alone or by combination of their Contribution(s)
461
+ with the Work to which such Contribution(s) was submitted. If You
462
+ institute patent litigation against any entity (including a
463
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
464
+ or a Contribution incorporated within the Work constitutes direct
465
+ or contributory patent infringement, then any patent licenses
466
+ granted to You under this License for that Work shall terminate
467
+ as of the date such litigation is filed.
468
+
469
+ 4. Redistribution. You may reproduce and distribute copies of the
470
+ Work or Derivative Works thereof in any medium, with or without
471
+ modifications, and in Source or Object form, provided that You
472
+ meet the following conditions:
473
+
474
+ (a) You must give any other recipients of the Work or
475
+ Derivative Works a copy of this License; and
476
+
477
+ (b) You must cause any modified files to carry prominent notices
478
+ stating that You changed the files; and
479
+
480
+ (c) You must retain, in the Source form of any Derivative Works
481
+ that You distribute, all copyright, patent, trademark, and
482
+ attribution notices from the Source form of the Work,
483
+ excluding those notices that do not pertain to any part of
484
+ the Derivative Works; and
485
+
486
+ (d) If the Work includes a "NOTICE" text file as part of its
487
+ distribution, then any Derivative Works that You distribute must
488
+ include a readable copy of the attribution notices contained
489
+ within such NOTICE file, excluding those notices that do not
490
+ pertain to any part of the Derivative Works, in at least one
491
+ of the following places: within a NOTICE text file distributed
492
+ as part of the Derivative Works; within the Source form or
493
+ documentation, if provided along with the Derivative Works; or,
494
+ within a display generated by the Derivative Works, if and
495
+ wherever such third-party notices normally appear. The contents
496
+ of the NOTICE file are for informational purposes only and
497
+ do not modify the License. You may add Your own attribution
498
+ notices within Derivative Works that You distribute, alongside
499
+ or as an addendum to the NOTICE text from the Work, provided
500
+ that such additional attribution notices cannot be construed
501
+ as modifying the License.
502
+
503
+ You may add Your own copyright statement to Your modifications and
504
+ may provide additional or different license terms and conditions
505
+ for use, reproduction, or distribution of Your modifications, or
506
+ for any such Derivative Works as a whole, provided Your use,
507
+ reproduction, and distribution of the Work otherwise complies with
508
+ the conditions stated in this License.
509
+
510
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
511
+ any Contribution intentionally submitted for inclusion in the Work
512
+ by You to the Licensor shall be under the terms and conditions of
513
+ this License, without any additional terms or conditions.
514
+ Notwithstanding the above, nothing herein shall supersede or modify
515
+ the terms of any separate license agreement you may have executed
516
+ with Licensor regarding such Contributions.
517
+
518
+ 6. Trademarks. This License does not grant permission to use the trade
519
+ names, trademarks, service marks, or product names of the Licensor,
520
+ except as required for reasonable and customary use in describing the
521
+ origin of the Work and reproducing the content of the NOTICE file.
522
+
523
+ 7. Disclaimer of Warranty. Unless required by applicable law or
524
+ agreed to in writing, Licensor provides the Work (and each
525
+ Contributor provides its Contributions) on an "AS IS" BASIS,
526
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
527
+ implied, including, without limitation, any warranties or conditions
528
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
529
+ PARTICULAR PURPOSE. You are solely responsible for determining the
530
+ appropriateness of using or redistributing the Work and assume any
531
+ risks associated with Your exercise of permissions under this License.
532
+
533
+ 8. Limitation of Liability. In no event and under no legal theory,
534
+ whether in tort (including negligence), contract, or otherwise,
535
+ unless required by applicable law (such as deliberate and grossly
536
+ negligent acts) or agreed to in writing, shall any Contributor be
537
+ liable to You for damages, including any direct, indirect, special,
538
+ incidental, or consequential damages of any character arising as a
539
+ result of this License or out of the use or inability to use the
540
+ Work (including but not limited to damages for loss of goodwill,
541
+ work stoppage, computer failure or malfunction, or any and all
542
+ other commercial damages or losses), even if such Contributor
543
+ has been advised of the possibility of such damages.
544
+
545
+ 9. Accepting Warranty or Additional Liability. While redistributing
546
+ the Work or Derivative Works thereof, You may choose to offer,
547
+ and charge a fee for, acceptance of support, warranty, indemnity,
548
+ or other liability obligations and/or rights consistent with this
549
+ License. However, in accepting such obligations, You may act only
550
+ on Your own behalf and on Your sole responsibility, not on behalf
551
+ of any other Contributor, and only if You agree to indemnify,
552
+ defend, and hold each Contributor harmless for any liability
553
+ incurred by, or claims asserted against, such Contributor by reason
554
+ of your accepting any such warranty or additional liability.
555
+
556
+ END OF TERMS AND CONDITIONS
557
+
558
+ APPENDIX: How to apply the Apache License to your work.
559
+
560
+ To apply the Apache License to your work, attach the following
561
+ boilerplate notice, with the fields enclosed by brackets "[]"
562
+ replaced with your own identifying information. (Don't include
563
+ the brackets!) The text should be enclosed in the appropriate
564
+ comment syntax for the file format. We also recommend that a
565
+ file or class name and description of purpose be included on the
566
+ same "printed page" as the copyright notice for easier
567
+ identification within third-party archives.
568
+
569
+ Copyright 2025 OpenAI
570
+
571
+ Licensed under the Apache License, Version 2.0 (the "License");
572
+ you may not use this file except in compliance with the License.
573
+ You may obtain a copy of the License at
574
+
575
+ http://www.apache.org/licenses/LICENSE-2.0
576
+
577
+ Unless required by applicable law or agreed to in writing, software
578
+ distributed under the License is distributed on an "AS IS" BASIS,
579
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
580
+ See the License for the specific language governing permissions and
581
+ limitations under the License.
582
+ ---------------------------------------------------------
583
+
584
+ ---------------------------------------------------------
585
+
378
586
  Colorsublime-Themes 0.1.0
379
587
  https://github.com/Colorsublime/Colorsublime-Themes
380
588
 
@@ -528,7 +736,7 @@ dompurify 3.2.7 - Apache 2.0
528
736
  https://github.com/cure53/DOMPurify
529
737
 
530
738
  DOMPurify
531
- Copyright 2025 Dr.-Ing. Mario Heiderich, Cure53
739
+ Copyright 2025-2026 Dr.-Ing. Mario Heiderich, Cure53
532
740
 
533
741
  DOMPurify is free software; you can redistribute it and/or modify it under the
534
742
  terms of either:
@@ -726,7 +934,7 @@ b) the Mozilla Public License Version 2.0
726
934
  same "printed page" as the copyright notice for easier
727
935
  identification within third-party archives.
728
936
 
729
- Copyright [yyyy] [name of copyright owner]
937
+ Copyright 2025-2026 Dr.-Ing. Mario Heiderich, Cure53
730
938
 
731
939
  Licensed under the Apache License, Version 2.0 (the "License");
732
940
  you may not use this file except in compliance with the License.
@@ -1985,7 +2193,7 @@ THE SOFTWARE.
1985
2193
  marked 14.0.0 - MIT
1986
2194
  https://github.com/markedjs/marked
1987
2195
 
1988
- information
2196
+ # License information
1989
2197
 
1990
2198
  ## Contribution License Agreement
1991
2199
 
package/code.mjs CHANGED
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
6
  // Auto-updated by scripts/pack.ts
7
- const codeArchiveHash = "096c26773369f84b";
7
+ const codeArchiveHash = "c433dbc9db2649ca";
8
8
 
9
9
  const archivePath = fileURLToPath(new URL("./code.tar.zst", import.meta.url));
10
10
 
package/code.tar.zst CHANGED
Binary file
@@ -39,6 +39,10 @@ function setupOutgoing(outgoing, options, req, forward) {
39
39
  const value = options[forward || "target"][e];
40
40
  if (value !== void 0) outgoing[e] = value;
41
41
  }
42
+ if (outgoing.host === void 0 && typeof outgoing.hostname === "string") {
43
+ const bracketedHost = outgoing.hostname.includes(":") && !outgoing.hostname.startsWith("[") ? `[${outgoing.hostname}]` : outgoing.hostname;
44
+ outgoing.host = outgoing.port ? `${bracketedHost}:${outgoing.port}` : bracketedHost;
45
+ }
42
46
  outgoing.method = options.method || req.method;
43
47
  outgoing.headers = { ...req.headers };
44
48
  if (req.headers?.[":authority"]) outgoing.headers.host = req.headers[":authority"];
@@ -48,7 +52,7 @@ function setupOutgoing(outgoing, options, req, forward) {
48
52
  if (options.ca) outgoing.ca = options.ca;
49
53
  if (isSSL.test(options[forward || "target"].protocol ?? "http")) outgoing.rejectUnauthorized = options.secure === void 0 ? true : options.secure;
50
54
  if (options.agent !== void 0) outgoing.agent = options.agent || false;
51
- else if (req.httpVersionMajor > 1) outgoing.agent = false;
55
+ else if (req.httpVersionMajor > 1 || upgradeHeader.test(req.headers.connection || "")) outgoing.agent = false;
52
56
  else {
53
57
  const targetProto = options[forward || "target"].protocol ?? "http";
54
58
  outgoing.agent = isSSL.test(targetProto) ? defaultAgents.https : defaultAgents.http;
@@ -76,7 +80,7 @@ function setupOutgoing(outgoing, options, req, forward) {
76
80
  }
77
81
  function joinURL(base, path) {
78
82
  if (!base || base === "/") return path || "/";
79
- if (!path || path === "/") return base || "/";
83
+ if (!path) return base;
80
84
  const baseHasTrailing = base[base.length - 1] === "/";
81
85
  const pathHasLeading = path[0] === "/";
82
86
  if (baseHasTrailing && pathHasLeading) return base + path.slice(1);
@@ -235,7 +239,7 @@ const webIncomingMiddleware = [
235
239
  "proto"
236
240
  ]) {
237
241
  const key = "x-forwarded-" + header;
238
- if (!req.headers[key]) req.headers[key] = values[header];
242
+ if (!req.headers[key] && values[header] !== void 0) req.headers[key] = values[header];
239
243
  }
240
244
  req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers.host || "";
241
245
  }),
@@ -393,7 +397,7 @@ const websocketIncomingMiddleware = [
393
397
  "proto"
394
398
  ]) {
395
399
  const key = "x-forwarded-" + header;
396
- if (!req.headers[key]) req.headers[key] = values[header];
400
+ if (!req.headers[key] && values[header] !== void 0) req.headers[key] = values[header];
397
401
  }
398
402
  }),
399
403
  defineProxyMiddleware((req, socket, options, server, head, callback) => {
@@ -464,7 +468,7 @@ var ProxyServer = class extends EventEmitter {
464
468
  this.web = _createProxyFn("web", this);
465
469
  this.ws = _createProxyFn("ws", this);
466
470
  }
467
- listen(port, hostname) {
471
+ listen(port, hostname, listeningListener) {
468
472
  const closure = (req, res) => {
469
473
  return this.web(req, res);
470
474
  };
@@ -479,7 +483,7 @@ var ProxyServer = class extends EventEmitter {
479
483
  if (this.options.ws) this._server.on("upgrade", (req, socket, head) => {
480
484
  this.ws(req, socket, this.options, head).catch(() => {});
481
485
  });
482
- this._server.listen(port, hostname);
486
+ this._server.listen(port, hostname, listeningListener);
483
487
  return this;
484
488
  }
485
489
  close(callback) {
@@ -537,15 +541,15 @@ function _createProxyFn(type, server) {
537
541
  for (const pass of server._getPasses(type)) {
538
542
  let stop;
539
543
  try {
540
- stop = pass(req, res, requestOptions, server, head, (error) => {
544
+ stop = pass(req, res, requestOptions, server, head, (error, _req, _res, url) => {
541
545
  if (server.listenerCount("error") > 0) {
542
- server.emit("error", error, req, res);
546
+ server.emit("error", error, req, res, url);
543
547
  _resolve();
544
548
  } else _reject(error);
545
549
  });
546
550
  } catch (error) {
547
551
  if (server.listenerCount("error") > 0) {
548
- server.emit("error", error, req, res);
552
+ server.emit("error", error, req, res, requestOptions.target || requestOptions.forward);
549
553
  _resolve();
550
554
  } else _reject(error);
551
555
  break;
@@ -317,11 +317,19 @@ async function startCodeServer(opts = {}) {
317
317
  const address = server.address();
318
318
  const actualPort = address && typeof address === "object" && "port" in address ? address.port : void 0;
319
319
  const basePath = normalizeBaseURL(opts.baseURL ?? opts.vscode?.["server-base-path"]);
320
+ let url;
321
+ if (socketPath) url = `unix:${socketPath}`;
322
+ else {
323
+ const baseUrl = new URL(`http://localhost:${actualPort}${basePath}/`);
324
+ if (handler.connectionToken) baseUrl.searchParams.set("tkn", handler.connectionToken);
325
+ const rawUrl = opts.formatURL ? opts.formatURL(baseUrl) ?? baseUrl : baseUrl;
326
+ url = rawUrl instanceof URL ? rawUrl.toString() : rawUrl;
327
+ }
320
328
  return {
321
329
  server,
322
330
  port: actualPort,
323
331
  socketPath,
324
- url: socketPath ? `unix:${socketPath}` : handler.connectionToken ? `http://localhost:${actualPort}${basePath}/?tkn=${handler.connectionToken}` : `http://localhost:${actualPort}${basePath}/`,
332
+ url,
325
333
  connectionToken: handler.connectionToken,
326
334
  async close() {
327
335
  await handler.dispose();
package/dist/index.d.mts CHANGED
@@ -1,4 +1,6 @@
1
+ import { ChildProcess } from "node:child_process";
1
2
  import { IncomingMessage, Server, ServerResponse } from "node:http";
3
+ import { EventEmitter } from "node:events";
2
4
  import { Duplex } from "node:stream";
3
5
  /**
4
6
  * Options for `createServer()` from VS Code server
@@ -81,6 +83,12 @@ interface VSCodeServerOptions {
81
83
  interface CreateCodeServerOptions {
82
84
  /** Workspace folder opened when no input is given in the URL. */
83
85
  defaultFolder?: string;
86
+ /**
87
+ * Customize the URL returned by the server. Called with the base URL after
88
+ * auth params are applied. Return a modified URL, a string, or `undefined`
89
+ * to keep the original.
90
+ */
91
+ formatURL?: (url: URL) => string | URL | undefined;
84
92
  /** Connection token (shared auth secret). Auto-generated if omitted. */
85
93
  connectionToken?: string;
86
94
  /** Host/interface to bind (used to infer local-only access for token default). */
@@ -120,4 +128,59 @@ interface CodeServerHandle {
120
128
  }
121
129
  declare function createCodeServer(opts?: CreateCodeServerOptions): Promise<CodeServerHandler>;
122
130
  declare function startCodeServer(opts?: StartCodeServerOptions): Promise<CodeServerHandle>;
123
- export { type CodeServerHandle, type CodeServerHandler, type CreateCodeServerOptions, type StartCodeServerOptions, createCodeServer, startCodeServer };
131
+ interface SpawnProcessOptions {
132
+ /** Extra environment variables merged into the worker's `process.env`. */
133
+ env?: NodeJS.ProcessEnv;
134
+ /** Node.js exec argv forwarded to the worker (e.g. `["--inspect"]`). */
135
+ execArgv?: string[];
136
+ /**
137
+ * stdio for the forked worker. Defaults to `"inherit"` for stdout/stderr and
138
+ * `"ignore"` for stdin. Pass `"pipe"` to capture output via `handle.proc`.
139
+ */
140
+ stdio?: "inherit" | "pipe" | "ignore";
141
+ /**
142
+ * Max ms to wait for the worker to report `ready`. Defaults to 60000.
143
+ * On timeout, the worker is killed and the promise rejects.
144
+ */
145
+ startupTimeout?: number;
146
+ }
147
+ interface SpawnCodeServerOptions extends StartCodeServerOptions {
148
+ /** Options for the forked worker process. */
149
+ spawn?: SpawnProcessOptions;
150
+ }
151
+ interface SpawnedCodeServer {
152
+ /**
153
+ * Emitted when the handle loses its worker: crash, explicit kill, or a
154
+ * `reload()` whose respawn failed (the old worker is already gone; the
155
+ * failure also rejects the `reload()` promise). Not emitted for `close()`
156
+ * or the successful half of `reload()`.
157
+ */
158
+ on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
159
+ /**
160
+ * Emitted for worker `error` events (spawn failure, IPC send failure) and
161
+ * for post-ready fatal errors forwarded by the worker (uncaughtException,
162
+ * unhandledRejection).
163
+ */
164
+ on(event: "error", listener: (err: Error) => void): this;
165
+ on(event: string, listener: (...args: unknown[]) => void): this;
166
+ }
167
+ declare class SpawnedCodeServer extends EventEmitter {
168
+ #private;
169
+ /** The forked worker process (changes after `reload`). */
170
+ proc: ChildProcess;
171
+ url: string;
172
+ /** TCP port the server is bound to, or `undefined` when listening on a unix socket. */
173
+ port?: number;
174
+ /** Unix socket path the server is bound to, or `undefined` when listening on TCP. */
175
+ socketPath?: string;
176
+ connectionToken: string;
177
+ private constructor();
178
+ /** Spawn a new worker and resolve with a handle once it reports ready. */
179
+ static spawn(opts?: SpawnCodeServerOptions): Promise<SpawnedCodeServer>;
180
+ /** Terminate the worker process. Sends SIGTERM, then SIGKILL after 5s. Idempotent. */
181
+ close(): Promise<void>;
182
+ /** Kill the current worker and spawn a new one with the original options. */
183
+ reload(): Promise<void>;
184
+ }
185
+ declare function spawnCodeServer(opts?: SpawnCodeServerOptions): Promise<SpawnedCodeServer>;
186
+ export { type CodeServerHandle, type CodeServerHandler, type CreateCodeServerOptions, type SpawnCodeServerOptions, type SpawnProcessOptions, SpawnedCodeServer, type StartCodeServerOptions, createCodeServer, spawnCodeServer, startCodeServer };
package/dist/index.mjs CHANGED
@@ -1,2 +1,171 @@
1
1
  import { r as startCodeServer, t as createCodeServer } from "./_chunks/server.mjs";
2
- export { createCodeServer, startCodeServer };
2
+ import { fileURLToPath } from "node:url";
3
+ import { fork } from "node:child_process";
4
+ import { EventEmitter } from "node:events";
5
+ var SpawnedCodeServer = class SpawnedCodeServer extends EventEmitter {
6
+ proc;
7
+ url;
8
+ port;
9
+ socketPath;
10
+ connectionToken;
11
+ #opts;
12
+ #detach;
13
+ #reloading;
14
+ #closed = false;
15
+ constructor(opts, state) {
16
+ super();
17
+ this.#opts = opts;
18
+ this.#adopt(state);
19
+ }
20
+ static async spawn(opts = {}) {
21
+ return new SpawnedCodeServer(opts, await spawnWorker(opts));
22
+ }
23
+ async close() {
24
+ if (this.#closed) return;
25
+ this.#closed = true;
26
+ if (this.#reloading) try {
27
+ await this.#reloading;
28
+ } catch {}
29
+ this.#detach();
30
+ await terminateChild(this.proc);
31
+ }
32
+ async reload() {
33
+ if (this.#closed) throw new Error("SpawnedCodeServer is closed");
34
+ if (this.#reloading) return this.#reloading;
35
+ this.#reloading = (async () => {
36
+ this.#detach();
37
+ await terminateChild(this.proc);
38
+ if (this.#closed) throw new Error("SpawnedCodeServer was closed during reload");
39
+ let next;
40
+ try {
41
+ next = await spawnWorker(this.#opts);
42
+ } catch (err) {
43
+ const dead = this.proc;
44
+ queueMicrotask(() => this.emit("exit", dead.exitCode, dead.signalCode));
45
+ throw err;
46
+ }
47
+ if (this.#closed) {
48
+ await terminateChild(next.proc);
49
+ throw new Error("SpawnedCodeServer was closed during reload");
50
+ }
51
+ this.#adopt(next);
52
+ })();
53
+ try {
54
+ await this.#reloading;
55
+ } finally {
56
+ this.#reloading = void 0;
57
+ }
58
+ }
59
+ #adopt(state) {
60
+ this.proc = state.proc;
61
+ this.url = state.url;
62
+ this.port = state.port;
63
+ this.socketPath = state.socketPath;
64
+ this.connectionToken = state.connectionToken;
65
+ this.#detach = this.#attachListeners(state.proc);
66
+ }
67
+ #attachListeners(proc) {
68
+ const onExit = (code, signal) => this.emit("exit", code, signal);
69
+ const onError = (err) => this.emit("error", err);
70
+ const onMessage = (msg) => {
71
+ if (msg?.type === "error") this.emit("error", new Error(msg.message ?? "worker error"));
72
+ };
73
+ proc.on("exit", onExit);
74
+ proc.on("error", onError);
75
+ proc.on("message", onMessage);
76
+ return () => {
77
+ proc.off("exit", onExit);
78
+ proc.off("error", onError);
79
+ proc.off("message", onMessage);
80
+ };
81
+ }
82
+ };
83
+ function spawnCodeServer(opts = {}) {
84
+ return SpawnedCodeServer.spawn(opts);
85
+ }
86
+ async function spawnWorker(opts) {
87
+ const { spawn: spawnOpts = {}, ...serverOpts } = opts;
88
+ const { env, execArgv, stdio = "inherit", startupTimeout = 6e4 } = spawnOpts;
89
+ const workerPath = fileURLToPath(import.meta.resolve("#worker"));
90
+ const childEnv = {
91
+ ...process.env,
92
+ ...env
93
+ };
94
+ delete childEnv.CODE_SERVER_PARENT_PID;
95
+ const proc = fork(workerPath, {
96
+ stdio: [
97
+ "ignore",
98
+ stdio,
99
+ stdio,
100
+ "ipc"
101
+ ],
102
+ env: childEnv,
103
+ ...execArgv !== void 0 ? { execArgv } : {}
104
+ });
105
+ const ready = await new Promise((resolve, reject) => {
106
+ const onMessage = (msg) => {
107
+ if (msg?.type === "ready") {
108
+ cleanup();
109
+ resolve(msg);
110
+ } else if (msg?.type === "error") {
111
+ cleanup();
112
+ reject(new Error(msg.message ?? "worker error"));
113
+ }
114
+ };
115
+ const onExit = (code) => {
116
+ cleanup();
117
+ reject(/* @__PURE__ */ new Error(`coderaft worker exited before ready (code=${code})`));
118
+ };
119
+ const onError = (err) => {
120
+ cleanup();
121
+ proc.kill("SIGKILL");
122
+ reject(err);
123
+ };
124
+ const timer = setTimeout(() => {
125
+ cleanup();
126
+ proc.kill("SIGKILL");
127
+ reject(/* @__PURE__ */ new Error(`coderaft worker did not become ready within ${startupTimeout}ms`));
128
+ }, startupTimeout);
129
+ timer.unref?.();
130
+ const cleanup = () => {
131
+ clearTimeout(timer);
132
+ proc.off("message", onMessage);
133
+ proc.off("exit", onExit);
134
+ proc.off("error", onError);
135
+ };
136
+ proc.on("message", onMessage);
137
+ proc.once("exit", onExit);
138
+ proc.once("error", onError);
139
+ proc.send({
140
+ type: "start",
141
+ opts: serverOpts
142
+ }, (err) => {
143
+ if (err) {
144
+ cleanup();
145
+ reject(err);
146
+ }
147
+ });
148
+ });
149
+ return {
150
+ proc,
151
+ url: ready.url,
152
+ port: ready.port,
153
+ socketPath: ready.socketPath,
154
+ connectionToken: ready.connectionToken
155
+ };
156
+ }
157
+ async function terminateChild(proc) {
158
+ if (proc.exitCode !== null || proc.signalCode !== null) return;
159
+ await new Promise((resolve) => {
160
+ const timer = setTimeout(() => {
161
+ if (proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL");
162
+ }, 5e3);
163
+ timer.unref?.();
164
+ proc.once("exit", () => {
165
+ clearTimeout(timer);
166
+ resolve();
167
+ });
168
+ proc.kill("SIGTERM");
169
+ });
170
+ }
171
+ export { SpawnedCodeServer, createCodeServer, spawnCodeServer, startCodeServer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coderaft",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
4
4
  "repository": "pithings/coderaft",
5
5
  "bin": {
6
6
  "coderaft": "./dist/cli.mjs"
@@ -11,6 +11,7 @@
11
11
  "ThirdPartyNotices.txt",
12
12
  "tar.mjs",
13
13
  "code.mjs",
14
+ "worker.mjs",
14
15
  "android-preload.cjs",
15
16
  "code.tar.zst"
16
17
  ],
@@ -21,12 +22,14 @@
21
22
  },
22
23
  "imports": {
23
24
  "#code": "./code.mjs",
25
+ "#worker": "./worker.mjs",
24
26
  "#android-preload": "./android-preload.cjs"
25
27
  },
26
28
  "scripts": {
27
29
  "build": "obuild"
28
30
  },
29
31
  "devDependencies": {
32
+ "code-server": "^4.117.0",
30
33
  "@github/copilot": "workspace:*",
31
34
  "@github/copilot-sdk": "workspace:*",
32
35
  "@microsoft/1ds-core-js": "workspace:*",
@@ -39,21 +42,21 @@
39
42
  "@vscode/proxy-agent": "workspace:*",
40
43
  "@vscode/ripgrep": "workspace:*",
41
44
  "@vscode/spdlog": "workspace:*",
42
- "@vscode/tree-sitter-wasm": "^0.3.0",
45
+ "@vscode/sqlite3": "workspace:*",
46
+ "@vscode/tree-sitter-wasm": "^0.3.1",
43
47
  "@vscode/vscode-languagedetection": "1.0.23",
44
48
  "@vscode/windows-process-tree": "workspace:*",
45
49
  "@vscode/windows-registry": "workspace:*",
46
- "@xterm/addon-clipboard": "^0.3.0-beta.191",
47
- "@xterm/addon-image": "^0.10.0-beta.191",
48
- "@xterm/addon-ligatures": "^0.11.0-beta.191",
49
- "@xterm/addon-progress": "^0.3.0-beta.191",
50
- "@xterm/addon-search": "^0.17.0-beta.191",
51
- "@xterm/addon-serialize": "^0.15.0-beta.191",
52
- "@xterm/addon-unicode11": "^0.10.0-beta.191",
53
- "@xterm/addon-webgl": "^0.20.0-beta.190",
54
- "@xterm/headless": "^6.1.0-beta.191",
55
- "@xterm/xterm": "^6.1.0-beta.191",
56
- "code-server": "^4.114.1",
50
+ "@xterm/addon-clipboard": "^0.3.0-beta.197",
51
+ "@xterm/addon-image": "^0.10.0-beta.197",
52
+ "@xterm/addon-ligatures": "^0.11.0-beta.197",
53
+ "@xterm/addon-progress": "^0.3.0-beta.197",
54
+ "@xterm/addon-search": "^0.17.0-beta.197",
55
+ "@xterm/addon-serialize": "^0.15.0-beta.197",
56
+ "@xterm/addon-unicode11": "^0.10.0-beta.197",
57
+ "@xterm/addon-webgl": "^0.20.0-beta.196",
58
+ "@xterm/headless": "^6.1.0-beta.197",
59
+ "@xterm/xterm": "^6.1.0-beta.197",
57
60
  "cookie": "^0.7.0",
58
61
  "http-proxy-agent": "^7.0.0",
59
62
  "https-proxy-agent": "^7.0.2",
@@ -63,8 +66,9 @@
63
66
  "kerberos": "workspace:*",
64
67
  "minimist": "^1.2.8",
65
68
  "node-pty": "workspace:*",
69
+ "ssh2": "workspace:*",
66
70
  "tas-client": "0.3.1",
67
- "typescript": "^6.0.2",
71
+ "typescript": "^6.0.3",
68
72
  "vscode-oniguruma": "1.7.0",
69
73
  "vscode-regexpp": "^3.1.0",
70
74
  "vscode-textmate": "^9.3.2",
package/worker.mjs ADDED
@@ -0,0 +1,64 @@
1
+ // Forked worker entry used by `spawnCodeServer`. Starts a coderaft code server
2
+ // on IPC `{ type: "start", opts }` and replies with `{ type: "ready", ... }`.
3
+ // On SIGTERM/SIGINT, gracefully closes the server before exiting so the parent's
4
+ // `handle.close()` cleanly disposes VS Code and releases sockets/locks.
5
+ import { startCodeServer } from "./dist/index.mjs";
6
+
7
+ let handle;
8
+ let shuttingDown = false;
9
+
10
+ process.on("message", async (msg) => {
11
+ if (msg?.type !== "start") return;
12
+ try {
13
+ handle = await startCodeServer(msg.opts);
14
+ process.send?.({
15
+ type: "ready",
16
+ url: handle.url,
17
+ port: handle.port,
18
+ socketPath: handle.socketPath,
19
+ connectionToken: handle.connectionToken,
20
+ });
21
+ } catch (err) {
22
+ // Flush the error message over IPC before exiting — `process.exit` can
23
+ // tear down the channel before the message reaches the parent, which
24
+ // would leave the parent rejecting with the generic `exited before ready`.
25
+ const exit = () => process.exit(1);
26
+ if (process.send) {
27
+ process.send({ type: "error", message: err?.message ?? String(err) }, exit);
28
+ } else {
29
+ exit();
30
+ }
31
+ }
32
+ });
33
+
34
+ const shutdown = async (signal) => {
35
+ if (shuttingDown) return;
36
+ shuttingDown = true;
37
+ try {
38
+ await handle?.close();
39
+ } catch (err) {
40
+ console.error(`[coderaft worker] close failed on ${signal}:`, err);
41
+ }
42
+ process.exit(0);
43
+ };
44
+
45
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
46
+ process.on("SIGINT", () => shutdown("SIGINT"));
47
+
48
+ // Forward fatal async errors to the parent before exiting. Without this, the
49
+ // parent only sees an anonymous non-zero exit and has to scrape stderr for the
50
+ // reason — which is the exact failure mode the pre-ready IPC flush avoids.
51
+ const forwardFatal = (kind) => (err) => {
52
+ if (shuttingDown) return;
53
+ shuttingDown = true;
54
+ const detail = err?.stack ?? err?.message ?? String(err);
55
+ const exit = () => process.exit(1);
56
+ if (process.send) {
57
+ process.send({ type: "error", message: `[${kind}] ${detail}` }, exit);
58
+ } else {
59
+ exit();
60
+ }
61
+ };
62
+
63
+ process.on("uncaughtException", forwardFatal("uncaughtException"));
64
+ process.on("unhandledRejection", forwardFatal("unhandledRejection"));