@b12k/porto 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +92 -2
- package/dist/busy-ports-error.d.ts +11 -0
- package/dist/busy-ports-error.js +10 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +116 -0
- package/dist/config.d.ts +72 -0
- package/dist/config.js +101 -0
- package/dist/error.d.ts +5 -0
- package/dist/error.js +13 -0
- package/dist/errors.d.ts +46 -0
- package/dist/errors.js +47 -0
- package/dist/files.d.ts +4 -0
- package/dist/files.js +43 -0
- package/dist/git.d.ts +7 -0
- package/dist/git.js +64 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +57 -0
- package/dist/load-config.d.ts +1 -0
- package/dist/load-config.js +17 -0
- package/dist/log.d.ts +4 -0
- package/dist/log.js +19 -0
- package/dist/output.d.ts +18 -0
- package/dist/output.js +159 -0
- package/dist/ports.d.ts +16 -0
- package/dist/ports.js +70 -0
- package/dist/registry.d.ts +14 -0
- package/dist/registry.js +45 -0
- package/dist/reserve.d.ts +36 -0
- package/dist/reserve.js +84 -0
- package/dist/schemas.d.ts +33 -0
- package/dist/schemas.js +72 -0
- package/dist/vars.d.ts +14 -0
- package/dist/vars.js +87 -0
- package/package.json +94 -4
package/dist/git.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
3
|
+
import node_path from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { PortoError } from "./error.js";
|
|
6
|
+
import { checkIsFileMissing } from "./files.js";
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
function getWorktreeId(commonDirectory, gitDirectory) {
|
|
9
|
+
return node_path.relative(commonDirectory, gitDirectory).split(node_path.sep).join('/') || '.';
|
|
10
|
+
}
|
|
11
|
+
async function fetchGitContext() {
|
|
12
|
+
try {
|
|
13
|
+
const { stdout } = await execFileAsync('git', [
|
|
14
|
+
'rev-parse',
|
|
15
|
+
'--path-format=absolute',
|
|
16
|
+
'--show-toplevel',
|
|
17
|
+
'--git-common-dir',
|
|
18
|
+
'--absolute-git-dir'
|
|
19
|
+
]);
|
|
20
|
+
const [worktreePath, commonPath, gitPath] = stdout.split(/\r?\n/u);
|
|
21
|
+
if (!worktreePath || !commonPath || !gitPath) throw new Error('Missing Git paths.');
|
|
22
|
+
const [worktree, commonDirectory, gitDirectory] = await Promise.all([
|
|
23
|
+
realpath(worktreePath),
|
|
24
|
+
realpath(commonPath),
|
|
25
|
+
realpath(gitPath)
|
|
26
|
+
]);
|
|
27
|
+
return {
|
|
28
|
+
commonDirectory,
|
|
29
|
+
worktree,
|
|
30
|
+
worktreeId: getWorktreeId(commonDirectory, gitDirectory)
|
|
31
|
+
};
|
|
32
|
+
} catch (error) {
|
|
33
|
+
throw new PortoError('worktreeNotFound', void 0, {
|
|
34
|
+
cause: error
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function fetchLinkedWorktreeId(commonDirectory, worktree) {
|
|
39
|
+
const gitLink = await readFile(node_path.join(worktree, '.git'), 'utf8');
|
|
40
|
+
const gitPath = /^gitdir: (?<gitPath>.+)\r?\n?$/u.exec(gitLink)?.groups?.['gitPath'];
|
|
41
|
+
return gitPath && getWorktreeId(commonDirectory, await realpath(node_path.resolve(worktree, gitPath)));
|
|
42
|
+
}
|
|
43
|
+
async function listWorktreePaths(commonDirectory) {
|
|
44
|
+
const { stdout } = await execFileAsync('git', [
|
|
45
|
+
'worktree',
|
|
46
|
+
'list',
|
|
47
|
+
'--porcelain',
|
|
48
|
+
'-z'
|
|
49
|
+
]);
|
|
50
|
+
const worktreePathsById = new Map();
|
|
51
|
+
await Promise.all(stdout.split('\0\0').map(async (entry, index)=>{
|
|
52
|
+
const [location, ...flags] = entry.split('\0');
|
|
53
|
+
if (!location?.startsWith('worktree ') || flags.some((flag)=>'bare' === flag || flag.startsWith('prunable '))) return;
|
|
54
|
+
try {
|
|
55
|
+
const worktree = await realpath(location.slice(9));
|
|
56
|
+
const worktreeId = 0 === index ? '.' : await fetchLinkedWorktreeId(commonDirectory, worktree);
|
|
57
|
+
if (worktreeId) worktreePathsById.set(worktreeId, worktree);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (!checkIsFileMissing(error)) throw error;
|
|
60
|
+
}
|
|
61
|
+
}));
|
|
62
|
+
return worktreePathsById;
|
|
63
|
+
}
|
|
64
|
+
export { fetchGitContext, listWorktreePaths };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ReservationRecord } from './registry.js';
|
|
2
|
+
import { buildBlock } from './ports.js';
|
|
3
|
+
type PortBlock = ReturnType<typeof buildBlock>;
|
|
4
|
+
type ReservationStats = Omit<ReservationRecord, 'worktreeId'> & {
|
|
5
|
+
end: number;
|
|
6
|
+
isExpired: boolean;
|
|
7
|
+
};
|
|
8
|
+
declare function cleanup(): Promise<{
|
|
9
|
+
end: number;
|
|
10
|
+
getPort(offset?: number): number;
|
|
11
|
+
index: number;
|
|
12
|
+
start: number;
|
|
13
|
+
}[]>;
|
|
14
|
+
declare function current(): Promise<{
|
|
15
|
+
end: number;
|
|
16
|
+
getPort(offset?: number): number;
|
|
17
|
+
index: number;
|
|
18
|
+
start: number;
|
|
19
|
+
}[]>;
|
|
20
|
+
declare function release(): Promise<({
|
|
21
|
+
end: number;
|
|
22
|
+
getPort(offset?: number): number;
|
|
23
|
+
index: number;
|
|
24
|
+
start: number;
|
|
25
|
+
} & {
|
|
26
|
+
ports: number[];
|
|
27
|
+
})[]>;
|
|
28
|
+
declare function stats(): Promise<{
|
|
29
|
+
index: number;
|
|
30
|
+
lastUsedAt: string;
|
|
31
|
+
ports: Array<number>;
|
|
32
|
+
end: number;
|
|
33
|
+
isExpired: boolean;
|
|
34
|
+
start: number;
|
|
35
|
+
worktree: string;
|
|
36
|
+
host?: string | undefined;
|
|
37
|
+
idleTtlMinutes: number;
|
|
38
|
+
keep: boolean;
|
|
39
|
+
size: number;
|
|
40
|
+
}[]>;
|
|
41
|
+
export { cleanup, current, release, stats };
|
|
42
|
+
export type { PortBlock, ReservationStats };
|
|
43
|
+
export { BusyPortsError } from './busy-ports-error.js';
|
|
44
|
+
export { defineConfig } from './config.js';
|
|
45
|
+
export type { PortoConfig } from './config.js';
|
|
46
|
+
export { PortoError } from './error.js';
|
|
47
|
+
export { reserve } from './reserve.js';
|
|
48
|
+
export type { ReserveOptions } from './reserve.js';
|
|
49
|
+
export type { VarFactory, Vars } from './vars.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { remove, sortBy } from "es-toolkit";
|
|
2
|
+
import { BusyPortsError } from "./busy-ports-error.js";
|
|
3
|
+
import { fetchGitContext, listWorktreePaths } from "./git.js";
|
|
4
|
+
import { buildBlock, listBusyPorts } from "./ports.js";
|
|
5
|
+
import { updateRegistry } from "./registry.js";
|
|
6
|
+
import { checkIsExpired, removeExpiredRecords, reserve } from "./reserve.js";
|
|
7
|
+
async function cleanup() {
|
|
8
|
+
const { commonDirectory } = await fetchGitContext();
|
|
9
|
+
return updateRegistry(commonDirectory, (records)=>removeExpiredRecords(records, Date.now()));
|
|
10
|
+
}
|
|
11
|
+
async function current() {
|
|
12
|
+
const { commonDirectory, worktreeId } = await fetchGitContext();
|
|
13
|
+
return updateRegistry(commonDirectory, (records)=>records.filter((record)=>record.worktreeId === worktreeId).map((record)=>buildBlock(record)));
|
|
14
|
+
}
|
|
15
|
+
async function release() {
|
|
16
|
+
const { commonDirectory, worktreeId } = await fetchGitContext();
|
|
17
|
+
return updateRegistry(commonDirectory, async (records)=>{
|
|
18
|
+
const currentRecords = records.filter((record)=>record.worktreeId === worktreeId);
|
|
19
|
+
const portsByRecord = await Promise.all(currentRecords.map(async (record)=>{
|
|
20
|
+
const block = buildBlock(record);
|
|
21
|
+
const ports = await listBusyPorts(block.start, block.end, {
|
|
22
|
+
host: record.host
|
|
23
|
+
});
|
|
24
|
+
return ports.map((port)=>({
|
|
25
|
+
block: block.index,
|
|
26
|
+
port
|
|
27
|
+
}));
|
|
28
|
+
}));
|
|
29
|
+
const busyPorts = portsByRecord.flat();
|
|
30
|
+
if (busyPorts.length > 0) throw new BusyPortsError(busyPorts);
|
|
31
|
+
remove(records, (record)=>record.worktreeId === worktreeId);
|
|
32
|
+
return currentRecords.map((record)=>Object.assign(buildBlock(record), {
|
|
33
|
+
ports: record.ports
|
|
34
|
+
}));
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async function stats() {
|
|
38
|
+
const { commonDirectory } = await fetchGitContext();
|
|
39
|
+
const worktreePathsById = await listWorktreePaths(commonDirectory);
|
|
40
|
+
return updateRegistry(commonDirectory, (records)=>sortBy(records.map(({ worktreeId, ...record })=>{
|
|
41
|
+
const { end, start } = buildBlock(record);
|
|
42
|
+
const worktree = worktreePathsById.get(worktreeId) ?? record.worktree;
|
|
43
|
+
return {
|
|
44
|
+
...record,
|
|
45
|
+
end,
|
|
46
|
+
isExpired: checkIsExpired(record, Date.now()),
|
|
47
|
+
start,
|
|
48
|
+
worktree
|
|
49
|
+
};
|
|
50
|
+
}), [
|
|
51
|
+
'start',
|
|
52
|
+
'worktree'
|
|
53
|
+
]));
|
|
54
|
+
}
|
|
55
|
+
export { defineConfig } from "./config.js";
|
|
56
|
+
export { PortoError } from "./error.js";
|
|
57
|
+
export { BusyPortsError, cleanup, current, release, reserve, stats };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function loadConfigFile(filePath: string): Promise<unknown>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { cosmiconfig } from "cosmiconfig";
|
|
2
|
+
import { createJiti } from "jiti";
|
|
3
|
+
function loadTypeScriptConfig(filePath) {
|
|
4
|
+
return createJiti(import.meta.url).import(filePath, {
|
|
5
|
+
default: true
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
async function loadConfigFile(filePath) {
|
|
9
|
+
const result = await cosmiconfig('porto', {
|
|
10
|
+
loaders: {
|
|
11
|
+
'.ts': loadTypeScriptConfig
|
|
12
|
+
}
|
|
13
|
+
}).load(filePath);
|
|
14
|
+
const config = result?.config;
|
|
15
|
+
return config;
|
|
16
|
+
}
|
|
17
|
+
export { loadConfigFile };
|
package/dist/log.d.ts
ADDED
package/dist/log.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import boxen from "boxen";
|
|
2
|
+
import { libraryName } from "./config.js";
|
|
3
|
+
import { PortoError } from "./error.js";
|
|
4
|
+
import { ERRORS_BY_KEY } from "./errors.js";
|
|
5
|
+
function log(message, options) {
|
|
6
|
+
process.stderr.write(`${boxen(message, options)}\n`);
|
|
7
|
+
}
|
|
8
|
+
function logError(error) {
|
|
9
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
10
|
+
const instruction = error instanceof PortoError ? ERRORS_BY_KEY[error.code].instruction : '';
|
|
11
|
+
log([
|
|
12
|
+
message,
|
|
13
|
+
instruction
|
|
14
|
+
].filter(Boolean).join('\n\n'), {
|
|
15
|
+
borderColor: 'red',
|
|
16
|
+
title: `[${libraryName}]`
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export { log, logError };
|
package/dist/output.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PortBlock, ReservationStats } from './index.js';
|
|
2
|
+
type Environment = Record<string, number | string>;
|
|
3
|
+
declare function fetchExportPaths(settings: {
|
|
4
|
+
env: boolean;
|
|
5
|
+
envFile: string;
|
|
6
|
+
jsonFile: false | string;
|
|
7
|
+
}, commonDirectory: string): Promise<{
|
|
8
|
+
environmentPath: string | undefined;
|
|
9
|
+
jsonPath: string | undefined;
|
|
10
|
+
}>;
|
|
11
|
+
declare function formatEnvironment(environment: Environment): string;
|
|
12
|
+
declare function formatReserveOutput(block: PortBlock, environment: Environment | undefined, isJson: boolean): string;
|
|
13
|
+
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, block: PortBlock, environment: Environment | undefined): Promise<void>;
|
|
17
|
+
export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile, };
|
|
18
|
+
export type { Environment };
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { formatDistance } from "date-fns/formatDistance";
|
|
2
|
+
import { readFile, stat } from "node:fs/promises";
|
|
3
|
+
import node_path from "node:path";
|
|
4
|
+
import proper_lockfile from "proper-lockfile";
|
|
5
|
+
import { PortoError } from "./error.js";
|
|
6
|
+
import { checkIsFileMissing, fetchCanonicalPath, writeFileAtomically } from "./files.js";
|
|
7
|
+
import { getRegistryPath } from "./registry.js";
|
|
8
|
+
const ENV_ASSIGNMENT_PATTERN = /^(?<prefix>\uFEFF?[ \t]*(?:export[ \t]+)?)(?<name>[^#=\s][^=\r\n]*?)(?<separator>[ \t]*=[ \t]*)(?:'[^']*'|"(?:\\[\s\S]|[^"\\])*"|`[^`]*`|[^\r\n#]*?)(?<suffix>[ \t]*(?:#[^\r\n]*)?)(?=\r?$)/gmu;
|
|
9
|
+
async function fetchFileIdentity(filePath) {
|
|
10
|
+
try {
|
|
11
|
+
const { dev, ino } = await stat(filePath, {
|
|
12
|
+
bigint: true
|
|
13
|
+
});
|
|
14
|
+
return `${dev}:${ino}`;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
if (!checkIsFileMissing(error)) throw error;
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function normalizePathForComparison(filePath) {
|
|
21
|
+
if ('win32' === process.platform) return filePath.replace(/[ .]+$/u, '').toLowerCase();
|
|
22
|
+
return 'darwin' === process.platform ? filePath.toLowerCase() : filePath;
|
|
23
|
+
}
|
|
24
|
+
async function assertExportPaths(exportPaths, registryPath) {
|
|
25
|
+
if (0 === exportPaths.length) return;
|
|
26
|
+
const lockPath = `${registryPath}.lock`;
|
|
27
|
+
const [registryTarget, lockTarget] = await Promise.all([
|
|
28
|
+
fetchCanonicalPath(registryPath),
|
|
29
|
+
fetchCanonicalPath(lockPath)
|
|
30
|
+
]);
|
|
31
|
+
const registryPaths = new Set([
|
|
32
|
+
registryPath,
|
|
33
|
+
registryTarget
|
|
34
|
+
].map((filePath)=>normalizePathForComparison(filePath)));
|
|
35
|
+
const lockPaths = [
|
|
36
|
+
lockPath,
|
|
37
|
+
lockTarget
|
|
38
|
+
].map((filePath)=>normalizePathForComparison(filePath));
|
|
39
|
+
const protectedIdentities = new Set(await Promise.all([
|
|
40
|
+
fetchFileIdentity(registryTarget),
|
|
41
|
+
fetchFileIdentity(lockTarget)
|
|
42
|
+
]));
|
|
43
|
+
protectedIdentities.delete(false);
|
|
44
|
+
const exportIdentities = await Promise.all(exportPaths.map((filePath)=>fetchFileIdentity(filePath)));
|
|
45
|
+
if (exportPaths.some((filePath)=>{
|
|
46
|
+
const normalizedPath = normalizePathForComparison(filePath);
|
|
47
|
+
return registryPaths.has(normalizedPath) || lockPaths.some((targetPath)=>normalizedPath === targetPath || normalizedPath.startsWith(`${targetPath}${node_path.sep}`));
|
|
48
|
+
}) || exportIdentities.some((identity)=>protectedIdentities.has(identity))) throw new PortoError('exportInvalid', 'The Porto registry and its lock are reserved.');
|
|
49
|
+
}
|
|
50
|
+
async function fetchEnvironmentContents(filePath) {
|
|
51
|
+
try {
|
|
52
|
+
return await readFile(filePath, 'utf8');
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (!checkIsFileMissing(error)) throw error;
|
|
55
|
+
return '';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function fetchExportPaths(settings, commonDirectory) {
|
|
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);
|
|
62
|
+
if (arePathsEqual) throw new PortoError('exportInvalid', '--json-file and --env-file must use different files.');
|
|
63
|
+
await assertExportPaths([
|
|
64
|
+
jsonPath,
|
|
65
|
+
environmentPath
|
|
66
|
+
].filter((filePath)=>void 0 !== filePath), getRegistryPath(commonDirectory));
|
|
67
|
+
return {
|
|
68
|
+
environmentPath,
|
|
69
|
+
jsonPath
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function formatEnvironmentValue(entry) {
|
|
73
|
+
const text = String(entry);
|
|
74
|
+
if (/^[A-Za-z0-9_./:@%+,-]*$/u.test(text)) return text;
|
|
75
|
+
if (!text.includes("'")) return `'${text}'`;
|
|
76
|
+
if (!text.includes('"') && !text.includes('\\')) return `"${text}"`;
|
|
77
|
+
throw new PortoError('mappingInvalid', 'Value cannot be represented safely on a single env line.');
|
|
78
|
+
}
|
|
79
|
+
function formatEnvironment(environment) {
|
|
80
|
+
return Object.entries(environment).map(([name, entry])=>`${name}=${formatEnvironmentValue(entry)}`).join('\n');
|
|
81
|
+
}
|
|
82
|
+
function formatReserveOutput(block, environment, isJson) {
|
|
83
|
+
if (isJson) return JSON.stringify(environment ?? {
|
|
84
|
+
end: block.end,
|
|
85
|
+
index: block.index,
|
|
86
|
+
start: block.start
|
|
87
|
+
});
|
|
88
|
+
return environment ? formatEnvironment(environment) : String(block.index);
|
|
89
|
+
}
|
|
90
|
+
function formatTable(headers, rows) {
|
|
91
|
+
const widths = headers.map((header, index)=>Math.max(header.length, ...rows.map((row)=>row[index]?.length ?? 0)));
|
|
92
|
+
return [
|
|
93
|
+
headers,
|
|
94
|
+
...rows
|
|
95
|
+
].map((row)=>row.map((cell, index)=>cell.padEnd(widths[index] ?? 0)).join(' ').trimEnd()).join('\n');
|
|
96
|
+
}
|
|
97
|
+
function formatStatsTable(reservations) {
|
|
98
|
+
const now = Date.now();
|
|
99
|
+
return formatTable([
|
|
100
|
+
'BLOCK',
|
|
101
|
+
'PORTS',
|
|
102
|
+
'WORKTREE',
|
|
103
|
+
'PATH',
|
|
104
|
+
'LAST USED',
|
|
105
|
+
'IDLE (MIN)',
|
|
106
|
+
'KEEP',
|
|
107
|
+
'EXPIRED'
|
|
108
|
+
], reservations.map((record)=>[
|
|
109
|
+
String(record.index),
|
|
110
|
+
`${record.start}-${record.end}`,
|
|
111
|
+
node_path.basename(record.worktree) || record.worktree,
|
|
112
|
+
record.worktree,
|
|
113
|
+
formatDistance(record.lastUsedAt, now, {
|
|
114
|
+
addSuffix: true
|
|
115
|
+
}),
|
|
116
|
+
String(record.idleTtlMinutes),
|
|
117
|
+
record.keep ? 'yes' : 'no',
|
|
118
|
+
record.isExpired ? 'yes' : 'no'
|
|
119
|
+
]));
|
|
120
|
+
}
|
|
121
|
+
async function saveEnvironmentFile(filePath, environment) {
|
|
122
|
+
const contents = await fetchEnvironmentContents(filePath);
|
|
123
|
+
const lineEnding = contents.includes('\r\n') ? '\r\n' : '\n';
|
|
124
|
+
const pendingEntries = new Map(Object.entries(environment));
|
|
125
|
+
const updated = contents.replaceAll(ENV_ASSIGNMENT_PATTERN, (line, ...captures)=>{
|
|
126
|
+
const [prefix, name, separator, suffix] = captures;
|
|
127
|
+
const entry = Object.hasOwn(environment, name) ? environment[name] : void 0;
|
|
128
|
+
if (void 0 === entry) return line;
|
|
129
|
+
pendingEntries.delete(name);
|
|
130
|
+
return `${prefix}${name}${separator}${formatEnvironmentValue(entry)}${suffix}`;
|
|
131
|
+
});
|
|
132
|
+
const appended = formatEnvironment(Object.fromEntries(pendingEntries)).replaceAll('\n', lineEnding);
|
|
133
|
+
const separator = updated.length > 0 && !updated.endsWith('\n') ? lineEnding : '';
|
|
134
|
+
await writeFileAtomically(filePath, `${updated}${appended ? `${separator}${appended}${lineEnding}` : ''}`);
|
|
135
|
+
}
|
|
136
|
+
async function updateEnvironmentFile(filePath, environment, commonDirectory) {
|
|
137
|
+
const targetPath = await fetchCanonicalPath(filePath);
|
|
138
|
+
if (void 0 !== commonDirectory) await assertExportPaths([
|
|
139
|
+
targetPath
|
|
140
|
+
], getRegistryPath(commonDirectory));
|
|
141
|
+
const unlock = await proper_lockfile.lock(targetPath, {
|
|
142
|
+
realpath: false,
|
|
143
|
+
retries: {
|
|
144
|
+
factor: 1,
|
|
145
|
+
maxTimeout: 100,
|
|
146
|
+
minTimeout: 100,
|
|
147
|
+
retries: 200
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
try {
|
|
151
|
+
await saveEnvironmentFile(targetPath, environment);
|
|
152
|
+
} finally{
|
|
153
|
+
await unlock();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function writeReserveJsonFile(filePath, block, environment) {
|
|
157
|
+
await writeFileAtomically(filePath, `${formatReserveOutput(block, environment, true)}\n`);
|
|
158
|
+
}
|
|
159
|
+
export { fetchExportPaths, formatEnvironment, formatReserveOutput, formatStatsTable, formatTable, updateEnvironmentFile, writeReserveJsonFile };
|
package/dist/ports.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
declare function buildBlock(record: {
|
|
2
|
+
index: number;
|
|
3
|
+
size: number;
|
|
4
|
+
start: number;
|
|
5
|
+
}): {
|
|
6
|
+
end: number;
|
|
7
|
+
getPort(offset?: number): number;
|
|
8
|
+
index: number;
|
|
9
|
+
start: number;
|
|
10
|
+
};
|
|
11
|
+
declare function listBusyPorts(start: number, end: number, { host, limit }?: {
|
|
12
|
+
host?: string | undefined;
|
|
13
|
+
limit?: number;
|
|
14
|
+
}): Promise<number[]>;
|
|
15
|
+
declare function checkHasBusyPort(start: number, end: number, host?: string): Promise<boolean>;
|
|
16
|
+
export { buildBlock, checkHasBusyPort, listBusyPorts };
|
package/dist/ports.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createServer } from "node:net";
|
|
2
|
+
import { networkInterfaces } from "node:os";
|
|
3
|
+
import { PortoError } from "./error.js";
|
|
4
|
+
function buildBlock(record) {
|
|
5
|
+
const start = record.start + record.index * record.size;
|
|
6
|
+
return {
|
|
7
|
+
end: start + record.size - 1,
|
|
8
|
+
getPort (offset = 0) {
|
|
9
|
+
if (!Number.isInteger(offset) || offset < 0 || offset >= record.size) throw new PortoError('offsetInvalid', `offset must be an integer between 0 and ${record.size - 1}.`);
|
|
10
|
+
return start + offset;
|
|
11
|
+
},
|
|
12
|
+
index: record.index,
|
|
13
|
+
start
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function checkIsAddressAvailable(port, host, isAutomatic) {
|
|
17
|
+
return new Promise((resolve, reject)=>{
|
|
18
|
+
const server = createServer();
|
|
19
|
+
server.once('error', (error)=>{
|
|
20
|
+
if ('EADDRINUSE' === error.code || 'EACCES' === error.code) resolve(false);
|
|
21
|
+
else if (isAutomatic && host.includes(':') && ('EAFNOSUPPORT' === error.code || 'EADDRNOTAVAIL' === error.code)) resolve(true);
|
|
22
|
+
else reject(error);
|
|
23
|
+
});
|
|
24
|
+
server.listen({
|
|
25
|
+
exclusive: true,
|
|
26
|
+
host,
|
|
27
|
+
ipv6Only: true,
|
|
28
|
+
port
|
|
29
|
+
}, ()=>{
|
|
30
|
+
server.close((error)=>{
|
|
31
|
+
if (error) reject(error);
|
|
32
|
+
else resolve(true);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function getProbeHosts() {
|
|
38
|
+
const interfaceHosts = Object.entries(networkInterfaces()).flatMap(([name, addresses])=>(addresses ?? []).map((address)=>{
|
|
39
|
+
if ('IPv6' !== address.family || 0 === address.scopeid) return address.address;
|
|
40
|
+
const zone = 'win32' === process.platform ? address.scopeid : name;
|
|
41
|
+
return `${address.address}%${zone}`;
|
|
42
|
+
}));
|
|
43
|
+
return new Set([
|
|
44
|
+
'0.0.0.0',
|
|
45
|
+
'127.0.0.1',
|
|
46
|
+
'::',
|
|
47
|
+
'::1',
|
|
48
|
+
...interfaceHosts
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
async function listBusyPorts(start, end, { host, limit = 1 / 0 } = {}) {
|
|
52
|
+
const busyPorts = [];
|
|
53
|
+
const hosts = void 0 === host ? getProbeHosts() : [
|
|
54
|
+
host
|
|
55
|
+
];
|
|
56
|
+
for(let port = start; port <= end; port += 1)for (const probeHost of hosts)if (!await checkIsAddressAvailable(port, probeHost, void 0 === host)) {
|
|
57
|
+
busyPorts.push(port);
|
|
58
|
+
if (busyPorts.length === limit) return busyPorts;
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return busyPorts;
|
|
62
|
+
}
|
|
63
|
+
async function checkHasBusyPort(start, end, host) {
|
|
64
|
+
const busyPorts = await listBusyPorts(start, end, {
|
|
65
|
+
host,
|
|
66
|
+
limit: 1
|
|
67
|
+
});
|
|
68
|
+
return busyPorts.length > 0;
|
|
69
|
+
}
|
|
70
|
+
export { buildBlock, checkHasBusyPort, listBusyPorts };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SetRequired } from 'type-fest';
|
|
2
|
+
import type { ReserveOptions } from './index.js';
|
|
3
|
+
type ReservationRecord = SetRequired<Omit<ReserveOptions, 'vars'>, 'idleTtlMinutes' | 'size' | 'start'> & {
|
|
4
|
+
index: number;
|
|
5
|
+
keep: boolean;
|
|
6
|
+
lastUsedAt: string;
|
|
7
|
+
ports: Array<number>;
|
|
8
|
+
worktree: string;
|
|
9
|
+
worktreeId: string;
|
|
10
|
+
};
|
|
11
|
+
declare function getRegistryPath(commonDirectory: string): string;
|
|
12
|
+
declare function updateRegistry<Result>(commonDirectory: string, handleRecords: (records: Array<ReservationRecord>) => Promise<Result> | Result): Promise<Result>;
|
|
13
|
+
export { getRegistryPath, updateRegistry };
|
|
14
|
+
export type { ReservationRecord };
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import proper_lockfile from "proper-lockfile";
|
|
4
|
+
import { PortoError } from "./error.js";
|
|
5
|
+
import { checkIsFileMissing, writeFileAtomically } from "./files.js";
|
|
6
|
+
import { REGISTRY_SCHEMA } from "./schemas.js";
|
|
7
|
+
function getRegistryPath(commonDirectory) {
|
|
8
|
+
return node_path.join(commonDirectory, 'porto-registry.json');
|
|
9
|
+
}
|
|
10
|
+
async function listReservations(filePath) {
|
|
11
|
+
try {
|
|
12
|
+
return REGISTRY_SCHEMA.parse(JSON.parse(await readFile(filePath, 'utf8')));
|
|
13
|
+
} catch (error) {
|
|
14
|
+
if (checkIsFileMissing(error)) return [];
|
|
15
|
+
throw new PortoError('registryInvalid', filePath, {
|
|
16
|
+
cause: error
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function writeReservations(filePath, records, previousContents) {
|
|
21
|
+
const contents = JSON.stringify(records);
|
|
22
|
+
if (contents !== previousContents) await writeFileAtomically(filePath, `${contents}\n`);
|
|
23
|
+
}
|
|
24
|
+
async function updateRegistry(commonDirectory, handleRecords) {
|
|
25
|
+
const filePath = getRegistryPath(commonDirectory);
|
|
26
|
+
const unlock = await proper_lockfile.lock(filePath, {
|
|
27
|
+
realpath: false,
|
|
28
|
+
retries: {
|
|
29
|
+
factor: 1,
|
|
30
|
+
maxTimeout: 100,
|
|
31
|
+
minTimeout: 100,
|
|
32
|
+
retries: 200
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
try {
|
|
36
|
+
const records = await listReservations(filePath);
|
|
37
|
+
const previousContents = JSON.stringify(records);
|
|
38
|
+
const result = await handleRecords(records);
|
|
39
|
+
await writeReservations(filePath, records, previousContents);
|
|
40
|
+
return result;
|
|
41
|
+
} finally{
|
|
42
|
+
await unlock();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export { getRegistryPath, updateRegistry };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ReservationRecord } from './registry.js';
|
|
2
|
+
import type { Vars } from './vars.js';
|
|
3
|
+
import { fetchGitContext } from './git.js';
|
|
4
|
+
import { parseOptions } from './schemas.js';
|
|
5
|
+
type ReserveOptions = Partial<ReturnType<typeof parseOptions>> & {
|
|
6
|
+
vars?: undefined | Vars;
|
|
7
|
+
};
|
|
8
|
+
declare function checkIsExpired(record: Pick<ReservationRecord, 'idleTtlMinutes' | 'keep' | 'lastUsedAt'>, now: number): boolean;
|
|
9
|
+
declare function issuePorts(record: ReservationRecord, portsCount: number): {
|
|
10
|
+
end: number;
|
|
11
|
+
getPort(offset?: number): number;
|
|
12
|
+
index: number;
|
|
13
|
+
start: number;
|
|
14
|
+
} & {
|
|
15
|
+
ports: number[];
|
|
16
|
+
};
|
|
17
|
+
declare function removeExpiredRecords(records: Array<ReservationRecord>, now: number): Promise<{
|
|
18
|
+
end: number;
|
|
19
|
+
getPort(offset?: number): number;
|
|
20
|
+
index: number;
|
|
21
|
+
start: number;
|
|
22
|
+
}[]>;
|
|
23
|
+
declare function reserveBlock<Result>({ git, host, idleTtlMinutes, keep, portsCount, size, start, }: ReturnType<typeof parseOptions> & {
|
|
24
|
+
git?: Awaited<ReturnType<typeof fetchGitContext>>;
|
|
25
|
+
portsCount: number;
|
|
26
|
+
}, prepare: (block: ReturnType<typeof issuePorts>) => Result): Promise<Result>;
|
|
27
|
+
declare function reserve(options?: ReserveOptions): Promise<{
|
|
28
|
+
end: number;
|
|
29
|
+
getPort(offset?: number): number;
|
|
30
|
+
index: number;
|
|
31
|
+
start: number;
|
|
32
|
+
} & {
|
|
33
|
+
ports: number[];
|
|
34
|
+
}>;
|
|
35
|
+
export { checkIsExpired, removeExpiredRecords, reserve, reserveBlock };
|
|
36
|
+
export type { ReserveOptions };
|
package/dist/reserve.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { range, remove, union } from "es-toolkit";
|
|
2
|
+
import { PortoError } from "./error.js";
|
|
3
|
+
import { fetchGitContext } from "./git.js";
|
|
4
|
+
import { buildBlock, checkHasBusyPort } from "./ports.js";
|
|
5
|
+
import { updateRegistry } from "./registry.js";
|
|
6
|
+
import { parseOptions } from "./schemas.js";
|
|
7
|
+
import { assertVarsFit, parseVarEntries } from "./vars.js";
|
|
8
|
+
async function allocateRecord(records, options) {
|
|
9
|
+
for(let index = 0; options.start + (index + 1) * options.size - 1 <= 65535; index += 1){
|
|
10
|
+
const record = {
|
|
11
|
+
...options,
|
|
12
|
+
index
|
|
13
|
+
};
|
|
14
|
+
const block = buildBlock(record);
|
|
15
|
+
const hasOverlap = records.some((reserved)=>{
|
|
16
|
+
const reservedBlock = buildBlock(reserved);
|
|
17
|
+
return block.start <= reservedBlock.end && block.end >= reservedBlock.start;
|
|
18
|
+
});
|
|
19
|
+
if (!hasOverlap && !await checkHasBusyPort(block.start, block.end, options.host)) return record;
|
|
20
|
+
}
|
|
21
|
+
throw new PortoError('blockUnavailable');
|
|
22
|
+
}
|
|
23
|
+
function checkIsExpired(record, now) {
|
|
24
|
+
return !record.keep && now - Date.parse(record.lastUsedAt) > 60000 * record.idleTtlMinutes;
|
|
25
|
+
}
|
|
26
|
+
function issuePorts(record, portsCount) {
|
|
27
|
+
const block = buildBlock(record);
|
|
28
|
+
record.ports = union(record.ports, range(block.start, block.start + portsCount));
|
|
29
|
+
return Object.assign(block, {
|
|
30
|
+
ports: record.ports
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
async function removeExpiredRecords(records, now) {
|
|
34
|
+
const candidates = await Promise.all(records.filter((record)=>checkIsExpired(record, now)).map(async (record)=>{
|
|
35
|
+
const { end, start } = buildBlock(record);
|
|
36
|
+
return {
|
|
37
|
+
hasBusyPort: await checkHasBusyPort(start, end, record.host),
|
|
38
|
+
record
|
|
39
|
+
};
|
|
40
|
+
}));
|
|
41
|
+
const expiredRecords = candidates.filter(({ hasBusyPort })=>!hasBusyPort).map(({ record })=>record);
|
|
42
|
+
remove(records, (record)=>expiredRecords.includes(record));
|
|
43
|
+
return expiredRecords.map((record)=>buildBlock(record));
|
|
44
|
+
}
|
|
45
|
+
async function reserveBlock({ git, host, idleTtlMinutes, keep, portsCount, size, start }, prepare) {
|
|
46
|
+
assertVarsFit(portsCount, size);
|
|
47
|
+
const { commonDirectory, worktree, worktreeId } = git ?? await fetchGitContext();
|
|
48
|
+
return updateRegistry(commonDirectory, async (records)=>{
|
|
49
|
+
const now = Date.now();
|
|
50
|
+
const existingRecord = records.find((record)=>record.worktreeId === worktreeId && record.start === start && record.size === size);
|
|
51
|
+
const lastUsedAt = new Date(now).toISOString();
|
|
52
|
+
if (existingRecord) Object.assign(existingRecord, {
|
|
53
|
+
host: host ?? existingRecord.host,
|
|
54
|
+
idleTtlMinutes,
|
|
55
|
+
keep: keep ?? existingRecord.keep,
|
|
56
|
+
lastUsedAt,
|
|
57
|
+
worktree
|
|
58
|
+
});
|
|
59
|
+
await removeExpiredRecords(records, now);
|
|
60
|
+
const record = existingRecord ?? await allocateRecord(records, {
|
|
61
|
+
host,
|
|
62
|
+
idleTtlMinutes,
|
|
63
|
+
keep: keep ?? false,
|
|
64
|
+
lastUsedAt,
|
|
65
|
+
ports: [],
|
|
66
|
+
size,
|
|
67
|
+
start,
|
|
68
|
+
worktree,
|
|
69
|
+
worktreeId
|
|
70
|
+
});
|
|
71
|
+
if (!existingRecord) records.push(record);
|
|
72
|
+
return prepare(issuePorts(record, portsCount));
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function reserve(options = {}) {
|
|
76
|
+
const settings = parseOptions(options);
|
|
77
|
+
const portsCount = void 0 === options.vars ? 0 : parseVarEntries(options.vars).length;
|
|
78
|
+
const block = await reserveBlock({
|
|
79
|
+
...settings,
|
|
80
|
+
portsCount
|
|
81
|
+
}, (reservedBlock)=>reservedBlock);
|
|
82
|
+
return block;
|
|
83
|
+
}
|
|
84
|
+
export { checkIsExpired, removeExpiredRecords, reserve, reserveBlock };
|