@b12k/porto 0.10.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
@@ -6,10 +6,10 @@
6
6
 
7
7
  ๐Ÿ’ช **Port reservations on steroids.**
8
8
 
9
- Porto reserves a range of TCP ports, called a slot, for each Git checkout or worktree.
9
+ Porto reserves a range of TCP ports, called a slot, for each Git worktree.
10
10
  It checks for port conflicts and saves the slot for the next run.
11
11
 
12
- ๐Ÿงน **It can haz cleanups.** When you reserve ports, Porto removes expired reservations if all their ports are free.
12
+ ๐Ÿงน **It can haz cleanups.** When you reserve ports, Porto removes expired slots if all their ports are free.
13
13
 
14
14
  ## ๐Ÿš€ Install
15
15
 
@@ -48,40 +48,45 @@ bun add --dev @b12k/porto
48
48
  ```css
49
49
  porto [reserve?] [options]
50
50
  porto show [slot-number?] [--all?]
51
- porto release [slot-number?] [--all?]
51
+ porto release [slot-number?] [--all?] [--force?]
52
52
  porto cleanup
53
53
  ```
54
54
 
55
55
  #### Commands
56
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. |
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.
79
84
 
80
85
  Use `-h` or `--help` for help. Use `-V` or `--version` for the version.
81
86
 
82
87
  ##### `--vars` template syntax
83
88
 
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}}`.
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"`.
85
90
 
86
91
  ##### Write to files
87
92
 
@@ -89,7 +94,7 @@ Use `;` to move to the next port and `|` to share the current port. Use `NAME` f
89
94
  pnpm porto --vars "CLIENT_PORT|HOST_URL=http://localhost:{{port}};API_PORT" --env-file .env.local --json-file env.json
90
95
  ```
91
96
 
92
- Both files always include `PORTO_SLOT`, the slot index. If the first slot is free, Porto writes these files.
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.
93
98
 
94
99
  `.env.local`
95
100
 
@@ -97,18 +102,17 @@ Both files always include `PORTO_SLOT`, the slot index. If the first slot is fre
97
102
  CLIENT_PORT=10000
98
103
  HOST_URL=http://localhost:10000
99
104
  API_PORT=10001
100
- PORTO_SLOT=0
101
105
  ```
102
106
 
103
107
  `env.json`
104
108
 
105
109
  ```json
106
- { "CLIENT_PORT": 10000, "HOST_URL": "http://localhost:10000", "API_PORT": 10001, "PORTO_SLOT": 0 }
110
+ { "CLIENT_PORT": 10000, "HOST_URL": "http://localhost:10000", "API_PORT": 10001 }
107
111
  ```
108
112
 
109
113
  Run the same command again in this worktree to reuse its slot. A second worktree gets its own slot.
110
114
 
111
- `--start` and `--size` are shared by all worktrees. Omit them to reuse the saved settings. Release all slots before changing them.
115
+ To change `--start` or `--size`, release all slots first.
112
116
 
113
117
  | Worktree | Slot | Ports |
114
118
  | -------- | ---: | ----------- |
@@ -119,16 +123,15 @@ Run the same command again in this worktree to reuse its slot. A second worktree
119
123
 
120
124
  | Argument or option | Default | Action |
121
125
  | ------------------ | -------------------- | ------------------------------------- |
122
- | `[slot-number]` | This checkout's slot | Select a slot by index. |
126
+ | `[slot-number]` | This worktree's slot | Select a slot by index. |
123
127
  | `--all` | Off | Select all slots for this repository. |
128
+ | `--force` | Off | Release slots even if ports are busy. |
124
129
 
125
- Use a slot number or `--all`. If a port is busy, `release --all` keeps every slot.
130
+ Use a slot number or `--all`. If a port is busy, `release --all` keeps every slot, unless `--force` is set.
126
131
 
127
132
  ### Config
128
133
 
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.
130
-
131
- 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.
132
135
 
133
136
  ```ts
134
137
  import { defineConfig } from '@b12k/porto';
@@ -143,7 +146,7 @@ export default defineConfig({
143
146
  envFile: '.env.local',
144
147
  jsonFile: 'ports.json',
145
148
  silent: false,
146
- vars: ['PORT', (_slot, port) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}` }), 'DB_PORT'],
149
+ vars: ['PORT', (port, slot) => ({ PORT_2: port, HOST_NAME: `https://localhost:${port}`, SLOT: slot }), 'DB_PORT'],
147
150
  onReserved(slot, ports) {
148
151
  console.error(`Reserved slot ${slot.index} with ports ${ports.join(', ')}`);
149
152
  },
@@ -153,32 +156,20 @@ export default defineConfig({
153
156
  });
