@b12k/porto 0.8.0 โ†’ 0.10.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,63 +2,129 @@
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 checkout or 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 reservations 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?]
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` to release all slots when their ports are free. |
62
+ | `cleanup` | Remove expired reservations when their ports are free. |
63
+
64
+ #### `reserve` options
65
+
66
+ | Option | Default | Action |
67
+ | --------------------------------------- | ----------------- | ---------------------------------------------- |
68
+ | `--start <port>` | `10000` | Set the first port of the range. |
69
+ | `--host <host>` | Local addresses | Check this host for busy ports. |
70
+ | `--size <count>` | `10` | Set the number of ports per slot. |
71
+ | `--idle <minutes>` | 60 minutes | Set the idle time limit. |
72
+ | `--keep` / `--no-keep` | Off for new slots | Keep the slot during idle cleanup. |
73
+ | `--vars <entries>` / `--no-vars` | None | Set or clear the variable list. |
74
+ | `--env` / `--no-env` | Off | Turn env file output on or off. |
75
+ | `--env-file <file>` | `.env` | Set the env file path and turn on env output. |
76
+ | `--json-file <file>` / `--no-json-file` | Off | Set or clear the JSON output file. |
77
+ | `--json` | Off | Print JSON to stdout. Also works with `show`. |
78
+ | `--silent` / `--no-silent` | Off | Hide or show the reservation result on stdout. |
50
79
 
51
80
  Use `-h` or `--help` for help. Use `-V` or `--version` for the version.
52
81
 
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}}`.
82
+ ##### `--vars` template syntax
83
+
84
+ 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}}`.
85
+
86
+ ##### Write to files
54
87
 
55
88
  ```sh
56
- pnpm exec porto --vars 'PORT|HOST_URL=http://localhost:{{port}};API_PORT' --env
89
+ pnpm porto --vars "CLIENT_PORT|HOST_URL=http://localhost:{{port}};API_PORT" --env-file .env.local --json-file env.json
90
+ ```
91
+
92
+ Both files always include `PORTO_SLOT`, the slot index. If the first slot is free, Porto writes these files.
93
+
94
+ `.env.local`
95
+
96
+ ```dotenv
97
+ CLIENT_PORT=10000
98
+ HOST_URL=http://localhost:10000
99
+ API_PORT=10001
100
+ PORTO_SLOT=0
101
+ ```
102
+
103
+ `env.json`
104
+
105
+ ```json
106
+ { "CLIENT_PORT": 10000, "HOST_URL": "http://localhost:10000", "API_PORT": 10001, "PORTO_SLOT": 0 }
57
107
  ```
58
108
 
59
- With no variables, `--env` writes `PORTO_BLOCK`.
109
+ Run the same command again in this worktree to reuse its slot. A second worktree gets its own slot.
60
110
 
61
- ## โš™๏ธ Config
111
+ `--start` and `--size` are shared by all worktrees. Omit them to reuse the saved settings. Release all slots before changing them.
112
+
113
+ | Worktree | Slot | Ports |
114
+ | -------- | ---: | ----------- |
115
+ | Main | 0 | 10000-10009 |
116
+ | Feature | 1 | 10010-10019 |
117
+
118
+ #### `show` and `release` options
119
+
120
+ | Argument or option | Default | Action |
121
+ | ------------------ | -------------------- | ------------------------------------- |
122
+ | `[slot-number]` | This checkout's slot | Select a slot by index. |
123
+ | `--all` | Off | Select all slots for this repository. |
124
+
125
+ Use a slot number or `--all`. If a port is busy, `release --all` keeps every slot.
126
+
127
+ ### Config
62
128
 
63
129
  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.
64
130
 
@@ -77,98 +143,99 @@ export default defineConfig({
77
143
  envFile: '.env.local',
78
144
  jsonFile: 'ports.json',
79
145
  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(', ')}`);
