@b12k/porto 0.9.0 โ†’ 0.11.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/README.md CHANGED
@@ -2,67 +2,136 @@
2
2
  <img src="./porto.png" alt="Porto banner with a tree formed from Ethernet cables" />
3
3
  </p>
4
4
 
5
- # ๐ŸŒณ :porto
5
+ # ๐ŸŒณ Porto
6
6
 
7
- Porto reserves TCP port blocks for Git checkouts and worktrees.
7
+ ๐Ÿ’ช **Port reservations on steroids.**
8
8
 
9
- ## ๐Ÿš€ Start
9
+ Porto reserves a range of TCP ports, called a slot, for each Git worktree.
10
+ It checks for port conflicts and saves the slot for the next run.
10
11
 
11
- Install Node.js 24 or later and Git 2.36 or later.
12
+ ๐Ÿงน **It can haz cleanups.** When you reserve ports, Porto removes expired slots if all their ports are free.
13
+
14
+ ## ๐Ÿš€ Install
15
+
16
+ **npm**
17
+
18
+ ```sh
19
+ npm install -D @b12k/porto
20
+ ```
21
+
22
+ **pnpm**
12
23
 
13
24
  ```sh
14
25
  pnpm add -D @b12k/porto
15
- pnpm exec porto --vars API_PORT --env
16
26
  ```
17
27
 