154
157
  ```
155
158
 
156
- All properties are optional.
157
-
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`. |
159
+ All properties are optional. Every setting from [reserve settings](#reserve-settings) also works as a config key.
172
160
 
173
- 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`. |
174
165
 
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.
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.
176
167
 
177
168
  Both hooks receive `(slot, ports)`, where `ports` lists the ports assigned to that slot. Hooks can return a promise.
178
169
 
179
170
  ### API
180
171
 
181
- Run the API inside a Git checkout.
172
+ Run the API inside a Git worktree.
182
173
 
183
174
  #### Get ports by offset
184
175
 
@@ -204,7 +195,7 @@ const { PORT, API_PORT } = slot.vars;
204
195
  const DB_PORT = slot.getPort(2); // 10002 if the first slot is free
205
196
  ```
206
197
 
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.
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.
208
199
 
209
200
  #### Share a port between variables
210
201
 
@@ -217,25 +208,28 @@ const slot = await reserve({
217
208
  host: '127.0.0.1',
218
209
  idleTtlMinutes: 30,
219
210
  keep: true,
220
- vars: ['PORT', (_slot, port) => ({ API_PORT: port, API_URL: `http://localhost:${port}` })],
211
+ vars: ['PORT', (port, slot) => ({ API_PORT: port, API_URL: `http://localhost:${port}`, SLOT: slot })],
221
212
  });
222
213
  const { API_PORT, API_URL } = slot.vars;
223
214
  ```
224
215
 
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.
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.
226
217
 
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.
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.
228
219
 
229
- #### Read and release reservations
220
+ #### Read and release slots
230
221
 
231
222
  ```js
232
223
  import { cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot } from '@b12k/porto';
233
224
 
234
- const currentSlot = await getSlot(); // Current slot for this checkout
225
+ const currentSlot = await getSlot(); // Current slot for this worktree
235
226
  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
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
238
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
239
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
240
234
  const expiredSlots = await cleanupSlots(); // Release expired slots if their ports are free
241
235
  ```
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { Command } from "commander";
3
3
  import { pickBy } from "es-toolkit";
4
4
  import update_notifier from "update-notifier";
5
- import { 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
7
  import { BusyPortsError, PortoError, cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot } from "./index.js";
8
8
  import { logError } from "./log.js";
@@ -18,13 +18,13 @@ async function fetchSettings(flags, command, worktreePath) {
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
24
  ...configured,
25
25
  ...explicit,
26
26
  json: json ?? false,
27
- vars: entries
27
+ vars: resolvedVars
28
28
  };
29
29
  }
30
30
  async function runHook(hookName, hook) {
@@ -41,24 +41,16 @@ function writeOutput(contents) {
41
41
  }
42
42
  async function handleReserve(flags, command) {
43
43
  const git = await fetchGitContext();
44
- const { json, onReserved, vars: entries, ...settings } = await fetchSettings(flags, command, git.worktreePath);
45
- const prepared = await commitReservation(git, {
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, {
46
47
  ...settings,
47
- vars: entries
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);
52
- return {
53
- ...paths,
54
- environment,
55
- output,
56
- slot
57
- };
48
+ vars: resolvedVars
58
49
  });
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);
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);
62
54
  if (onReserved) await runHook('onReserved', ()=>onReserved(slot, slot.ports));
63
55
  if (void 0 !== output) writeOutput(output);
64
56
  }
@@ -75,31 +67,32 @@ update_notifier({
75
67
  });
76
68
  cli.command('reserve', {
77
69
  isDefault: true
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)=>{
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)=>{
80
72
  if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
81
73
  if (flags.all) {
82
- const reservedSlots = await getAllSlots();
83
- writeOutput(flags.json ? JSON.stringify(reservedSlots) : formatStatsTable(reservedSlots));
74
+ const slots = await getAllSlots();
75
+ writeOutput(flags.json ? JSON.stringify(slots) : formatStatsTable(slots));
84
76
  return;
85
77
  }
86
78
  const slot = await getSlot(slotIndex);
87
79
  if (void 0 === slot) throw new PortoError('reservationNotFound');
88
80
  writeOutput(flags.json ? JSON.stringify(slot) : String(slot.index));
89
81
  });
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)=>{
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)=>{
91
83
  if (flags.all && void 0 !== slotIndex) throw new PortoError('slotSelectionInvalid');
92
84
  const { worktreePath } = await fetchGitContext();
93
85
  const { onReleased } = await fetchConfig(worktreePath);
94
- const releasedSlots = flags.all ? await releaseAllSlots() : [
95
- await releaseSlot(slotIndex)
86
+ const force = flags.force ?? false;
87
+ const slots = flags.all ? await releaseAllSlots(force) : [
88
+ await releaseSlot(slotIndex, force)
96
89
  ].filter((slot)=>void 0 !== slot);
97
90
  if (!onReleased) return;
98
- const results = await Promise.allSettled(releasedSlots.map((slot)=>runHook('onReleased', ()=>onReleased(slot, slot.ports))));
91
+ const results = await Promise.allSettled(slots.map((slot)=>runHook('onReleased', ()=>onReleased(slot, slot.ports))));
99
92
  const failure = results.find((result)=>'rejected' === result.status);
100
93
  if (failure) throw failure.reason;
101
94
  });
102
- cli.command('cleanup').description('Remove idle reservations whose ports are all free').action(async ()=>{
95
+ cli.command('cleanup').description('Remove idle slots whose ports are all free').action(async ()=>{
103
96
  await cleanupSlots();
104
97
  });
105
98
  cli.version(version);
package/dist/config.d.ts CHANGED
@@ -14,9 +14,24 @@ declare const CONFIG_SCHEMA: z.ZodObject<{
14
14
  vars: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<import("./vars.js").VarFactory, import("./vars.js").VarFactory>]>>>;
15
15
  }, z.core.$strict>;
16
16
  type PortoConfig = z.input<typeof CONFIG_SCHEMA>;
17
+ type ResolvedReserveConfig = ReturnType<typeof applyReserveDefaults>;
17
18
  declare const libraryName = "porto";
18
19
  declare const name: string, version: string;
19
- declare function applyReserveDefaults(settings: Omit<PortoConfig, 'onReleased' | 'onReserved' | 'vars'>, range: {
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: {
20
35
  portsPerSlot: number;
21
36
  startPort: number;
22
37
  }): {
@@ -24,8 +39,8 @@ declare function applyReserveDefaults(settings: Omit<PortoConfig, 'onReleased' |
24
39
  keep?: boolean | undefined;
25
40
  env: boolean;
26
41
  envFile: string;
27
- idleTtlMinutes: number;
28
42
  jsonFile: string | false;
43
+ idleTtlMinutes: number;
29
44
  silent: boolean;
30
45
  size: number;
31
46
  start: number;
@@ -59,5 +74,5 @@ declare function parseConfig(config: unknown): {
59
74
  vars?: (string | import("./vars.js").VarFactory)[] | undefined;
60
75
  };
61
76
  declare function fetchConfig(worktreePath: string): Promise<PortoConfig>;
62
- export { applyReserveDefaults, defineConfig, fetchConfig, libraryName, name, parseConfig, version };
63
- export type { PortoConfig };
77
+ export { applyReserveDefaults, DEFAULT_CONFIG, defineConfig, fetchConfig, libraryName, name, parseConfig, resolveOutputSettings, version, };
78
+ export type { PortoConfig, ResolvedReserveConfig };
package/dist/config.js CHANGED
@@ -20,17 +20,31 @@ const CONFIG_SCHEMA = z.strictObject({
20
20
  }).partial();
21
21
  const libraryName = 'porto';
22
22
  const { name: config_name, version } = package_0;
23
- function applyReserveDefaults(settings, range) {
24
- const size = settings.size ?? range.portsPerSlot;
25
- const start = settings.start ?? range.startPort;
23
+ const DEFAULT_CONFIG = {
24
+ env: false,
25
+ envFile: '.env',
26
+ idleTtlMinutes: 60,
27
+ jsonFile: false,
28
+ silent: false,
29
+ size: 10,
30
+ start: 10000
31
+ };
32
+ function resolveOutputSettings(settings) {
33
+ return {
34
+ env: settings.env ?? DEFAULT_CONFIG.env,
35
+ envFile: settings.envFile ?? DEFAULT_CONFIG.envFile,
36
+ jsonFile: settings.jsonFile ?? DEFAULT_CONFIG.jsonFile
37
+ };
38
+ }
39
+ function applyReserveDefaults(settings, storedRange) {
40
+ const size = settings.size ?? storedRange.portsPerSlot;
41
+ const start = settings.start ?? storedRange.startPort;
26
42
  if (start + size - 1 > 65535) throw new PortoError('optionsInvalid', 'size: size must fit in the TCP port range.');
27
43
  return {
28
44
  ...settings,
29
- env: settings.env ?? false,
30
- envFile: settings.envFile ?? '.env',
31
- idleTtlMinutes: settings.idleTtlMinutes ?? 60,
32
- jsonFile: settings.jsonFile ?? false,
33
- silent: settings.silent ?? false,
45
+ ...resolveOutputSettings(settings),
46
+ idleTtlMinutes: settings.idleTtlMinutes ?? DEFAULT_CONFIG.idleTtlMinutes,
47
+ silent: settings.silent ?? DEFAULT_CONFIG.silent,
34
48
  size,
35
49
  start
36
50
  };
@@ -75,4 +89,4 @@ async function fetchConfig(worktreePath) {
75
89
  }
76
90
  return settings;
77
91
  }
78
- export { applyReserveDefaults, config_name as name, defineConfig, fetchConfig, libraryName, parseConfig, version };
92
+ export { DEFAULT_CONFIG, applyReserveDefaults, config_name as name, defineConfig, fetchConfig, libraryName, parseConfig, resolveOutputSettings, version };
package/dist/errors.d.ts CHANGED
@@ -32,7 +32,7 @@ export declare const ERRORS_BY_KEY: {
32
32
  readonly message: 'Port range settings differ from the repository registry.';
33
33
  };
34
34
  readonly registryInvalid: {
35
- readonly instruction: 'Restore or repair the reservation file before continuing.';
35
+ readonly instruction: 'Restore or repair the slot file before continuing.';
36
36
  readonly message: 'Cannot read reservation.';
37
37
  };
38
38
  readonly reservationNotFound: {
@@ -52,7 +52,7 @@ export declare const ERRORS_BY_KEY: {
52
52
  readonly message: 'No free port slot remains in the TCP port range.';
53
53
  };
54
54
  readonly worktreeNotFound: {
55
- readonly instruction: 'Run Porto inside a regular Git checkout or linked worktree.';
55
+ readonly instruction: 'Run Porto inside a regular Git worktree.';
56
56
  readonly message: 'Porto must run inside a Git working tree.';
57
57
  };
58
58
  };
package/dist/errors.js CHANGED
@@ -32,7 +32,7 @@ const ERRORS_BY_KEY = {
32
32
  message: 'Port range settings differ from the repository registry.'
33
33
  },
34
34
  registryInvalid: {
35
- instruction: 'Restore or repair the reservation file before continuing.',
35
+ instruction: 'Restore or repair the slot file before continuing.',
36
36
  message: 'Cannot read reservation.'
37
37
  },
38
38
  reservationNotFound: {
@@ -52,7 +52,7 @@ const ERRORS_BY_KEY = {
52
52
  message: 'No free port slot remains in the TCP port range.'
53
53
  },
54
54
  worktreeNotFound: {
55
- instruction: 'Run Porto inside a regular Git checkout or linked worktree.',
55
+ instruction: 'Run Porto inside a regular Git worktree.',
56
56
  message: 'Porto must run inside a Git working tree.'
57
57
  }
58
58
  };
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ declare function cleanupSlots(): Promise<({
19
19
  lastUsedAt: string;
20
20
  ports: number[];
21
21
  vars: {
22
- PORTO_SLOT: number;
22
+ [k: string]: string | number;
23
23
  };
24
24
  worktreeId: string;
25
25
  worktreePath: string;
@@ -44,7 +44,7 @@ declare function getAllSlots(): Promise<{
44
44
  lastUsedAt: string;
45
45
  ports: number[];
46
46
  vars: {
47
- PORTO_SLOT: number;
47
+ [k: string]: string | number;
48
48
  };
49
49
  }[]>;
50
50
  declare function getSlot(slotIndex?: number): Promise<({
@@ -61,7 +61,7 @@ declare function getSlot(slotIndex?: number): Promise<({
61
61
  lastUsedAt: string;
62
62
  ports: number[];
63
63
  vars: {
64
- PORTO_SLOT: number;
64
+ [k: string]: string | number;
65
65
  };
66
66
  worktreeId: string;
67
67
  worktreePath: string;
@@ -69,7 +69,7 @@ declare function getSlot(slotIndex?: number): Promise<({
69
69
  getPort(offset?: number): number;
70
70
  index: number;
71
71
  }) | undefined>;
72
- declare function releaseAllSlots(): Promise<({
72
+ declare function releaseAllSlots(force?: boolean): Promise<({
73
73
  env: boolean;
74
74
  envFile: string;
75
75
  jsonFile: string | false;
@@ -83,7 +83,7 @@ declare function releaseAllSlots(): Promise<({
83
83
  lastUsedAt: string;
84
84
  ports: number[];
85
85
  vars: {
86
- PORTO_SLOT: number;
86
+ [k: string]: string | number;
87
87
  };
88
88
  worktreeId: string;
89
89
  worktreePath: string;
@@ -91,28 +91,8 @@ declare function releaseAllSlots(): Promise<({
91
91
  getPort(offset?: number): number;
92
92
  index: number;
93
93
  })[]>;
94
- declare function releaseSlot(slotIndex?: number): Promise<({
95
- env: boolean;
96
- envFile: string;
97
- jsonFile: string | false;
98
- silent: boolean;
99
- expiresAt: string | null;
100
- firstPort: number;
101
- host?: string | undefined;
102
- idleTtlMinutes: number;
103
- keep: boolean;
104
- lastPort: number;
105
- lastUsedAt: string;
106
- ports: number[];
107
- vars: {
108
- PORTO_SLOT: number;
109
- };
110
- worktreeId: string;
111
- worktreePath: string;
112
- } & {
113
- getPort(offset?: number): number;
114
- index: number;
115
- }) | undefined>;
94
+ declare function releaseSlot(force?: boolean): Promise<PortSlot | undefined>;
95
+ declare function releaseSlot(slotIndex: number | undefined, force?: boolean): Promise<PortSlot | undefined>;
116
96
  export { cleanupSlots, getAllSlots, getSlot, releaseAllSlots, releaseSlot };
117
97
  export type { PortSlot, ReservationStats };
118
98
  export { BusyPortsError } from './busy-ports-error.js';
package/dist/index.js CHANGED
@@ -12,13 +12,13 @@ async function getAllSlots() {
12
12
  const worktreePathsById = await listWorktreePaths(commonDirectory);
13
13
  return updateRegistry(commonDirectory, ({ slots })=>{
14
14
  const now = Date.now();
15
- return slots.flatMap((record, index)=>{
16
- if (null === record) return [];
17
- const { worktreeId, ...settings } = record;
15
+ return Object.entries(slots).flatMap(([key, record])=>{
16
+ const index = Number(key);
17
+ const { worktreeId, ...slotFields } = record;
18
18
  const worktreePath = worktreePathsById.get(worktreeId) ?? record.worktreePath;
19
19
  return [
20
20
  {
21
- ...settings,
21
+ ...slotFields,
22
22
  index,
23
23
  isExpired: checkIsExpired(record, now),
24
24
  worktreePath
@@ -31,26 +31,37 @@ async function getSlot(slotIndex) {
31
31
  if (void 0 !== slotIndex && (!Number.isSafeInteger(slotIndex) || slotIndex < 0)) throw new PortoError('slotIndexInvalid');
32
32
  const { commonDirectory, worktreeId } = await fetchGitContext();
33
33
  return updateRegistry(commonDirectory, ({ slots })=>{
34
- const index = slotIndex ?? slots.findIndex((record)=>record?.worktreeId === worktreeId);
35
- const record = slots[index];
36
- return record ? buildSlot(record, index) : void 0;
34
+ if (void 0 !== slotIndex) {
35
+ const record = slots[slotIndex];
36
+ return record ? buildSlot(record, slotIndex) : void 0;
37
+ }
38
+ const found = Object.entries(slots).find(([, record])=>record.worktreeId === worktreeId);
39
+ return found ? buildSlot(found[1], Number(found[0])) : void 0;
37
40
  });
38
41
  }
39
- async function releaseAllSlots() {
42
+ async function releaseAllSlots(force = false) {
40
43
  const { commonDirectory } = await fetchGitContext();
41
44
  return updateRegistry(commonDirectory, async (registry)=>{
42
45
  const releasedSlots = [];
43
- for (const [index, record] of registry.slots.entries())if (null !== record) releasedSlots.push(await releaseRecord(registry, index, record));
46
+ for (const [key, record] of Object.entries(registry.slots)){
47
+ const index = Number(key);
48
+ releasedSlots.push(await releaseRecord(registry, index, record, force));
49
+ }
44
50
  return releasedSlots;
45
51
  });
46
52
  }
47
- async function releaseSlot(slotIndex) {
48
- if (void 0 !== slotIndex && (!Number.isSafeInteger(slotIndex) || slotIndex < 0)) throw new PortoError('slotIndexInvalid');
53
+ async function releaseSlot(slotIndex, force = false) {
54
+ const selected = 'boolean' == typeof slotIndex ? void 0 : slotIndex;
55
+ const forced = 'boolean' == typeof slotIndex ? slotIndex : force;
56
+ if (void 0 !== selected && (!Number.isSafeInteger(selected) || selected < 0)) throw new PortoError('slotIndexInvalid');
49
57
  const { commonDirectory, worktreeId } = await fetchGitContext();
50
58
  return updateRegistry(commonDirectory, (registry)=>{
51
- const index = slotIndex ?? registry.slots.findIndex((record)=>record?.worktreeId === worktreeId);
52
- const record = registry.slots[index];
53
- return record ? releaseRecord(registry, index, record) : void 0;
59
+ if (void 0 !== selected) {
60
+ const record = registry.slots[selected];
61
+ return record ? releaseRecord(registry, selected, record, forced) : void 0;
62
+ }
63
+ const found = Object.entries(registry.slots).find(([, record])=>record.worktreeId === worktreeId);
64
+ return found ? releaseRecord(registry, Number(found[0]), found[1], forced) : void 0;
54
65
  });
55
66
  }
56
67
  export { BusyPortsError } from "./busy-ports-error.js";
package/dist/output.d.ts CHANGED
@@ -1,18 +1,19 @@
1
1
  import type { PortSlot, ReservationStats } from './index.js';
2
- type Environment = Record<string, number | string>;
2
+ type Environment = SlotVars;
3
+ type SlotVars = Record<string, number | string>;
3
4
  declare function fetchExportPaths(settings: {
4
5
  env: boolean;
5
6
  envFile: string;
6
7
  jsonFile: false | string;
7
8
  }, commonDirectory: string): Promise<{
8
- environmentPath: string | undefined;
9
+ envPath: string | undefined;
9
10
  jsonPath: string | undefined;
10
11
  }>;
11
- declare function formatEnvironment(environment: Environment): string;
12
- declare function formatReserveOutput(slot: PortSlot, environment: Environment | undefined, isJson: boolean): string;
12
+ declare function formatEnvironment(vars: SlotVars): string;
13
+ declare function formatReserveOutput(slot: PortSlot, vars: SlotVars | undefined, isJson: boolean): string;
13
14
  declare function formatTable(headers: Array<string>, rows: Array<Array<string>>): string;
14
- declare function formatStatsTable(reservations: Array<ReservationStats>): string;
15
- declare function updateEnvironmentFile(filePath: string, environment: Environment, commonDirectory?: string): Promise<void>;
16
- declare function writeReserveJsonFile(filePath: string, slot: PortSlot, environment: Environment | undefined): Promise<void>;
15
+ declare function formatStatsTable(slots: Array<ReservationStats>): string;
16
+ declare function updateEnvironmentFile(filePath: string, vars: SlotVars, commonDirectory?: string): Promise<void>;
17
+ declare function writeReserveJsonFile(filePath: string, slot: PortSlot, vars: SlotVars | undefined): Promise<void>;
17
18
  export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile, };
18
- export type { Environment };
19
+ export type { Environment, SlotVars };
package/dist/output.js CHANGED
@@ -57,35 +57,35 @@ async function fetchEnvironmentContents(filePath) {
57
57
  }
58
58
  async function fetchExportPaths(settings, commonDirectory) {
59
59
  const jsonPath = settings.jsonFile ? await fetchCanonicalPath(node_path.resolve(settings.jsonFile)) : void 0;
60
- const environmentPath = settings.env ? await fetchCanonicalPath(node_path.resolve(settings.envFile)) : void 0;
61
- const arePathsEqual = void 0 !== jsonPath && void 0 !== environmentPath && normalizePathForComparison(jsonPath) === normalizePathForComparison(environmentPath);
60
+ const envPath = settings.env ? await fetchCanonicalPath(node_path.resolve(settings.envFile)) : void 0;
61
+ const arePathsEqual = void 0 !== jsonPath && void 0 !== envPath && normalizePathForComparison(jsonPath) === normalizePathForComparison(envPath);
62
62
  if (arePathsEqual) throw new PortoError('exportInvalid', '--json-file and --env-file must use different files.');
63
63
  await assertExportPaths([
64
64
  jsonPath,
65
- environmentPath
65
+ envPath
66
66
  ].filter((filePath)=>void 0 !== filePath), getRegistryPath(commonDirectory));
67
67
  return {
68
- environmentPath,
68
+ envPath,
69
69
  jsonPath
70
70
  };
71
71
  }
72
- function formatEnvironmentValue(entry) {
73
- const text = String(entry);
72
+ function formatEnvironmentValue(value) {
73
+ const text = String(value);
74
74
  if (/^[A-Za-z0-9_./:@%+,-]*$/u.test(text)) return text;
75
75
  if (!text.includes("'")) return `'${text}'`;
76
76
  if (!text.includes('"') && !text.includes('\\')) return `"${text}"`;
77
77
  throw new PortoError('mappingInvalid', 'Value cannot be represented safely on a single env line.');
78
78
  }
79
- function formatEnvironment(environment) {
80
- return Object.entries(environment).map(([name, entry])=>`${name}=${formatEnvironmentValue(entry)}`).join('\n');
79
+ function formatEnvironment(vars) {
80
+ return Object.entries(vars).map(([name, value])=>`${name}=${formatEnvironmentValue(value)}`).join('\n');
81
81
  }
82
- function formatReserveOutput(slot, environment, isJson) {
83
- if (isJson) return JSON.stringify(environment ?? {
82
+ function formatReserveOutput(slot, vars, isJson) {
83
+ if (isJson) return JSON.stringify(vars ?? {
84
84
  firstPort: slot.firstPort,
85
85
  index: slot.index,
86
86
  lastPort: slot.lastPort
87
87
  });
88
- return environment ? formatEnvironment(environment) : String(slot.index);
88
+ return vars ? formatEnvironment(vars) : String(slot.index);
89
89
  }
90
90
  function formatTable(headers, rows) {
91
91
  const widths = headers.map((header, index)=>Math.max(header.length, ...rows.map((row)=>row[index]?.length ?? 0)));
@@ -94,7 +94,7 @@ function formatTable(headers, rows) {
94
94
  ...rows
95
95
  ].map((row)=>row.map((cell, index)=>cell.padEnd(widths[index] ?? 0)).join(' ').trimEnd()).join('\n');
96
96
  }
97
- function formatStatsTable(reservations) {
97
+ function formatStatsTable(slots) {
98
98
  const now = Date.now();
99
99
  return formatTable([
100
100
  'SLOT',
@@ -105,35 +105,35 @@ function formatStatsTable(reservations) {
105
105
  'IDLE (MIN)',
106
106
  'KEEP',
107
107
  'EXPIRED'
108
- ], reservations.map((record)=>[
109
- String(record.index),
110
- `${record.firstPort}-${record.lastPort}`,
111
- node_path.basename(record.worktreePath) || record.worktreePath,
112
- record.worktreePath,
113
- formatDistance(record.lastUsedAt, now, {
108
+ ], slots.map((slot)=>[
109
+ String(slot.index),
110
+ `${slot.firstPort}-${slot.lastPort}`,
111
+ node_path.basename(slot.worktreePath) || slot.worktreePath,
112
+ slot.worktreePath,
113
+ formatDistance(slot.lastUsedAt, now, {
114
114
  addSuffix: true
115
115
  }),
116
- String(record.idleTtlMinutes),
117
- record.keep ? 'yes' : 'no',
118
- record.isExpired ? 'yes' : 'no'
116
+ String(slot.idleTtlMinutes),
117
+ slot.keep ? 'yes' : 'no',
118
+ slot.isExpired ? 'yes' : 'no'
119
119
  ]));
120
120
  }
121
- async function saveEnvironmentFile(filePath, environment) {
121
+ async function saveEnvironmentFile(filePath, vars) {
122
122
  const contents = await fetchEnvironmentContents(filePath);
123
123
  const lineEnding = contents.includes('\r\n') ? '\r\n' : '\n';
124
- const pendingEntries = new Map(Object.entries(environment));
124
+ const pendingVars = new Map(Object.entries(vars));
125
125
  const updated = contents.replaceAll(ENV_ASSIGNMENT_PATTERN, (line, ...captures)=>{
126
126
  const [prefix, name, separator, suffix] = captures;
127
- const entry = Object.hasOwn(environment, name) ? environment[name] : void 0;
127
+ const entry = Object.hasOwn(vars, name) ? vars[name] : void 0;
128
128
  if (void 0 === entry) return line;
129
- pendingEntries.delete(name);
129
+ pendingVars.delete(name);
130
130
  return `${prefix}${name}${separator}${formatEnvironmentValue(entry)}${suffix}`;
131
131
  });
132
- const appended = formatEnvironment(Object.fromEntries(pendingEntries)).replaceAll('\n', lineEnding);
132
+ const appended = formatEnvironment(Object.fromEntries(pendingVars)).replaceAll('\n', lineEnding);
133
133
  const separator = updated.length > 0 && !updated.endsWith('\n') ? lineEnding : '';
134
134
  await writeFileAtomically(filePath, `${updated}${appended ? `${separator}${appended}${lineEnding}` : ''}`);
135
135
  }
136
- async function updateEnvironmentFile(filePath, environment, commonDirectory) {
136
+ async function updateEnvironmentFile(filePath, vars, commonDirectory) {
137
137
  const targetPath = await fetchCanonicalPath(filePath);
138
138
  if (void 0 !== commonDirectory) await assertExportPaths([
139
139
  targetPath
@@ -148,13 +148,13 @@ async function updateEnvironmentFile(filePath, environment, commonDirectory) {
148
148
  }
149
149
  });
150
150
  try {
151
- await saveEnvironmentFile(targetPath, environment);
151
+ await saveEnvironmentFile(targetPath, vars);
152
152
  } finally{
153
153
  await unlock();
154
154
  }
155
155
  }
156
- async function writeReserveJsonFile(filePath, slot, environment) {
157
- const variables = environment ?? {
156
+ async function writeReserveJsonFile(filePath, slot, vars) {
157
+ const variables = vars ?? {
158
158
  firstPort: slot.firstPort,
159
159
  index: slot.index,
160
160
  lastPort: slot.lastPort,
package/dist/registry.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import node_path from "node:path";
3
3
  import proper_lockfile from "proper-lockfile";
4
+ import { DEFAULT_CONFIG } from "./config.js";
4
5
  import { PortoError } from "./error.js";
5
6
  import { checkIsFileMissing, writeFileAtomically } from "./files.js";
6
7
  import { REGISTRY_SCHEMA } from "./schemas.js";
@@ -9,9 +10,9 @@ async function fetchRegistry(filePath) {
9
10
  return REGISTRY_SCHEMA.parse(JSON.parse(await readFile(filePath, 'utf8')));
10
11
  } catch (error) {
11
12
  if (checkIsFileMissing(error)) return {
12
- portsPerSlot: 10,
13
- slots: [],
14
- startPort: 10000
13
+ portsPerSlot: DEFAULT_CONFIG.size,
14
+ slots: {},
15
+ startPort: DEFAULT_CONFIG.start
15
16
  };
16
17
  throw new PortoError('registryInvalid', filePath, {
17
18
  cause: error
@@ -22,7 +23,6 @@ function getRegistryPath(commonDirectory) {
22
23
  return node_path.join(commonDirectory, 'porto-registry.json');
23
24
  }
24
25
  async function writeRegistry(filePath, registry, previousContents) {
25
- while(null === registry.slots.at(-1))registry.slots.pop();
26
26
  const contents = JSON.stringify(registry);
27
27
  if (contents !== previousContents) await writeFileAtomically(filePath, `${contents}\n`);
28
28
  }
package/dist/reserve.d.ts CHANGED
@@ -6,15 +6,15 @@ import type { Vars, VarsResult } from './vars.js';
6
6
  import { fetchGitContext } from './git.js';
7
7
  import { buildSlot } from './ports.js';
8
8
  type ReservedSlot<Entries extends Vars = Vars> = Omit<ReturnType<typeof buildSlot<ReservationRecord>>, 'vars'> & {
9
- vars: VarsResult<Entries> & {
10
- PORTO_SLOT: number;
11
- };
9
+ vars: Entries extends readonly [] ? {
10
+ SLOT: number;
11
+ } : VarsResult<Entries>;
12
12
  };
13
13
  type ReserveOptions = Partial<z.output<typeof OPTIONS_SCHEMA>> & {
14
14
  vars?: undefined | Vars;
15
15
  };
16
16
  declare function checkIsExpired(record: Pick<ReservationRecord, 'expiresAt'>, now: number): boolean;
17
- declare function issuePorts(record: ReservationRecord, index: number, entries: Vars): {
17
+ declare function releaseRecord(registry: Registry, index: number, record: ReservationRecord, force?: boolean): Promise<{
18
18
  env: boolean;
19
19
  envFile: string;
20
20
  jsonFile: string | false;
@@ -28,15 +28,15 @@ declare function issuePorts(record: ReservationRecord, index: number, entries: V
28
28
  lastUsedAt: string;
29
29
  ports: number[];
30
30
  vars: {
31
- PORTO_SLOT: number;
31
+ [k: string]: string | number;
32
32
  };
33
33
  worktreeId: string;
34
34
  worktreePath: string;
35
35
  } & {
36
36
  getPort(offset?: number): number;
37
37
  index: number;
38
- };
39
- declare function releaseRecord(registry: Registry, index: number, record: ReservationRecord): Promise<{
38
+ }>;
39
+ declare function removeExpiredRecords(registry: Registry, now: number): Promise<({
40
40
  env: boolean;
41
41
  envFile: string;
42
42
  jsonFile: string | false;
@@ -50,15 +50,15 @@ declare function releaseRecord(registry: Registry, index: number, record: Reserv
50
50
  lastUsedAt: string;
51
51
  ports: number[];
52
52
  vars: {
53
- PORTO_SLOT: number;
53
+ [k: string]: string | number;
54
54
  };
55
55
  worktreeId: string;
56
56
  worktreePath: string;
57
57
  } & {
58
58
  getPort(offset?: number): number;
59
59
  index: number;
60
- }>;
61
- declare function removeExpiredRecords(registry: Registry, now: number): Promise<({
60
+ })[]>;
61
+ declare function commitReservation({ commonDirectory, worktreeId, worktreePath }: Awaited<ReturnType<typeof fetchGitContext>>, { vars, ...options }: Omit<PortoConfig, 'onReleased' | 'onReserved'>): Promise<{
62
62
  env: boolean;
63
63
  envFile: string;
64
64
  jsonFile: string | false;
@@ -72,15 +72,14 @@ declare function removeExpiredRecords(registry: Registry, now: number): Promise<
72
72
  lastUsedAt: string;
73
73
  ports: number[];
74
74
  vars: {
75
- PORTO_SLOT: number;
75
+ [k: string]: string | number;
76
76
  };
77
77
  worktreeId: string;
78
78
  worktreePath: string;
79
79
  } & {
80
80
  getPort(offset?: number): number;
81
81
  index: number;
82
- })[]>;
83
- declare function commitReservation<Result>({ commonDirectory, worktreeId, worktreePath }: Awaited<ReturnType<typeof fetchGitContext>>, { vars, ...options }: Omit<PortoConfig, 'onReleased' | 'onReserved'>, prepare: (slot: ReturnType<typeof issuePorts>) => Promise<Result> | Result): Promise<Result>;
82
+ }>;
84
83
  declare function reserve<const Entries extends Vars>(options: ReserveOptions & {
85
84
  vars: Entries;
86
85
  }): Promise<ReservedSlot<Entries>>;
package/dist/reserve.js CHANGED
@@ -13,14 +13,13 @@ async function allocateRecord(registry, options) {
13
13
  for(let index = 0; index < slotsCount; index += 1){
14
14
  const firstPort = startPort + index * portsPerSlot;
15
15
  const lastPort = firstPort + portsPerSlot - 1;
16
- if (!slots[index] && !await checkHasBusyPort(firstPort, lastPort, options.host)) {
16
+ const isOccupied = void 0 !== slots[index];
17
+ if (!isOccupied && !await checkHasBusyPort(firstPort, lastPort, options.host)) {
17
18
  const record = {
18
19
  ...options,
19
20
  firstPort,
20
21
  lastPort,
21
- vars: {
22
- PORTO_SLOT: index
23
- }
22
+ vars: {}
24
23
  };
25
24
  slots[index] = record;
26
25
  return {
@@ -36,48 +35,51 @@ function checkIsExpired(record, now) {
36
35
  }
37
36
  function issuePorts(record, index, entries) {
38
37
  const { firstPort } = record;
39
- record.vars = {
40
- ...mapSlotToVars({
41
- firstPort,
42
- index
43
- }, entries),
44
- PORTO_SLOT: index
45
- };
38
+ record.vars = 0 === entries.length ? {
39
+ SLOT: index
40
+ } : mapSlotToVars({
41
+ firstPort,
42
+ index
43
+ }, entries);
46
44
  record.ports = union(record.ports, range(firstPort, firstPort + entries.length));
47
45
  return buildSlot(record, index);
48
46
  }
49
- async function releaseRecord(registry, index, record) {
50
- const busyPorts = await listBusyPorts(record.firstPort, record.lastPort, {
51
- host: record.host
52
- });
53
- if (busyPorts.length > 0) throw new BusyPortsError(busyPorts.map((port)=>({
54
- port,
55
- slot: index
56
- })));
57
- registry.slots[index] = null;
47
+ async function releaseRecord(registry, index, record, force = false) {
48
+ if (!force) {
49
+ const busyPorts = await listBusyPorts(record.firstPort, record.lastPort, {
50
+ host: record.host
51
+ });
52
+ if (busyPorts.length > 0) throw new BusyPortsError(busyPorts.map((port)=>({
53
+ port,
54
+ slot: index
55
+ })));
56
+ }
57
+ delete registry.slots[index];
58
58
  return buildSlot(record, index);
59
59
  }
60
60
  async function removeExpiredRecords(registry, now) {
61
- const checkedSlots = await Promise.all(registry.slots.flatMap((record, index)=>{
62
- if (null === record || !checkIsExpired(record, now)) return [];
61
+ const checkedSlots = await Promise.all(Object.entries(registry.slots).flatMap(([key, record])=>{
62
+ const index = Number(key);
63
+ if (!checkIsExpired(record, now)) return [];
63
64
  return [
64
65
  checkHasBusyPort(record.firstPort, record.lastPort, record.host).then((hasBusyPort)=>hasBusyPort ? void 0 : buildSlot(record, index))
65
66
  ];
66
67
  }));
67
68
  const expiredSlots = checkedSlots.filter((slot)=>void 0 !== slot);
68
- for (const { index } of expiredSlots)registry.slots[index] = null;
69
+ for (const { index } of expiredSlots)delete registry.slots[index];
69
70
  return expiredSlots;
70
71
  }
71
- function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars = [], ...options }, prepare) {
72
+ function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars = [], ...options }) {
72
73
  return updateRegistry(commonDirectory, async (registry)=>{
73
74
  const { env, envFile, host, idleTtlMinutes, jsonFile, keep, silent, size, start } = applyReserveDefaults(options, registry);
74
75
  assertVarsFit(vars.length, size);
75
- if ((registry.startPort !== start || registry.portsPerSlot !== size) && registry.slots.some((record)=>null !== record)) throw new PortoError('rangeMismatch');
76
+ if ((registry.startPort !== start || registry.portsPerSlot !== size) && Object.keys(registry.slots).length > 0) throw new PortoError('rangeMismatch');
76
77
  registry.startPort = start;
77
78
  registry.portsPerSlot = size;
78
79
  const now = Date.now();
79
- const existingIndex = registry.slots.findIndex((record)=>record?.worktreeId === worktreeId);
80
- const existingRecord = registry.slots[existingIndex];
80
+ const existingEntry = Object.entries(registry.slots).find(([, record])=>record.worktreeId === worktreeId);
81
+ const existingIndex = void 0 === existingEntry ? -1 : Number(existingEntry[0]);
82
+ const existingRecord = existingEntry?.[1];
81
83
  const lastUsedAt = new Date(now).toISOString();
82
84
  const isKept = keep ?? existingRecord?.keep ?? false;
83
85
  const settings = {
@@ -102,7 +104,7 @@ function commitReservation({ commonDirectory, worktreeId, worktreePath }, { vars
102
104
  ports: [],
103
105
  worktreeId
104
106
  });
105
- return prepare(issuePorts(record, index, vars));
107
+ return issuePorts(record, index, vars);
106
108
  });
107
109
  }
108
110
  async function reserve(options = {}) {
@@ -112,6 +114,6 @@ async function reserve(options = {}) {
112
114
  return commitReservation(git, {
113
115
  ...parseOptions(optionsWithoutVars),
114
116
  vars
115
- }, (slot)=>slot);
117
+ });
116
118
  }
117
119
  export { checkIsExpired, commitReservation, releaseRecord, removeExpiredRecords, reserve };
package/dist/schemas.d.ts CHANGED
@@ -30,20 +30,16 @@ declare const RECORD_SCHEMA: z.ZodObject<{
30
30
  lastPort: z.ZodInt;
31
31
  lastUsedAt: z.ZodISODateTime;
32
32
  ports: z.ZodArray<z.ZodInt>;
33
- vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
33
+ vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
34
34
  [k: string]: string | number;
35
- }, [string, string | number][]>>, z.ZodTransform<{
36
- PORTO_SLOT: number;
37
- }, {
38
- [k: string]: string | number;
39
- }>>;
35
+ }, [string, string | number][]>>;
40
36
  worktreeId: z.ZodString;
41
37
  worktreePath: z.ZodString;
42
38
  }, z.core.$strip>;
43
39
  type ReservationRecord = z.output<typeof RECORD_SCHEMA>;
44
40
  declare const REGISTRY_SCHEMA: z.ZodObject<{
45
41
  portsPerSlot: z.ZodInt;
46
- slots: z.ZodArray<z.ZodNullable<z.ZodObject<{
42
+ slots: z.ZodRecord<z.ZodCoercedNumber<unknown>, z.ZodObject<{
47
43
  env: z.ZodBoolean;
48
44
  envFile: z.ZodString;
49
45
  jsonFile: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodString]>;
@@ -56,16 +52,12 @@ declare const REGISTRY_SCHEMA: z.ZodObject<{
56
52
  lastPort: z.ZodInt;
57
53
  lastUsedAt: z.ZodISODateTime;
58
54
  ports: z.ZodArray<z.ZodInt>;
59
- vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
60
- [k: string]: string | number;
61
- }, [string, string | number][]>>, z.ZodTransform<{
62
- PORTO_SLOT: number;
63
- }, {
55
+ vars: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
64
56
  [k: string]: string | number;
65
- }>>;
57
+ }, [string, string | number][]>>;
66
58
  worktreeId: z.ZodString;
67
59
  worktreePath: z.ZodString;
68
- }, z.core.$strip>>>;
60
+ }, z.core.$strip>>;
69
61
  startPort: z.ZodInt;
70
62
  }, z.core.$strip>;
71
63
  type Registry = z.output<typeof REGISTRY_SCHEMA>;
package/dist/schemas.js CHANGED
@@ -51,19 +51,29 @@ const RECORD_SCHEMA = z.object({
51
51
  'expiresAt'
52
52
  ]
53
53
  });
54
+ const SLOTS_SCHEMA = z.record(z.coerce.number().int().nonnegative(), RECORD_SCHEMA).refine((slots)=>Object.keys(slots).every((key)=>key === String(Number(key))), {
55
+ message: 'Slot keys must be canonical non-negative integer strings.'
56
+ });
54
57
  const REGISTRY_SCHEMA = z.object({
55
58
  portsPerSlot: PORT_SCHEMA,
56
- slots: z.array(RECORD_SCHEMA.nullable()),
59
+ slots: SLOTS_SCHEMA,
57
60
  startPort: PORT_SCHEMA
58
- }).refine(({ portsPerSlot, slots, startPort })=>startPort + Math.max(slots.length, 1) * portsPerSlot - 1 <= 65535, {
61
+ }).refine(({ portsPerSlot, slots, startPort })=>{
62
+ const keys = Object.keys(slots).map(Number);
63
+ const usedSlots = 0 === keys.length ? 1 : Math.max(...keys) + 1;
64
+ return startPort + usedSlots * portsPerSlot - 1 <= 65535;
65
+ }, {
59
66
  message: 'Port slots must fit in the TCP port range.'
60
67
  }).refine(({ slots })=>{
61
- const records = slots.filter((record)=>null !== record);
68
+ const records = Object.values(slots);
62
69
  return new Set(records.map((record)=>record.worktreeId)).size === records.length;
63
70
  }, {
64
- message: 'Each checkout can have only one reservation.'
65
- }).refine(({ portsPerSlot, slots, startPort })=>slots.every((record, index)=>null === record || record.firstPort === startPort + index * portsPerSlot && record.lastPort === record.firstPort + portsPerSlot - 1 && record.vars.PORTO_SLOT === index), {
66
- message: 'Slot bounds and PORTO_SLOT must match its array index and the repository range.'
71
+ message: 'Each worktree can have only one slot.'
72
+ }).refine(({ portsPerSlot, slots, startPort })=>Object.entries(slots).every(([key, record])=>{
73
+ const index = Number(key);
74
+ return record.firstPort === startPort + index * portsPerSlot && record.lastPort === record.firstPort + portsPerSlot - 1;
75
+ }), {
76
+ message: 'Slot bounds must match its slot index and the repository range.'
67
77
  });
68
78
  function parseOptions(options) {
69
79
  const result = INPUT_OPTIONS_SCHEMA.safeParse(options);
package/dist/vars.d.ts CHANGED
@@ -2,19 +2,15 @@ import { z } from 'zod';
2
2
  import type { PortSlot } from './index.js';
3
3
  type VarEntry = string | VarFactory;
4
4
  type VarEntryResult<Entry extends VarEntry> = Entry extends string ? string extends Entry ? Partial<Record<string, number>> : Record<Entry, number> : Entry extends VarFactory ? ReturnType<Entry> : never;
5
- type VarFactory = (slotIndex: number, port: number, index: number) => Record<string, number | string>;
5
+ type VarFactory = (port: number, slot: number) => Record<string, number | string>;
6
6
  type Vars = ReadonlyArray<VarEntry>;
7
7
  type VarsResult<Entries extends Vars> = Entries extends readonly [
8
8
  infer Entry extends VarEntry,
9
9
  ...infer Rest extends Vars
10
10
  ] ? VarEntryResult<Entry> & VarsResult<Rest> : number extends Entries['length'] ? Partial<Record<string, number | string>> : object;
11
- declare const VAR_VALUES_SCHEMA: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
11
+ declare const VAR_VALUES_SCHEMA: z.ZodPipe<z.ZodPipe<z.ZodPipe<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>, z.ZodTransform<[string, unknown][], Record<string, unknown>>>, z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>], null>>>, z.ZodTransform<{
12
12
  [k: string]: string | number;
13
- }, [string, string | number][]>>, z.ZodTransform<{
14
- PORTO_SLOT: number;
15
- }, {
16
- [k: string]: string | number;
17
- }>>;
13
+ }, [string, string | number][]>>;
18
14
  declare const VARS_SCHEMA: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<VarFactory, VarFactory>]>>;
19
15
  declare function assertVarsFit(varsCount: number, size: number): void;
20
16
  declare function mapSlotToVars(slot: Pick<PortSlot, 'firstPort' | 'index'>, entries: Vars): {
package/dist/vars.js CHANGED
@@ -13,18 +13,7 @@ const VAR_RESULT_ENTRY_SCHEMA = z.tuple([
13
13
  ])
14
14
  ]);
15
15
  const VAR_RESULT_SCHEMA = z.custom(isPlainObject).transform((variables)=>Object.entries(variables)).pipe(z.array(VAR_RESULT_ENTRY_SCHEMA));
16
- const VAR_VALUES_SCHEMA = VAR_RESULT_SCHEMA.transform((entries)=>Object.fromEntries(entries)).refine((variables)=>{
17
- const slotIndex = variables['PORTO_SLOT'];
18
- return 'number' == typeof slotIndex && Number.isSafeInteger(slotIndex) && slotIndex >= 0;
19
- }, {
20
- message: 'PORTO_SLOT must be a non-negative integer.',
21
- path: [
22
- 'PORTO_SLOT'
23
- ]
24
- }).transform((variables)=>({
25
- ...variables,
26
- PORTO_SLOT: Number(variables['PORTO_SLOT'])
27
- }));
16
+ const VAR_VALUES_SCHEMA = VAR_RESULT_SCHEMA.transform((entries)=>Object.fromEntries(entries));
28
17
  const VARS_SCHEMA = z.array(z.union([
29
18
  VAR_NAME_SCHEMA,
30
19
  VAR_FACTORY_SCHEMA
@@ -46,8 +35,11 @@ function mapVarEntry(entry, slot, index) {
46
35
  ]
47
36
  ];
48
37
  try {
49
- const variables = entry(slot.index, port, index);
50
- if (types.isPromise(variables)) variables.catch(()=>{});
38
+ const variables = entry(port, slot.index);
39
+ if (types.isPromise(variables)) {
40
+ variables.catch(()=>{});
41
+ throw new PortoError('mappingInvalid', `Cannot create variables for entry ${index + 1}; async factories are not supported, return a plain object.`);
42
+ }
51
43
  return VAR_RESULT_SCHEMA.parse(variables);
52
44
  } catch (error) {
53
45
  throw new PortoError('mappingInvalid', `Cannot create variables for entry ${index + 1}; expected an object with valid names and single-line strings or finite numbers.`, {
@@ -63,13 +55,13 @@ function mapSlotToVars(slot, entries) {
63
55
  }
64
56
  return Object.fromEntries(environment);
65
57
  }
66
- function parseVar(entry) {
67
- const separator = entry.indexOf('=');
68
- const name = (-1 === separator ? entry : entry.slice(0, separator)).trim();
58
+ function parseVar(source) {
59
+ const separator = source.indexOf('=');
60
+ const name = (-1 === separator ? source : source.slice(0, separator)).trim();
69
61
  if (-1 === separator) return {
70
62
  name
71
63
  };
72
- const template = entry.slice(separator + 1);
64
+ const template = source.slice(separator + 1);
73
65
  const result = VAR_TEXT_SCHEMA.safeParse(template);
74
66
  if (!result.success) throw new PortoError('mappingInvalid', 'Vars templates must fit on one line.', {
75
67
  cause: result.error
@@ -92,9 +84,9 @@ function parseVars(source) {
92
84
  return groups.map((group)=>{
93
85
  const [firstVar] = group;
94
86
  if (1 === group.length && firstVar && void 0 === firstVar.template) return firstVar.name;
95
- return (slotIndex, port)=>Object.fromEntries(group.map(({ name, template })=>[
87
+ return (port, slot)=>Object.fromEntries(group.map(({ name, template })=>[
96
88
  name,
97
- template?.replaceAll('{{slot}}', String(slotIndex)).replaceAll('{{port}}', String(port)) ?? port
89
+ template?.replaceAll('{{slot}}', String(slot)).replaceAll('{{port}}', String(port)) ?? port
98
90
  ]));
99
91
  });
100
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@b12k/porto",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Port range allocator for git worktrees",
5
5
  "keywords": [
6
6
  "cli",