@buildkitgg/dev-domains 0.0.1 → 0.0.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.0.2
4
+
5
+ - Allow projects with different domains to share Portless without endpoint-name collisions. For example,
6
+ `local.copacker.ai` and `local.spawnkit.cloud` now remain separate routes on one proxy.
7
+ - Preserve explicit `proxy.domains` aliases and reject occupied complete hostnames without takeover.
8
+ - Reserve an OS-assigned port through route registration, retry bounded bind failures, and clean only owned routes.
9
+ - Execute framework commands directly with argument arrays on Windows, Linux, and macOS.
10
+
11
+ Existing configuration files and public APIs remain compatible. Shared projects still need the same proxy port and TLS
12
+ mode, and custom domains must resolve locally. No DNS or provider settings are changed automatically.
13
+
14
+ ## 0.0.1
15
+
16
+ Initial public release.
package/README.md CHANGED
@@ -7,7 +7,7 @@ Stable local URLs for your app, Storybook, and end-to-end test servers, across r
7
7
  `https://shop-fix-login.localhost` in a worktree, while Portless assigns the underlying ports. A configuration file lets
8
8
  you choose your own names, use a real domain, describe authentication callbacks, and expose selected webhook routes.
9
9
 
10
- **Initial release: 0.0.1.** Requires Node.js 24 or later. Supports Windows, macOS, and Linux.
10
+ Requires Node.js 24 or later. Supports Windows, macOS, and Linux.
11
11
 
12
12
  ## Table of contents
13
13
 
@@ -48,8 +48,8 @@ The package follows a few principles:
48
48
  configuration when your project needs different names or commands.
49
49
  - **Readable checkout names.** Identify linked worktrees by their folder names. The primary checkout has no `main`
50
50
  label, and hostnames do not acquire random hashes.
51
- - **Reuse Portless.** Portless owns the proxy, certificates, routing, and server-port allocation. This package adds
52
- project conventions and integrations around it.
51
+ - **Reuse Portless.** Portless owns the proxy, certificates, and shared route registry. This package adds project
52
+ conventions and integrations around it.
53
53
  - **Report conflicts.** A running endpoint keeps its hostname. Another process must choose a different name instead of
54
54
  taking over the route.
55
55
  - **Keep application choices with the application.** Authentication providers, cloud resources, DNS administration, and
@@ -60,18 +60,10 @@ package manages local server addresses and processes; resource isolation remains
60
60
 
61
61
  ## Installation
62
62
 
