insta 0.0.60 → 0.0.62
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/dist/commands/compute.js +1 -1
- package/dist/commands/services.js +7 -3
- package/dist/commands/template.js +29 -8
- package/dist/github-source.js +327 -0
- package/dist/index.js +10 -9
- package/dist/template-manifest.js +24 -2
- package/package.json +1 -1
package/dist/commands/compute.js
CHANGED
|
@@ -589,7 +589,7 @@ export async function computeAlwaysOn(mode, serviceName, opts) {
|
|
|
589
589
|
if (opts.json)
|
|
590
590
|
return printJson(res.body);
|
|
591
591
|
const on = res.body.service?.always_on;
|
|
592
|
-
info(`compute ${res.body.service?.name ?? id}: always-on ${on ? 'ENABLED — machines stay warm (no cold starts; idle RAM bills at actual usage)' : 'disabled — scales to zero when idle
|
|
592
|
+
info(`compute ${res.body.service?.name ?? id}: always-on ${on ? 'ENABLED — machines stay warm (no cold starts; idle RAM bills at actual usage)' : 'disabled — scales to zero when idle'}`);
|
|
593
593
|
}
|
|
594
594
|
// ---- limits (the resource ceiling; paid plans) ----
|
|
595
595
|
// Parse a human memory value into MB: "512", "512mb", "1gb", "2g", "1.5gb".
|
|
@@ -85,7 +85,10 @@ export function servicesAddRequestBody(type, name, branch, opts) {
|
|
|
85
85
|
type, name, ...(branch ? { branch } : {}), public: !!opts.public,
|
|
86
86
|
...(opts.image ? { image: opts.image } : {}), ...(opts.port ? { port: parsePort(opts.port) } : {}),
|
|
87
87
|
...(opts.region ? { region: opts.region } : {}),
|
|
88
|
-
|
|
88
|
+
// Sent whenever the flag was given, false included: compute is born always-on by default
|
|
89
|
+
// (insta-platform #385, 2026-09-07), so `--no-always-on` must reach the API as an explicit
|
|
90
|
+
// false. Omitted means the platform default.
|
|
91
|
+
...(opts.alwaysOn !== undefined ? { alwaysOn: opts.alwaysOn } : {}),
|
|
89
92
|
...(opts.volume !== undefined ? { volumeGib: parseVolumeGib(opts.volume) } : {}),
|
|
90
93
|
};
|
|
91
94
|
}
|
|
@@ -102,8 +105,9 @@ export async function servicesAdd(type, name, opts = {}) {
|
|
|
102
105
|
throw new Error('--port is only valid for compute services');
|
|
103
106
|
parsePort(opts.port); // junk fails here, before any config/network access
|
|
104
107
|
}
|
|
105
|
-
|
|
106
|
-
|
|
108
|
+
// Presence, not truthiness: `--no-always-on` is an explicit false and is just as compute-only.
|
|
109
|
+
if (opts.alwaysOn !== undefined && type !== 'compute')
|
|
110
|
+
throw new Error('--always-on / --no-always-on is only valid for compute services (for postgres, use `insta db always-on on|off` after creation)');
|
|
107
111
|
if (opts.volume !== undefined) {
|
|
108
112
|
if (type !== 'compute')
|
|
109
113
|
throw new Error('--volume is only valid for compute services (postgres has one by default — grow it with `insta db volume --size`)');
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// `insta template` — browse the platform template registry and deploy a template (by registry
|
|
2
|
-
// code,
|
|
2
|
+
// code, from a local directory carrying insta.template.yaml, or from a github.com URL whose
|
|
3
|
+
// manifest github-source.ts fetches with the user's own git credentials) onto a branch. The deploy is a
|
|
3
4
|
// platform-side pipeline (create services → write variables → deploy → health check); the CLI
|
|
4
5
|
// submits it and renders progress by polling the deployment resource.
|
|
5
6
|
import { join, resolve } from 'node:path';
|
|
@@ -9,6 +10,7 @@ import * as clack from '@clack/prompts';
|
|
|
9
10
|
import { ApiClient, ApiError, requireProject } from '../api.js';
|
|
10
11
|
import { info, printJson, handleApproval, renderNextActions, CliCancel } from '../util.js';
|
|
11
12
|
import { MANIFEST_FILE, collectManifestVariables, loadTemplateManifest } from '../template-manifest.js';
|
|
13
|
+
import { parseGitHubTemplateUrl, fetchGitHubTemplate } from '../github-source.js';
|
|
12
14
|
// One aligned row per template; numeric columns right-aligned. Plain padded columns, as the rest
|
|
13
15
|
// of the CLI (storage list, compute check-domain) — no table library.
|
|
14
16
|
export function templateListLines(templates) {
|
|
@@ -172,12 +174,18 @@ export function looksLikePath(target) {
|
|
|
172
174
|
// tool should fake.
|
|
173
175
|
const expandHome = (target) => target.replace(/^~(?=[/\\]|$)/, () => homedir());
|
|
174
176
|
/**
|
|
175
|
-
* Which deploy mode a target selects.
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
177
|
+
* Which deploy mode a target selects. A URL is classified FIRST — it contains `/`, which
|
|
178
|
+
* looksLikePath would otherwise claim as a directory, and a non-GitHub URL must be named as
|
|
179
|
+
* unsupported rather than reported as a missing manifest. Then: local mode is OPTED INTO by a
|
|
180
|
+
* path-looking target (./dir, /abs, sub/dir); a bare word is ALWAYS a registry code — even when a
|
|
181
|
+
* same-named directory with a manifest sits in the working directory, deploying it must be
|
|
182
|
+
* explicit (./plausible), never a cwd coincidence. And a path-looking target with no manifest is a
|
|
183
|
+
* mistake, never a registry code.
|
|
179
184
|
*/
|
|
180
185
|
export function deployMode(target, hasManifest = (d) => existsSync(join(d, MANIFEST_FILE))) {
|
|
186
|
+
const github = parseGitHubTemplateUrl(target);
|
|
187
|
+
if (github)
|
|
188
|
+
return { kind: 'github', target: github };
|
|
181
189
|
if (!looksLikePath(target))
|
|
182
190
|
return { kind: 'registry', code: target };
|
|
183
191
|
const dir = resolve(process.cwd(), expandHome(target));
|
|
@@ -314,8 +322,21 @@ export async function templateDeploy(target, opts = {}, deps = {}) {
|
|
|
314
322
|
// code, so a same-named local directory can never shadow the registry template.
|
|
315
323
|
const mode = deployMode(target);
|
|
316
324
|
let manifest;
|
|
325
|
+
let source;
|
|
317
326
|
let vars;
|
|
318
|
-
if (mode.kind === '
|
|
327
|
+
if (mode.kind === 'github') {
|
|
328
|
+
const fetched = await (deps.fetchGitHub ?? ((t) => fetchGitHubTemplate(t)))(mode.target);
|
|
329
|
+
manifest = fetched.manifest;
|
|
330
|
+
source = fetched.source;
|
|
331
|
+
vars = collectManifestVariables(manifest);
|
|
332
|
+
// Spec 4.4: exactly ONE line in front of today's output. A second "deploying template …" line
|
|
333
|
+
// would read as a duplicate of the "deploying template <code> to branch <branch>" line below,
|
|
334
|
+
// so the manifest's code@version rides on this one instead.
|
|
335
|
+
if (!quiet) {
|
|
336
|
+
info(`fetching template ${manifest.code}@${manifest.version} from github.com/${source.repo}@${source.ref}${source.path ? ` (${source.path})` : ''} at ${source.commit.slice(0, 7)}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
else if (mode.kind === 'local') {
|
|
319
340
|
manifest = loadTemplateManifest(mode.dir); // parse + local validation (pinned images, described vars)
|
|
320
341
|
vars = collectManifestVariables(manifest);
|
|
321
342
|
if (!quiet)
|
|
@@ -331,7 +352,7 @@ export async function templateDeploy(target, opts = {}, deps = {}) {
|
|
|
331
352
|
const onAutoResolved = quiet ? undefined : (v) => info(` ${v.name}: ${v.generate ? `platform-generated (${v.generate})` : `default (${v.default})`}`);
|
|
332
353
|
const variables = await resolveVariables(vars, given, { tty, ask, onAutoResolved });
|
|
333
354
|
// The endpoint takes the branch NAME directly (branchId is its uuid alias) — no lookup needed.
|
|
334
|
-
const body = { ...(mode.kind === '
|
|
355
|
+
const body = { ...(mode.kind === 'registry' ? { templateCode: mode.code } : { manifest }), branch: branchName, variables };
|
|
335
356
|
let res;
|
|
336
357
|
try {
|
|
337
358
|
res = await api.rawRequest('POST', `/projects/${p.projectId}/template-deployments`, body);
|
|
@@ -355,7 +376,7 @@ export async function templateDeploy(target, opts = {}, deps = {}) {
|
|
|
355
376
|
info(`deploying template ${codeLabel} to branch ${branchName} (${deploymentId})`);
|
|
356
377
|
const dep = await watchDeployment((id) => api.request('GET', `/template-deployments/${id}`), deploymentId, quiet ? () => { } : info, deps.wait);
|
|
357
378
|
if (opts.json)
|
|
358
|
-
return printJson(dep);
|
|
379
|
+
return printJson(source ? { source, ...dep } : dep);
|
|
359
380
|
info(`template ${codeLabel} deployed to branch ${branchName}`);
|
|
360
381
|
for (const u of deploymentUrls(dep))
|
|
361
382
|
info(` ${u}`);
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// Fetch a template manifest out of a GitHub repository, on this machine, with the user's own git
|
|
2
|
+
// credentials. Parsing, ref resolution and the shallow clone live here; the deploy path stays in
|
|
3
|
+
// commands/template.ts. See docs/superpowers/specs/2026-09-04-template-deploy-github-url-design.md.
|
|
4
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
5
|
+
import { mkdtempSync, rmSync, existsSync, realpathSync, statSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join, sep } from 'node:path';
|
|
8
|
+
import { parseManifestYaml, MANIFEST_FILE } from './template-manifest.js';
|
|
9
|
+
const GITHUB_HOST = /^(?:https?:\/\/)?(?:www\.)?github\.com\//i;
|
|
10
|
+
// An explicit address: a scheme, or an scp-style user@host:path. Never a local path.
|
|
11
|
+
// A scheme (with or without its slashes) or an scp-style user@host:path. The slashes are optional
|
|
12
|
+
// because `https:/github.com/o/r`, a URL that lost one, must be named as a bad address rather than
|
|
13
|
+
// resolved as a directory called `https:`. Two or more scheme characters are required so a Windows
|
|
14
|
+
// drive letter (`C:\src`, `C:/src`) stays a path.
|
|
15
|
+
const EXPLICIT_ADDRESS = /^[a-z][a-z0-9+.-]+:|^[^/\\]+@[^/\\]+:/i;
|
|
16
|
+
// Scheme-less first segments we still read as a host. A bare `<name>/<path>` is otherwise a LOCAL
|
|
17
|
+
// PATH: `v1.0/templates` and `my.app/bot` are directories, and reading every dotted first segment
|
|
18
|
+
// as a host broke them. Only names that unambiguously host code belong here.
|
|
19
|
+
const KNOWN_GIT_HOSTS = new Set([
|
|
20
|
+
'gitlab.com', 'www.gitlab.com', 'bitbucket.org', 'www.bitbucket.org', 'gist.github.com',
|
|
21
|
+
'codeberg.org', 'git.sr.ht', 'dev.azure.com', 'ssh.dev.azure.com', 'gitea.com', 'sourceforge.net',
|
|
22
|
+
]);
|
|
23
|
+
const SEGMENT = /^[A-Za-z0-9_.-]+$/;
|
|
24
|
+
/** Is this an address rather than a path? Only an explicit scheme/scp form, or a first segment
|
|
25
|
+
* naming a host we recognise. A scheme-less name is far likelier to be someone's directory than
|
|
26
|
+
* a git host, so everything else falls through to local and registry modes. */
|
|
27
|
+
function isAddress(target) {
|
|
28
|
+
if (EXPLICIT_ADDRESS.test(target))
|
|
29
|
+
return true;
|
|
30
|
+
return KNOWN_GIT_HOSTS.has((target.split(/[/\\]/, 1)[0] ?? '').toLowerCase());
|
|
31
|
+
}
|
|
32
|
+
export function unsupportedSourceMessage(target) {
|
|
33
|
+
return `unsupported template source: ${target}. Use a registry code, a local directory, or https://github.com/<owner>/<repo>[/tree/<ref>[/<dir>]]`;
|
|
34
|
+
}
|
|
35
|
+
// Percent-decode first, so %2e%2e and %2f cannot smuggle a traversal past the segment check.
|
|
36
|
+
function decodedSegments(parts, target) {
|
|
37
|
+
return parts.map((raw) => {
|
|
38
|
+
let seg;
|
|
39
|
+
try {
|
|
40
|
+
seg = decodeURIComponent(raw);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
44
|
+
}
|
|
45
|
+
if (!seg || seg === '.' || seg === '..' || /[/\\\0]/.test(seg))
|
|
46
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
47
|
+
return seg;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** Parse a github.com URL into owner, repo and the still-unsplit ref+path tail.
|
|
51
|
+
* null = not URL-shaped, so the caller's local-directory and registry modes still get a look.
|
|
52
|
+
* A URL-shaped target that is not a github.com repository URL throws (spec 4.1). */
|
|
53
|
+
export function parseGitHubTemplateUrl(target) {
|
|
54
|
+
if (!GITHUB_HOST.test(target)) {
|
|
55
|
+
// Name a non-GitHub address for what it is; let everything else reach local/registry mode.
|
|
56
|
+
if (isAddress(target))
|
|
57
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
// Links copied from GitHub's UI carry ?plain=1, #L1-L5 or ?tab=readme-ov-file, and none of that
|
|
61
|
+
// names a file. A `?` or `#` in a real path arrives percent-encoded, so a bare one is always the
|
|
62
|
+
// delimiter. Dropping it silently beats a "directory" called `bot?tab=readme-ov-file`.
|
|
63
|
+
const clean = target.replace(/[?#][\s\S]*$/, '');
|
|
64
|
+
const rest = clean.replace(GITHUB_HOST, '').replace(/\/+$/, '');
|
|
65
|
+
const parts = rest.split('/');
|
|
66
|
+
const owner = parts[0] ?? '';
|
|
67
|
+
const repo = (parts[1] ?? '').replace(/\.git$/i, '');
|
|
68
|
+
if (!SEGMENT.test(owner) || !SEGMENT.test(repo))
|
|
69
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
70
|
+
const kind = parts[2];
|
|
71
|
+
if (kind === undefined)
|
|
72
|
+
return { owner, repo, refAndPath: '' };
|
|
73
|
+
if (kind !== 'tree' && kind !== 'blob')
|
|
74
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
75
|
+
let tail = decodedSegments(parts.slice(3), target);
|
|
76
|
+
if (!tail.length)
|
|
77
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
78
|
+
if (kind === 'blob') {
|
|
79
|
+
// A file link is read as its directory, and only for the manifest itself.
|
|
80
|
+
if (tail[tail.length - 1] !== MANIFEST_FILE)
|
|
81
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
82
|
+
tail = tail.slice(0, -1);
|
|
83
|
+
if (!tail.length)
|
|
84
|
+
throw new Error(unsupportedSourceMessage(target));
|
|
85
|
+
}
|
|
86
|
+
return { owner, repo, refAndPath: tail.join('/') };
|
|
87
|
+
}
|
|
88
|
+
export const LS_REMOTE_TIMEOUT_MS = 30_000;
|
|
89
|
+
export const CLONE_TIMEOUT_MS = 120_000;
|
|
90
|
+
export function gitMissingMessage() {
|
|
91
|
+
return `git is required to deploy a template from a GitHub URL. Install git, or clone the repository yourself and run: insta template deploy ./<dir>`;
|
|
92
|
+
}
|
|
93
|
+
// git asks for nothing: no terminal credential prompt, no SSH host-key or passphrase prompt (an
|
|
94
|
+
// insteadOf rewrite can send the clone over SSH). The environment stops it asking; only the
|
|
95
|
+
// timeout stops it waiting.
|
|
96
|
+
// GIT_SSH_COMMAND is EXTENDED, never replaced: a user's own `ssh -i <key>` IS how their private
|
|
97
|
+
// repository authenticates, and overwriting it would drop the credentials this feature runs on.
|
|
98
|
+
function nonInteractiveEnv(env = process.env) {
|
|
99
|
+
const ssh = env.GIT_SSH_COMMAND?.trim();
|
|
100
|
+
return {
|
|
101
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
102
|
+
GIT_SSH_COMMAND: ssh ? `${ssh} -o BatchMode=yes` : 'ssh -o BatchMode=yes',
|
|
103
|
+
GCM_INTERACTIVE: 'never',
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
// git spawns helpers (ssh, a credential manager) that inherit its pipes, so a timeout has to take
|
|
107
|
+
// the whole group. Windows has no process groups; taskkill /T walks the tree instead.
|
|
108
|
+
function killTree(child) {
|
|
109
|
+
try {
|
|
110
|
+
if (process.platform === 'win32' && child.pid) {
|
|
111
|
+
// spawn reports a missing binary ASYNCHRONOUSLY: without this listener an absent taskkill
|
|
112
|
+
// becomes an uncaught ENOENT that kills the CLI, and try/catch never sees it.
|
|
113
|
+
nodeSpawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' })
|
|
114
|
+
.on('error', () => { });
|
|
115
|
+
}
|
|
116
|
+
else if (child.pid) {
|
|
117
|
+
process.kill(-child.pid, 'SIGKILL'); // negative pid addresses the group
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch { /* already gone */ }
|
|
121
|
+
try {
|
|
122
|
+
child.kill('SIGKILL');
|
|
123
|
+
}
|
|
124
|
+
catch { /* already gone */ }
|
|
125
|
+
}
|
|
126
|
+
// A settled promise does not let the CLI exit. Node keeps its event loop alive for an open pipe,
|
|
127
|
+
// and a grandchild that escaped the kill still holds the write end. Releasing our read ends and
|
|
128
|
+
// unref-ing the child is what actually lets the process end.
|
|
129
|
+
function releaseChild(child) {
|
|
130
|
+
try {
|
|
131
|
+
child.stdout?.destroy();
|
|
132
|
+
}
|
|
133
|
+
catch { /* already closed */ }
|
|
134
|
+
try {
|
|
135
|
+
child.stderr?.destroy();
|
|
136
|
+
}
|
|
137
|
+
catch { /* already closed */ }
|
|
138
|
+
try {
|
|
139
|
+
child.unref();
|
|
140
|
+
}
|
|
141
|
+
catch { /* already gone */ }
|
|
142
|
+
}
|
|
143
|
+
/** spawnFn is injected so the timeout path is testable without a network (spec FAQ 7.15). */
|
|
144
|
+
export function makeGitRunner(spawnFn = nodeSpawn) {
|
|
145
|
+
return (args, opts) => new Promise((resolve) => {
|
|
146
|
+
// Spawned directly, NOT through resolveSpawnable: that wrapper exists for npm-installed
|
|
147
|
+
// `.cmd` shims, and its cmd.exe hop breaks any executable path containing a space —
|
|
148
|
+
// `cmd /s /c "C:\Program Files\Git\cmd\git.exe" --version` has its quotes stripped and
|
|
149
|
+
// dies with `'C:\Program' is not recognized`. git ships a real git.exe, which spawn finds
|
|
150
|
+
// through PATHEXT by itself; a `.cmd`-only git fails ENOENT, which reads as gitMissingMessage.
|
|
151
|
+
const child = spawnFn('git', args, {
|
|
152
|
+
env: { ...process.env, ...nonInteractiveEnv() },
|
|
153
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
154
|
+
// Own process group on POSIX, so killTree can reach git's helpers.
|
|
155
|
+
detached: process.platform !== 'win32',
|
|
156
|
+
});
|
|
157
|
+
let stdout = '';
|
|
158
|
+
let stderr = '';
|
|
159
|
+
let settled = false;
|
|
160
|
+
const finish = (r) => {
|
|
161
|
+
if (settled)
|
|
162
|
+
return;
|
|
163
|
+
settled = true;
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
resolve(r);
|
|
166
|
+
};
|
|
167
|
+
const timer = setTimeout(() => {
|
|
168
|
+
killTree(child);
|
|
169
|
+
// Then let go of the pipes. Killing can miss a grandchild that changed process group, and
|
|
170
|
+
// its inherited write end would keep BOTH 'close' and the CLI's event loop waiting
|
|
171
|
+
// (measured: promise settled at 203ms, process exited at 20094ms).
|
|
172
|
+
releaseChild(child);
|
|
173
|
+
// Settle NOW. 'close' waits for every inherited pipe; waiting would void the bound.
|
|
174
|
+
finish({ code: -1, stdout, stderr, timedOut: true });
|
|
175
|
+
}, opts.timeoutMs);
|
|
176
|
+
child.stdout?.on('data', (b) => { stdout += b.toString(); });
|
|
177
|
+
child.stderr?.on('data', (b) => { stderr += b.toString(); });
|
|
178
|
+
child.on('error', (err) => finish({ code: -1, stdout, stderr: `${stderr}${err.message}`, timedOut: false }));
|
|
179
|
+
child.on('close', (code) => finish({ code: code ?? -1, stdout, stderr, timedOut: false }));
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
export const defaultGitRunner = makeGitRunner();
|
|
183
|
+
export function repoUrl(t) {
|
|
184
|
+
return `https://github.com/${t.owner}/${t.repo}.git`;
|
|
185
|
+
}
|
|
186
|
+
function repoLabel(t) {
|
|
187
|
+
return `https://github.com/${t.owner}/${t.repo}`;
|
|
188
|
+
}
|
|
189
|
+
export function unreadableRepoMessage(t, stderr) {
|
|
190
|
+
const tail = stderr.trim().split('\n').slice(-2).join('\n');
|
|
191
|
+
return [
|
|
192
|
+
`could not read ${repoLabel(t)}: repository not found or not accessible.`,
|
|
193
|
+
'If this is a private repository, configure git credentials and retry. With GitHub CLI:',
|
|
194
|
+
' gh auth login',
|
|
195
|
+
' gh auth setup-git',
|
|
196
|
+
...(tail ? [`git said: ${tail}`] : []),
|
|
197
|
+
].join('\n');
|
|
198
|
+
}
|
|
199
|
+
/** Read `git ls-remote --symref`: the HEAD symref names the default branch, and every other line
|
|
200
|
+
* is `<sha>\t<refname>`. Keyed by FULL ref, so refs/heads/x and refs/tags/x stay distinct.
|
|
201
|
+
* Peeled entries (`^{}`) are dropped: they name a commit, not a ref anyone can clone. */
|
|
202
|
+
export function parseLsRemote(stdout) {
|
|
203
|
+
let head = null;
|
|
204
|
+
const refs = new Map();
|
|
205
|
+
for (const line of stdout.split('\n')) {
|
|
206
|
+
const symref = /^ref:\s+refs\/heads\/(\S+)\s+HEAD$/.exec(line);
|
|
207
|
+
if (symref) {
|
|
208
|
+
head = symref[1];
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const m = /^([0-9a-f]{40})\s+(refs\/(?:heads|tags)\/.+)$/.exec(line);
|
|
212
|
+
if (!m || m[2].endsWith('^{}'))
|
|
213
|
+
continue;
|
|
214
|
+
refs.set(m[2], m[1]);
|
|
215
|
+
}
|
|
216
|
+
return { head, refs };
|
|
217
|
+
}
|
|
218
|
+
/** Longest-first, because a ref may contain `/` and only the real ref list can say where it ends.
|
|
219
|
+
* A branch beats a tag of the same name, which is what `git clone --branch` does with the short
|
|
220
|
+
* name; qualifiedRef records that choice for the reader, the clone still gets `ref`. */
|
|
221
|
+
export function splitRefAndPath(refAndPath, refs) {
|
|
222
|
+
const segments = refAndPath.split('/');
|
|
223
|
+
for (let take = segments.length; take > 0; take--) {
|
|
224
|
+
const ref = segments.slice(0, take).join('/');
|
|
225
|
+
const qualifiedRef = refs.has(`refs/heads/${ref}`) ? `refs/heads/${ref}`
|
|
226
|
+
: refs.has(`refs/tags/${ref}`) ? `refs/tags/${ref}`
|
|
227
|
+
: null;
|
|
228
|
+
if (qualifiedRef)
|
|
229
|
+
return { ref, qualifiedRef, path: segments.slice(take).join('/') };
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
/** One round trip answers two questions: the default branch, and where the ref ends. The commit
|
|
234
|
+
* is NOT taken from here — an annotated tag lists its tag object, and a branch can move before
|
|
235
|
+
* the clone. fetchGitHubTemplate reads it from the checkout instead (spec FAQ 7.10). */
|
|
236
|
+
export async function resolveGitHubRef(t, run) {
|
|
237
|
+
// HEAD is listed EXPLICITLY: adding refspecs otherwise drops the symref line that names the
|
|
238
|
+
// default branch (measured on this repo: 375 refs unfiltered, 188 with the filter, and no
|
|
239
|
+
// `ref: refs/heads/... HEAD` unless HEAD is asked for by name).
|
|
240
|
+
const res = await run(['ls-remote', '--symref', repoUrl(t), 'HEAD', 'refs/heads/*', 'refs/tags/*'], { timeoutMs: LS_REMOTE_TIMEOUT_MS });
|
|
241
|
+
if (res.timedOut)
|
|
242
|
+
throw new Error(`timed out after ${LS_REMOTE_TIMEOUT_MS / 1000}s resolving ${repoLabel(t)}`);
|
|
243
|
+
if (/\bENOENT\b/.test(res.stderr))
|
|
244
|
+
throw new Error(gitMissingMessage());
|
|
245
|
+
if (res.code !== 0)
|
|
246
|
+
throw new Error(unreadableRepoMessage(t, res.stderr));
|
|
247
|
+
const { head, refs } = parseLsRemote(res.stdout);
|
|
248
|
+
if (!t.refAndPath) {
|
|
249
|
+
if (!head)
|
|
250
|
+
throw new Error(unreadableRepoMessage(t, 'the remote named no default branch'));
|
|
251
|
+
return { ref: head, qualifiedRef: `refs/heads/${head}`, path: '' };
|
|
252
|
+
}
|
|
253
|
+
const split = splitRefAndPath(t.refAndPath, refs);
|
|
254
|
+
if (!split)
|
|
255
|
+
throw new Error(`no branch or tag ${t.refAndPath} in ${t.owner}/${t.repo}`);
|
|
256
|
+
return split;
|
|
257
|
+
}
|
|
258
|
+
/** What to call the manifest in a message: where the user pointed, never the temporary clone that
|
|
259
|
+
* is deleted before they read it. */
|
|
260
|
+
export function manifestLabel(t, r) {
|
|
261
|
+
return `${t.owner}/${t.repo}@${r.ref}:${r.path ? `${r.path}/` : ''}${MANIFEST_FILE}`;
|
|
262
|
+
}
|
|
263
|
+
export function missingManifestMessage(t, r) {
|
|
264
|
+
return [
|
|
265
|
+
`no ${MANIFEST_FILE} at ${t.owner}/${t.repo}@${r.ref}:${r.path || '/'}.`,
|
|
266
|
+
`Point the URL at the directory that contains it, for example https://github.com/${t.owner}/${t.repo}/tree/${r.ref}/templates/<name>`,
|
|
267
|
+
].join(' ');
|
|
268
|
+
}
|
|
269
|
+
export function escapedManifestMessage(t, r) {
|
|
270
|
+
return `${MANIFEST_FILE} at ${t.owner}/${t.repo}@${r.ref}:${r.path || '/'} resolves outside the repository — refusing to read it`;
|
|
271
|
+
}
|
|
272
|
+
// The clone root, symlinks resolved, so containment is compared like with like.
|
|
273
|
+
function containedRealPath(root, candidate) {
|
|
274
|
+
const realRoot = realpathSync(root);
|
|
275
|
+
const real = realpathSync(candidate);
|
|
276
|
+
if (real !== realRoot && !real.startsWith(realRoot + sep))
|
|
277
|
+
return null;
|
|
278
|
+
return real;
|
|
279
|
+
}
|
|
280
|
+
/** Resolve the ref, shallow-clone it, read the commit that was checked out, prove the manifest
|
|
281
|
+
* sits inside the clone, parse it, delete the clone. Nothing on disk outlives this call: not the
|
|
282
|
+
* variable prompt, not the POST, not the watcher. */
|
|
283
|
+
export async function fetchGitHubTemplate(target, run = defaultGitRunner, parse = parseManifestYaml) {
|
|
284
|
+
const resolved = await resolveGitHubRef(target, run);
|
|
285
|
+
const dir = mkdtempSync(join(tmpdir(), 'insta-tpl-gh-'));
|
|
286
|
+
try {
|
|
287
|
+
// The short name, not resolved.qualifiedRef: `--branch` rejects a fully-qualified ref, and
|
|
288
|
+
// git's own short-name tie-break already agrees with splitRefAndPath (spec FAQ 7.14).
|
|
289
|
+
const cloned = await run(['clone', '--depth', '1', '--quiet', '--branch', resolved.ref, repoUrl(target), dir], { timeoutMs: CLONE_TIMEOUT_MS });
|
|
290
|
+
if (cloned.timedOut)
|
|
291
|
+
throw new Error(`timed out after ${CLONE_TIMEOUT_MS / 1000}s cloning https://github.com/${target.owner}/${target.repo}`);
|
|
292
|
+
if (/\bENOENT\b/.test(cloned.stderr))
|
|
293
|
+
throw new Error(gitMissingMessage());
|
|
294
|
+
if (cloned.code !== 0)
|
|
295
|
+
throw new Error(unreadableRepoMessage(target, cloned.stderr));
|
|
296
|
+
// The deployed commit is the one in the checkout: an annotated tag's listing entry is its tag
|
|
297
|
+
// object, and a branch can move between ls-remote and here (spec FAQ 7.10).
|
|
298
|
+
const head = await run(['-C', dir, 'rev-parse', 'HEAD'], { timeoutMs: LS_REMOTE_TIMEOUT_MS });
|
|
299
|
+
// Same three outcomes the other two calls distinguish, so a timeout or a missing git here is
|
|
300
|
+
// not reported as an unreadable repository.
|
|
301
|
+
if (head.timedOut)
|
|
302
|
+
throw new Error(`timed out after ${LS_REMOTE_TIMEOUT_MS / 1000}s reading the clone of ${repoLabel(target)}`);
|
|
303
|
+
if (/\bENOENT\b/.test(head.stderr))
|
|
304
|
+
throw new Error(gitMissingMessage());
|
|
305
|
+
if (head.code !== 0)
|
|
306
|
+
throw new Error(unreadableRepoMessage(target, head.stderr));
|
|
307
|
+
const commit = head.stdout.trim();
|
|
308
|
+
const manifestDir = resolved.path ? join(dir, resolved.path) : dir;
|
|
309
|
+
if (!existsSync(join(manifestDir, MANIFEST_FILE)))
|
|
310
|
+
throw new Error(missingManifestMessage(target, resolved));
|
|
311
|
+
// A committed symlink can point anywhere; only the resolved path proves what is being read.
|
|
312
|
+
const real = containedRealPath(dir, join(manifestDir, MANIFEST_FILE));
|
|
313
|
+
if (!real || !statSync(real).isFile())
|
|
314
|
+
throw new Error(escapedManifestMessage(target, resolved));
|
|
315
|
+
// Read and parse separately so a validation failure names where the user pointed. Handing the
|
|
316
|
+
// loader a directory makes it report the temp path, which is gone by the time they see it.
|
|
317
|
+
const manifest = parse(readFileSync(real, 'utf8'), manifestLabel(target, resolved));
|
|
318
|
+
return {
|
|
319
|
+
source: { repo: `${target.owner}/${target.repo}`, ref: resolved.ref, path: resolved.path, commit },
|
|
320
|
+
manifest,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
rmSync(dir, { recursive: true, force: true });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=github-source.js.map
|
package/dist/index.js
CHANGED
|
@@ -131,8 +131,9 @@ svc.command('add [type] [name]').description('Provision a service on demand (ass
|
|
|
131
131
|
.option('--public', 'storage only: serve the bucket with anonymous public-read (default private)')
|
|
132
132
|
.option('--image <url>', 'compute only: run this container image at creation')
|
|
133
133
|
.option('--port <n>', 'compute only: port the image listens on (default 8080)')
|
|
134
|
-
.option('--always-on', 'compute only: create as always-on — never scales to zero (all plans; billing is actual usage either way)')
|
|
135
|
-
.option('--
|
|
134
|
+
.option('--always-on', 'compute only: create as always-on — never scales to zero (the default for new compute services; all plans; billing is actual usage either way)')
|
|
135
|
+
.option('--no-always-on', 'compute only: create as scale-to-zero — idle machines suspend and wake on the next request')
|
|
136
|
+
.option('--volume <gi>', 'compute only: attach a persistent /data volume of this many whole Gi (also attachable later: `insta compute volume <name> --size <gi>`; any plan may attach at the default 10 (the free cap, on every plan); larger sizes are paid and plan-capped). Volume services keep 1 machine and stop (cold wake) instead of suspend when idle')
|
|
136
137
|
.option('--json')
|
|
137
138
|
.action(guard(async (type, name, o) => {
|
|
138
139
|
const a = await resolveServiceArgs(type, name, serviceArgsDeps(o.json), o);
|
|
@@ -220,10 +221,10 @@ compute.command('restart [service]').description("Restart a compute service by r
|
|
|
220
221
|
.option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((service, o) => computeCmd.computeRestart(service, o)));
|
|
221
222
|
compute.command('status [service]').description("Show a compute service's desired vs. live state")
|
|
222
223
|
.option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((service, o) => computeCmd.computeStatus(service, o)));
|
|
223
|
-
compute.command('limits [service]').description("Show or set a compute service's resource ceiling (paid
|
|
224
|
+
compute.command('limits [service]').description("Show or set a compute service's resource ceiling (any plan within the free cap; raising above it needs a paid plan). --memory is the dial; cpu derives from it unless --cpu is given. Billing is actual usage — the ceiling caps what the app may burn, it is not a price")
|
|
224
225
|
.option('--memory <size>', 'memory ceiling, e.g. 512mb or 1gb').option('--cpu <n>', 'vCPU ceiling override (provider sizes: 1, 2, 4, 6, 8)')
|
|
225
226
|
.option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((service, o) => computeCmd.computeLimits(service, o)));
|
|
226
|
-
compute.command('always-on <mode> [service]').description('Set a compute service always-on (mode: on|off). on = machines never scale to zero; off =
|
|
227
|
+
compute.command('always-on <mode> [service]').description('Set a compute service always-on (mode: on|off). on = machines never scale to zero (the default for new compute services); off = scale-to-zero. All plans; billing is actual usage either way')
|
|
227
228
|
.option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((mode, service, o) => computeCmd.computeAlwaysOn(mode, service, o)));
|
|
228
229
|
const execCmd = compute.command('exec [service]').description("Run a one-shot command inside a compute service's machine (`insta compute exec [service] -- <command> [args…]`) — no interactive shell/PTY: `command` is argv, no shell is invoked (use [\"sh\", \"-c\", \"...\"] for shell features). Wakes the machine first if it's scaled to zero — expect a few seconds of latency, billed as uptime, not an error. Exits with the remote command's own exit code (agents rely on this)")
|
|
229
230
|
.action(guard((service, o) => computeCmd.computeExec(service, execCommand, o, { windowsFallback: execWindowsFallback })));
|
|
@@ -231,7 +232,7 @@ const execCmd = compute.command('exec [service]').description("Run a one-shot co
|
|
|
231
232
|
// new option cannot reach the CLI surface while the split still reads it as part of the command.
|
|
232
233
|
for (const [flags, description] of computeCmd.EXEC_OPTIONS)
|
|
233
234
|
execCmd.option(flags, description);
|
|
234
|
-
compute.command('volume [service]').description("Show, attach, grow, or delete a compute service's persistent /data volume. No flag: print size, mount path, and the plan cap (any plan). --size on a volumeless service ATTACHES one (any plan at the default
|
|
235
|
+
compute.command('volume [service]').description("Show, attach, grow, or delete a compute service's persistent /data volume. No flag: print size, mount path, and the plan cap (any plan). --size on a volumeless service ATTACHES one (any plan at the default 10Gi, the free cap; larger is paid and plan-capped; the disk mounts at /data on the next deploy); on a volume-bearing one it grows (paid plans; grow-only — a provisioned disk cannot shrink). --delete DESTROYS the disk and ALL its data immediately (no detach, no undo; billing stops now, and suspend fast-wake + scale-out return). Billing is actual data stored — the size is a cap, not a price")
|
|
235
236
|
.option('--size <gi>', 'new size in whole Gi, e.g. 10 (must be ≥ the current size)')
|
|
236
237
|
.option('--delete', 'destroy the volume and ALL its data (irreversible; download anything you need first)')
|
|
237
238
|
.option('--json').option('--branch <branch>', 'branch (default: current)').action(guard((service, o) => computeCmd.computeVolume(service, o)));
|
|
@@ -243,7 +244,7 @@ db.command('url').description('Print the postgres connection string (DSN) — ba
|
|
|
243
244
|
db.command('connect').description("Open an interactive psql session on the postgres service (needs psql on PATH; gated: secrets.read). A suspended instance wakes on connect — the first prompt can take a few seconds. Exits with psql's own exit code")
|
|
244
245
|
.option('--branch <branch>', 'branch (default: current)').option('--group <g>', 'postgres service name (default: the sole/default one)')
|
|
245
246
|
.action(guard((o) => dbCmd.dbConnect(o)));
|
|
246
|
-
db.command('limits').description("Show or set a postgres service's resource ceiling (paid
|
|
247
|
+
db.command('limits').description("Show or set a postgres service's resource ceiling (any plan within the free cap, paid above it; insta-db-backed only). Moves both directions")
|
|
247
248
|
.option('--cpu <n>', "vCPU ceiling, e.g. 2 or 2500m").option('--memory <size>', "memory ceiling, e.g. 4Gi")
|
|
248
249
|
.option('--json').option('--branch <branch>', 'branch (default: current)').option('--group <g>', 'postgres service name (default: the sole/default one)')
|
|
249
250
|
.action(guard((o) => dbCmd.dbLimits(o)));
|
|
@@ -281,12 +282,12 @@ storage.command('delete <key>').description('DELETES one object from the bucket
|
|
|
281
282
|
.option('--service <name>', 'storage service (default: the sole one on the branch)')
|
|
282
283
|
.option('--branch <b>', 'branch (default: current)').option('--json')
|
|
283
284
|
.action(guard((key, o) => storageCmd.storageDelete(key, o)));
|
|
284
|
-
// ---- templates (registry
|
|
285
|
-
const tpl = program.command('template').description('Browse and deploy app templates (registry,
|
|
285
|
+
// ---- templates (registry, local insta.template.yaml, or a GitHub URL) ----
|
|
286
|
+
const tpl = program.command('template').description('Browse and deploy app templates (registry, a local dir, or a GitHub URL)');
|
|
286
287
|
tpl.command('list').description('List templates in the platform registry').option('--json').action(guard((o) => template.templateList(o)));
|
|
287
288
|
tpl.command('info <code>').description('Show a template: version, upstream pin, services, and its required/optional variables')
|
|
288
289
|
.option('--json').action(guard((code, o) => template.templateInfo(code, o)));
|
|
289
|
-
tpl.command('deploy <code-or-dir>').description('Deploy a template onto a branch — a registry code,
|
|
290
|
+
tpl.command('deploy <code-or-dir-or-url>').description('Deploy a template onto a branch — a registry code, a local directory containing insta.template.yaml (a path-looking target is always read as a directory), or a github.com URL (https://github.com/<owner>/<repo>[/tree/<ref>[/<dir>]]) whose manifest is fetched with your own git credentials. Missing required variables are prompted for on a terminal; generator-backed (secret:N) and defaulted ones are resolved by the platform')
|
|
290
291
|
.option('--branch <b>', 'target branch (default: current)')
|
|
291
292
|
.option('--set <NAME=value>', 'set a template variable (repeatable)', (v, prev) => [...prev, v], [])
|
|
292
293
|
.option('-y, --yes', 'non-interactive: missing required variables fail with a --set list instead of prompting')
|
|
@@ -78,8 +78,30 @@ export function validateManifest(m) {
|
|
|
78
78
|
for (const name of names) {
|
|
79
79
|
const svc = services[name] ?? {};
|
|
80
80
|
const where = `services.${name}`;
|
|
81
|
-
if (svc.type !== 'web' && svc.type !== 'worker')
|
|
82
|
-
problems.push(`${where}.type must be web or
|
|
81
|
+
if (svc.type !== 'web' && svc.type !== 'worker' && svc.type !== 'postgres') {
|
|
82
|
+
problems.push(`${where}.type must be web, worker or postgres`);
|
|
83
|
+
}
|
|
84
|
+
// A managed postgres service is BARE: the platform owns its image, port, sizing, credentials
|
|
85
|
+
// and env, so every other rule below would be asking about fields it must not carry. Mirrors
|
|
86
|
+
// the platform's own check (provisioning/templateManifest.ts) so an author hears it here.
|
|
87
|
+
if (svc.type === 'postgres') {
|
|
88
|
+
const bare = svc;
|
|
89
|
+
for (const field of ['image', 'build', 'port', 'healthcheck', 'volume', 'volumeGib', 'spec', 'alwaysOn']) {
|
|
90
|
+
if (bare[field] !== undefined) {
|
|
91
|
+
problems.push(`${where}.${field}: a postgres service is platform-managed and carries no ${field} — declare it bare ({ type: postgres })`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const groups = ['fixed', 'generated', 'platform', 'required', 'optional'];
|
|
95
|
+
const envShell = bare.env;
|
|
96
|
+
if (envShell !== undefined) {
|
|
97
|
+
const emptyShell = !!envShell && typeof envShell === 'object' && !Array.isArray(envShell)
|
|
98
|
+
&& Object.entries(envShell).every(([g, v]) => groups.includes(g) && !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0);
|
|
99
|
+
if (!emptyShell) {
|
|
100
|
+
problems.push(`${where}.env: a postgres service is platform-managed and carries no env — declare it bare ({ type: postgres })`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
83
105
|
if (svc.image && svc.build)
|
|
84
106
|
problems.push(`${where}: image and build are mutually exclusive`);
|
|
85
107
|
if (!svc.image && !svc.build)
|