@buildkitgg/dev-domains 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ ### Changed defaults
6
+
7
+ - App discovery uses the package's `dev` script. Other script names remain supported through explicit `script`
8
+ configuration, but are no longer automatically preferred or selected.
9
+ - Suggested E2E endpoints no longer set `DEV_DOMAINS_OUTPUT_DIR`. Configure framework output and cache isolation in the
10
+ application. Existing explicit `env` values remain supported.
11
+
12
+ ### Fixes
13
+
14
+ - A dedicated test endpoint added in the wizard keeps the selected app command, including custom servers without a `dev`
15
+ script.
16
+ - Installation, examples, and setup guidance use public commands and neutral project names. Contributor documentation
17
+ holds runtime implementation details.
18
+
19
+ Existing saved configurations remain valid. This pre-1.0 minor release makes the discovery changes explicit; projects
20
+ that relied on the previous inferred values should save their intended scripts and environment settings in a config.
21
+
22
+ ## 0.0.2
23
+
24
+ - Allow projects with different domains to share Portless without endpoint-name collisions. For example,
25
+ `local.example.com` and `local.example.org` now remain separate routes on one proxy.
26
+ - Preserve explicit `proxy.domains` aliases and reject occupied complete hostnames without takeover.
27
+ - Assign backend ports automatically and leave other projects running when a server stops.
28
+ - Run server commands consistently on Windows, Linux, and macOS.
29
+
30
+ Existing configuration files and public APIs remain compatible. Shared projects still need the same proxy port and TLS
31
+ mode, and custom domains must resolve locally. No DNS or provider settings are changed automatically.
32
+
33
+ ## 0.0.1
34
+
35
+ Initial public release.
package/README.md CHANGED
@@ -4,10 +4,10 @@ Stable local URLs for your app, Storybook, and end-to-end test servers, across r
4
4
 
5
5
  `@buildkitgg/dev-domains` gives each server a predictable hostname and runs it through