63
- The commands below install version 0.0.1 from npm. For an unreleased revision, use
64
- [Building from source](#building-from-source). Install the package as a development dependency in your project:
63
+ Install the package from npm as a development dependency in your project:
65
64
 
66
65
  ```sh
67
- npm install --save-dev @buildkitgg/dev-domains@0.0.1
68
- ```
69
-
70
- Use your package manager's equivalent if you use pnpm, Yarn, or Bun. For a pnpm monorepo with a root configuration,
71
- install it at the repository root:
72
-
73
- ```sh
74
- pnpm add -Dw @buildkitgg/dev-domains@0.0.1
66
+ npm install --save-dev @buildkitgg/dev-domains
75
67
  ```
76
68
 
77
69
  Install where the configuration and CLI are used. A root `dev-domains.config.ts` must be able to import the package from
@@ -83,27 +75,6 @@ Consumer-facing commands use `npx @buildkitgg/dev-domains`, which runs the local
83
75
  and locking the dependency keeps the CLI and configuration helpers on the same version. Portless is included; a separate
84
76
  global installation is unnecessary. Your application frameworks and any tunnel executable must already be installed.
85
77
 
86
- ### Building from source
87
-
88
- To try an unreleased revision, check out the corresponding branch or commit from the
89
- [Buildkit repository](https://github.com/AndrewCraswell/buildkit). With Node.js 24+ and pnpm 12, run these commands from
90
- that checkout's root:
91
-
92
- ```sh
93
- pnpm install --frozen-lockfile
94
- pnpm --filter @buildkitgg/dev-domains pack
95
- ```
96
-
97
- The pack command builds the package and prints the tarball location. In the project where you want to use it, install
98
- that file as a development dependency, replacing the example path:
99
-
100
- ```sh
101
- npm install --save-dev /absolute/path/to/buildkitgg-dev-domains-0.0.1.tgz
102
- ```
103
-
104
- Use the versioned tarball path printed by the pack command if it differs from this example. Install the tarball in the
105
- same location you would install the registry package.
106
-
107
78
  On Windows, Portless also requires OpenSSL on `PATH`. Initial HTTPS setup can require permission to trust a local
108
79
  certificate authority, bind the proxy port, or update the hosts file. Run setup interactively on each development
109
80
  machine.
@@ -425,12 +396,12 @@ Names, paths, and templates are validated when the config is loaded or resolved.
425
396
 
426
397
  ### Proxy fields
427
398
 
428
- | Field | Type | Default | Description |
429
- | ----------------- | --------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------- |
430
- | `proxy.port` | Integer, 1–65535 | `443` | Browser-facing proxy port, not an app's upstream port |
431
- | `proxy.https` | `boolean` | `true` | Serve local origins over HTTPS |
432
- | `proxy.syncHosts` | `boolean` | `true` | Allow Portless to synchronize local hosts entries |
433
- | `proxy.domains` | Nonempty string array | `[domain]` when omitted | Shared suffix list; must include this project's `domain`; each suffix follows the same rules as `domain` |
399
+ | Field | Type | Default | Description |
400
+ | ----------------- | --------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------ |
401
+ | `proxy.port` | Integer, 1–65535 | `443` | Browser-facing proxy port, not an app's upstream port |
402
+ | `proxy.https` | `boolean` | `true` | Serve local origins over HTTPS |
403
+ | `proxy.syncHosts` | `boolean` | `true` | Allow Portless to synchronize local hosts entries |
404
+ | `proxy.domains` | Nonempty string array | `[domain]` when omitted | Explicit aliases for this project; must include its `domain`; each suffix follows the same rules as `domain` |
434
405
 
435
406
  ### Endpoint fields
436
407
 
@@ -658,8 +629,8 @@ running. A hosted receiver, durable delivery, and replay are not included.
658
629
 
659
630
  ## Sharing a proxy across projects
660
631
 
661
- One machine can run many endpoints through one Portless proxy. Use distinct project names and keep participating
662
- projects' proxy settings aligned. A project can choose its preferred suffix from a shared list:
632
+ One machine can run many endpoints through one Portless proxy, with a separate domain for each project. Keep the proxy
633
+ port and TLS mode aligned. To give one project's endpoints additional aliases, configure an explicit list:
663
634
 
664
635
  ```ts
665
636
  // Root configuration fields, alongside project and endpoints.
@@ -672,18 +643,23 @@ proxy: {
672
643
  }
673
644
  ```
674
645
 
675
- Use the same ordered `proxy.domains` list in each participating project, including every project's `domain`. Portless
676
- registers each endpoint name under every suffix in that list, so names must be unique across the shared proxy. The
677
- chosen `domain` determines the origin reported for this project.
646
+ Each project registers complete hostnames in Portless's shared route registry. Projects can use different domains
647
+ without coordinating a suffix list: `local.copacker.ai` and `local.spawnkit.cloud` can run together on the same proxy.
648
+ Leave `proxy.domains` unset unless this project's endpoints should have additional aliases. An explicit list registers
649
+ each endpoint under those suffixes only; `domain` selects its canonical origin. This preserves existing alias configs. A
650
+ collision means the **complete hostname** is occupied, not just the endpoint name.
678
651
 
679
- An existing proxy with incompatible domain, port, or TLS settings is not forcibly restarted. Coordinate changes with
680
- other users and agents before changing the shared proxy. `npx @buildkitgg/dev-domains doctor` helps diagnose the current
681
- state.
652
+ Projects sharing one proxy must agree on its port and TLS settings. Buildkit reuses a compatible proxy without changing
653
+ its startup suffixes or restarting it. DNS must resolve every custom hostname to loopback; either use Portless's hosts
654
+ synchronization or configure DNS yourself. If the existing proxy was started with hosts synchronization disabled,
655
+ `syncHosts: true` cannot change that running process. Coordinate proxy configuration or configure DNS separately.
656
+ `npx @buildkitgg/dev-domains doctor` helps diagnose the current state.
682
657
 
683
- Portless probes for an available upstream port. This is not an atomic reservation: another process can bind the port
684
- before the app does. `dev-domains` makes at most three attempts, retrying only after an explicit `EADDRINUSE` or
685
- address-in-use failure. Make startup safe to repeat. A hostname collision is a different error and does not trigger a
686
- forced route takeover.
658
+ Buildkit holds an OS-assigned loopback port while registering the route, then releases the socket immediately before
659
+ starting the server. Other Buildkit launchers avoid ports in the shared registry, including servers still starting. Most
660
+ framework CLIs cannot inherit the reserved socket, so unrelated programs can still race that final handoff. Buildkit
661
+ makes at most three attempts, retrying only an explicit `EADDRINUSE` or address-in-use failure. Make startup safe to
662
+ repeat. A hostname collision never triggers a forced route takeover.
687
663
 
688
664
  ## CI usage
689
665
 
@@ -735,7 +711,7 @@ stops. The shared proxy is left running. After a hard crash, Portless handles st
735
711
  | Multiple configs or Storybook candidates were found | Keep one dev-domains config per directory; select the intended Storybook script or config directory explicitly |
736
712
  | The wrong package manager is used | In a saved config, set `packageManager`; during discovery, check the root declaration and conflicting lockfiles |
737
713
  | A hostname is already in use | Check `status`, then choose a distinct name or stop the server you own; do not take over another process's route |
738
- | The proxy has different settings | Align domains, port, and TLS settings with the existing shared proxy before restarting your endpoint |
714
+ | The proxy has different settings | Align port and TLS settings with the existing shared proxy before restarting your endpoint |
739
715
  | The hostname does not resolve or HTTPS is untrusted | Run `doctor`; check loopback DNS or hosts synchronization and complete Portless certificate setup |
740
716
  | The framework rejects the hostname | Configure its allowed hosts or development origins for your generated domains |
741
717
  | App and E2E servers conflict despite different ports | Configure separate framework build/output directories; verify the app consumes `DEV_DOMAINS_OUTPUT_DIR` |
@@ -4,8 +4,9 @@ import { configSchema } from "../config/schema.js";
4
4
  import { resolveEndpoints } from "../domains/resolve.js";
5
5
  import { detectConfig } from "../project/detect.js";
6
6
  import { projectIdentity } from "../project/identity.js";
7
- import { proxyCommand, runEndpoint } from "../runtime/portless.js";
7
+ import { runEndpoint } from "../runtime/portless.js";
8
8
  import { withSignals } from "../runtime/process.js";
9
+ import { proxyCommand } from "../runtime/proxy.js";
9
10
  import { runTunnel } from "../webhooks/tunnel.js";
10
11
  import { defineCliCommand as defineCommand } from "./command.js";
11
12
  import { initialize } from "./init.js";
@@ -1,4 +1,4 @@
1
1
  import { type Endpoint, type ResolvedConfig } from "../config/schema.js";
2
2
  import { type ResolvedEndpoint } from "../domains/resolve.js";
3
3
  export declare function serverCommand(endpoint: Endpoint, packageManager: ResolvedConfig["packageManager"], cwd: string, variables: Record<string, string>, port: number): Promise<string[]>;
4
- export declare function serverEnvironment(endpoint: ResolvedEndpoint, port: number, inherited: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
4
+ export declare function serverEnvironment(endpoint: ResolvedEndpoint, port: number, inherited: NodeJS.ProcessEnv, hostnames?: string[]): NodeJS.ProcessEnv;
@@ -37,7 +37,7 @@ export async function serverCommand(endpoint, packageManager, cwd, variables, po
37
37
  }
38
38
  return command;
39
39
  }
40
- export function serverEnvironment(endpoint, port, inherited) {
40
+ export function serverEnvironment(endpoint, port, inherited, hostnames = [endpoint.hostname]) {
41
41
  const env = {
42
42
  ...inherited,
43
43
  ...Object.fromEntries(Object.entries(endpoint.endpoint.env).map(([key, value]) => [
@@ -67,6 +67,8 @@ export function serverEnvironment(endpoint, port, inherited) {
67
67
  PATH: [...bins, path.dirname(process.execPath), existingPath].join(path.delimiter),
68
68
  PORT: String(port),
69
69
  HOST: "127.0.0.1",
70
+ PORTLESS_URL: endpoint.origin,
71
+ __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: hostnames.join(","),
70
72
  BUILDKIT_ACTIVE: "1",
71
73
  DEV_DOMAINS_ORIGIN: endpoint.origin,
72
74
  DEV_DOMAINS_HOSTNAME: endpoint.hostname,
@@ -0,0 +1,5 @@
1
+ /** Hold an OS-assigned port until its route is registered, then hand it to the server. */
2
+ export declare function reservePort(): Promise<{
3
+ port: number;
4
+ release: () => Promise<void>;
5
+ }>;
@@ -0,0 +1,37 @@
1
+ import { createServer } from "node:net";
2
+ import { routeStore } from "./state.js";
3
+ /** Hold an OS-assigned port until its route is registered, then hand it to the server. */
4
+ export async function reservePort() {
5
+ for (let attempt = 0; attempt < 20; attempt++) {
6
+ const server = createServer();
7
+ await new Promise((resolve, reject) => {
8
+ server.once("error", reject);
9
+ server.listen({ host: "127.0.0.1", port: 0, exclusive: true }, resolve);
10
+ });
11
+ const address = server.address();
12
+ let released;
13
+ const release = () => (released ??= new Promise((resolve, reject) => {
14
+ server.close((error) => (error ? reject(error) : resolve()));
15
+ }));
16
+ if (!address || typeof address === "string") {
17
+ await release();
18
+ throw new Error("Could not reserve a local server port");
19
+ }
20
+ // Another launcher may have registered its route and released its socket,
21
+ // but its framework has not bound the port yet.
22
+ try {
23
+ if (routeStore()
24
+ .loadRoutes()
25
+ .some((route) => route.port === address.port)) {
26
+ await release();
27
+ continue;
28
+ }
29
+ }
30
+ catch (error) {
31
+ await release();
32
+ throw error;
33
+ }
34
+ return { port: address.port, release };
35
+ }
36
+ throw new Error("Could not reserve an unused local server port. Try again.");
37
+ }
@@ -1,11 +1,2 @@
1
- import { RouteStore } from "portless";
2
1
  import { type Project, type ResolvedEndpoint } from "../domains/resolve.js";
3
- export declare function stateDirectory(): string;
4
- export declare function routeStore(): RouteStore;
5
- export declare function proxyEnvironment(project: Project): NodeJS.ProcessEnv;
6
- export declare function proxyCommand(project: Project, action: "setup" | "status" | "doctor", signal?: AbortSignal): Promise<{
7
- code: number;
8
- stderr: string;
9
- pid?: number;
10
- }>;
11
2
  export declare function runEndpoint(project: Project, endpoint: ResolvedEndpoint, signal?: AbortSignal, quiet?: boolean): Promise<number>;
@@ -1,84 +1,46 @@
1
- import path from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import { RouteStore, resolveUserHome } from "portless";
1
+ import { RouteConflictError } from "portless";
4
2
  import { endpointDirectory } from "../domains/resolve.js";
3
+ import { serverCommand, serverEnvironment } from "./command.js";
4
+ import { reservePort } from "./port.js";
5
5
  import { runProcess } from "./process.js";
6
- const cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("portless")));
7
- export function stateDirectory() {
8
- return process.env.PORTLESS_STATE_DIR || path.join(resolveUserHome(), ".portless");
9
- }
10
- export function routeStore() {
11
- return new RouteStore(stateDirectory());
12
- }
13
- export function proxyEnvironment(project) {
14
- const proxy = project.config.proxy;
15
- return {
16
- ...process.env,
17
- // We invoke our pinned local dependency directly, not through a package
18
- // downloader. Do not pass the caller's pnpm exec/npx launcher markers.
19
- npm_command: undefined,
20
- PNPM_SCRIPT_SRC_DIR: undefined,
21
- PORTLESS: "1",
22
- PORTLESS_TLD: (proxy.domains ?? [project.config.domain]).join(","),
23
- PORTLESS_PORT: String(proxy.port),
24
- PORTLESS_HTTPS: proxy.https ? "1" : "0",
25
- PORTLESS_LAN: "0",
26
- PORTLESS_SYNC_HOSTS: proxy.syncHosts ? "1" : "0",
27
- PORTLESS_NGROK: "0",
28
- PORTLESS_TAILSCALE: "0",
29
- PORTLESS_FUNNEL: "0",
30
- PORTLESS_APP_PORT: ""
31
- };
32
- }
33
- export async function proxyCommand(project, action, signal) {
34
- const args = action === "setup"
35
- ? [
36
- "proxy",
37
- "start",
38
- ...(project.config.proxy.domains ?? [project.config.domain]).flatMap((domain) => ["--tld", domain]),
39
- "--port",
40
- String(project.config.proxy.port),
41
- ...(project.config.proxy.https ? [] : ["--no-tls"])
42
- ]
43
- : [action === "status" ? "list" : "doctor"];
44
- return runProcess([process.execPath, cli, ...args], { cwd: project.root, env: proxyEnvironment(project), signal });
45
- }
6
+ import { ensureProxy, proxyEnvironment } from "./proxy.js";
7
+ import { routeStore } from "./state.js";
46
8
  export async function runEndpoint(project, endpoint, signal, quiet = false) {
47
9
  if (process.env.BUILDKIT_ACTIVE) {
48
10
  throw new Error("Recursive dev-domains invocation. Configure the underlying server command.");
49
11
  }
50
12
  await endpointDirectory(project, endpoint);
51
13
  const hostnames = (project.config.proxy.domains ?? [project.config.domain]).map((domain) => `${endpoint.name}.${domain}`);
52
- const conflict = routeStore()
53
- .loadRoutes()
54
- .find((route) => hostnames.includes(route.hostname));
55
- if (conflict) {
56
- throw new Error(`Domain ${conflict.hostname} is already in use on port ${conflict.port}. Rename the worktree or configure a different endpoint name. The existing server was left running.`);
57
- }
58
- const env = proxyEnvironment(project);
59
- env.BUILDKIT_RUN_CONTEXT = JSON.stringify({
60
- config: project.config,
61
- root: project.root,
62
- worktree: project.worktree,
63
- service: endpoint.service
64
- });
65
- env.BUILDKIT_RUNNER = new URL("./runner.js", import.meta.url).href;
66
- // Portless 0.15.8 joins Windows arguments through cmd.exe. Keep user input in the
67
- // environment and pass only a fixed bootstrap expression through that shell.
68
- const expression = "import(process.env.BUILDKIT_RUNNER)";
69
- const args = [process.execPath, cli, "--name", endpoint.name, "node", "-e", expression];
14
+ await ensureProxy(project, signal);
15
+ const store = routeStore();
70
16
  for (let attempt = 0; attempt < 3; attempt++) {
71
- let owner;
17
+ signal?.throwIfAborted();
18
+ const reservation = await reservePort();
19
+ const claimed = [];
72
20
  try {
73
- const result = await runProcess(args, {
74
- cwd: endpoint.cwd,
75
- env,
76
- signal,
77
- quiet,
78
- onSpawn: (pid) => {
79
- owner = pid;
21
+ const command = await serverCommand(endpoint.endpoint, project.config.packageManager, endpoint.cwd, endpoint.variables, reservation.port);
22
+ for (const hostname of hostnames) {
23
+ try {
24
+ const existing = store.loadRoutes().find((route) => route.hostname === hostname);
25
+ if (existing) {
26
+ throw new RouteConflictError(hostname, existing.pid);
27
+ }
28
+ // addRoute takes Portless's cross-process lock and never replaces a live owner.
29
+ store.addRoute(hostname, reservation.port, process.pid);
30
+ claimed.push(hostname);
80
31
  }
81
- });
32
+ catch (error) {
33
+ if (error instanceof RouteConflictError) {
34
+ throw new Error(`Domain ${hostname} is already in use. Rename the worktree or configure a different endpoint name. The existing server was left running.`, { cause: error });
35
+ }
36
+ throw error;
37
+ }
38
+ }
39
+ const env = serverEnvironment(endpoint, reservation.port, proxyEnvironment(project), hostnames);
40
+ // Most framework CLIs accept a port, not an inherited listening socket.
41
+ // Keep the registration until the child exits; retry a competing external bind.
42
+ await reservation.release();
43
+ const result = await runProcess(command, { cwd: endpoint.cwd, env, signal, quiet });
82
44
  if (signal?.aborted ||
83
45
  result.code === 0 ||
84
46
  !/EADDRINUSE|address already in use/i.test(result.stderr) ||
@@ -87,14 +49,14 @@ export async function runEndpoint(project, endpoint, signal, quiet = false) {
87
49
  }
88
50
  }
89
51
  finally {
90
- // Windows termination may skip Portless's JS exit handler. Owner checks
91
- // prevent this cleanup from removing a route acquired by another process.
92
- if (owner) {
93
- const store = routeStore();
94
- for (const route of store.loadRoutesRaw()) {
95
- if (route.pid === owner) {
96
- store.removeRoute(route.hostname, owner);
97
- }
52
+ // Closing an already released reservation is harmless. Cleanup must also
53
+ // cover command validation failures and partially registered alias sets.
54
+ try {
55
+ await reservation.release();
56
+ }
57
+ finally {
58
+ for (const hostname of claimed) {
59
+ store.removeRoute(hostname, process.pid);
98
60
  }
99
61
  }
100
62
  }
@@ -0,0 +1,10 @@
1
+ import type { Project } from "../domains/resolve.js";
2
+ export declare function proxyEnvironment(project: Project): NodeJS.ProcessEnv;
3
+ /** Suffixes do not limit Portless's exact routes or its per-hostname TLS certificates. */
4
+ export declare function hasCompatibleProxy(project: Project, signal?: AbortSignal): Promise<boolean>;
5
+ export declare function proxyCommand(project: Project, action: "setup" | "status" | "doctor", signal?: AbortSignal): Promise<{
6
+ code: number;
7
+ stderr: string;
8
+ pid?: number;
9
+ }>;
10
+ export declare function ensureProxy(project: Project, signal?: AbortSignal): Promise<void>;
@@ -0,0 +1,102 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import http from "node:http";
4
+ import https from "node:https";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { isErrnoException, isProcessAlive, PORTLESS_HEADER } from "portless";
8
+ import { runProcess } from "./process.js";
9
+ import { stateDirectory } from "./state.js";
10
+ const cli = fileURLToPath(new URL("./cli.js", import.meta.resolve("portless")));
11
+ export function proxyEnvironment(project) {
12
+ const proxy = project.config.proxy;
13
+ const caPath = path.join(stateDirectory(), "ca.pem");
14
+ return {
15
+ ...process.env,
16
+ npm_command: undefined,
17
+ PNPM_SCRIPT_SRC_DIR: undefined,
18
+ NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS || (proxy.https && existsSync(caPath) ? caPath : undefined),
19
+ PORTLESS: "1",
20
+ PORTLESS_TLD: (proxy.domains ?? [project.config.domain]).join(","),
21
+ PORTLESS_PORT: String(proxy.port),
22
+ PORTLESS_HTTPS: proxy.https ? "1" : "0",
23
+ PORTLESS_LAN: "0",
24
+ PORTLESS_SYNC_HOSTS: proxy.syncHosts ? "1" : "0",
25
+ PORTLESS_NGROK: "0",
26
+ PORTLESS_TAILSCALE: "0",
27
+ PORTLESS_FUNNEL: "0",
28
+ PORTLESS_APP_PORT: ""
29
+ };
30
+ }
31
+ async function readState(name) {
32
+ try {
33
+ return (await readFile(path.join(stateDirectory(), name), "utf8")).trim();
34
+ }
35
+ catch (error) {
36
+ if (isErrnoException(error) && error.code === "ENOENT") {
37
+ return undefined;
38
+ }
39
+ throw error;
40
+ }
41
+ }
42
+ /** Suffixes do not limit Portless's exact routes or its per-hostname TLS certificates. */
43
+ export async function hasCompatibleProxy(project, signal) {
44
+ const pid = Number(await readState("proxy.pid"));
45
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !isProcessAlive(pid)) {
46
+ return false;
47
+ }
48
+ const proxy = project.config.proxy;
49
+ const port = Number(await readState("proxy.port"));
50
+ const isHttps = existsSync(path.join(stateDirectory(), "proxy.tls"));
51
+ if (port !== proxy.port || isHttps !== proxy.https) {
52
+ throw new Error("The shared Portless proxy has different port or TLS settings. Coordinate those settings before starting this endpoint. The proxy was left running.");
53
+ }
54
+ const ca = isHttps ? await readFile(path.join(stateDirectory(), "ca.pem")) : undefined;
55
+ const request = isHttps ? https.request : http.request;
56
+ const hostname = `proxy.${project.config.domain}`;
57
+ await new Promise((resolve, reject) => {
58
+ const req = request({
59
+ host: "127.0.0.1",
60
+ port,
61
+ method: "HEAD",
62
+ path: "/",
63
+ servername: hostname,
64
+ ca,
65
+ headers: { host: hostname },
66
+ signal: AbortSignal.any([AbortSignal.timeout(10000), ...(signal ? [signal] : [])])
67
+ }, (response) => {
68
+ response.resume();
69
+ if (response.headers[PORTLESS_HEADER.toLowerCase()] !== "1") {
70
+ reject(new Error("The configured port is not responding as Portless. The existing process was left running."));
71
+ }
72
+ else {
73
+ resolve();
74
+ }
75
+ });
76
+ req.once("error", reject);
77
+ req.end();
78
+ });
79
+ return true;
80
+ }
81
+ export async function proxyCommand(project, action, signal) {
82
+ if (action === "setup" && (await hasCompatibleProxy(project, signal))) {
83
+ return { code: 0, stderr: "" };
84
+ }
85
+ const args = action === "setup"
86
+ ? [
87
+ "proxy",
88
+ "start",
89
+ ...(project.config.proxy.domains ?? [project.config.domain]).flatMap((domain) => ["--tld", domain]),
90
+ "--port",
91
+ String(project.config.proxy.port),
92
+ ...(project.config.proxy.https ? [] : ["--no-tls"])
93
+ ]
94
+ : [action === "status" ? "list" : "doctor"];
95
+ return runProcess([process.execPath, cli, ...args], { cwd: project.root, env: proxyEnvironment(project), signal });
96
+ }
97
+ export async function ensureProxy(project, signal) {
98
+ const result = await proxyCommand(project, "setup", signal);
99
+ if (result.code !== 0 || !(await hasCompatibleProxy(project, signal))) {
100
+ throw new Error("Could not start the Portless proxy. Run dev-domains setup and resolve the reported issue.");
101
+ }
102
+ }
@@ -0,0 +1,3 @@
1
+ import { RouteStore } from "portless";
2
+ export declare function stateDirectory(): string;
3
+ export declare function routeStore(): RouteStore;
@@ -0,0 +1,8 @@
1
+ import path from "node:path";
2
+ import { RouteStore, resolveUserHome } from "portless";
3
+ export function stateDirectory() {
4
+ return process.env.PORTLESS_STATE_DIR || path.join(resolveUserHome(), ".portless");
5
+ }
6
+ export function routeStore() {
7
+ return new RouteStore(stateDirectory());
8
+ }
@@ -1,6 +1,6 @@
1
1
  import { interpolate } from "../domains/resolve.js";
2
- import { routeStore } from "../runtime/portless.js";
3
2
  import { runProcess } from "../runtime/process.js";
3
+ import { routeStore } from "../runtime/state.js";
4
4
  import { startGateway } from "./gateway.js";
5
5
  export async function runTunnel(project, endpoint, signal) {
6
6
  const tunnel = endpoint.endpoint.tunnel;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@buildkitgg/dev-domains",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -35,6 +35,7 @@
35
35
  "dist/**/*.js",
36
36
  "dist/**/*.d.ts",
37
37
  "README.md",
38
+ "CHANGELOG.md",
38
39
  "LICENSE"
39
40
  ],
40
41
  "exports": {
@@ -1 +0,0 @@
1
- export {};
@@ -1,48 +0,0 @@
1
- import { z } from "zod";
2
- import { configSchema } from "../config/schema.js";
3
- import { resolveEndpoints } from "../domains/resolve.js";
4
- import { serverCommand, serverEnvironment } from "./command.js";
5
- import { routeStore } from "./portless.js";
6
- import { runProcess, withSignals } from "./process.js";
7
- const contextSchema = z.object({
8
- config: configSchema,
9
- root: z.string(),
10
- worktree: z.string().nullable(),
11
- service: z.string()
12
- });
13
- try {
14
- const context = contextSchema.parse(JSON.parse(process.env.BUILDKIT_RUN_CONTEXT || "null"));
15
- const endpoint = resolveEndpoints({ ...context, file: undefined }).find((candidate) => candidate.service === context.service);
16
- if (!endpoint) {
17
- throw new Error("Endpoint disappeared from the runtime context");
18
- }
19
- const actual = new URL(process.env.PORTLESS_URL || "");
20
- const domains = context.config.proxy.domains ?? [context.config.domain];
21
- const actualPort = Number(actual.port || (actual.protocol === "https:" ? 443 : 80));
22
- if (!domains.some((domain) => actual.hostname === `${endpoint.name}.${domain}`) ||
23
- actualPort !== context.config.proxy.port ||
24
- actual.protocol !== (context.config.proxy.https ? "https:" : "http:")) {
25
- throw new Error("The running Portless proxy has different settings. Coordinate its domains, port, and TLS configuration before running this endpoint.");
26
- }
27
- const port = z.coerce.number().int().min(1).max(65535).parse(process.env.PORT);
28
- // Registrations are written in place by Portless. Concurrent writers can
29
- // briefly produce an empty read; wait for our exact route to settle.
30
- const deadline = Date.now() + 2000;
31
- while (!routeStore()
32
- .loadRoutes()
33
- .some((route) => route.hostname === endpoint.hostname && route.port === port)) {
34
- if (Date.now() >= deadline) {
35
- throw new Error(`The running proxy did not register ${endpoint.hostname}. Align proxy.domains across your projects.`);
36
- }
37
- await new Promise((resolve) => setTimeout(resolve, 50));
38
- }
39
- const command = await serverCommand(endpoint.endpoint, context.config.packageManager, endpoint.cwd, endpoint.variables, port);
40
- const env = serverEnvironment(endpoint, port, process.env);
41
- delete env.BUILDKIT_RUN_CONTEXT;
42
- delete env.BUILDKIT_RUNNER;
43
- process.exitCode = (await withSignals((signal) => runProcess(command, { cwd: endpoint.cwd, env, signal }))).code;
44
- }
45
- catch (error) {
46
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
47
- process.exitCode = 1;
48
- }