146
+ vars: ['PORT', (_slot, port) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}` }), 'DB_PORT'],
147
+ onReserved(slot, ports) {
148
+ console.error(`Reserved slot ${slot.index} with ports ${ports.join(', ')}`);
83
149
  },
84
- onReleased(block, ports) {
85
- console.error(`Released block ${block.index} with ports ${ports.join(', ')}`);
150
+ onReleased(slot, ports) {
151
+ console.error(`Released slot ${slot.index} with ports ${ports.join(', ')}`);
86
152
  },
87
153
  });
88
154
  ```
89
155
 
90
156
  All properties are optional.
91
157
 
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`. |
158
+ | Property | Default | Effect |
159
+ | ---------------- | --------------------- | ------------------------------------------------------------------------------------------- |
160
+ | `start` | `10000` | Set the first port of the candidate range. |
161
+ | `size` | `10` | Set the number of ports per slot. |
162
+ | `host` | Local addresses | Check a specific host for busy ports. Porto saves the host for `release` and `cleanup`. |
163
+ | `idleTtlMinutes` | `60` | Set the idle time limit in minutes. A new `reserve` call refreshes the timer. |
164
+ | `keep` | `false` for new slots | Keep a slot during idle cleanup. Omit to keep its current setting. Set `false` to clear it. |
165
+ | `env` | `false` | Write variables and `PORTO_SLOT` to an env file. |
166
+ | `envFile` | `.env` | Set the env file path. An explicit path enables `env` unless you set `env: false`. |
167
+ | `jsonFile` | `false` | Save variables or slot details with `PORTO_SLOT` to a JSON file. Use a path to enable it. |
168
+ | `silent` | `false` | Hide the `reserve` result on stdout. Porto still writes requested files and reports errors. |
169
+ | `vars` | Unset | Assign one port per entry. Use a name for a port number or a function for several values. |
170
+ | `onReserved` | Unset | Run after Porto saves the slot and writes the requested files. |
171
+ | `onReleased` | Unset | Run once per slot freed by `release`. |
106
172
 
107
173
  Relative paths in config start at the config directory. Relative paths in flags start at the current directory.
108
174
 
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.
175
+ A `vars` function receives `(slotIndex, 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.
110
176
 
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.
177
+ Both hooks receive `(slot, ports)`, where `ports` lists the ports assigned to that slot. Hooks can return a promise.
112
178
 
113
- ## ๐Ÿ“ฆ API
179
+ ### API
114
180
 
115
- Run the API inside a Git checkout. It uses the options you pass in code and the built-in defaults.
181
+ Run the API inside a Git checkout.
116
182
 
117
- ### Get ports by offset
183
+ #### Get ports by offset
118
184
 
119
185
  ```js
120
186
  import { reserve } from '@b12k/porto';
121
187
 
122
- const block = await reserve();
123
- const firstPort = block.getPort();
124
- const secondPort = block.getPort(1);
188
+ const slot = await reserve();
189
+ const firstPort = slot.getPort();
190
+ const secondPort = slot.getPort(1);
125
191
  ```
126
192
 
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.
193
+ `reserve()` returns the saved slot with `getPort(offset = 0)`. Offsets start at zero and must fit inside the slot.
128
194
 
129
- ### Get ports by name
195
+ `firstPort` and `lastPort` are the slot's inclusive bounds.
196
+
197
+ #### Get ports by name
130
198
 
131
199
  ```js
132
200
  import { reserve } from '@b12k/porto';
133
201
 
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
202
+ const slot = await reserve({ start: 10_000, size: 5, vars: ['PORT', 'API_PORT'] });
203
+ const { PORT, API_PORT } = slot.vars;
204
+ const DB_PORT = slot.getPort(2); // 10002 if the first slot is free
137
205
  ```
138
206
 
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.
207
+ TypeScript infers `PORT` and `API_PORT` as `number`. `slot.vars` contains this call's named values and the built-in `PORTO_SLOT`. `slot.ports` lists the ports assigned through `vars` across calls. `getPort()` reads a port by offset.
140
208
 
141
- ### Share a port between variables
209
+ #### Share a port between variables
142
210
 
143
211
  ```js
144
212
  import { reserve } from '@b12k/porto';
145
213
 
146
- const block = await reserve({
214
+ const slot = await reserve({
147
215
  start: 10_000,
148
216
  size: 2,
149
217
  host: '127.0.0.1',
150
218
  idleTtlMinutes: 30,
151
219
  keep: true,
152
- vars: ['PORT', (_block, port) => ({ API_PORT: port, API_URL: `http://localhost:${port}` })],
220
+ vars: ['PORT', (_slot, port) => ({ API_PORT: port, API_URL: `http://localhost:${port}` })],
153
221
  });
