@infosupport/huddle-cli 1.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/README.md +68 -0
- package/dist/api.js +73 -0
- package/dist/config.js +43 -0
- package/dist/experiment.js +99 -0
- package/dist/firewall.js +69 -0
- package/dist/images.js +31 -0
- package/dist/index.js +235 -0
- package/dist/init.js +112 -0
- package/dist/runtime.js +61 -0
- package/dist/self-update.js +76 -0
- package/dist/start.js +91 -0
- package/dist/utils.js +73 -0
- package/package.json +39 -0
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Huddle CLI
|
|
2
|
+
|
|
3
|
+
Cross-platform Node CLI for Huddle. The CLI talks to the existing Huddle REST API; container management and firewall resolution therefore live in the gateway, not re-implemented in the command client.
|
|
4
|
+
|
|
5
|
+
## Installing
|
|
6
|
+
|
|
7
|
+
The packages are public, so you don't need a GitHub token or registry login.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g @infosupport/huddle-cli
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Starting Huddle
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
huddle init
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Pulls `ghcr.io/infosupport/huddle:latest` and starts the container. Works with Docker and Podman: the runtime is detected automatically (Docker first, then Podman), or pick one explicitly with `huddle init --runtime <docker|podman>` or the `HUDDLE_RUNTIME` env var. If you run `huddle` while Huddle isn't running, you automatically get a hint to run this command.
|
|
20
|
+
|
|
21
|
+
## Starting devcontainers
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
huddle # start an IntelliJ devcontainer for the current directory
|
|
25
|
+
huddle ./project # start for a specific directory
|
|
26
|
+
huddle --ide rider
|
|
27
|
+
huddle --ide vscode --name devcontainer-demo
|
|
28
|
+
huddle fw list
|
|
29
|
+
huddle firewall list -i
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Default API URL: `http://localhost:3000`. Override it with `--url` or `HUDDLE_URL`.
|
|
33
|
+
|
|
34
|
+
## Experiments
|
|
35
|
+
|
|
36
|
+
An experiment is a complete Huddle version (CLI + all Docker images) tied to a single GitHub issue. Push a branch `experiment/<issue-number>-<description>` and the pipeline publishes everything under the tag `experiment-<issue-number>`, fully separated from the normal releases.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
huddle init --experiment 123 # activate the experiment and run init
|
|
40
|
+
huddle experiment use 123 # same as above
|
|
41
|
+
huddle experiment status # show the active channel and CLI version
|
|
42
|
+
huddle experiment reset # back to the stable release
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
On activation the CLI stores the experiment in `~/.huddle/config.json`, reinstalls itself as `@infosupport/huddle-cli@experiment-123`, restarts itself, and then runs `huddle init` with the `experiment-123` Docker images. So the CLI and the images always run on exactly the same version.
|
|
46
|
+
|
|
47
|
+
The experiment stays active — including on the next `huddle init` — until you explicitly run `huddle experiment reset`. That removes the local experiment config, reinstalls the stable CLI, and from then on `huddle init` uses the `latest` images again.
|
|
48
|
+
|
|
49
|
+
## Development
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npm install
|
|
53
|
+
npm run build
|
|
54
|
+
npm run install-global
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Main flags:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
--ide <intellij|rider|vscode>
|
|
61
|
+
--workspace <path>
|
|
62
|
+
--name <name>
|
|
63
|
+
--image <image>
|
|
64
|
+
--empty
|
|
65
|
+
-i, --interactive
|
|
66
|
+
--container <name>
|
|
67
|
+
--status <requested|allow|deny>
|
|
68
|
+
```
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.del = exports.put = exports.post = exports.get = exports.ApiError = void 0;
|
|
4
|
+
exports.setBaseUrl = setBaseUrl;
|
|
5
|
+
exports.apiCall = apiCall;
|
|
6
|
+
let baseUrl = normalizeBaseUrl(process.env.HUDDLE_URL ?? 'http://localhost:3000');
|
|
7
|
+
class ApiError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
constructor(message, status) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.name = 'ApiError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
exports.ApiError = ApiError;
|
|
16
|
+
function setBaseUrl(url) {
|
|
17
|
+
baseUrl = normalizeBaseUrl(url);
|
|
18
|
+
}
|
|
19
|
+
async function apiCall(method, path, body) {
|
|
20
|
+
let res;
|
|
21
|
+
try {
|
|
22
|
+
res = await fetch(`${baseUrl}${path}`, {
|
|
23
|
+
method,
|
|
24
|
+
headers: body !== undefined ? { 'content-type': 'application/json' } : {},
|
|
25
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
30
|
+
throw new ApiError(`Cannot reach Huddle API at ${baseUrl}: ${detail}`);
|
|
31
|
+
}
|
|
32
|
+
const raw = await res.text();
|
|
33
|
+
const payload = parsePayload(raw);
|
|
34
|
+
if (!res.ok) {
|
|
35
|
+
const msg = errorMessage(payload) ?? res.statusText;
|
|
36
|
+
throw new ApiError(`${method} ${path} -> ${res.status}: ${msg}`, res.status);
|
|
37
|
+
}
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
const get = (path) => apiCall('GET', path);
|
|
41
|
+
exports.get = get;
|
|
42
|
+
const post = (path, body) => apiCall('POST', path, body);
|
|
43
|
+
exports.post = post;
|
|
44
|
+
const put = (path, body) => apiCall('PUT', path, body);
|
|
45
|
+
exports.put = put;
|
|
46
|
+
const del = (path) => apiCall('DELETE', path);
|
|
47
|
+
exports.del = del;
|
|
48
|
+
function normalizeBaseUrl(url) {
|
|
49
|
+
const trimmed = url.trim();
|
|
50
|
+
if (!trimmed)
|
|
51
|
+
throw new Error('Huddle URL must not be empty');
|
|
52
|
+
return trimmed.replace(/\/+$/, '');
|
|
53
|
+
}
|
|
54
|
+
function parsePayload(raw) {
|
|
55
|
+
if (!raw)
|
|
56
|
+
return undefined;
|
|
57
|
+
try {
|
|
58
|
+
return JSON.parse(raw);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return raw;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function errorMessage(payload) {
|
|
65
|
+
if (!payload || typeof payload !== 'object')
|
|
66
|
+
return typeof payload === 'string' ? payload : undefined;
|
|
67
|
+
const obj = payload;
|
|
68
|
+
if (typeof obj.message === 'string')
|
|
69
|
+
return obj.message;
|
|
70
|
+
if (typeof obj.error === 'string')
|
|
71
|
+
return obj.error;
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.configPath = configPath;
|
|
7
|
+
exports.readConfig = readConfig;
|
|
8
|
+
exports.writeConfig = writeConfig;
|
|
9
|
+
exports.activeExperiment = activeExperiment;
|
|
10
|
+
exports.imageTag = imageTag;
|
|
11
|
+
const fs_1 = __importDefault(require("fs"));
|
|
12
|
+
const os_1 = __importDefault(require("os"));
|
|
13
|
+
const path_1 = __importDefault(require("path"));
|
|
14
|
+
const CONFIG_DIR = path_1.default.join(os_1.default.homedir(), '.huddle');
|
|
15
|
+
const CONFIG_PATH = path_1.default.join(CONFIG_DIR, 'config.json');
|
|
16
|
+
function configPath() {
|
|
17
|
+
return CONFIG_PATH;
|
|
18
|
+
}
|
|
19
|
+
function readConfig() {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(fs_1.default.readFileSync(CONFIG_PATH, 'utf8'));
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function writeConfig(config) {
|
|
28
|
+
fs_1.default.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
29
|
+
fs_1.default.writeFileSync(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
|
|
30
|
+
}
|
|
31
|
+
/** Active experiment number, or undefined when running on stable. */
|
|
32
|
+
function activeExperiment() {
|
|
33
|
+
const cfg = readConfig();
|
|
34
|
+
if (cfg.channel === 'experiment' && Number.isInteger(cfg.experiment) && cfg.experiment > 0) {
|
|
35
|
+
return cfg.experiment;
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
/** Docker image tag that belongs to the active channel. */
|
|
40
|
+
function imageTag() {
|
|
41
|
+
const experiment = activeExperiment();
|
|
42
|
+
return experiment !== undefined ? `experiment-${experiment}` : 'latest';
|
|
43
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cliExperiment = cliExperiment;
|
|
4
|
+
exports.parseIssueNumber = parseIssueNumber;
|
|
5
|
+
exports.ensureCliForChannel = ensureCliForChannel;
|
|
6
|
+
exports.runExperimentUse = runExperimentUse;
|
|
7
|
+
exports.runExperimentReset = runExperimentReset;
|
|
8
|
+
exports.runExperimentStatus = runExperimentStatus;
|
|
9
|
+
const utils_1 = require("./utils");
|
|
10
|
+
const config_1 = require("./config");
|
|
11
|
+
const self_update_1 = require("./self-update");
|
|
12
|
+
const images_1 = require("./images");
|
|
13
|
+
const init_1 = require("./init");
|
|
14
|
+
/**
|
|
15
|
+
* Experiment number baked into the version of this CLI build.
|
|
16
|
+
* Experimental builds get a version like `0.0.0-experiment-123.42` from the
|
|
17
|
+
* pipeline; stable releases don't match here.
|
|
18
|
+
*/
|
|
19
|
+
function cliExperiment() {
|
|
20
|
+
const match = (0, self_update_1.cliVersion)().match(/-experiment-(\d+)\./);
|
|
21
|
+
return match ? Number(match[1]) : undefined;
|
|
22
|
+
}
|
|
23
|
+
function parseIssueNumber(raw) {
|
|
24
|
+
const issue = Number(raw);
|
|
25
|
+
if (!raw || !Number.isInteger(issue) || issue <= 0) {
|
|
26
|
+
throw new Error(`Invalid issue number: ${raw ?? '(empty)'}. Use e.g. "huddle experiment use 123".`);
|
|
27
|
+
}
|
|
28
|
+
return issue;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Ensures the running CLI process belongs to the configured channel.
|
|
32
|
+
* This function only determines which version should be running; the switch
|
|
33
|
+
* itself (install + restart) is done by self-update.ts. On a switch this
|
|
34
|
+
* function does not return (process.exit with the exit code of the new process).
|
|
35
|
+
*/
|
|
36
|
+
function ensureCliForChannel(relaunchArgs) {
|
|
37
|
+
const wanted = (0, config_1.activeExperiment)();
|
|
38
|
+
if (wanted === cliExperiment())
|
|
39
|
+
return;
|
|
40
|
+
const spec = wanted !== undefined ? `${self_update_1.CLI_PACKAGE}@experiment-${wanted}` : `${self_update_1.CLI_PACKAGE}@latest`;
|
|
41
|
+
try {
|
|
42
|
+
(0, self_update_1.switchGlobalCli)(spec, relaunchArgs);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
46
|
+
throw new Error(`${message} Use "huddle experiment reset" to go back to stable (config: ${(0, config_1.configPath)()}).`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Activates an experiment and then runs init. This is the shared path behind
|
|
51
|
+
* `huddle experiment use <nr>` and `huddle init --experiment <nr>`.
|
|
52
|
+
*/
|
|
53
|
+
async function runExperimentUse(issue, initOpts = {}) {
|
|
54
|
+
const previous = (0, config_1.readConfig)();
|
|
55
|
+
(0, config_1.writeConfig)({ ...previous, channel: 'experiment', experiment: issue });
|
|
56
|
+
console.log((0, utils_1.green)(`Experiment ${issue} activated`) + (0, utils_1.dim)(` (${(0, config_1.configPath)()})`));
|
|
57
|
+
const relaunchArgs = ['init', ...(initOpts.runtime ? ['--runtime', initOpts.runtime] : [])];
|
|
58
|
+
try {
|
|
59
|
+
ensureCliForChannel(relaunchArgs);
|
|
60
|
+
}
|
|
61
|
+
catch (err) {
|
|
62
|
+
// Activation failed → roll back the config so a subsequent `huddle init`
|
|
63
|
+
// doesn't stay stuck on an experiment that cannot be installed.
|
|
64
|
+
(0, config_1.writeConfig)(previous);
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
|
|
68
|
+
}
|
|
69
|
+
/** Puts Huddle back on the stable release. */
|
|
70
|
+
async function runExperimentReset() {
|
|
71
|
+
const config = (0, config_1.readConfig)();
|
|
72
|
+
if ((0, config_1.activeExperiment)() === undefined && cliExperiment() === undefined) {
|
|
73
|
+
console.log('No experiment active; Huddle is already running on stable.');
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
delete config.experiment;
|
|
77
|
+
config.channel = 'stable';
|
|
78
|
+
(0, config_1.writeConfig)(config);
|
|
79
|
+
console.log((0, utils_1.green)('Experiment config removed') + (0, utils_1.dim)(` (${(0, config_1.configPath)()})`));
|
|
80
|
+
// If an experimental CLI is still running, this installs the stable version
|
|
81
|
+
// and the new CLI restarts itself to show the status.
|
|
82
|
+
ensureCliForChannel(['experiment', 'status']);
|
|
83
|
+
runExperimentStatus();
|
|
84
|
+
}
|
|
85
|
+
function runExperimentStatus() {
|
|
86
|
+
const experiment = (0, config_1.activeExperiment)();
|
|
87
|
+
console.log(`CLI version: ${(0, self_update_1.cliVersion)()}`);
|
|
88
|
+
if (experiment !== undefined) {
|
|
89
|
+
console.log(`Channel: experiment ${experiment} (images: experiment-${experiment})`);
|
|
90
|
+
console.log((0, utils_1.dim)('Back to stable: huddle experiment reset'));
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
console.log('Channel: stable (images: latest)');
|
|
94
|
+
}
|
|
95
|
+
if (cliExperiment() !== experiment) {
|
|
96
|
+
console.log((0, utils_1.yellow)('[!] CLI version does not belong to the configured channel; ' +
|
|
97
|
+
'the next "huddle init" fixes this automatically.'));
|
|
98
|
+
}
|
|
99
|
+
}
|
package/dist/firewall.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runFirewallList = runFirewallList;
|
|
4
|
+
const api_1 = require("./api");
|
|
5
|
+
const utils_1 = require("./utils");
|
|
6
|
+
async function runFirewallList(opts) {
|
|
7
|
+
const qs = new URLSearchParams({ status: opts.status ?? 'requested' });
|
|
8
|
+
if (opts.container)
|
|
9
|
+
qs.set('container', opts.container);
|
|
10
|
+
const rules = await (0, api_1.get)(`/api/rules?${qs}`);
|
|
11
|
+
if (rules.length === 0) {
|
|
12
|
+
console.log((0, utils_1.dim)('No pending firewall requests.'));
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (!opts.interactive) {
|
|
16
|
+
printRulesTable(rules);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
console.log(`${(0, utils_1.bold)(String(rules.length))} pending request(s). Review each:\n`);
|
|
20
|
+
for (let i = 0; i < rules.length; i++) {
|
|
21
|
+
await reviewRule(rules[i], i + 1, rules.length);
|
|
22
|
+
console.log();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function reviewRule(rule, idx, total) {
|
|
26
|
+
const target = formatTarget(rule);
|
|
27
|
+
const scope = rule.container_id ? `container: ${rule.container_id}` : 'global';
|
|
28
|
+
const example = rule.last_path ? `, example: ${rule.last_path}` : '';
|
|
29
|
+
console.log(`[${idx}/${total}] ${(0, utils_1.bold)((0, utils_1.cyan)(target))} ${(0, utils_1.dim)(`(${scope}, ${rule.request_count} req, ${(0, utils_1.formatTime)(rule.last_seen)}${example})`)}`);
|
|
30
|
+
const key = await (0, utils_1.promptKey)(` ${(0, utils_1.bold)('[a]')}llow ${(0, utils_1.bold)('[d]')}eny ${(0, utils_1.bold)('[A]')}llow global ${(0, utils_1.bold)('[D]')}eny global ${(0, utils_1.bold)('[s]')}kip > `);
|
|
31
|
+
switch (key) {
|
|
32
|
+
case 'a':
|
|
33
|
+
await resolveRule(rule, 'allow', 'rule');
|
|
34
|
+
console.log((0, utils_1.green)(` [OK] Allowed for ${rule.container_id ?? 'global'}`));
|
|
35
|
+
break;
|
|
36
|
+
case 'd':
|
|
37
|
+
await resolveRule(rule, 'deny', 'rule');
|
|
38
|
+
console.log((0, utils_1.red)(` [OK] Blocked for ${rule.container_id ?? 'global'}`));
|
|
39
|
+
break;
|
|
40
|
+
case 'A':
|
|
41
|
+
await resolveRule(rule, 'allow', 'global');
|
|
42
|
+
console.log((0, utils_1.green)(` [OK] Allowed globally: ${target}`));
|
|
43
|
+
break;
|
|
44
|
+
case 'D':
|
|
45
|
+
await resolveRule(rule, 'deny', 'global');
|
|
46
|
+
console.log((0, utils_1.red)(` [OK] Blocked globally: ${target}`));
|
|
47
|
+
break;
|
|
48
|
+
default:
|
|
49
|
+
console.log((0, utils_1.dim)(' Skipped'));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function resolveRule(rule, status, scope) {
|
|
53
|
+
await (0, api_1.post)(`/api/rules/${rule.id}/resolve`, { status, scope });
|
|
54
|
+
}
|
|
55
|
+
function printRulesTable(rules) {
|
|
56
|
+
const headers = ['ID', 'Status', 'Domain/path', 'Container', 'Requests', 'Seen'];
|
|
57
|
+
const rows = rules.map((r) => [
|
|
58
|
+
String(r.id),
|
|
59
|
+
r.status,
|
|
60
|
+
formatTarget(r),
|
|
61
|
+
r.container_id ?? '(global)',
|
|
62
|
+
String(r.request_count),
|
|
63
|
+
(0, utils_1.formatTime)(r.last_seen),
|
|
64
|
+
]);
|
|
65
|
+
(0, utils_1.printTable)(headers, rows);
|
|
66
|
+
}
|
|
67
|
+
function formatTarget(rule) {
|
|
68
|
+
return rule.path_pattern ? `${rule.domain}${rule.path_pattern}` : rule.domain;
|
|
69
|
+
}
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveImages = resolveImages;
|
|
4
|
+
exports.gatewayEnvFlags = gatewayEnvFlags;
|
|
5
|
+
const config_1 = require("./config");
|
|
6
|
+
function resolveImages() {
|
|
7
|
+
const experiment = (0, config_1.activeExperiment)();
|
|
8
|
+
const tag = (0, config_1.imageTag)();
|
|
9
|
+
return {
|
|
10
|
+
experiment,
|
|
11
|
+
tag,
|
|
12
|
+
image: process.env.HUDDLE_IMAGE ?? `ghcr.io/infosupport/huddle:${tag}`,
|
|
13
|
+
baseImages: [
|
|
14
|
+
{ image: process.env.BASE_IMAGE ?? `ghcr.io/infosupport/base-devimage:${tag}` },
|
|
15
|
+
{ image: process.env.BASE_IMAGE_RIDER ?? `ghcr.io/infosupport/base-devimage-rider:${tag}`, gatewayEnv: 'BASE_IMAGE_RIDER' },
|
|
16
|
+
{ image: process.env.BASE_IMAGE_INTELLIJ ?? `ghcr.io/infosupport/base-devimage-intellij:${tag}`, gatewayEnv: 'BASE_IMAGE_INTELLIJ' },
|
|
17
|
+
{ image: process.env.BASE_IMAGE_VSCODE ?? `ghcr.io/infosupport/base-devimage-vscode:${tag}`, gatewayEnv: 'BASE_IMAGE_VSCODE' },
|
|
18
|
+
],
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* `-e` flags for the gateway container. During an experiment (or with an
|
|
23
|
+
* explicit override) the gateway must start devcontainers from the same
|
|
24
|
+
* base images the CLI just pulled.
|
|
25
|
+
*/
|
|
26
|
+
function gatewayEnvFlags(resolved) {
|
|
27
|
+
return resolved.baseImages
|
|
28
|
+
.filter((b) => b.gatewayEnv && (resolved.experiment !== undefined || process.env[b.gatewayEnv]))
|
|
29
|
+
.map((b) => ` -e ${b.gatewayEnv}=${b.image}`)
|
|
30
|
+
.join('');
|
|
31
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
4
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
5
|
+
};
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const api_1 = require("./api");
|
|
10
|
+
const start_1 = require("./start");
|
|
11
|
+
const firewall_1 = require("./firewall");
|
|
12
|
+
const init_1 = require("./init");
|
|
13
|
+
const images_1 = require("./images");
|
|
14
|
+
const self_update_1 = require("./self-update");
|
|
15
|
+
const utils_1 = require("./utils");
|
|
16
|
+
const experiment_1 = require("./experiment");
|
|
17
|
+
const VALUE_FLAGS = new Set(['url', 'ide', 'name', 'image', 'workspace', 'container', 'status', 'runtime', 'experiment']);
|
|
18
|
+
const BOOLEAN_FLAGS = new Set(['help', 'h', 'empty', 'i', 'interactive', 'version', 'v']);
|
|
19
|
+
const COMMANDS = new Set(['start', 'firewall', 'fw', 'init', 'experiment', 'help', 'version']);
|
|
20
|
+
function parseArgs(argv) {
|
|
21
|
+
const positional = [];
|
|
22
|
+
const flags = {};
|
|
23
|
+
for (let i = 0; i < argv.length; i++) {
|
|
24
|
+
const arg = argv[i];
|
|
25
|
+
if (arg === '--') {
|
|
26
|
+
positional.push(...argv.slice(i + 1));
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
if (arg.startsWith('--')) {
|
|
30
|
+
const raw = arg.slice(2);
|
|
31
|
+
const eq = raw.indexOf('=');
|
|
32
|
+
const name = eq >= 0 ? raw.slice(0, eq) : raw;
|
|
33
|
+
if (!name)
|
|
34
|
+
throw new Error(`Invalid option: ${arg}`);
|
|
35
|
+
if (eq >= 0) {
|
|
36
|
+
flags[name] = raw.slice(eq + 1);
|
|
37
|
+
}
|
|
38
|
+
else if (VALUE_FLAGS.has(name)) {
|
|
39
|
+
const next = argv[i + 1];
|
|
40
|
+
if (next === undefined || next.startsWith('-')) {
|
|
41
|
+
throw new Error(`Option --${name} expects a value`);
|
|
42
|
+
}
|
|
43
|
+
flags[name] = next;
|
|
44
|
+
i++;
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
flags[name] = true;
|
|
48
|
+
}
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (arg.startsWith('-') && arg !== '-') {
|
|
52
|
+
const raw = arg.slice(1);
|
|
53
|
+
if ([...raw].every((c) => BOOLEAN_FLAGS.has(c))) {
|
|
54
|
+
for (const c of raw)
|
|
55
|
+
flags[c] = true;
|
|
56
|
+
}
|
|
57
|
+
else if (raw.length === 1 && VALUE_FLAGS.has(raw)) {
|
|
58
|
+
const next = argv[i + 1];
|
|
59
|
+
if (next === undefined || next.startsWith('-')) {
|
|
60
|
+
throw new Error(`Option -${raw} expects a value`);
|
|
61
|
+
}
|
|
62
|
+
flags[raw] = next;
|
|
63
|
+
i++;
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
67
|
+
}
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
positional.push(arg);
|
|
71
|
+
}
|
|
72
|
+
return { positional, flags };
|
|
73
|
+
}
|
|
74
|
+
function readVersion() {
|
|
75
|
+
// npm always includes package.json in the published tarball, and it holds the
|
|
76
|
+
// version published by CI (GitVersion) to the packages registry.
|
|
77
|
+
// dist/index.js -> ../package.json.
|
|
78
|
+
try {
|
|
79
|
+
const pkgPath = path_1.default.join(__dirname, '..', 'package.json');
|
|
80
|
+
const pkg = JSON.parse(fs_1.default.readFileSync(pkgPath, 'utf8'));
|
|
81
|
+
if (typeof pkg.version === 'string')
|
|
82
|
+
return pkg.version;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// fall back to 'unknown' below
|
|
86
|
+
}
|
|
87
|
+
return 'unknown';
|
|
88
|
+
}
|
|
89
|
+
function printHelp() {
|
|
90
|
+
console.log(`
|
|
91
|
+
Usage:
|
|
92
|
+
huddle [options] [folder] Start a devcontainer in the current or given folder
|
|
93
|
+
huddle start [options] [folder] Explicitly start a devcontainer
|
|
94
|
+
huddle init [options] Pull the Huddle + devcontainer base images and
|
|
95
|
+
start them via Docker or Podman
|
|
96
|
+
huddle firewall list [options] Show firewall requests
|
|
97
|
+
huddle fw list [options] Alias for firewall list
|
|
98
|
+
huddle experiment use <nr> Activate the experimental build of issue <nr>
|
|
99
|
+
and run init
|
|
100
|
+
huddle experiment reset Back to the stable release
|
|
101
|
+
huddle experiment status Show the active channel and CLI version
|
|
102
|
+
|
|
103
|
+
Init options:
|
|
104
|
+
--runtime <docker|podman> Container runtime (default: auto-detected;
|
|
105
|
+
also via the HUDDLE_RUNTIME env var)
|
|
106
|
+
--experiment <nr> Use the experimental build of issue <nr>
|
|
107
|
+
(same as "huddle experiment use <nr>")
|
|
108
|
+
|
|
109
|
+
Start options:
|
|
110
|
+
--ide <intellij|rider|vscode> IDE (default: intellij)
|
|
111
|
+
--workspace <path> Workspace directory (default: current directory)
|
|
112
|
+
--name <name> Container name (default: devcontainer-<foldername>)
|
|
113
|
+
--image <image> Use a specific image
|
|
114
|
+
--empty Empty container without a workspace
|
|
115
|
+
|
|
116
|
+
Firewall options:
|
|
117
|
+
-i, --interactive Interactively approve/deny
|
|
118
|
+
--container <name> Filter by container
|
|
119
|
+
--status <requested|allow|deny> Filter by status (default: requested)
|
|
120
|
+
|
|
121
|
+
Global options:
|
|
122
|
+
--url <url> Huddle URL (default: http://localhost:3000)
|
|
123
|
+
Or via the HUDDLE_URL env var
|
|
124
|
+
--help, -h Show help
|
|
125
|
+
--version, -v Show version (as published to
|
|
126
|
+
GitHub packages)
|
|
127
|
+
`);
|
|
128
|
+
}
|
|
129
|
+
async function main() {
|
|
130
|
+
let parsed;
|
|
131
|
+
try {
|
|
132
|
+
parsed = parseArgs(process.argv.slice(2));
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
136
|
+
console.error('Run "huddle --help" for help.');
|
|
137
|
+
process.exit(1);
|
|
138
|
+
}
|
|
139
|
+
const { positional, flags } = parsed;
|
|
140
|
+
const [cmd, sub] = positional;
|
|
141
|
+
if (flagBool(flags, 'version', 'v') || cmd === 'version') {
|
|
142
|
+
console.log(readVersion());
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (flagBool(flags, 'help', 'h') || cmd === 'help') {
|
|
146
|
+
printHelp();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const url = flagString(flags, 'url') ?? process.env.HUDDLE_URL ?? 'http://localhost:3000';
|
|
150
|
+
(0, api_1.setBaseUrl)(url);
|
|
151
|
+
const startsWithExistingPath = cmd !== undefined && !COMMANDS.has(cmd) && fs_1.default.existsSync(path_1.default.resolve(cmd));
|
|
152
|
+
if (!cmd || cmd === 'start' || startsWithExistingPath) {
|
|
153
|
+
const startArgs = cmd === 'start' ? positional.slice(1) : startsWithExistingPath ? positional : [];
|
|
154
|
+
if (startArgs.length > 1 && !flagString(flags, 'workspace')) {
|
|
155
|
+
throw new Error(`Too many start arguments: ${startArgs.slice(1).join(' ')}`);
|
|
156
|
+
}
|
|
157
|
+
await (0, start_1.runStart)({
|
|
158
|
+
ide: flagString(flags, 'ide') ?? 'intellij',
|
|
159
|
+
workspace: flagString(flags, 'workspace') ?? startArgs[0],
|
|
160
|
+
name: flagString(flags, 'name'),
|
|
161
|
+
image: flagString(flags, 'image'),
|
|
162
|
+
empty: flagBool(flags, 'empty'),
|
|
163
|
+
});
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (cmd === 'init') {
|
|
167
|
+
// Shows the exact CLI build, so with experiments it's immediately visible
|
|
168
|
+
// which version is running.
|
|
169
|
+
console.log((0, utils_1.dim)(`CLI version: ${(0, self_update_1.cliVersion)()} (Node ${process.version}, ${process.platform}/${process.arch})`));
|
|
170
|
+
const initOpts = { runtime: flagString(flags, 'runtime') };
|
|
171
|
+
const experimentFlag = flagString(flags, 'experiment');
|
|
172
|
+
if (experimentFlag !== undefined) {
|
|
173
|
+
await (0, experiment_1.runExperimentUse)((0, experiment_1.parseIssueNumber)(experimentFlag), initOpts);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
// While an experiment is active, the CLI itself must also run on the matching
|
|
177
|
+
// version; if needed this installs the right version and restarts the
|
|
178
|
+
// process itself (in which case it does not return).
|
|
179
|
+
(0, experiment_1.ensureCliForChannel)(process.argv.slice(2));
|
|
180
|
+
await (0, init_1.runInit)(initOpts, (0, images_1.resolveImages)());
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (cmd === 'experiment') {
|
|
184
|
+
const subCmd = sub ?? 'status';
|
|
185
|
+
if (subCmd === 'use') {
|
|
186
|
+
await (0, experiment_1.runExperimentUse)((0, experiment_1.parseIssueNumber)(positional[2]), { runtime: flagString(flags, 'runtime') });
|
|
187
|
+
}
|
|
188
|
+
else if (subCmd === 'reset') {
|
|
189
|
+
await (0, experiment_1.runExperimentReset)();
|
|
190
|
+
}
|
|
191
|
+
else if (subCmd === 'status') {
|
|
192
|
+
(0, experiment_1.runExperimentStatus)();
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
console.error(`Unknown experiment subcommand: ${subCmd}`);
|
|
196
|
+
console.error('Usage: huddle experiment <use <nr>|reset|status>');
|
|
197
|
+
process.exit(1);
|
|
198
|
+
}
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (cmd === 'firewall' || cmd === 'fw') {
|
|
202
|
+
const subCmd = sub ?? 'list';
|
|
203
|
+
if (subCmd !== 'list') {
|
|
204
|
+
console.error(`Unknown firewall subcommand: ${subCmd}`);
|
|
205
|
+
process.exit(1);
|
|
206
|
+
}
|
|
207
|
+
await (0, firewall_1.runFirewallList)({
|
|
208
|
+
interactive: flagBool(flags, 'i', 'interactive'),
|
|
209
|
+
container: flagString(flags, 'container'),
|
|
210
|
+
status: flagString(flags, 'status'),
|
|
211
|
+
});
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
console.error(`Unknown command: ${cmd}`);
|
|
215
|
+
console.error('Run "huddle --help" for help.');
|
|
216
|
+
process.exit(1);
|
|
217
|
+
}
|
|
218
|
+
function flagString(flags, ...names) {
|
|
219
|
+
for (const name of names) {
|
|
220
|
+
const value = flags[name];
|
|
221
|
+
if (typeof value === 'string')
|
|
222
|
+
return value;
|
|
223
|
+
}
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
function flagBool(flags, ...names) {
|
|
227
|
+
return names.some((name) => flags[name] === true);
|
|
228
|
+
}
|
|
229
|
+
main().catch((err) => {
|
|
230
|
+
console.error(`Error: ${err.message ?? err}`);
|
|
231
|
+
if (err instanceof api_1.ApiError && err.message.includes('Cannot reach Huddle API')) {
|
|
232
|
+
console.error('\nHuddle does not appear to be running. Start it with:\n huddle init');
|
|
233
|
+
}
|
|
234
|
+
process.exit(1);
|
|
235
|
+
});
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runInit = runInit;
|
|
7
|
+
const child_process_1 = require("child_process");
|
|
8
|
+
const utils_1 = require("./utils");
|
|
9
|
+
const runtime_1 = require("./runtime");
|
|
10
|
+
const images_1 = require("./images");
|
|
11
|
+
const fs_1 = __importDefault(require("fs"));
|
|
12
|
+
const CONTAINER = 'huddle';
|
|
13
|
+
const VOLUME = 'huddle-data';
|
|
14
|
+
const INTERNAL_NET = 'devcontainer-net';
|
|
15
|
+
const HOST_PORT = process.env.HUDDLE_PORT ?? '3000';
|
|
16
|
+
function run(cmd) {
|
|
17
|
+
(0, child_process_1.execSync)(cmd, { stdio: 'inherit' });
|
|
18
|
+
}
|
|
19
|
+
function runSilent(cmd) {
|
|
20
|
+
try {
|
|
21
|
+
(0, child_process_1.execSync)(cmd, { stdio: 'ignore' });
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Pulls the devcontainer base images ahead of time. Best-effort: if an image is
|
|
30
|
+
* not (yet) available in the registry, we only warn — the gateway then builds it
|
|
31
|
+
* from the bundled Dockerfile on the first start.
|
|
32
|
+
*/
|
|
33
|
+
function pullBaseImages(rt, images) {
|
|
34
|
+
console.log((0, utils_1.dim)(`Pulling devcontainer base images (${images.length})`));
|
|
35
|
+
const failed = [];
|
|
36
|
+
for (const image of images) {
|
|
37
|
+
console.log((0, utils_1.dim)(` Pulling ${image}`));
|
|
38
|
+
try {
|
|
39
|
+
run(`${rt} pull ${image}`);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
failed.push(image);
|
|
43
|
+
console.log((0, utils_1.yellow)(` [!] Could not pull ${image} — the gateway will build it later if needed.`));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (failed.length === images.length) {
|
|
47
|
+
console.log((0, utils_1.yellow)('[!] No base image could be pulled. Are the images published and reachable?'));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Starts the Huddle gateway. Which images run (stable or experiment) is decided
|
|
52
|
+
* by the caller via `images` (see resolveImages() in images.ts); this function
|
|
53
|
+
* only does runtime and container orchestration.
|
|
54
|
+
*/
|
|
55
|
+
async function runInit(opts, images) {
|
|
56
|
+
console.log(`${(0, utils_1.bold)('Starting Huddle...')}\n`);
|
|
57
|
+
const IMAGE = images.image;
|
|
58
|
+
if (images.experiment !== undefined) {
|
|
59
|
+
console.log((0, utils_1.yellow)(`Experiment ${images.experiment} active → images with tag ${images.tag}`));
|
|
60
|
+
}
|
|
61
|
+
const runtime = (0, runtime_1.resolveRuntime)(opts.runtime);
|
|
62
|
+
const rt = runtime.name;
|
|
63
|
+
console.log((0, utils_1.dim)(`Container runtime: ${rt}`));
|
|
64
|
+
if (process.env.HUDDLE_NO_PULL === '1') {
|
|
65
|
+
console.log((0, utils_1.dim)(`HUDDLE_NO_PULL=1 → skipping pull, using local image ${IMAGE}`));
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
console.log((0, utils_1.dim)(`Pulling ${IMAGE}`));
|
|
69
|
+
run(`${rt} pull ${IMAGE}`);
|
|
70
|
+
pullBaseImages(rt, images.baseImages.map((b) => b.image));
|
|
71
|
+
}
|
|
72
|
+
console.log((0, utils_1.dim)(`Volume: ${VOLUME}`));
|
|
73
|
+
runSilent(`${rt} volume inspect ${VOLUME}`) || run(`${rt} volume create ${VOLUME}`);
|
|
74
|
+
console.log((0, utils_1.dim)(`Network: ${INTERNAL_NET}`));
|
|
75
|
+
runSilent(`${rt} network inspect ${INTERNAL_NET}`) || run(`${rt} network create --internal ${INTERNAL_NET}`);
|
|
76
|
+
console.log((0, utils_1.dim)(`Removing old container if it exists`));
|
|
77
|
+
runSilent(`${rt} rm -f ${CONTAINER}`);
|
|
78
|
+
console.log((0, utils_1.dim)(`Socket directory: /tmp/dc-sockets`));
|
|
79
|
+
// The mount SOURCE must be the path on the Docker ENGINE host (on Windows:
|
|
80
|
+
// the WSL2/Linux VM), even when the CLI itself runs on Windows. The gateway
|
|
81
|
+
// (SOCKET_DIR in docker.ts) and every devcontainer socket mount rely on
|
|
82
|
+
// /tmp/dc-sockets on the engine host; mounting a Windows temp dir splits
|
|
83
|
+
// gateway and devcontainers across two filesystems, and Unix sockets are
|
|
84
|
+
// unreliable on such a drvfs/9p mount anyway.
|
|
85
|
+
const hostTmpSockets = '/tmp/dc-sockets';
|
|
86
|
+
if (process.platform === 'win32') {
|
|
87
|
+
// Cannot be created locally from Windows; the engine creates a missing
|
|
88
|
+
// bind source itself in the VM on `run`.
|
|
89
|
+
console.log((0, utils_1.dim)(` (Windows: the engine creates ${hostTmpSockets} in the VM)`));
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
try {
|
|
93
|
+
fs_1.default.mkdirSync(hostTmpSockets, { recursive: true });
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
console.log((0, utils_1.yellow)(`[!] Could not create ${hostTmpSockets}: ${err}`));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
console.log((0, utils_1.dim)(`Starting container`));
|
|
100
|
+
run(`${rt} run -d` +
|
|
101
|
+
` --name ${CONTAINER}` +
|
|
102
|
+
` --network ${INTERNAL_NET}` +
|
|
103
|
+
` -p ${HOST_PORT}:3000` +
|
|
104
|
+
` -v ${VOLUME}:/data` +
|
|
105
|
+
` -v ${runtime.socketPath}:/var/run/docker.sock` +
|
|
106
|
+
` -v "${hostTmpSockets}:/tmp/dc-sockets"` +
|
|
107
|
+
(0, images_1.gatewayEnvFlags)(images) +
|
|
108
|
+
` ${IMAGE}`);
|
|
109
|
+
runSilent(`${rt} network connect ${runtime.defaultNetwork} ${CONTAINER}`);
|
|
110
|
+
console.log();
|
|
111
|
+
console.log((0, utils_1.green)(`[OK] Huddle is running at http://localhost:${HOST_PORT}`));
|
|
112
|
+
}
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseRuntimeName = parseRuntimeName;
|
|
4
|
+
exports.resolveRuntime = resolveRuntime;
|
|
5
|
+
const child_process_1 = require("child_process");
|
|
6
|
+
function commandOutput(cmd) {
|
|
7
|
+
try {
|
|
8
|
+
return (0, child_process_1.execSync)(cmd, { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function isAvailable(runtime) {
|
|
15
|
+
// 'info' only succeeds if the daemon/machine is actually reachable.
|
|
16
|
+
return commandOutput(`${runtime} info`) !== undefined;
|
|
17
|
+
}
|
|
18
|
+
function podmanSocketPath() {
|
|
19
|
+
// Podman knows where its own (rootless or rootful) socket lives.
|
|
20
|
+
const reported = commandOutput(`podman info --format "{{.Host.RemoteSocket.Path}}"`);
|
|
21
|
+
if (reported) {
|
|
22
|
+
return reported.replace(/^unix:\/\//, '');
|
|
23
|
+
}
|
|
24
|
+
return '/run/podman/podman.sock';
|
|
25
|
+
}
|
|
26
|
+
function dockerSocketPath() {
|
|
27
|
+
return process.platform === 'win32' ? '//var/run/docker.sock' : '/var/run/docker.sock';
|
|
28
|
+
}
|
|
29
|
+
function buildRuntime(name) {
|
|
30
|
+
if (name === 'podman') {
|
|
31
|
+
return { name, socketPath: podmanSocketPath(), defaultNetwork: 'podman' };
|
|
32
|
+
}
|
|
33
|
+
return { name, socketPath: dockerSocketPath(), defaultNetwork: 'bridge' };
|
|
34
|
+
}
|
|
35
|
+
function parseRuntimeName(value) {
|
|
36
|
+
const normalized = value.toLowerCase().trim();
|
|
37
|
+
if (normalized === 'docker' || normalized === 'podman')
|
|
38
|
+
return normalized;
|
|
39
|
+
throw new Error(`Unknown container runtime: ${value}. Choose docker or podman.`);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Determines which container runtime to use.
|
|
43
|
+
* An explicit choice (via --runtime or HUDDLE_RUNTIME) wins; otherwise it is
|
|
44
|
+
* auto-detected: Docker first, then Podman.
|
|
45
|
+
*/
|
|
46
|
+
function resolveRuntime(explicit) {
|
|
47
|
+
const requested = explicit ?? process.env.HUDDLE_RUNTIME;
|
|
48
|
+
if (requested) {
|
|
49
|
+
const name = parseRuntimeName(requested);
|
|
50
|
+
if (!isAvailable(name)) {
|
|
51
|
+
throw new Error(`Container runtime '${name}' is not available. Is the daemon/machine running?`);
|
|
52
|
+
}
|
|
53
|
+
return buildRuntime(name);
|
|
54
|
+
}
|
|
55
|
+
if (isAvailable('docker'))
|
|
56
|
+
return buildRuntime('docker');
|
|
57
|
+
if (isAvailable('podman'))
|
|
58
|
+
return buildRuntime('podman');
|
|
59
|
+
throw new Error('No working container runtime found. Install and start Docker or Podman,\n' +
|
|
60
|
+
'or pick one explicitly with --runtime <docker|podman> or the HUDDLE_RUNTIME env var.');
|
|
61
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.CLI_PACKAGE = void 0;
|
|
7
|
+
exports.cliVersion = cliVersion;
|
|
8
|
+
exports.switchGlobalCli = switchGlobalCli;
|
|
9
|
+
const child_process_1 = require("child_process");
|
|
10
|
+
const fs_1 = __importDefault(require("fs"));
|
|
11
|
+
const path_1 = __importDefault(require("path"));
|
|
12
|
+
const utils_1 = require("./utils");
|
|
13
|
+
/**
|
|
14
|
+
* Infrastructure for CLI self-updates: version info of the running build,
|
|
15
|
+
* global (re)installation via npm, and restarting the process itself.
|
|
16
|
+
* Which version should be installed (stable or experiment) is a domain
|
|
17
|
+
* decision and lives in experiment.ts.
|
|
18
|
+
*/
|
|
19
|
+
exports.CLI_PACKAGE = '@infosupport/huddle-cli';
|
|
20
|
+
// Guard against a restart loop: set on a relaunch, so the new CLI doesn't
|
|
21
|
+
// reinstall again if the version still doesn't match.
|
|
22
|
+
const RELAUNCH_ENV = 'HUDDLE_EXPERIMENT_RELAUNCHED';
|
|
23
|
+
function cliVersion() {
|
|
24
|
+
try {
|
|
25
|
+
const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(__dirname, '..', 'package.json'), 'utf8'));
|
|
26
|
+
return String(pkg.version ?? 'unknown');
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return 'unknown';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Switches the global CLI to the given package spec and then restarts this
|
|
34
|
+
* process with relaunchArgs. Never returns: the process exits with the exit
|
|
35
|
+
* code of the new CLI, or this function throws (installation failed, or this
|
|
36
|
+
* process was already a restart and is therefore stuck in a loop).
|
|
37
|
+
*/
|
|
38
|
+
function switchGlobalCli(spec, relaunchArgs) {
|
|
39
|
+
if (wasRelaunched()) {
|
|
40
|
+
throw new Error(`Could not switch to ${spec}: this process was already restarted after a reinstall, ` +
|
|
41
|
+
`but is still running version ${cliVersion()}. Install manually: npm install -g ${spec}`);
|
|
42
|
+
}
|
|
43
|
+
console.log((0, utils_1.bold)(`Switching CLI to ${spec}`));
|
|
44
|
+
console.log((0, utils_1.dim)(`Current version: ${cliVersion()}`));
|
|
45
|
+
try {
|
|
46
|
+
(0, child_process_1.execSync)(`npm install -g ${spec}`, { stdio: 'inherit' });
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new Error(`Could not install ${spec}. Is the package published and reachable?`);
|
|
50
|
+
}
|
|
51
|
+
relaunchCli(relaunchArgs);
|
|
52
|
+
}
|
|
53
|
+
/** True when this process is already a restart after a self-update. */
|
|
54
|
+
function wasRelaunched() {
|
|
55
|
+
return process.env[RELAUNCH_ENV] === '1';
|
|
56
|
+
}
|
|
57
|
+
/** Restarts the (just installed) global CLI with the given arguments. */
|
|
58
|
+
function relaunchCli(args) {
|
|
59
|
+
console.log((0, utils_1.dim)(`Restarting: huddle ${args.join(' ')}`));
|
|
60
|
+
const env = { ...process.env, [RELAUNCH_ENV]: '1' };
|
|
61
|
+
const entry = resolveGlobalEntry();
|
|
62
|
+
const result = entry
|
|
63
|
+
? (0, child_process_1.spawnSync)(process.execPath, [entry, ...args], { stdio: 'inherit', env })
|
|
64
|
+
: (0, child_process_1.spawnSync)('huddle', args, { stdio: 'inherit', env, shell: process.platform === 'win32' });
|
|
65
|
+
process.exit(result.status ?? 1);
|
|
66
|
+
}
|
|
67
|
+
function resolveGlobalEntry() {
|
|
68
|
+
try {
|
|
69
|
+
const root = (0, child_process_1.execSync)('npm root -g', { encoding: 'utf8' }).trim();
|
|
70
|
+
const entry = path_1.default.join(root, ...exports.CLI_PACKAGE.split('/'), 'dist', 'index.js');
|
|
71
|
+
return fs_1.default.existsSync(entry) ? entry : undefined;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
package/dist/start.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runStart = runStart;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const api_1 = require("./api");
|
|
10
|
+
const utils_1 = require("./utils");
|
|
11
|
+
async function runStart(opts) {
|
|
12
|
+
const ide = parseIde(opts.ide);
|
|
13
|
+
const workspaceDir = opts.empty ? undefined : resolveWorkspace(opts.workspace);
|
|
14
|
+
const baseName = opts.empty ? 'empty' : path_1.default.basename(workspaceDir);
|
|
15
|
+
const containerName = opts.name ? validateContainerName(opts.name) : defaultContainerName(baseName);
|
|
16
|
+
console.log(`Starting ${(0, utils_1.bold)(containerName)} with ${(0, utils_1.bold)(ide)}...`);
|
|
17
|
+
if (workspaceDir)
|
|
18
|
+
console.log((0, utils_1.dim)(`Workspace: ${workspaceDir}`));
|
|
19
|
+
let imageName = opts.image;
|
|
20
|
+
if (!imageName) {
|
|
21
|
+
const res = await (0, api_1.get)(`/api/docker/base-image?ide=${encodeURIComponent(ide)}`);
|
|
22
|
+
imageName = res.imageName;
|
|
23
|
+
console.log((0, utils_1.dim)(`Image: ${imageName}`));
|
|
24
|
+
}
|
|
25
|
+
const body = {
|
|
26
|
+
imageName,
|
|
27
|
+
containerName,
|
|
28
|
+
ideName: ide,
|
|
29
|
+
};
|
|
30
|
+
if (opts.empty) {
|
|
31
|
+
body.empty = true;
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
body.workspaceDir = workspaceDir;
|
|
35
|
+
}
|
|
36
|
+
const result = await (0, api_1.post)('/api/docker/start', body);
|
|
37
|
+
console.log((0, utils_1.green)(`[OK] Container started: ${result.containerName} (${result.id.slice(0, 12)})`));
|
|
38
|
+
console.log();
|
|
39
|
+
if (ide === 'vscode') {
|
|
40
|
+
console.log(`Open in VS Code: ${(0, utils_1.cyan)('Dev Containers: Attach to Running Container')} -> ${(0, utils_1.bold)(result.containerName)}`);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
console.log(`Open in JetBrains Gateway: ${(0, utils_1.cyan)('Remote Development > Dev Containers')} -> ${(0, utils_1.bold)(result.containerName)}`);
|
|
44
|
+
await tryPrintIdeLink(result.containerName);
|
|
45
|
+
}
|
|
46
|
+
async function tryPrintIdeLink(containerName) {
|
|
47
|
+
await new Promise((resolve) => setTimeout(resolve, 3000));
|
|
48
|
+
try {
|
|
49
|
+
const res = await (0, api_1.get)(`/api/docker/containers/${encodeURIComponent(containerName)}/ide-link`);
|
|
50
|
+
if (res?.link)
|
|
51
|
+
console.log((0, utils_1.dim)(`Gateway-link: ${res.link}`));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// The IDE link is best-effort; JetBrains may still be starting the backend.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function resolveWorkspace(workspace) {
|
|
58
|
+
const resolved = path_1.default.resolve(workspace ?? process.cwd());
|
|
59
|
+
let stat;
|
|
60
|
+
try {
|
|
61
|
+
stat = fs_1.default.statSync(resolved);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new Error(`Workspace directory does not exist: ${resolved}`);
|
|
65
|
+
}
|
|
66
|
+
if (!stat.isDirectory()) {
|
|
67
|
+
throw new Error(`Workspace path is not a directory: ${resolved}`);
|
|
68
|
+
}
|
|
69
|
+
return resolved.replace(/[\\/]+$/, '');
|
|
70
|
+
}
|
|
71
|
+
function defaultContainerName(baseName) {
|
|
72
|
+
const slug = baseName.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^[_.-]+|[_.-]+$/g, '');
|
|
73
|
+
return `devcontainer-${slug || 'workspace'}`;
|
|
74
|
+
}
|
|
75
|
+
function validateContainerName(name) {
|
|
76
|
+
const trimmed = name.trim();
|
|
77
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(trimmed)) {
|
|
78
|
+
throw new Error(`Invalid container name: ${name}`);
|
|
79
|
+
}
|
|
80
|
+
return trimmed;
|
|
81
|
+
}
|
|
82
|
+
function parseIde(value) {
|
|
83
|
+
const normalized = value.toLowerCase().replace(/[ _-]+/g, '');
|
|
84
|
+
if (normalized === 'rider')
|
|
85
|
+
return 'rider';
|
|
86
|
+
if (normalized === 'vscode' || normalized === 'code')
|
|
87
|
+
return 'vscode';
|
|
88
|
+
if (normalized === 'intellij' || normalized === 'intelij' || normalized === 'idea')
|
|
89
|
+
return 'intellij';
|
|
90
|
+
throw new Error(`Unknown IDE: ${value}. Choose intellij, rider, or vscode.`);
|
|
91
|
+
}
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cyan = exports.yellow = exports.green = exports.red = exports.dim = exports.bold = void 0;
|
|
4
|
+
exports.formatTime = formatTime;
|
|
5
|
+
exports.promptKey = promptKey;
|
|
6
|
+
exports.printTable = printTable;
|
|
7
|
+
const readline_1 = require("readline");
|
|
8
|
+
const ESC = '\x1b[';
|
|
9
|
+
const isTTY = process.stdout.isTTY && process.env.NO_COLOR !== '1';
|
|
10
|
+
const fmt = (code, text) => (isTTY ? `${ESC}${code}m${text}${ESC}0m` : text);
|
|
11
|
+
const bold = (t) => fmt(1, t);
|
|
12
|
+
exports.bold = bold;
|
|
13
|
+
const dim = (t) => fmt(2, t);
|
|
14
|
+
exports.dim = dim;
|
|
15
|
+
const red = (t) => fmt(31, t);
|
|
16
|
+
exports.red = red;
|
|
17
|
+
const green = (t) => fmt(32, t);
|
|
18
|
+
exports.green = green;
|
|
19
|
+
const yellow = (t) => fmt(33, t);
|
|
20
|
+
exports.yellow = yellow;
|
|
21
|
+
const cyan = (t) => fmt(36, t);
|
|
22
|
+
exports.cyan = cyan;
|
|
23
|
+
function formatTime(unixSec) {
|
|
24
|
+
const diff = Math.max(0, Math.floor(Date.now() / 1000) - unixSec);
|
|
25
|
+
if (diff < 60)
|
|
26
|
+
return `${diff}s ago`;
|
|
27
|
+
if (diff < 3600)
|
|
28
|
+
return `${Math.floor(diff / 60)}m ago`;
|
|
29
|
+
if (diff < 86400)
|
|
30
|
+
return `${Math.floor(diff / 3600)}h ago`;
|
|
31
|
+
return `${Math.floor(diff / 86400)}d ago`;
|
|
32
|
+
}
|
|
33
|
+
function promptKey(prompt) {
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
process.stdout.write(prompt);
|
|
36
|
+
const stdin = process.stdin;
|
|
37
|
+
const hasRaw = stdin.isTTY && typeof stdin.setRawMode === 'function';
|
|
38
|
+
if (!hasRaw) {
|
|
39
|
+
const rl = (0, readline_1.createInterface)({ input: process.stdin });
|
|
40
|
+
rl.once('line', (line) => {
|
|
41
|
+
rl.close();
|
|
42
|
+
resolve(line.trim().charAt(0));
|
|
43
|
+
});
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
stdin.setRawMode(true);
|
|
47
|
+
stdin.resume();
|
|
48
|
+
stdin.setEncoding('utf8');
|
|
49
|
+
stdin.once('data', (data) => {
|
|
50
|
+
stdin.setRawMode(false);
|
|
51
|
+
stdin.pause();
|
|
52
|
+
const key = data.toString();
|
|
53
|
+
if (key === '\u0003') {
|
|
54
|
+
process.stdout.write('\n');
|
|
55
|
+
process.exit(0);
|
|
56
|
+
}
|
|
57
|
+
if (key === '\u001b') {
|
|
58
|
+
process.stdout.write('\n');
|
|
59
|
+
resolve('');
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
process.stdout.write(`${key}\n`);
|
|
63
|
+
resolve(key);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function printTable(headers, rows) {
|
|
68
|
+
const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
|
|
69
|
+
const line = (cells, colorFn) => cells.map((c, i) => (colorFn ? colorFn(c.padEnd(widths[i])) : c.padEnd(widths[i]))).join(' ');
|
|
70
|
+
console.log((0, exports.bold)(line(headers)));
|
|
71
|
+
console.log((0, exports.dim)('-'.repeat(widths.reduce((a, w) => a + w + 2, -2))));
|
|
72
|
+
rows.forEach((row) => console.log(line(row)));
|
|
73
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@infosupport/huddle-cli",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Huddle CLI \u2014 start devcontainers and manage firewall rules",
|
|
5
|
+
"license": "GPL-3.0-or-later",
|
|
6
|
+
"author": "Info Support B.V.",
|
|
7
|
+
"homepage": "https://github.com/infosupport/huddle",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/infosupport/huddle.git",
|
|
11
|
+
"directory": "cli"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/infosupport/huddle/issues"
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"huddle": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "tsc",
|
|
21
|
+
"dev": "tsc --watch",
|
|
22
|
+
"install-global": "npm run build && npm install -g .",
|
|
23
|
+
"typecheck": "tsc --noEmit"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^22.0.0",
|
|
27
|
+
"typescript": "^5.0.0"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"registry": "https://registry.npmjs.org",
|
|
37
|
+
"access": "public"
|
|
38
|
+
}
|
|
39
|
+
}
|