18
- Porto writes `API_PORT` to `.env`. Run the same command again to reuse the block.
19
-
20
- | Worktree | Block | Ports |
21
- | -------- | ----: | ----------- |
22
- | Main | 0 | 10000โ€“10009 |
23
- | Feature | 1 | 10010โ€“10019 |
24
-
25
- ## ๐Ÿ–ฅ๏ธ Commands
26
-
27
- Run each command with `pnpm exec porto`. `reserve` is the default command.
28
-
29
- | Command | Action |
30
- | --------- | --------------------------------------------------------- |
31
- | `reserve` | Reserve a block and print its index or variables. |
32
- | `current` | Show the blocks for this checkout. |
33
- | `stats` | Show all reservations for this repository. |
34
- | `release` | Release this checkout's blocks when their ports are free. |
35
- | `cleanup` | Remove expired reservations when their ports are free. |
36
-
37
- | `reserve` option | Action |
38
- | --------------------------------------- | ------------------------------------------------------------ |
39
- | `--start <port>` | Set the first port of the range. Default `10000`. |
40
- | `--host <host>` | Check this host for busy ports. Default local addresses. |
41
- | `--size <count>` | Set the ports per block. Default `10`. |
42
- | `--idle <minutes>` | Set the idle time limit. Default `60`. |
43
- | `--keep` / `--no-keep` | Turn idle cleanup off or on for the block. |
44
- | `--vars <entries>` / `--no-vars` | Set or clear the variable list. |
45
- | `--env` / `--no-env` | Turn env file output on or off. Default off. File `.env`. |
46
- | `--env-file <file>` | Set the env file path and turn on env output. |
47
- | `--json-file <file>` / `--no-json-file` | Set or clear the JSON output file. |
48
- | `--json` | Print JSON to stdout. Also works with `current` and `stats`. |
49
- | `--silent` / `--no-silent` | Hide or show the reservation result on stdout. |
28
+ **Yarn**
29
+
30
+ ```sh
31
+ yarn add -D @b12k/porto
32
+ ```
33
+
34
+ **Bun**
35
+
36
+ ```sh
37
+ bun add --dev @b12k/porto
38
+ ```
39
+
40
+ ## Use Porto
41
+
42
+ - [CLI](#cli) - Pass options when you run `pnpm porto`.
43
+ - [Config](#config) - Save settings in `porto.config.ts` or `porto.config.js`.
44
+ - [API](#api) - Add `@b12k/porto` as a dependency and call `reserve()` from your code.
45
+
46
+ ### CLI
47
+
48
+ ```css
49
+ porto [reserve?] [options]
50
+ porto show [slot-number?] [--all?]
51
+ porto release [slot-number?] [--all?] [--force?]
52
+ porto cleanup
53
+ ```
54
+
55
+ #### Commands
56
+
57
+ | Command | Action |
58
+ | --------- | ---------------------------------------------------------------------- |
59
+ | `reserve` | _**(default)**_ Allocate a port slot and print its index or variables. |
60
+ | `show` | Show a slot. Use `--all` to show all slots. |
61
+ | `release` | Release a slot. Use `--all` for all slots, `--force` for busy ports. |
62
+ | `cleanup` | Remove expired slots when their ports are free. |
63
+
64
+ #### `reserve` settings
65
+
66
+ One setting, three ways to set it. Precedence: CLI flag โ†’ config file โ†’ saved repository settings (`start` and `size` only) โ†’ default.
67
+
68
+ | Setting | CLI flag | Config key | Default | Effect |
69
+ | -------------- | --------------------------------------- | ---------------- | ----------------- | ---------------------------------------------------------------------------------------- |
70
+ | First port | `--start <port>` | `start` | `10000` | First port of the range. Shared by all worktrees. |
71
+ | Ports per slot | `--size <count>` | `size` | `10` | Ports per slot. Shared by all worktrees. |
72
+ | Host | `--host <host>` | `host` | Local addresses | Host to check for busy ports. Remembered with the slot, so repeat runs need no `--host`. |
73
+ | Idle TTL | `--idle <minutes>` | `idleTtlMinutes` | `60` | Idle limit, minutes. Each `reserve` restarts the countdown. |
74
+ | Keep | `--keep` / `--no-keep` | `keep` | Off for new slots | Keep the slot during idle cleanup. Omit to keep the current value. |
75
+ | Variables | `--vars <vars>` / `--no-vars` | `vars` | Unset | One port per entry. `--no-vars` clears the configured list. |
76
+ | Env output | `--env` / `--no-env` | `env` | `false` | Write variables and `SLOT` to an env file. |
77
+ | Env file | `--env-file <file>` | `envFile` | `.env` | An explicit path enables `env` unless you set `env: false`. |
78
+ | JSON file | `--json-file <file>` / `--no-json-file` | `jsonFile` | `false` | Save variables or slot details with `SLOT`. A path enables it. |
79
+ | Silent | `--silent` / `--no-silent` | `silent` | `false` | Hide the `reserve` result on stdout. Files are still written. |
80
+
81
+ CLI-only flags: `--json` (print JSON to stdout, also works with `show`).
82
+
83
+ Relative paths in config start at the config directory. Relative paths in flags start at the current directory.
50
84
 
51
85
  Use `-h` or `--help` for help. Use `-V` or `--version` for the version.
52
86
 
53
- Use `|` to share a port between variables and `;` to advance to the next port. Use `NAME` for a port number or `NAME=template` for text. Templates accept `{{block}}` and `{{port}}`.
87
+ ##### `--vars` template syntax
88
+
89
+ Use `;` to move to the next port and `|` to share the current port. Use `NAME` for a port number or `NAME=template` for text. Templates accept `{{slot}}` and `{{port}}`. Map `SLOT` explicitly when you need the slot index next to other variables: `--vars "SLOT={{slot}};API_PORT"`.
90
+
91
+ ##### Write to files
54
92
 
55
93
  ```sh
56
- pnpm exec porto --vars 'PORT|HOST_URL=http://localhost:{{port}};API_PORT' --env
94
+ pnpm porto --vars "CLIENT_PORT|HOST_URL=http://localhost:{{port}};API_PORT" --env-file .env.local --json-file env.json
95
+ ```
96
+
97
+ If the first slot is free, Porto writes these files. `SLOT` is included only when no other variables are given โ€” otherwise map it explicitly as shown above.
98
+
99
+ `.env.local`
100
+
101
+ ```dotenv
102
+ CLIENT_PORT=10000
103
+ HOST_URL=http://localhost:10000
104
+ API_PORT=10001
105
+ ```
106
+
107
+ `env.json`
108
+
109
+ ```json
110
+ { "CLIENT_PORT": 10000, "HOST_URL": "http://localhost:10000", "API_PORT": 10001 }
57
111
  ```
58
112
 
59
- With no variables, `--env` writes `PORTO_BLOCK`.
113
+ Run the same command again in this worktree to reuse its slot. A second worktree gets its own slot.
114
+
115
+ To change `--start` or `--size`, release all slots first.
116
+
117
+ | Worktree | Slot | Ports |
118
+ | -------- | ---: | ----------- |
119
+ | Main | 0 | 10000-10009 |
120
+ | Feature | 1 | 10010-10019 |
121
+
122
+ #### `show` and `release` options
123
+
124
+ | Argument or option | Default | Action |
125
+ | ------------------ | -------------------- | ------------------------------------- |
126
+ | `[slot-number]` | This worktree's slot | Select a slot by index. |
127
+ | `--all` | Off | Select all slots for this repository. |
128
+ | `--force` | Off | Release slots even if ports are busy. |
60
129
 
61
- ## โš™๏ธ Config
130
+ Use a slot number or `--all`. If a port is busy, `release --all` keeps every slot, unless `--force` is set.
62
131
 
63
- The CLI loads config for `reserve` and `release`. Create `porto.config.ts` or `porto.config.js` in your checkout. Porto searches from the current directory to the checkout root. If both files are in one directory, Porto uses the TypeScript file.
132
+ ### Config
64
133
 
65
- CLI options override config values. Config values override defaults.
134
+ The CLI loads config for `reserve` and `release`. Create `porto.config.ts` or `porto.config.js` in your worktree. Porto searches from the current directory to the worktree root. If both files are in one directory, Porto uses the TypeScript file.
66
135
 
67
136
  ```ts
68
137
  import { defineConfig } from '@b12k/porto';
@@ -77,98 +146,90 @@ export default defineConfig({
77
146
  envFile: '.env.local',
78
147
  jsonFile: 'ports.json',
79
148
  silent: false,
80
- vars: ['PORT', (_block, port) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}` }), 'DB_PORT'],
81
- onReserved(block, ports) {
82
- console.error(`Reserved block ${block.index} with ports ${ports.join(', ')}`);
149
+ vars: ['PORT', (port, slot) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}`, SLOT: slot }), 'DB_PORT'],
150
+ onReserved(slot, ports) {
151
+ console.error(`Reserved slot ${slot.index} with ports ${ports.join(', ')}`);
83
152
  },
84
- onReleased(block, ports) {
85
- console.error(`Released block ${block.index} with ports ${ports.join(', ')}`);
153
+ onReleased(slot, ports) {
154
+ console.error(`Released slot ${slot.index} with ports ${ports.join(', ')}`);
86
155
  },
87
156
  });
88
157
  ```
89
158
 
90
- All properties are optional.
91
-
92
- | Property | Default | Effect |
93
- | ---------------- | ---------------------- | -------------------------------------------------------------------------------------------- |
94
- | `start` | `10000` | Set the first port of the candidate range. |
95
- | `size` | `10` | Set the number of ports per block. |
96
- | `host` | Local addresses | Check a specific host for busy ports. Porto saves the host for `release` and `cleanup`. |
97
- | `idleTtlMinutes` | `60` | Set the idle time limit in minutes. A new `reserve` call refreshes the timer. |
98
- | `keep` | `false` for new blocks | Keep a block during idle cleanup. Omit to keep its current setting. Set `false` to clear it. |
99
- | `env` | `false` | Write variables to an env file. With no variables, write `PORTO_BLOCK`. |
100
- | `envFile` | `.env` | Set the env file path. An explicit path enables `env` unless you set `env: false`. |
101
- | `jsonFile` | `false` | Save variables or block details to a JSON file. Use a path to enable it. |
102
- | `silent` | `false` | Hide the `reserve` result on stdout. Porto still writes requested files and reports errors. |
103
- | `vars` | Unset | Assign one port per entry. Use a name for a port number or a function for several values. |
104
- | `onReserved` | Unset | Run after Porto saves the block and writes the requested files. |
105
- | `onReleased` | Unset | Run once per block freed by `release`. |
159
+ All properties are optional. Every setting from [reserve settings](#reserve-settings) also works as a config key.
106
160
 
107
- Relative paths in config start at the config directory. Relative paths in flags start at the current directory.
161
+ | Property | Effect |
162
+ | ------------ | -------------------------------------------------------------- |
163
+ | `onReserved` | Run after Porto saves the slot and writes the requested files. |
164
+ | `onReleased` | Run once per slot freed by `release`. |
108
165
 
109
- A `vars` function receives `(blockIndex, port, entryIndex)`, where `entryIndex` starts at zero. Return an object with string or number values. In the example, `PORT_2` and `HOST_NAME` use the same port.
166
+ A `vars` function receives `(port, slot)`. Return an object with string or number values. In the example, `PORT_2` and `HOST_NAME` use the same port, and `SLOT` maps the slot index explicitly.
110
167
 
111
- Both hooks receive `(block, ports)`, where `ports` lists the ports assigned to that block. Hooks can return a promise. Porto runs release hooks in parallel.
168
+ Both hooks receive `(slot, ports)`, where `ports` lists the ports assigned to that slot. Hooks can return a promise.
112
169
 
113
- ## ๐Ÿ“ฆ API
170
+ ### API
114
171
 
115
- Run the API inside a Git checkout. It uses the options you pass in code and the built-in defaults.
172
+ Run the API inside a Git worktree.
116
173
 
117
- ### Get ports by offset
174
+ #### Get ports by offset
118
175
 
119
176
  ```js
120
177
  import { reserve } from '@b12k/porto';
121
178
 
122
- const block = await reserve();
123
- const firstPort = block.getPort();
124
- const secondPort = block.getPort(1);
179
+ const slot = await reserve();
180
+ const firstPort = slot.getPort();
181
+ const secondPort = slot.getPort(1);
125
182
  ```
126
183
 
127
- `reserve()` returns `index`, `start`, `end`, `getPort(offset = 0)`, `ports`, and `vars`. The bounds are inclusive. Offsets start at zero and must fit inside the block.
184
+ `reserve()` returns the saved slot with `getPort(offset = 0)`. Offsets start at zero and must fit inside the slot.
185
+
186
+ `firstPort` and `lastPort` are the slot's inclusive bounds.
128
187
 
129
- ### Get ports by name
188
+ #### Get ports by name
130
189
 
131
190
  ```js
132
191
  import { reserve } from '@b12k/porto';
133
192
 
134
- const block = await reserve({ start: 10_000, size: 5, vars: ['PORT', 'API_PORT'] });
135
- const { PORT, API_PORT } = block.vars;
136
- const DB_PORT = block.getPort(2); // 10002 if the first block is free
193
+ const slot = await reserve({ start: 10_000, size: 5, vars: ['PORT', 'API_PORT'] });
194
+ const { PORT, API_PORT } = slot.vars;
195
+ const DB_PORT = slot.getPort(2); // 10002 if the first slot is free
137
196
  ```
138
197
 
139
- TypeScript infers `PORT` and `API_PORT` as `number`. `block.vars` contains this call's named values and defaults to `{}`. `block.ports` lists the ports assigned through `vars` across calls. `getPort()` reads a port by offset.
198
+ TypeScript infers `PORT` and `API_PORT` as `number`. `slot.vars` contains this call's named values; with no `vars` given it contains only the built-in `SLOT`. `slot.ports` lists the ports assigned through `vars`. `getPort()` reads a port by offset.
140
199
 
141
- ### Share a port between variables
200
+ #### Share a port between variables
142
201
 
143
202
  ```js
144
203
  import { reserve } from '@b12k/porto';
145
204
 
146
- const block = await reserve({
205
+ const slot = await reserve({
147
206
  start: 10_000,
148
207
  size: 2,
149
208
  host: '127.0.0.1',
150
209
  idleTtlMinutes: 30,
151
210
  keep: true,
152
- vars: ['PORT', (_block, port) => ({ API_PORT: port, API_URL: `http://localhost:${port}` })],
211
+ vars: ['PORT', (port, slot) => ({ API_PORT: port, API_URL: `http://localhost:${port}`, SLOT: slot })],
153
212
  });