154
- const { API_PORT, API_URL } = block.vars;
222
+ const { API_PORT, API_URL } = slot.vars;
155
223
  ```
156
224
 
157
- `reserve()` accepts `start`, `size`, `host`, `idleTtlMinutes`, `keep`, and `vars`. All six options are optional and use the defaults in the config table.
225
+ `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 config table.
158
226
 
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.
227
+ 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 reservation.
160
228
 
161
- ### Read and release reservations
229
+ #### Read and release reservations
162
230
 
163
231
  ```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
232
+ import { cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot } from '@b12k/porto';
233
+
234
+ const currentSlot = await getSlot(); // Current slot for this checkout
235
+ const selectedSlot = await getSlot(1); // Slot #1
236
+ const reservedSlots = await getAllSlots(); // All reserved slots for this repository
237
+ const releasedSlot = await releaseSlot(); // Release this checkout's slot if its ports are free
238
+ const releasedSelectedSlot = await releaseSlot(1); // Release slot #1 if its ports are free
239
+ const releasedSlots = await releaseAllSlots(); // Release all slots if their ports are free
240
+ const expiredSlots = await cleanupSlots(); // Release expired slots if their ports are free
170
241
  ```
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, 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,
@@ -21,12 +21,10 @@ async function fetchSettings(flags, command, worktree) {
21
21
  let entries = configured.vars;
22
22
  if (void 0 !== vars) entries = 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: entries
30
28
  };
31
29
  }
32
30
  async function runHook(hookName, hook) {
@@ -43,28 +41,25 @@ 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: entries, ...settings } = await fetchSettings(flags, command, git.worktreePath);
45
+ const prepared = await commitReservation(git, {
49
46
  ...settings,
50
- git,
51
47
  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);
48
+ }, async (slot)=>{
49
+ const paths = await fetchExportPaths(slot, git.commonDirectory);
50
+ const environment = void 0 === entries ? void 0 : slot.vars;
51
+ const output = slot.silent ? void 0 : formatReserveOutput(slot, environment, json);
55
52
  return {
56
- block,
53
+ ...paths,
57
54
  environment,
58
55
  output,
59
- ports
56
+ slot
60
57
  };
61
58
  });
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));
59
+ const { environment, environmentPath, jsonPath, output, slot } = prepared;
60
+ if (jsonPath) await writeReserveJsonFile(jsonPath, slot, environment);
61
+ if (environmentPath) await updateEnvironmentFile(environmentPath, slot.vars, git.commonDirectory);
62
+ if (onReserved) await runHook('onReserved', ()=>onReserved(slot, slot.ports));
68
63
  if (void 0 !== output) writeOutput(output);
69
64
  }
70
65
  const cli = new Command('porto');
@@ -80,36 +75,42 @@ update_notifier({
80
75
  });
81
76
  cli.command('reserve', {
82
77
  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));
78
+ }).description('Reserve a stable TCP port slot 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 slot (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);
79
+ cli.command('show').argument('[slot-number]', 'Slot index (default: current checkout)', (index)=>Number(index.trim() || 0 / 0)).description('Show the current checkout 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)=>{
80
+ if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
81
+ if (flags.all) {
82
+ const reservedSlots = await getAllSlots();
83
+ writeOutput(flags.json ? JSON.stringify(reservedSlots) : formatStatsTable(reservedSlots));
84
+ return;
85
+ }
86
+ const slot = await getSlot(slotIndex);
87
+ if (void 0 === slot) throw new PortoError('reservationNotFound');
88
+ writeOutput(flags.json ? JSON.stringify(slot) : String(slot.index));
92
89
  });
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))));
90
+ cli.command('release').argument('[slot-number]', 'Slot index (default: current checkout)', (index)=>Number(index.trim() || 0 / 0)).description('Release the current checkout slot or select slots by index or --all').option('--all', 'Release all slots if every port is free').action(async (slotIndex, flags)=>{
91
+ if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
92
+ const { worktreePath } = await fetchGitContext();
93
+ const { onReleased } = await fetchConfig(worktreePath);
94
+ const releasedSlots = flags.all ? await releaseAllSlots() : [
95
+ await releaseSlot(slotIndex)
96
+ ].filter((slot)=>void 0 !== slot);
97
+ if (!onReleased) return;
98
+ const results = await Promise.allSettled(releasedSlots.map((slot)=>runHook('onReleased', ()=>onReleased(slot, slot.ports))));
98
99
  const failure = results.find((result)=>'rejected' === result.status);
99
100
  if (failure) throw failure.reason;
100
101
  });