6
6
  [Portless](https://github.com/vercel-labs/portless). You can open `https://shop.localhost` in your primary checkout and
7
- `https://shop-fix-login.localhost` in a worktree, while Portless assigns the underlying ports. A configuration file lets
8
- you choose your own names, use a real domain, describe authentication callbacks, and expose selected webhook routes.
7
+ `https://shop-fix-login.localhost` in a worktree, with ports assigned automatically. A configuration file lets you
8
+ 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
 
@@ -30,7 +30,6 @@ you choose your own names, use a real domain, describe authentication callbacks,
30
30
  - [CI usage](#ci-usage)
31
31
  - [Command reference](#command-reference)
32
32
  - [Troubleshooting](#troubleshooting)
33
- - [Contributing and license](#contributing-and-license)
34
33
 
35
34
  ## Motivation and philosophy
36
35
 
@@ -48,8 +47,8 @@ The package follows a few principles:
48
47
  configuration when your project needs different names or commands.
49
48
  - **Readable checkout names.** Identify linked worktrees by their folder names. The primary checkout has no `main`
50
49
  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.
50
+ - **A convenience helper around Portless.** [Portless](https://github.com/vercel-labs/portless) provides local routing
51
+ and HTTPS. This package adds tool detection, typed configuration, and consistent domains across apps and worktrees.
53
52
  - **Report conflicts.** A running endpoint keeps its hostname. Another process must choose a different name instead of
54
53
  taking over the route.
55
54
  - **Keep application choices with the application.** Authentication providers, cloud resources, DNS administration, and
@@ -60,18 +59,10 @@ package manages local server addresses and processes; resource isolation remains
60
59
 
61
60
  ## Installation
62
61
 
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:
62
+ Install the package from npm as a development dependency in your project:
65
63
 
66
64
  ```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
65
+ npm install --save-dev @buildkitgg/dev-domains
75
66
  ```
76
67
 
77
68
  Install where the configuration and CLI are used. A root `dev-domains.config.ts` must be able to import the package from
@@ -83,27 +74,6 @@ Consumer-facing commands use `npx @buildkitgg/dev-domains`, which runs the local
83
74
  and locking the dependency keeps the CLI and configuration helpers on the same version. Portless is included; a separate
84
75
  global installation is unnecessary. Your application frameworks and any tunnel executable must already be installed.
85
76
 
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
77
  On Windows, Portless also requires OpenSSL on `PATH`. Initial HTTPS setup can require permission to trust a local
108
78
  certificate authority, bind the proxy port, or update the hosts file. Run setup interactively on each development
109
79
  machine.
@@ -172,39 +142,40 @@ When no configuration file is found, these conventions determine the candidates:
172
142
  | Project name | Root `package.json` name, otherwise the root folder name, normalized as described below |
173
143
  | Package manager | Root `packageManager`, then `devEngines.packageManager`, then lockfiles, then installation metadata; npm if none is found |
174
144
  | Workspace packages | Root plus declared `pnpm-workspace.yaml` packages or `package.json` workspaces; without declarations, packages found recursively below the root |
175
- | App server | First eligible script in this order: `dev:app`, `dev:raw`, `dev` |
145
+ | App server | The package's `dev` script, when it starts one server; other script names require explicit configuration |
176
146
  | Storybook server | A script containing `storybook dev`; otherwise a discovered `.storybook/main.*` config |
177
147
  | Playwright candidate | A `playwright.config.*` file, an `@playwright/test` dependency, or a `playwright test` script, together with an app dev script in the same package |
178
148
  | Framework | Recognized simple Next.js, Vite, and Storybook commands receive framework-specific flags; other commands are `custom` |
179
149
  | Local proxy | HTTPS on port 443, suffix `localhost`, hosts synchronization enabled |
180
150
  | Auth and public access | No callback paths or tunnels are inferred |
181
151
 
182
- Package-manager detection uses
183
- [`package-manager-detector`](https://github.com/antfu-collective/package-manager-detector). It stays at the selected
184
- project root instead of inheriting a manager from an unrelated parent folder. A declaration takes precedence over stale
185
- lockfiles. Conflicting lockfiles without a declaration require you to choose a manager in `package.json` or an explicit
186
- dev-domains config.
152
+ Package-manager detection stays at the selected project root. A declaration takes precedence over stale lockfiles.
153
+ Conflicting lockfiles without a declaration require you to choose a manager in `package.json` or an explicit config.
187
154
 
188
155
  Scripts that invoke `dev-domains`, `portless`, `turbo`, `run-p`, or `concurrently` are excluded from detection. Point
189
156
  configuration at the underlying server script when an aggregate or wrapper command is involved. A `playwright test`
190
157
  script is never used as the app server.
191
158
 
159
+ There is no universally required development script name. `dev` is the default convention; scripts with any other name
160
+ work through an explicit `script` setting. Detection does not guess whether `start`, `serve`, or a custom script is a
161
+ development server, production server, or build task.
162
+
192
163
  ### Storybook and Playwright discovery
193
164
 
194
- One read-only directory walk finds both `.storybook/main.*` and `playwright.config.*`. It recognizes `ts`, `mts`, `cts`,
195
- `js`, `mjs`, `cjs`, `tsx`, and `jsx` filenames. Configs belong to their nearest package, including nested paths such as
165
+ Discovery finds both `.storybook/main.*` and `playwright.config.*`. It recognizes `ts`, `mts`, `cts`, `js`, `mjs`,
166
+ `cjs`, `tsx`, and `jsx` filenames. Configs belong to their nearest package, including nested paths such as
196
167
  `tests/playwright.config.ts`. Tool configuration files are located without being imported or executed.
197
168
 
198
- The walk honors workspace exclusions and skips symlinks, hidden directories other than `.storybook`, `node_modules`,
199
- `dist`, `build`, `out`, `coverage`, `storybook-static`, `playwright-report`, and `test-results`. It stops with an error
200
- above 1,000 packages or 10,000 visited directories; use explicit configuration for larger or unusual layouts.
169
+ Discovery honors workspace exclusions and skips dependencies, generated output, symlinks, and hidden directories other
170
+ than `.storybook`. Use explicit configuration for unusual layouts or when discovery reports that a project is too large.
201
171
 
202
172
  For Storybook, a dev script takes precedence over config-file discovery. With one config and no dev script, the
203
173
  candidate runs the installed `storybook dev --config-dir <directory>` binary. Nothing is downloaded. Multiple dev
204
174
  scripts, or multiple configs without a clear dev script, require explicit configuration. An empty `.storybook` folder or
205
175
  a Storybook dependency alone does not establish a runnable server.
206
176
 
207
- For Playwright, the candidate starts a separate copy of the app dev server. It is named `app-e2e`, or
177
+ Finding Playwright does not reveal which server your tests need. The suggested endpoint starts a separate copy of the
178
+ package's `dev` server; it does not read Playwright's `webServer` configuration. It is named `app-e2e`, or
208
179
  `<package>-app-e2e` in a workspace. Select it explicitly in the wizard or run it by name when using zero configuration.
209
180
  `init --yes` omits it. A dependency on the `playwright` browser library alone does not imply an E2E test setup. Separate
210
181
  test-only packages and cross-package server relationships need explicit configuration. See [Playwright](#playwright)
@@ -259,7 +230,7 @@ export default defineConfig({
259
230
  endpoints: {
260
231
  app: {
261
232
  cwd: "apps/web",
262
- script: "dev:raw",
233
+ command: ["next", "dev"],
263
234
  framework: "next",
264
235
  primaryName: "local",
265
236
  name: "{worktree}.local"
@@ -376,10 +347,10 @@ A saved configuration is complete: detected endpoints are not merged into it. In
376
347
  in a saved config defaults to **npm**, while zero-config discovery detects the manager. Specify your manager when
377
348
  authoring a config for pnpm, Yarn, or Bun.
378
349
 
379
- Configuration loading uses c12 with home configuration, implicit `.env` loading, package.json config, remote extensions,
380
- and environment-specific merging disabled. Your framework may still load its own environment files. JavaScript and
381
- TypeScript configs execute as code when loaded; use configs from repositories you trust. The `detect` command always
382
- inspects project conventions without loading a dev-domains config.
350
+ Only the selected configuration file is loaded. The CLI does not load `.env` files, user-wide settings, remote
351
+ configuration, or environment-specific overrides. Your framework may still load its own environment files. JavaScript
352
+ and TypeScript configs execute as code when loaded; use configs from repositories you trust. `detect` inspects project
353
+ conventions without loading a dev-domains config.
383
354
 
384
355
  ### JSON editor support
385
356
 
@@ -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
 
@@ -527,9 +498,9 @@ Use `framework: "custom"` for compound shell scripts or commands that cannot acc
527
498
  automatically for compound scripts. In a saved config, choose the appropriate framework yourself. `kind` does not select
528
499
  it for you.
529
500
 
530
- Keep the underlying server script free of another `dev-domains` or Portless invocation. For example, a package can use
531
- `"dev": "npx @buildkitgg/dev-domains run app"` together with `"dev:raw": "vite"`, while the endpoint references
532
- `script: "dev:raw"`. Configuring `script: "dev"` in that example would recurse and is rejected.
501
+ If you replace your `dev` script with `npx @buildkitgg/dev-domains run app`, configure the endpoint with the server
502
+ command directly, such as `command: ["vite"]` and `framework: "vite"`. Pointing that endpoint back to `script: "dev"`
503
+ would start the CLI again and is rejected. You do not need a second package script with a special name.
533
504
 
534
505
  Your framework still controls allowed hosts, development origins, and output directories. Add your generated hostnames
535
506
  to its configuration where required. When a server exits, its exit code is propagated. Custom servers must fail on a
@@ -545,9 +516,8 @@ separate server, configure a dedicated endpoint:
545
516
  "app-e2e": {
546
517
  kind: "e2e",
547
518
  cwd: "apps/web",
548
- script: "dev:raw",
549
- framework: "next",
550
- env: { DEV_DOMAINS_OUTPUT_DIR: ".dev-domains/app-e2e" }
519
+ command: ["vite"],
520
+ framework: "vite"
551
521
  }
552
522
  ```
553
523
 
@@ -572,10 +542,10 @@ dev-domains config can be found.
572
542
  The endpoint's script must start a server, not run `playwright test`. The helper does not install Playwright or edit its
573
543
  configuration. Run `npx @buildkitgg/dev-domains setup` before the test run on a development machine.
574
544
 
575
- A dedicated endpoint gets a separate hostname and port, but you must also isolate build output when the framework
576
- requires it. Detection and the wizard set `DEV_DOMAINS_OUTPUT_DIR` for E2E candidates. The framework must consume that
577
- variable; for example, a Next.js config can set `distDir: process.env.DEV_DOMAINS_OUTPUT_DIR || ".next"`. Databases,
578
- storage, and credentials are still shared unless you configure them separately.
545
+ A dedicated endpoint gets a separate hostname and port. Configure separate build output or caches when your framework
546
+ requires them; this package does not change those settings or assign a framework output directory. Tests that need a
547
+ production build, another package, or a remote deployment need an explicit server configuration. Databases, storage, and
548
+ credentials remain shared unless you configure them separately.
579
549
 
580
550
  ## Node.js tooling
581
551
 
@@ -591,8 +561,8 @@ process.env.APP_URL = app.origin
591
561
  `getEndpoint(service, cwd?)` returns a promise containing `service`, `hostname`, `origin`, `callbacks` (resolved auth
592
562
  URLs), and `cwd` (the server's absolute working directory). It uses the CLI's configuration discovery and worktree
593
563
  naming rules; `cwd` defaults to `process.cwd()`. An unknown endpoint throws. The exported `EndpointInfo` type describes
594
- the result. This Node.js-only helper can execute trusted local configuration files, just like the CLI. It does not
595
- allocate a port, start the proxy, or register a route.
564
+ the result. This Node.js-only helper can execute trusted local configuration files, just like the CLI. It does not start
565
+ servers or change networking settings.
596
566
 
597
567
  ## Authentication callbacks
598
568
 
@@ -644,12 +614,11 @@ No separate webhook subdomain is required. A quick tunnel URL may change after r
644
614
  configure a stable tunnel with your provider and optionally record its HTTPS origin in `tunnel.publicUrl`. That property
645
615
  reports an existing address; it does not reserve a domain or configure the tunnel command.
646
616
 
647
- The tunnel targets a restricted gateway that holds an OS-assigned loopback port open. It forwards only POST requests
648
- whose paths exactly match `tunnel.paths`. Query strings, raw request bytes, and signature headers are preserved;
649
- hop-by-hop headers and the inbound `Forwarded`, `X-Forwarded-For`, and `X-Forwarded-Host` headers are stripped. Request
650
- bodies are limited to 1 MiB, upstream requests time out after 15 seconds, and payloads are not logged or stored. Your
651
- application must validate provider signatures. Providers that require a GET verification challenge need a different
652
- ingress arrangement; this gateway is POST-only.
617
+ The tunnel accepts only POST requests whose paths exactly match `tunnel.paths`. Query strings, raw request bytes, and
618
+ signature headers are preserved; hop-by-hop headers and the inbound `Forwarded`, `X-Forwarded-For`, and
619
+ `X-Forwarded-Host` headers are stripped. Request bodies are limited to 1 MiB, upstream requests time out after 15
620
+ seconds, and payloads are not logged or stored. Your application must validate provider signatures. Providers that
621
+ require a GET verification challenge need a different ingress arrangement; this gateway is POST-only.
653
622
 
654
623
  Install and authenticate the tunnel executable separately. It runs from the configuration root and inherits the shell
655
624
  environment, rather than the endpoint's server `env` overrides. Keep credentials in the provider's login store or
@@ -658,8 +627,8 @@ running. A hosted receiver, durable delivery, and replay are not included.
658
627
 
659
628
  ## Sharing a proxy across projects
660
629
 
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:
630
+ One machine can run many endpoints through one Portless proxy, with a separate domain for each project. Keep the proxy
631
+ port and TLS mode aligned. To give one project's endpoints additional aliases, configure an explicit list:
663
632
 
664
633
  ```ts
665
634
  // Root configuration fields, alongside project and endpoints.
@@ -672,18 +641,19 @@ proxy: {
672
641
  }
673
642
  ```
674
643
 
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.
644
+ Projects can use different domains: `local.example.com` and `local.example.org` can run together on the same proxy.
645
+ Leave `proxy.domains` unset unless this project's endpoints should have additional aliases. An explicit list registers
646
+ each endpoint under those suffixes only; `domain` selects its canonical origin. A collision means the **complete
647
+ hostname** is occupied, not just the endpoint name.
678
648
 
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.
649
+ Projects sharing one proxy must agree on its port and TLS settings. Starting an endpoint leaves other servers running.
650
+ DNS must resolve every custom hostname to loopback; either use Portless's hosts synchronization or configure DNS
651
+ yourself. If the existing proxy was started with hosts synchronization disabled, `syncHosts: true` cannot change that
652
+ running process. Coordinate proxy configuration or configure DNS separately. `npx @buildkitgg/dev-domains doctor` helps
653
+ diagnose the current state.
682
654
 
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.
655
+ Backend ports are assigned automatically. Startup may be retried after a port conflict, so server commands should be
656
+ safe to repeat. A running server keeps its hostname; choose another name if the CLI reports a collision.
687
657
 
688
658
  ## CI usage
689
659
 
@@ -721,32 +691,24 @@ first.
721
691
  `--cwd` defaults to the current directory. `--config` is a file path relative to `--cwd`. Use `--help` on a command for
722
692
  its options. `run` and `tunnel` require an endpoint name in noninteractive sessions when more than one candidate exists.
723
693
 
724
- The CLI never rewrites package scripts. It propagates server exit codes and cleans up its own routes when the server
725
- stops. The shared proxy is left running. After a hard crash, Portless handles stale routes during subsequent operation.
726
- `PORTLESS_STATE_DIR` can select a separate state directory; most consumers should keep the default shared state.
694
+ The CLI never rewrites package scripts. It propagates server exit codes and releases the endpoint's hostname when the
695
+ server stops normally. The shared proxy stays available for other servers. After a forced termination, check `status`
696
+ and stop any remaining server process you own before restarting it. `PORTLESS_STATE_DIR` can select a separate state
697
+ directory; most consumers should keep the default shared state.
727
698
 
728
699
  ## Troubleshooting
729
700
 
730
701
  | Symptom | What to check |
731
702
  | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
732
703
  | No endpoints were detected | Run `detect`; check the app script conventions or add an explicit `command` / `script` endpoint |
733
- | A wrapped script is rejected | Reference the underlying server script, such as `dev:raw`, instead of a script invoking dev-domains or Portless |
704
+ | A wrapped script is rejected | Set `command` to the server executable, or reference a script that starts the server directly |
734
705
  | An endpoint name is ambiguous | Use `urls` for configured names or `detect` for discovered names, then pass one to `run` |
735
706
  | Multiple configs or Storybook candidates were found | Keep one dev-domains config per directory; select the intended Storybook script or config directory explicitly |
736
707
  | The wrong package manager is used | In a saved config, set `packageManager`; during discovery, check the root declaration and conflicting lockfiles |
737
708
  | 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 |
709
+ | The proxy has different settings | Align port and TLS settings with the existing shared proxy before restarting your endpoint |
739
710
  | The hostname does not resolve or HTTPS is untrusted | Run `doctor`; check loopback DNS or hosts synchronization and complete Portless certificate setup |
740
711
  | The framework rejects the hostname | Configure its allowed hosts or development origins for your generated domains |
741
- | App and E2E servers conflict despite different ports | Configure separate framework build/output directories; verify the app consumes `DEV_DOMAINS_OUTPUT_DIR` |
712
+ | App and E2E servers conflict despite different ports | Configure separate framework build/output directories or caches |
742
713
  | A webhook returns 404 | Confirm it is a POST request to an exact allowed path; GET verification challenges are not supported by this gateway |
743
714
  | A webhook cannot reach the app | Start the target endpoint first, verify the provider's current public URL, and check the tunnel process |
744
-
745
- ## Contributing and license
746
-
747
- See the
748
- [architecture and testing guide](https://github.com/AndrewCraswell/buildkit/blob/main/packages/dev-domains/docs/README.md)
749
- and [contributor guide](https://github.com/AndrewCraswell/buildkit/blob/main/CONTRIBUTING.md) for development details.
750
-
751
- [MIT licensed](https://github.com/AndrewCraswell/buildkit/blob/main/LICENSE). Part of Buildkit, whose domain is
752
- [buildkit.gg](https://buildkit.gg). No Buildkit hosted service is required to use this package.
@@ -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";
package/dist/cli/init.js CHANGED
@@ -76,7 +76,7 @@ export async function initialize(cwd, options) {
76
76
  endpoint.primaryName = await ask(`Primary checkout name for ${key} ({project}, {service} supported)`, endpoint.primaryName || "{project}-{service}");
77
77
  endpoint.name = await ask(`Worktree name for ${key} ({project}, {worktree}, {service} supported)`, endpoint.name || "{project}-{worktree}-{service}");
78
78
  if (endpoint.kind === "e2e") {
79
- prompts.note("This starts a separate copy of the app server. For frameworks with build locks, use DEV_DOMAINS_OUTPUT_DIR for a separate output directory. Configure Playwright to use this endpoint; databases remain shared.", "Test server isolation");
79
+ prompts.note("This starts a separate copy of the app server. Configure Playwright to use its URL and isolate framework output and application resources as needed.", "Test server isolation");
80
80
  }
81
81
  if (endpoint.kind === "storybook" || endpoint.kind === "e2e") {
82
82
  continue;
@@ -97,7 +97,6 @@ export async function initialize(cwd, options) {
97
97
  .map((value) => value.trim());
98
98
  }
99
99
  if (capabilities.includes("e2e")) {
100
- const script = await ask("Script for the dedicated test server", endpoint.script || "dev");
101
100
  const name = `${key}-e2e`;
102
101
  if (candidate.endpoints[name]) {
103
102
  throw new Error(`Endpoint ${name} already exists`);
@@ -105,14 +104,11 @@ export async function initialize(cwd, options) {
105
104
  additions[name] = {
106
105
  ...endpoint,
107
106
  kind: "e2e",
108
- command: undefined,
109
- script,
110
107
  primaryName: "{project}-{service}",
111
108
  name: "{project}-{worktree}-{service}",
112
- auth: [],
113
- env: { DEV_DOMAINS_OUTPUT_DIR: `.dev-domains/${name}` }
109
+ auth: []
114
110
  };
115
- prompts.note("For frameworks with build locks, configure the test server to use DEV_DOMAINS_OUTPUT_DIR as a separate output directory. Databases remain shared.", "Test server isolation");
111
+ prompts.note("The test endpoint uses the same server command. Edit its configuration if tests need a different command, build output, or application resources.", "Test server isolation");
116
112
  }
117
113
  if (capabilities.includes("webhooks")) {
118
114
  prompts.note("Enter a tunnel command that uses {url} for its target. Credentials stay in the provider's environment or login store. Exposure starts only with dev-domains tunnel.", "Public webhook access");
@@ -140,9 +136,9 @@ export async function initialize(cwd, options) {
140
136
  }
141
137
  const file = await saveConfig(identity.root, candidate);
142
138
  if (options.yes) {
143
- text(`Saved ${file}\nNext: dev-domains setup, then dev-domains run <endpoint>`);
139
+ text(`Saved ${file}\nNext: npx @buildkitgg/dev-domains setup, then npx @buildkitgg/dev-domains run <endpoint>`);
144
140
  }
145
141
  else {
146
- prompts.outro(`Saved ${file}\nNext: dev-domains setup, then dev-domains run <endpoint>`);
142
+ prompts.outro(`Saved ${file}\nNext: npx @buildkitgg/dev-domains setup, then npx @buildkitgg/dev-domains run <endpoint>`);
147
143
  }
148
144
  }
@@ -58,9 +58,7 @@ export async function detectConfig(root) {
58
58
  ...endpoint
59
59
  };
60
60
  };
61
- const dev = ["dev:app", "dev:raw", "dev"]
62
- .map((name) => scripts.find(([script, source]) => script === name && !storybookDev.test(source) && !playwrightTest.test(source)))
63
- .find((entry) => entry !== undefined);
61
+ const dev = scripts.find(([script, source]) => script === "dev" && !storybookDev.test(source) && !playwrightTest.test(source));
64
62
  if (dev) {
65
63
  const [script, source] = dev;
66
64
  add("app", { kind: "app", script, framework: frameworkFor(source) });
@@ -92,8 +90,7 @@ export async function detectConfig(root) {
92
90
  add("app-e2e", {
93
91
  kind: "e2e",
94
92
  script: dev[0],
95
- framework: frameworkFor(dev[1]),
96
- env: { DEV_DOMAINS_OUTPUT_DIR: `.dev-domains/${prefix}app-e2e` }
93
+ framework: frameworkFor(dev[1])
97
94
  });
98
95
  }
99
96
  }
@@ -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.1.0",
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
- }