154
- const { API_PORT, API_URL } = block.vars;
213
+ const { API_PORT, API_URL } = slot.vars;
155
214
  ```
156
215
 
157
- `reserve()` accepts `start`, `size`, `host`, `idleTtlMinutes`, `keep`, and `vars`. All six options are optional and use the defaults in the config table.
216
+ `reserve()` accepts `start`, `size`, `host`, `idleTtlMinutes`, `keep`, and `vars`. All six options are optional. Omit `start` and `size` to reuse the saved repository settings. Other options use the defaults in the [reserve settings](#reserve-settings) table.
158
217
 
159
- Each entry in `vars` uses one port. The example returns three named values from two entries. With `size: 2`, three separate entries throw `PortoError` with code `mappingInvalid` before Porto saves a reservation.
218
+ Each entry in `vars` uses one port. The example defines three custom variables with two entries. With `size: 2`, three separate entries throw `PortoError` with code `mappingInvalid` before Porto saves a slot.
160
219
 
161
- ### Read and release reservations
220
+ #### Read and release slots
162
221
 
163
222
  ```js
164
- import { cleanup, current, release, stats } from '@b12k/porto';
165
-
166
- const blocks = await current(); // Blocks for this checkout
167
- const reservations = await stats(); // All reservations for this repository
168
- const released = await release(); // Release this checkout's blocks if their ports are free
169
- const expired = await cleanup(); // Release expired blocks if their ports are free
223
+ import { cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot } from '@b12k/porto';
224
+
225
+ const currentSlot = await getSlot(); // Current slot for this worktree
226
+ const selectedSlot = await getSlot(1); // Slot #1
227
+ const slots = await getAllSlots(); // All slots for this repository
228
+ const releasedSlot = await releaseSlot(); // Release this worktree's slot if its ports are free
229
+ const forceReleasedSlot = await releaseSlot(true); // Force release this worktree's slot
230
+ const releasedSelectedSlot = await releaseSlot(1); // Release slot #1 if its ports are free
231
+ const forceReleasedSelectedSlot = await releaseSlot(1, true); // Force release slot #1 even if its ports are busy
232
+ const releasedSlots = await releaseAllSlots(); // Release all slots if their ports are free
233
+ const forceReleasedSlots = await releaseAllSlots(true); // Force release all slots even if ports are busy
234
+ const expiredSlots = await cleanupSlots(); // Release expired slots if their ports are free
170
235
  ```
171
-
172
- `release()` throws `BusyPortsError` if a port is in use. Its `ports` property lists the blocked ports.
173
-
174
- Porto stores reservations in `<git-common-dir>/porto-registry.json`.
@@ -1,11 +1,11 @@
1
1
  import { PortoError } from './error.js';
2
2
  export declare class BusyPortsError extends PortoError {
3
3
  readonly ports: Array<{
4
- block: number;
5
4
  port: number;
5
+ slot: number;
6
6
  }>;
7
7
  constructor(ports: Array<{
8
- block: number;
9
8
  port: number;
9
+ slot: number;
10
10
  }>);
11
11
  }
package/dist/cli.js CHANGED
@@ -2,15 +2,15 @@
2
2
  import { Command } from "commander";
3
3
  import { pickBy } from "es-toolkit";
4
4
  import update_notifier from "update-notifier";
5
- import { applyReserveDefaults, fetchConfig, name as external_config_js_name, parseConfig, version } from "./config.js";
5
+ import { fetchConfig, name as external_config_js_name, parseConfig, resolveOutputSettings, version } from "./config.js";
6
6
  import { fetchGitContext } from "./git.js";
7
- import { BusyPortsError, PortoError, cleanup, current, release, stats } from "./index.js";
7
+ import { BusyPortsError, PortoError, cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot } from "./index.js";
8
8
  import { logError } from "./log.js";
9
9
  import { fetchExportPaths, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile } from "./output.js";
10
10
  import { commitReservation } from "./reserve.js";
11
11
  import { parseVars } from "./vars.js";
12
- async function fetchSettings(flags, command, worktree) {
13
- const configured = await fetchConfig(worktree);
12
+ async function fetchSettings(flags, command, worktreePath) {
13
+ const configured = await fetchConfig(worktreePath);
14
14
  const { idle, json, vars, ...overrides } = pickBy(flags, (_flag, key)=>'cli' === command.getOptionValueSource(key));
15
15
  const explicit = parseConfig({
16
16
  ...overrides,
@@ -18,15 +18,13 @@ async function fetchSettings(flags, command, worktree) {
18
18
  idleTtlMinutes: idle
19
19
  }
20
20
  });
21
- let entries = configured.vars;
22
- if (void 0 !== vars) entries = false === vars ? void 0 : parseVars(vars);
21
+ let resolvedVars = configured.vars;
22
+ if (void 0 !== vars) resolvedVars = false === vars ? void 0 : parseVars(vars);
23
23
  return {
24
- ...applyReserveDefaults({
25
- ...configured,
26
- ...explicit,
27
- vars: entries
28
- }),
29
- json: json ?? false
24
+ ...configured,
25
+ ...explicit,
26
+ json: json ?? false,
27
+ vars: resolvedVars
30
28
  };
31
29
  }
32
30
  async function runHook(hookName, hook) {
@@ -43,28 +41,17 @@ function writeOutput(contents) {
43
41
  }
44
42
  async function handleReserve(flags, command) {
45
43
  const git = await fetchGitContext();
46
- const { vars: entries, ...settings } = await fetchSettings(flags, command, git.worktree);
47
- const { environmentPath, jsonPath } = await fetchExportPaths(settings, git.commonDirectory);
48
- const prepared = await commitReservation({
44
+ const { json, onReserved, vars: resolvedVars, ...settings } = await fetchSettings(flags, command, git.worktreePath);
45
+ const { envPath, jsonPath } = await fetchExportPaths(resolveOutputSettings(settings), git.commonDirectory);
46
+ const slot = await commitReservation(git, {
49
47
  ...settings,
50
- git,
51
- vars: entries
52
- }, ({ ports, vars, ...block })=>{
53
- const environment = void 0 === entries ? void 0 : vars;
54
- const output = settings.silent ? void 0 : formatReserveOutput(block, environment, settings.json);
55
- return {
56
- block,
57
- environment,
58
- output,
59
- ports
60
- };
48
+ vars: resolvedVars
61
49
  });
62
- const { block, environment, output, ports } = prepared;
63
- if (jsonPath) await writeReserveJsonFile(jsonPath, block, environment);
64
- if (environmentPath) await updateEnvironmentFile(environmentPath, environment ?? {
65
- PORTO_BLOCK: block.index
66
- }, git.commonDirectory);
67
- await runHook('onReserved', ()=>settings.onReserved?.(block, ports));
50
+ const vars = void 0 === resolvedVars ? void 0 : slot.vars;
51
+ const output = slot.silent ? void 0 : formatReserveOutput(slot, vars, json);
52
+ if (jsonPath) await writeReserveJsonFile(jsonPath, slot, vars);
53
+ if (envPath) await updateEnvironmentFile(envPath, slot.vars, git.commonDirectory);
54
+ if (onReserved) await runHook('onReserved', ()=>onReserved(slot, slot.ports));
68
55
  if (void 0 !== output) writeOutput(output);
69
56
  }
70
57
  const cli = new Command('porto');
@@ -80,36 +67,43 @@ update_notifier({
80
67
  });
81
68
  cli.command('reserve', {
82
69
  isDefault: true
83
- }).description('Reserve a stable TCP port block for the current checkout').option('--start <port>', 'First port of the range (default: 10000)', Number).option('--host <host>', 'Host to check for busy ports (default: detect local addresses)').option('--size <count>', 'Number of ports in each block (default: 10)', Number).option('--idle <minutes>', 'Idle TTL in minutes (default: 60)', Number).option('--vars <entries>', 'NAME or NAME=template variables (| shares a port, ; starts the next)').option('--no-vars', 'Ignore configured variables').option('--json', 'Print JSON to stdout').option('--json-file <file>', 'Save JSON to a file independently of stdout').option('--no-json-file', 'Skip the configured JSON file').option('--silent', 'Skip the reservation output on stdout').option('--no-silent', 'Print the reservation output on stdout').option('--env', 'Update the env file (default: disabled)').option('--no-env', 'Skip the env file').option('--env-file <file>', 'Set the env filename and enable env output (default: .env)').option('--keep', 'Keep this reservation until explicitly released').option('--no-keep', 'Restore idle cleanup for this reservation').action(handleReserve);
84
- cli.command('current').description('Read the reservations of the current checkout').option('--json', 'Print JSON to stdout').action(async (flags)=>{
85
- const blocks = await current();
86
- if (0 === blocks.length) throw new PortoError('reservationNotFound');
87
- writeOutput(flags.json ? JSON.stringify(1 === blocks.length ? blocks[0] : blocks) : blocks.map((block)=>block.index).join('\n'));
88
- });
89
- cli.command('stats').description('List all reservations in this repository').option('--json', 'Print JSON to stdout').action(async (flags)=>{
90
- const reservations = await stats();
91
- writeOutput(flags.json ? JSON.stringify(reservations) : formatStatsTable(reservations));
70
+ }).description('Reserve a stable TCP port slot for the current worktree').option('--start <port>', 'First port of the range (default: 10000)', Number).option('--host <host>', 'Host to check for busy ports (default: detect local addresses)').option('--size <count>', 'Number of ports in each slot (default: 10)', Number).option('--idle <minutes>', 'Idle TTL in minutes (default: 60)', Number).option('--vars <vars>', 'NAME or NAME=template variables (| shares a port, ; starts the next)').option('--no-vars', 'Ignore configured variables').option('--json', 'Print JSON to stdout').option('--json-file <file>', 'Save JSON to a file independently of stdout').option('--no-json-file', 'Skip the configured JSON file').option('--silent', 'Skip the reservation output on stdout').option('--no-silent', 'Print the reservation output on stdout').option('--env', 'Update the env file (default: disabled)').option('--no-env', 'Skip the env file').option('--env-file <file>', 'Set the env filename and enable env output (default: .env)').option('--keep', 'Keep this slot until explicitly released').option('--no-keep', 'Restore idle cleanup for this slot').action(handleReserve);
71
+ cli.command('show').argument('[slot-number]', 'Slot index (default: current worktree)', (index)=>Number(index.trim() || 0 / 0)).description('Show the current worktree slot or select slots by index or --all').option('--all', 'Show all slots in this repository').option('--json', 'Print JSON to stdout').action(async (slotIndex, flags)=>{
72
+ if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
73
+ if (flags.all) {
74
+ const slots = await getAllSlots();
75
+ writeOutput(flags.json ? JSON.stringify(slots) : formatStatsTable(slots));
76
+ return;
77
+ }
78
+ const slot = await getSlot(slotIndex);
79
+ if (void 0 === slot) throw new PortoError('reservationNotFound');
80
+ writeOutput(flags.json ? JSON.stringify(slot) : String(slot.index));
92
81
  });
93
- cli.command('release').description('Release current checkout reservations if every port is free').action(async ()=>{
94
- const { worktree } = await fetchGitContext();
95
- const { onReleased } = await fetchConfig(worktree);
96
- const blocks = await release();
97
- const results = await Promise.allSettled(blocks.map(({ ports, ...block })=>runHook('onReleased', ()=>onReleased?.(block, ports))));
82
+ cli.command('release').argument('[slot-number]', 'Slot index (default: current worktree)', (index)=>Number(index.trim() || 0 / 0)).description('Release the current worktree slot or select slots by index or --all').option('--all', 'Release all slots if every port is free').option('--force', 'Release slots even if their ports are busy').action(async (slotIndex, flags)=>{
83
+ if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
84
+ const { worktreePath } = await fetchGitContext();
85
+ const { onReleased } = await fetchConfig(worktreePath);
86
+ const force = flags.force ?? false;
87
+ const slots = flags.all ? await releaseAllSlots(force) : [
88
+ await releaseSlot(slotIndex, force)
89
+ ].filter((slot)=>void 0 !== slot);
90
+ if (!onReleased) return;
91
+ const results = await Promise.allSettled(slots.map((slot)=>runHook('onReleased', ()=>onReleased(slot, slot.ports))));
98
92
  const failure = results.find((result)=>'rejected' === result.status);
99
93
  if (failure) throw failure.reason;
100
94
  });
101
- cli.command('cleanup').description('Remove idle reservations whose ports are all free').action(async ()=>{
102
- await cleanup();
95
+ cli.command('cleanup').description('Remove idle slots whose ports are all free').action(async ()=>{
96
+ await cleanupSlots();
103
97
  });
104
98
  cli.version(version);
105
99
  try {
106
100
  await cli.parseAsync();
107
101
  } catch (error) {
108
102
  if (error instanceof BusyPortsError) process.stderr.write(`${formatTable([
109
- 'BLOCK',
103
+ 'SLOT',
110
104
  'PORT'
111
- ], error.ports.map(({ block, port })=>[
112
- String(block),
105
+ ], error.ports.map(({ port, slot })=>[
106
+ String(slot),
113
107
  String(port)
114
108
  ]))}\n`);
115
109
  logError(error);
package/dist/config.d.ts CHANGED
@@ -1,77 +1,78 @@
1
1
  import { z } from 'zod';
2
- declare const DEFAULT_ENV_FILE = ".env";
3
2
  declare const CONFIG_SCHEMA: z.ZodObject<{
4
- onReleased: z.ZodOptional<z.ZodCustom<(block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void, (block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void>>;
5
- onReserved: z.ZodOptional<z.ZodCustom<(block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void, (block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void>>;
3
+ onReleased: z.ZodOptional<z.ZodCustom<(slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void, (slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void>>;
4
+ onReserved: z.ZodOptional<z.ZodCustom<(slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void, (slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void>>;
5
+ env: z.ZodOptional<z.ZodBoolean>;
6
+ envFile: z.ZodOptional<z.ZodString>;
7
+ jsonFile: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>>;
8
+ silent: z.ZodOptional<z.ZodBoolean>;
6
9
  host: z.ZodOptional<z.ZodOptional<z.ZodString>>;
7
10
  idleTtlMinutes: z.ZodOptional<z.ZodNumber>;
8
11
  keep: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
9
12
  size: z.ZodOptional<z.ZodInt>;
10
13
  start: z.ZodOptional<z.ZodInt>;
11
- env: z.ZodOptional<z.ZodBoolean>;
12
- envFile: z.ZodOptional<z.ZodString>;
13
- jsonFile: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>>;
14
- silent: z.ZodOptional<z.ZodBoolean>;
15
14
  vars: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<import("./vars.js").VarFactory, import("./vars.js").VarFactory>]>>>;
16
15
  }, z.core.$strict>;
17
16
  type PortoConfig = z.input<typeof CONFIG_SCHEMA>;
17
+ type ResolvedReserveConfig = ReturnType<typeof applyReserveDefaults>;
18
18
  declare const libraryName = "porto";
19
19
  declare const name: string, version: string;
20
- declare function defineConfig(config: PortoConfig): {
21
- onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
22
- onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
20
+ declare const DEFAULT_CONFIG: {
21
+ env: boolean;
22
+ envFile: string;
23
+ idleTtlMinutes: number;
24
+ jsonFile: false | string;
25
+ silent: boolean;
26
+ size: number;
27
+ start: number;
28
+ };
29
+ declare function resolveOutputSettings(settings: Pick<PortoConfig, 'env' | 'envFile' | 'jsonFile'>): {
30
+ env: boolean;
31
+ envFile: string;
32
+ jsonFile: string | false;
33
+ };
34
+ declare function applyReserveDefaults(settings: Omit<PortoConfig, 'onReleased' | 'onReserved' | 'vars'>, storedRange: {
35
+ portsPerSlot: number;
36
+ startPort: number;
37
+ }): {
23
38
  host?: string | undefined;
24
- idleTtlMinutes?: number | undefined;
25
39
  keep?: boolean | undefined;
26
- size?: number | undefined;
27
- start?: number | undefined;
40
+ env: boolean;
41
+ envFile: string;
42
+ jsonFile: string | false;
43
+ idleTtlMinutes: number;
44
+ silent: boolean;
45
+ size: number;
46
+ start: number;
47
+ };
48
+ declare function defineConfig(config: PortoConfig): {
49
+ onReleased?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
50
+ onReserved?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
28
51
  env?: boolean | undefined;
29
52
  envFile?: string | undefined;
30
53
  jsonFile?: string | false | undefined;
31
54
  silent?: boolean | undefined;
32
- vars?: (string | import("./vars.js").VarFactory)[] | undefined;
33
- };
34
- declare function parseConfig(config: unknown): {
35
- onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
36
- onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
37
55
  host?: string | undefined;
38
56
  idleTtlMinutes?: number | undefined;
39
57
  keep?: boolean | undefined;
40
58
  size?: number | undefined;
41
59
  start?: number | undefined;
60
+ vars?: (string | import("./vars.js").VarFactory)[] | undefined;
61
+ };
62
+ declare function parseConfig(config: unknown): {
63
+ onReleased?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
64
+ onReserved?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
42
65
  env?: boolean | undefined;
43
66
  envFile?: string | undefined;
44
67
  jsonFile?: string | false | undefined;
45
68
  silent?: boolean | undefined;
46
- vars?: (string | import("./vars.js").VarFactory)[] | undefined;
47
- };
48
- declare function applyReserveDefaults(settings: ReturnType<typeof parseConfig>): {
49
- onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
50
- onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
51
- host?: string | undefined;
52
- idleTtlMinutes: number;
53
- keep?: boolean | undefined;
54
- size: number;
55
- start: number;
56
- vars?: (string | import("./vars.js").VarFactory)[] | undefined;
57
- env: boolean;
58
- envFile: string;
59
- jsonFile: string | false;
60
- silent: boolean;
61
- };
62
- declare function fetchConfig(worktree: string): Promise<{
63
- onReleased?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
64
- onReserved?: ((block: import("./index.js").PortBlock, ports: Array<number>) => Promise<void> | void) | undefined;
65
69
  host?: string | undefined;
66
70
  idleTtlMinutes?: number | undefined;
67
71
  keep?: boolean | undefined;
68
72
  size?: number | undefined;
69
73
  start?: number | undefined;
70
- env?: boolean | undefined;
71
- envFile?: string | undefined;
72
- jsonFile?: string | false | undefined;
73
- silent?: boolean | undefined;
74
74
  vars?: (string | import("./vars.js").VarFactory)[] | undefined;
75
- }>;
76
- export { applyReserveDefaults, DEFAULT_ENV_FILE, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
77
- export type { PortoConfig };
75
+ };
76
+ declare function fetchConfig(worktreePath: string): Promise<PortoConfig>;
77
+ export { applyReserveDefaults, DEFAULT_CONFIG, defineConfig, fetchConfig, libraryName, name, parseConfig, resolveOutputSettings, version, };
78
+ export type { PortoConfig, ResolvedReserveConfig };