101
102
  cli.command('cleanup').description('Remove idle reservations whose ports are all free').action(async ()=>{
102
- await cleanup();
103
+ await cleanupSlots();
103
104
  });
104
105
  cli.version(version);
105
106
  try {
106
107
  await cli.parseAsync();
107
108
  } catch (error) {
108
109
  if (error instanceof BusyPortsError) process.stderr.write(`${formatTable([
109
- 'BLOCK',
110
+ 'SLOT',
110
111
  'PORT'
111
- ], error.ports.map(({ block, port })=>[
112
- String(block),
112
+ ], error.ports.map(({ port, slot })=>[
113
+ String(slot),
113
114
  String(port)
114
115
  ]))}\n`);
115
116
  logError(error);
package/dist/config.d.ts CHANGED
@@ -1,77 +1,63 @@
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>;
18
17
  declare const libraryName = "porto";
19
18
  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;
19
+ declare function applyReserveDefaults(settings: Omit<PortoConfig, 'onReleased' | 'onReserved' | 'vars'>, range: {
20
+ portsPerSlot: number;
21
+ startPort: number;
22
+ }): {
23
23
  host?: string | undefined;
24
- idleTtlMinutes?: number | undefined;
25
24
  keep?: boolean | undefined;
26
- size?: number | undefined;
27
- start?: number | undefined;
25
+ env: boolean;
26
+ envFile: string;
27
+ idleTtlMinutes: number;
28
+ jsonFile: string | false;
29
+ silent: boolean;
30
+ size: number;
31
+ start: number;
32
+ };
33
+ declare function defineConfig(config: PortoConfig): {
34
+ onReleased?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
35
+ onReserved?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
28
36
  env?: boolean | undefined;
29
37
  envFile?: string | undefined;
30
38
  jsonFile?: string | false | undefined;
31
39
  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
40
  host?: string | undefined;
38
41
  idleTtlMinutes?: number | undefined;
39
42
  keep?: boolean | undefined;
40
43
  size?: number | undefined;
41
44
  start?: number | undefined;
45
+ vars?: (string | import("./vars.js").VarFactory)[] | undefined;
46
+ };
47
+ declare function parseConfig(config: unknown): {
48
+ onReleased?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
49
+ onReserved?: ((slot: import("./index.js").PortSlot, ports: Array<number>) => Promise<void> | void) | undefined;
42
50
  env?: boolean | undefined;
43
51
  envFile?: string | undefined;
44
52
  jsonFile?: string | false | undefined;
45
53
  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
54
  host?: string | undefined;
66
55
  idleTtlMinutes?: number | undefined;
67
56
  keep?: boolean | undefined;
68
57
  size?: number | undefined;
69
58
  start?: number | undefined;
70
- env?: boolean | undefined;
71
- envFile?: string | undefined;
72
- jsonFile?: string | false | undefined;
73
- silent?: boolean | undefined;
74
59
  vars?: (string | import("./vars.js").VarFactory)[] | undefined;
75
- }>;
76
- export { applyReserveDefaults, DEFAULT_ENV_FILE, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
60
+ };
61
+ declare function fetchConfig(worktreePath: string): Promise<PortoConfig>;
62
+ export { applyReserveDefaults, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
77
63
  export type { PortoConfig };