@ptkl/toolkit 1.7.0 → 1.9.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 +11 -0
- package/dist/commands/__tests__/kiln.test.js +522 -0
- package/dist/commands/__tests__/kortexPlaybook.test.js +1 -1
- package/dist/commands/forge.js +24 -7
- package/dist/commands/generate-types.js +1 -1
- package/dist/commands/index.js +2 -0
- package/dist/commands/kiln.js +693 -0
- package/dist/commands/kortexPlaybook.js +12 -9
- package/dist/commands/validate-idl.js +1 -1
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +12 -0
- package/dist/lib/__tests__/forgeDevPublicHost.test.js +36 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +39 -2
- package/dist/lib/__tests__/resolveEnv.test.js +20 -0
- package/dist/lib/forgeDevKernelPlugin.js +2 -2
- package/dist/lib/forgeDevPublicHost.js +39 -0
- package/dist/lib/forgeDevServiceServer.js +10 -10
- package/dist/lib/kilnClient.js +106 -0
- package/dist/lib/kilnPack.js +61 -0
- package/dist/lib/scaffold.js +1 -1
- package/dist/lib/sdk.js +3 -2
- package/dist/lib/util.js +13 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
2
|
import { readFileSync, writeFileSync } from "fs";
|
|
3
|
-
import { kortex as kortexClient } from "../lib/sdk.js";
|
|
3
|
+
import { kortex as kortexClient, resolveEnv } from "../lib/sdk.js";
|
|
4
4
|
import { registerCommand, withProfile } from "../lib/scaffold.js";
|
|
5
5
|
import PlaybookValidator, { MAX_RULE_LENGTH } from "../lib/kortex/playbookValidator.js";
|
|
6
6
|
// The first @ptkl/sdk release with the Workforce methods.
|
|
@@ -219,16 +219,18 @@ export default class KortexPlaybookCommand {
|
|
|
219
219
|
.description('Put a version to work in dev or live')
|
|
220
220
|
.requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
|
|
221
221
|
.requiredOption('--version <version>', 'Version to deploy')).action(withProfile(async (profile, opts) => {
|
|
222
|
-
|
|
223
|
-
|
|
222
|
+
const env = resolveEnv();
|
|
223
|
+
this.checkEnv(env);
|
|
224
|
+
return (await this.client(profile).deployPlaybook(opts.uuid, { version: opts.version, env })).data;
|
|
224
225
|
}));
|
|
225
226
|
}
|
|
226
227
|
rollback() {
|
|
227
228
|
return registerCommand(new Command('rollback')
|
|
228
229
|
.description('Go back to the previous version in dev or live')
|
|
229
230
|
.requiredOption('-u, --uuid <uuid>', 'Playbook UUID')).action(withProfile(async (profile, opts) => {
|
|
230
|
-
|
|
231
|
-
|
|
231
|
+
const env = resolveEnv();
|
|
232
|
+
this.checkEnv(env);
|
|
233
|
+
return (await this.client(profile).rollbackPlaybook(opts.uuid, { env })).data;
|
|
232
234
|
}));
|
|
233
235
|
}
|
|
234
236
|
deployments() {
|
|
@@ -243,18 +245,19 @@ export default class KortexPlaybookCommand {
|
|
|
243
245
|
// Plain Command: `-f`/`-o` are not needed here and `--input` is a file.
|
|
244
246
|
run() {
|
|
245
247
|
return new Command('run')
|
|
246
|
-
.description('Start a run of the version deployed to --env (default dev). Exit: 0 done, 1 failed, 2 needs a person, 3 still waiting after --timeout (with --wait)')
|
|
248
|
+
.description('Start a run of the version deployed to --env (default PROJECT_ENV, else dev). Exit: 0 done, 1 failed, 2 needs a person, 3 still waiting after --timeout (with --wait)')
|
|
247
249
|
.requiredOption('-u, --uuid <uuid>', 'Playbook UUID')
|
|
248
|
-
.option('--env <env>', 'dev | live
|
|
250
|
+
.option('--env <env>', 'dev | live (default: PROJECT_ENV, else dev)')
|
|
249
251
|
.option('--instructions <text>', 'Instructions for this run')
|
|
250
252
|
.option('--input <file>', 'JSON file passed to the run as input')
|
|
251
253
|
.option('--wait', 'Wait until the run ends or needs a person, then print the outcome')
|
|
252
254
|
.option('--interval <seconds>', 'Seconds between checks with --wait', '3')
|
|
253
255
|
.option('--timeout <seconds>', 'Stop waiting after this long (0 = no limit)', '0')
|
|
254
256
|
.action(withProfile(async (profile, opts) => {
|
|
255
|
-
|
|
257
|
+
const env = resolveEnv();
|
|
258
|
+
this.checkEnv(env);
|
|
256
259
|
const client = this.client(profile);
|
|
257
|
-
const body = { env
|
|
260
|
+
const body = { env };
|
|
258
261
|
if (opts.instructions)
|
|
259
262
|
body.instructions = opts.instructions;
|
|
260
263
|
if (opts.input)
|
|
@@ -78,7 +78,7 @@ class ValidateIDLCommand {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
const profile = util.getCurrentProfile();
|
|
81
|
-
const client = new Api({ token: profile.token, host: profile.host, env: options.env });
|
|
81
|
+
const client = new Api({ token: profile.token, host: profile.host, env: options.env ?? process.env.PROJECT_ENV });
|
|
82
82
|
const target = options.ref ? `ref: ${options.ref}` : `inline IDL (${options.idlFile})`;
|
|
83
83
|
console.log(`⏳ Validating value against ${target}…`);
|
|
84
84
|
let result;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
|
|
2
3
|
import { forgeDevKernelPlugin } from '../forgeDevKernelPlugin.js';
|
|
3
4
|
const fake = (token, appUuid = '') => ({
|
|
4
5
|
configured: true,
|
|
@@ -31,4 +32,15 @@ describe('forgeDevKernelPlugin', () => {
|
|
|
31
32
|
expect(out[0].children).toContain("sessionStorage.removeItem('forge_app_uuid')");
|
|
32
33
|
expect(out[0].children).not.toContain("setItem('forge_app_uuid'");
|
|
33
34
|
});
|
|
35
|
+
it('points the hub at localhost by default', async () => {
|
|
36
|
+
const p = forgeDevKernelPlugin('app', 'https://p', 9229, 'dev', 'https://h', fake('tok'));
|
|
37
|
+
const out = await p.transformIndexHtml();
|
|
38
|
+
expect(out[0].children).toContain('window.__PTKL_DEV_HUB__="http://localhost:9229"');
|
|
39
|
+
});
|
|
40
|
+
it('points the hub at the public host when given', async () => {
|
|
41
|
+
const p = forgeDevKernelPlugin('app', 'https://p', 9229, 'dev', 'https://h', fake('tok'), new ForgeDevPublicHost('macbook-devbox'));
|
|
42
|
+
const out = await p.transformIndexHtml();
|
|
43
|
+
expect(out[0].children).toContain('window.__PTKL_DEV_HUB__="http://macbook-devbox:9229"');
|
|
44
|
+
expect(out[0].children).not.toContain('http://localhost:9229');
|
|
45
|
+
});
|
|
34
46
|
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
|
|
3
|
+
describe('ForgeDevPublicHost', () => {
|
|
4
|
+
it.each([undefined, '', ' '])('is disabled for %j', (v) => {
|
|
5
|
+
const h = new ForgeDevPublicHost(v);
|
|
6
|
+
expect(h.enabled).toBe(false);
|
|
7
|
+
expect(h.baseUrl(5173)).toBe('http://localhost:5173');
|
|
8
|
+
expect(h.listenAddress()).toBe('127.0.0.1');
|
|
9
|
+
expect(h.allowsOrigin('http://localhost:5173')).toBe(false);
|
|
10
|
+
});
|
|
11
|
+
it.each(['macbook-devbox', 'devbox.tail1234.ts.net', '100.64.0.7', ' macbook-devbox '])('accepts %j', (v) => {
|
|
12
|
+
expect(new ForgeDevPublicHost(v).enabled).toBe(true);
|
|
13
|
+
});
|
|
14
|
+
it.each(['http://x', 'x:5173', 'a/b', 'a b', '*', '*.example.com', '-x', 'x-', 'a_b'])('rejects %j', (v) => {
|
|
15
|
+
expect(() => new ForgeDevPublicHost(v)).toThrow(/--public-host/);
|
|
16
|
+
});
|
|
17
|
+
it('builds the base url and listens on all interfaces', () => {
|
|
18
|
+
const h = new ForgeDevPublicHost(' macbook-devbox ');
|
|
19
|
+
expect(h.baseUrl(9229)).toBe('http://macbook-devbox:9229');
|
|
20
|
+
expect(h.listenAddress()).toBe('0.0.0.0');
|
|
21
|
+
});
|
|
22
|
+
it.each([
|
|
23
|
+
['http://macbook-devbox:5201', true],
|
|
24
|
+
['https://MacBook-Devbox', true],
|
|
25
|
+
['http://macbook-devbox', true],
|
|
26
|
+
['http://other-host:5201', false],
|
|
27
|
+
['http://evil-macbook-devbox', false],
|
|
28
|
+
['http://macbook-devbox.evil.com', false],
|
|
29
|
+
['http://evil.com/macbook-devbox', false],
|
|
30
|
+
['ftp://macbook-devbox', false],
|
|
31
|
+
['not a url', false],
|
|
32
|
+
['', false],
|
|
33
|
+
])('allowsOrigin(%j) = %s', (origin, expected) => {
|
|
34
|
+
expect(new ForgeDevPublicHost('macbook-devbox').allowsOrigin(origin)).toBe(expected);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { ForgeDevServiceServer } from '../forgeDevServiceServer.js';
|
|
3
|
+
import { ForgeDevPublicHost } from '../forgeDevPublicHost.js';
|
|
3
4
|
import { ForgeDevServiceExec } from '../forgeDevServiceExec.js';
|
|
4
5
|
let server;
|
|
5
6
|
afterEach(() => new Promise((r) => (server ? server.close(() => r()) : r())));
|
|
6
|
-
async function start() {
|
|
7
|
+
async function start(publicHost) {
|
|
7
8
|
const posts = [];
|
|
8
9
|
const post = vi.fn(async (url, _p, c) => {
|
|
9
10
|
posts.push({ url, bearer: c.headers.Authorization });
|
|
@@ -15,7 +16,7 @@ async function start() {
|
|
|
15
16
|
const srv = new ForgeDevServiceServer({
|
|
16
17
|
port: 0, appName: 'app', appType: 'app', env: 'dev',
|
|
17
18
|
services: [{ name: 'gate' }], bundles: { gate: 'code' }, exec,
|
|
18
|
-
log: quiet, warn: quiet, error: quiet,
|
|
19
|
+
log: quiet, warn: quiet, error: quiet, publicHost,
|
|
19
20
|
});
|
|
20
21
|
await new Promise((r) => { server = srv.listen(r); });
|
|
21
22
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
@@ -110,4 +111,40 @@ describe('ForgeDevServiceServer', () => {
|
|
|
110
111
|
const { address } = await start();
|
|
111
112
|
expect(address.address).toBe('127.0.0.1');
|
|
112
113
|
});
|
|
114
|
+
describe('with --public-host', () => {
|
|
115
|
+
const pub = () => new ForgeDevPublicHost('macbook-devbox');
|
|
116
|
+
const origin = 'http://macbook-devbox:5201';
|
|
117
|
+
it('without it, the same remote origin is refused', async () => {
|
|
118
|
+
const { base, post } = await start();
|
|
119
|
+
const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: origin }, body: '{}' });
|
|
120
|
+
expect(res.status).toBe(403);
|
|
121
|
+
expect(post).not.toHaveBeenCalled();
|
|
122
|
+
});
|
|
123
|
+
it('accepts the public host origin and echoes it', async () => {
|
|
124
|
+
const { base } = await start(pub());
|
|
125
|
+
const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: origin }, body: '{}' });
|
|
126
|
+
expect(res.status).toBe(200);
|
|
127
|
+
expect(res.headers.get('access-control-allow-origin')).toBe(origin);
|
|
128
|
+
expect(res.headers.get('access-control-allow-credentials')).toBe('true');
|
|
129
|
+
});
|
|
130
|
+
it('still refuses any other remote origin', async () => {
|
|
131
|
+
const { base, post } = await start(pub());
|
|
132
|
+
const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Authorization: 'Bearer x', Origin: 'http://evil-macbook-devbox:5201' }, body: '{}' });
|
|
133
|
+
expect(res.status).toBe(403);
|
|
134
|
+
expect(res.headers.get('access-control-allow-origin')).toBeNull();
|
|
135
|
+
expect(post).not.toHaveBeenCalled();
|
|
136
|
+
});
|
|
137
|
+
it('still requires a bearer from the public origin', async () => {
|
|
138
|
+
const { base, post } = await start(pub());
|
|
139
|
+
const res = await fetch(`${base}/gate`, { method: 'POST', headers: { ...json, Origin: origin }, body: '{}' });
|
|
140
|
+
expect(res.status).toBe(401);
|
|
141
|
+
expect(post).not.toHaveBeenCalled();
|
|
142
|
+
});
|
|
143
|
+
it('lists services under the public host url and binds all interfaces', async () => {
|
|
144
|
+
const { base, address } = await start(pub());
|
|
145
|
+
const body = await (await fetch(`${base}/`)).json();
|
|
146
|
+
expect(body.services[0].url).toBe('http://macbook-devbox:0/gate');
|
|
147
|
+
expect(address.address).toBe('0.0.0.0');
|
|
148
|
+
});
|
|
149
|
+
});
|
|
113
150
|
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { resolveEnv } from '../sdk.js';
|
|
3
|
+
describe('resolveEnv', () => {
|
|
4
|
+
afterEach(() => {
|
|
5
|
+
delete process.env.PTKL_ACTIVE_ENV;
|
|
6
|
+
delete process.env.PROJECT_ENV;
|
|
7
|
+
});
|
|
8
|
+
it('is dev with nothing set', () => {
|
|
9
|
+
expect(resolveEnv()).toBe('dev');
|
|
10
|
+
});
|
|
11
|
+
it('uses PROJECT_ENV when no --env was given', () => {
|
|
12
|
+
process.env.PROJECT_ENV = 'live';
|
|
13
|
+
expect(resolveEnv()).toBe('live');
|
|
14
|
+
});
|
|
15
|
+
it('lets --env win over PROJECT_ENV', () => {
|
|
16
|
+
process.env.PROJECT_ENV = 'live';
|
|
17
|
+
process.env.PTKL_ACTIVE_ENV = 'dev';
|
|
18
|
+
expect(resolveEnv()).toBe('dev');
|
|
19
|
+
});
|
|
20
|
+
});
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* in platform-forge/src/lib/dynamicImport.ts — uses a DOM overlay with an iframe
|
|
8
8
|
* instead of a popup window to avoid popup blockers.
|
|
9
9
|
*/
|
|
10
|
-
export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEnv, apiHost, devToken) {
|
|
10
|
+
export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEnv, apiHost, devToken, publicHost) {
|
|
11
11
|
const appRef = appName ?? '';
|
|
12
12
|
const platUrl = platformUrl ? platformUrl.replace(/\/$/, '') : '';
|
|
13
13
|
// The consent page is a standalone load: without this it reads the dashboard's own env
|
|
@@ -20,7 +20,7 @@ export function forgeDevKernelPlugin(appName, platformUrl, devHubPort, projectEn
|
|
|
20
20
|
var _env=${JSON.stringify(env)};
|
|
21
21
|
var _apiHost=${JSON.stringify(host)};
|
|
22
22
|
window.$forge=window.$forge||{};
|
|
23
|
-
${devHubPort ? ` window.__PTKL_DEV_HUB__
|
|
23
|
+
${devHubPort ? ` window.__PTKL_DEV_HUB__=${JSON.stringify(publicHost?.baseUrl(devHubPort) ?? `http://localhost:${devHubPort}`)};\n window.DEV_HUB_PORT=${devHubPort};` : ''}
|
|
24
24
|
function openPlatformPopup(url){return window.open(url,'_blank');}
|
|
25
25
|
function showWaitingOverlay(message){
|
|
26
26
|
var overlay=document.createElement('div');
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Opt-in (`ptkl forge dev --public-host <host>`): the name other machines use to reach this
|
|
2
|
+
// one. Disabled by default, which keeps every dev listener on loopback.
|
|
3
|
+
const HOST_NAME = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/;
|
|
4
|
+
export class ForgeDevPublicHost {
|
|
5
|
+
host;
|
|
6
|
+
constructor(host) {
|
|
7
|
+
const trimmed = host?.trim();
|
|
8
|
+
if (!trimmed)
|
|
9
|
+
return;
|
|
10
|
+
if (!HOST_NAME.test(trimmed)) {
|
|
11
|
+
throw new Error(`--public-host must be a bare host name or IPv4 address (no scheme, port or path), got "${trimmed}"`);
|
|
12
|
+
}
|
|
13
|
+
this.host = trimmed;
|
|
14
|
+
}
|
|
15
|
+
get enabled() { return this.host !== undefined; }
|
|
16
|
+
/** The validated host name; undefined when disabled. */
|
|
17
|
+
get name() { return this.host; }
|
|
18
|
+
/** Where a browser reaches a dev listener on `port`. */
|
|
19
|
+
baseUrl(port) {
|
|
20
|
+
return `http://${this.host ?? 'localhost'}:${port}`;
|
|
21
|
+
}
|
|
22
|
+
/** True only for an http(s) origin on the public host, any port. */
|
|
23
|
+
allowsOrigin(origin) {
|
|
24
|
+
if (!this.host)
|
|
25
|
+
return false;
|
|
26
|
+
try {
|
|
27
|
+
const url = new URL(origin);
|
|
28
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
29
|
+
return false;
|
|
30
|
+
return url.hostname.toLowerCase() === this.host.toLowerCase();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
listenAddress() {
|
|
37
|
+
return this.enabled ? '0.0.0.0' : '127.0.0.1';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -3,7 +3,8 @@ import { randomUUID } from 'crypto';
|
|
|
3
3
|
// This server runs the app's services as the app token (your credential if it cannot mint) and
|
|
4
4
|
// has no `service::{name} forge::{uuid}` to enforce: dev services are unbuilt source with no
|
|
5
5
|
// revision and no app uuid. Two things bound who can call it: reachability (loopback bind and
|
|
6
|
-
// the local-origin check below
|
|
6
|
+
// the local-origin check below, unless --public-host widens both to that one host) and the
|
|
7
|
+
// caller's identity (a bearer is required).
|
|
7
8
|
const LOCAL_ORIGIN = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
|
|
8
9
|
const BEARER = /^Bearer\s+\S+/i;
|
|
9
10
|
export class ForgeDevServiceServer {
|
|
@@ -20,23 +21,22 @@ export class ForgeDevServiceServer {
|
|
|
20
21
|
error(m) { (this.opts.error ?? console.error)(m); }
|
|
21
22
|
listen(onListening) {
|
|
22
23
|
const server = http.createServer((req, res) => { void this.handle(req, res); });
|
|
23
|
-
// Loopback
|
|
24
|
-
|
|
25
|
-
server.listen(this.port, '127.0.0.1', onListening);
|
|
24
|
+
// Loopback unless --public-host was given.
|
|
25
|
+
server.listen(this.port, this.opts.publicHost?.listenAddress() ?? '127.0.0.1', onListening);
|
|
26
26
|
return server;
|
|
27
27
|
}
|
|
28
28
|
async handle(req, res) {
|
|
29
|
-
// CORS, for the local dev page only. A cross-origin POST of JSON
|
|
30
|
-
// refusing unknown origins here keeps a page you happen to be visiting from driving
|
|
29
|
+
// CORS, for the local dev page (or the --public-host page) only. A cross-origin POST of JSON
|
|
30
|
+
// is preflighted, so refusing unknown origins here keeps a page you happen to be visiting from driving
|
|
31
31
|
// your services. Requests with no Origin at all are your own tools (curl, tests).
|
|
32
32
|
const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
|
|
33
|
-
const localOrigin = origin === undefined || LOCAL_ORIGIN.test(origin);
|
|
33
|
+
const localOrigin = origin === undefined || LOCAL_ORIGIN.test(origin) || (this.opts.publicHost?.allowsOrigin(origin) ?? false);
|
|
34
34
|
res.setHeader('Vary', 'Origin');
|
|
35
35
|
if (origin && localOrigin) {
|
|
36
36
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
37
37
|
// The SDK's axios client sets withCredentials, so the browser treats every call here as
|
|
38
|
-
// credentialed and drops the response unless this says true. It is only ever sent back to
|
|
39
|
-
//
|
|
38
|
+
// credentialed and drops the response unless this says true. It is only ever sent back to an
|
|
39
|
+
// allowed origin, which was already checked above.
|
|
40
40
|
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
41
41
|
}
|
|
42
42
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
@@ -69,7 +69,7 @@ export class ForgeDevServiceServer {
|
|
|
69
69
|
services: this.opts.services.map((s) => ({
|
|
70
70
|
name: s.name,
|
|
71
71
|
access: s.access || 'public',
|
|
72
|
-
url: `http://localhost:${this.port}/${s.name}`,
|
|
72
|
+
url: `${this.opts.publicHost?.baseUrl(this.port) ?? `http://localhost:${this.port}`}/${s.name}`,
|
|
73
73
|
})),
|
|
74
74
|
}, null, 2));
|
|
75
75
|
return;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { resolveEnv } from "./sdk.js";
|
|
4
|
+
/** The Kiln API (sandbox `/v1/kiln`) behind luma's gateway: `<platform host>/luma/kiln{path}`. */
|
|
5
|
+
export default class KilnClient {
|
|
6
|
+
http;
|
|
7
|
+
constructor(profile) {
|
|
8
|
+
this.http = axios.create({
|
|
9
|
+
baseURL: `${profile.host.replace(/\/+$/, "")}/luma/kiln`,
|
|
10
|
+
timeout: 0,
|
|
11
|
+
maxBodyLength: Infinity,
|
|
12
|
+
maxContentLength: Infinity,
|
|
13
|
+
validateStatus: (s) => s >= 200 && s < 300,
|
|
14
|
+
});
|
|
15
|
+
// The token is read again for every request: inside a machine it is refreshed every few minutes.
|
|
16
|
+
this.http.interceptors.request.use((cfg) => {
|
|
17
|
+
cfg.headers.set("Authorization", `Bearer ${profile.token}`);
|
|
18
|
+
if (profile.project)
|
|
19
|
+
cfg.headers.set("X-Project-Uuid", profile.project);
|
|
20
|
+
cfg.headers.set("X-Project-Env", resolveEnv());
|
|
21
|
+
return cfg;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
async call(config) {
|
|
25
|
+
return (await this.http.request(config)).data;
|
|
26
|
+
}
|
|
27
|
+
images() { return this.call({ method: "GET", url: "/images" }); }
|
|
28
|
+
sizes() { return this.call({ method: "GET", url: "/sizes" }); }
|
|
29
|
+
usage() { return this.call({ method: "GET", url: "/usage" }); }
|
|
30
|
+
machineUsage(uuid) { return this.call({ method: "GET", url: `/machines/${uuid}/usage` }); }
|
|
31
|
+
list(deleted = false) {
|
|
32
|
+
return this.call({ method: "GET", url: "/machines", params: deleted ? { deleted: "true" } : undefined });
|
|
33
|
+
}
|
|
34
|
+
get(uuid) { return this.call({ method: "GET", url: `/machines/${uuid}` }); }
|
|
35
|
+
create(body) {
|
|
36
|
+
return this.call({ method: "POST", url: "/machines", data: body, headers: { "Idempotency-Key": randomUUID() } });
|
|
37
|
+
}
|
|
38
|
+
start(uuid, body) { return this.call({ method: "POST", url: `/machines/${uuid}/start`, data: body }); }
|
|
39
|
+
stop(uuid, force = false) { return this.call({ method: "POST", url: `/machines/${uuid}/stop${force ? "?force=true" : ""}` }); }
|
|
40
|
+
signal(uuid, signal) {
|
|
41
|
+
return this.call({ method: "POST", url: `/machines/${uuid}/signal`, data: { signal } });
|
|
42
|
+
}
|
|
43
|
+
extend(uuid, minutes) {
|
|
44
|
+
return this.call({
|
|
45
|
+
method: "POST", url: `/machines/${uuid}/extend`, data: { minutes },
|
|
46
|
+
headers: { "Idempotency-Key": randomUUID() },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** The API asks for the machine's name (its uuid when it has none) as confirmation. */
|
|
50
|
+
remove(uuid, name) {
|
|
51
|
+
return this.call({ method: "DELETE", url: `/machines/${uuid}`, data: { name } });
|
|
52
|
+
}
|
|
53
|
+
jobs() { return this.call({ method: "GET", url: "/jobs" }); }
|
|
54
|
+
job(ref) { return this.call({ method: "GET", url: `/jobs/${encodeURIComponent(ref)}` }); }
|
|
55
|
+
createJob(body) { return this.call({ method: "POST", url: "/jobs", data: body }); }
|
|
56
|
+
updateJob(ref, body) {
|
|
57
|
+
return this.call({ method: "PATCH", url: `/jobs/${encodeURIComponent(ref)}`, data: body });
|
|
58
|
+
}
|
|
59
|
+
removeJob(ref) { return this.call({ method: "DELETE", url: `/jobs/${encodeURIComponent(ref)}` }); }
|
|
60
|
+
runJob(ref) {
|
|
61
|
+
return this.call({ method: "POST", url: `/jobs/${encodeURIComponent(ref)}/runs`, headers: { "Idempotency-Key": randomUUID() } });
|
|
62
|
+
}
|
|
63
|
+
jobRuns(ref) { return this.call({ method: "GET", url: `/jobs/${encodeURIComponent(ref)}/runs` }); }
|
|
64
|
+
jobRun(ref, run) {
|
|
65
|
+
return this.call({ method: "GET", url: `/jobs/${encodeURIComponent(ref)}/runs/${encodeURIComponent(run)}` });
|
|
66
|
+
}
|
|
67
|
+
processes(uuid, limit) {
|
|
68
|
+
return this.call({ method: "GET", url: `/machines/${uuid}/processes`, params: limit ? { limit } : undefined });
|
|
69
|
+
}
|
|
70
|
+
exec(uuid, body) { return this.call({ method: "POST", url: `/machines/${uuid}/exec`, data: body }); }
|
|
71
|
+
logs(uuid, since) {
|
|
72
|
+
return this.call({ method: "GET", url: `/machines/${uuid}/logs`, params: since ? { since } : undefined });
|
|
73
|
+
}
|
|
74
|
+
/** The followed log: a stream of newline-delimited JSON events (ready, line, end). */
|
|
75
|
+
async followLogs(uuid, since) {
|
|
76
|
+
const res = await this.http.request({
|
|
77
|
+
method: "GET", url: `/machines/${uuid}/logs`, responseType: "stream",
|
|
78
|
+
params: { follow: "true", ...(since ? { since } : {}) },
|
|
79
|
+
});
|
|
80
|
+
return res.data;
|
|
81
|
+
}
|
|
82
|
+
status(uuid) { return this.call({ method: "GET", url: `/machines/${uuid}/status` }); }
|
|
83
|
+
listFiles(uuid, path, depth) {
|
|
84
|
+
return this.call({ method: "POST", url: `/machines/${uuid}/files/list`, data: { path, depth: depth ?? 0 } });
|
|
85
|
+
}
|
|
86
|
+
/** A file's bytes, and the time left the API reports in its headers. */
|
|
87
|
+
async getFile(uuid, path) {
|
|
88
|
+
const res = await this.http.request({
|
|
89
|
+
method: "GET", url: `/machines/${uuid}/files`, params: { path }, responseType: "arraybuffer",
|
|
90
|
+
});
|
|
91
|
+
const left = res.headers?.["x-kiln-time-left-sec"];
|
|
92
|
+
return { data: Buffer.from(res.data), timeLeftSec: left !== undefined ? Number(left) : undefined };
|
|
93
|
+
}
|
|
94
|
+
putFile(uuid, path, content, mode) {
|
|
95
|
+
return this.call({
|
|
96
|
+
method: "PUT", url: `/machines/${uuid}/files`, params: { path, ...(mode ? { mode } : {}) },
|
|
97
|
+
data: content, headers: { "Content-Type": "application/octet-stream", "Content-Length": content.length },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
putArchive(uuid, archive, to) {
|
|
101
|
+
return this.call({
|
|
102
|
+
method: "PUT", url: `/machines/${uuid}/archive`, params: to ? { path: to } : undefined,
|
|
103
|
+
data: archive, headers: { "Content-Type": "application/gzip", "Content-Length": archive.length },
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { join, relative } from "node:path";
|
|
4
|
+
import { create } from "tar";
|
|
5
|
+
export const KILN_ARCHIVE_LIMIT = 100 * 1024 * 1024;
|
|
6
|
+
/** Packs a directory as a `.tar.gz` for `PUT …/archive`. */
|
|
7
|
+
export default class KilnPack {
|
|
8
|
+
limit;
|
|
9
|
+
constructor(limit = KILN_ARCHIVE_LIMIT) {
|
|
10
|
+
this.limit = limit;
|
|
11
|
+
}
|
|
12
|
+
/** The files to send: what git would keep (tracked and untracked, minus .gitignore) inside a git
|
|
13
|
+
* work tree, else every file except `.git` and `node_modules`. Paths are relative to `dir`. */
|
|
14
|
+
files(dir) {
|
|
15
|
+
let names;
|
|
16
|
+
try {
|
|
17
|
+
const out = execFileSync("git", ["-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
|
|
18
|
+
encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 256 * 1024 * 1024,
|
|
19
|
+
});
|
|
20
|
+
names = out.split("\0").filter(Boolean);
|
|
21
|
+
}
|
|
22
|
+
catch { /* not a git work tree */ }
|
|
23
|
+
if (names)
|
|
24
|
+
return names.filter((n) => existsSync(join(dir, n)) && !statSync(join(dir, n)).isDirectory());
|
|
25
|
+
return this.walk(dir, dir);
|
|
26
|
+
}
|
|
27
|
+
walk(root, dir) {
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
30
|
+
if (e.name === ".git" || e.name === "node_modules")
|
|
31
|
+
continue;
|
|
32
|
+
const full = join(dir, e.name);
|
|
33
|
+
if (e.isDirectory())
|
|
34
|
+
out.push(...this.walk(root, full));
|
|
35
|
+
else
|
|
36
|
+
out.push(relative(root, full));
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
/** The archive, or an error when it is over the limit (checked as it is built). */
|
|
41
|
+
async pack(dir) {
|
|
42
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory())
|
|
43
|
+
throw new Error(`${dir} is not a directory`);
|
|
44
|
+
const files = this.files(dir);
|
|
45
|
+
if (files.length === 0)
|
|
46
|
+
throw new Error(`${dir} has no files to push`);
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let size = 0;
|
|
49
|
+
const stream = create({ gzip: true, cwd: dir, portable: true }, files);
|
|
50
|
+
stream.on("error", () => { });
|
|
51
|
+
for await (const chunk of stream) {
|
|
52
|
+
size += chunk.length;
|
|
53
|
+
if (size > this.limit) {
|
|
54
|
+
stream.destroy();
|
|
55
|
+
throw new Error(`The archive is over ${Math.round((this.limit / 1024 / 1024) * 100) / 100} MiB, the most a machine takes in one push. Push less, or add the large files to .gitignore`);
|
|
56
|
+
}
|
|
57
|
+
chunks.push(chunk);
|
|
58
|
+
}
|
|
59
|
+
return Buffer.concat(chunks);
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/lib/scaffold.js
CHANGED
|
@@ -8,7 +8,7 @@ export { OutputFormatCommand };
|
|
|
8
8
|
* downstream lib code — src/lib/sdk.ts's `resolveEnv()` — can read it without threading it
|
|
9
9
|
* through every function call). */
|
|
10
10
|
export function withEnvOption(command) {
|
|
11
|
-
return command.option("--env <env>", "Environment to target: dev | live
|
|
11
|
+
return command.option("--env <env>", "Environment to target: dev | live (default: PROJECT_ENV, else dev)");
|
|
12
12
|
}
|
|
13
13
|
/** Build an `OutputFormatCommand`-wrapped command that also carries the global `--env` option.
|
|
14
14
|
* This is the uniform shape new command groups should use:
|
package/dist/lib/sdk.js
CHANGED
|
@@ -7,11 +7,12 @@
|
|
|
7
7
|
// commands never have to think about which host to hit.
|
|
8
8
|
import { Platform, Integrations, Kortex, Workflow, Sandbox, Ratchet, Thunder, Project, Config, Payments, Mail, DMS, Timber, SerbiaMinFin, } from "@ptkl/sdk/beta";
|
|
9
9
|
import Util from "./util.js";
|
|
10
|
-
/** Resolve the active
|
|
10
|
+
/** Resolve the active env (dev|live): an explicit `--env`, else `PROJECT_ENV` (set inside a Kiln
|
|
11
|
+
* machine, the env its token acts in), else `dev`. Commands surface `--env` through
|
|
11
12
|
* the scaffold (see src/lib/scaffold.ts), which stores the resolved value in this env var —
|
|
12
13
|
* mirroring how the existing `--profile` flag is threaded via PTKL_ACTIVE_PROFILE. */
|
|
13
14
|
export function resolveEnv() {
|
|
14
|
-
return process.env.PTKL_ACTIVE_ENV || "dev";
|
|
15
|
+
return process.env.PTKL_ACTIVE_ENV || process.env.PROJECT_ENV || "dev";
|
|
15
16
|
}
|
|
16
17
|
function stripTrailingSlashes(url) {
|
|
17
18
|
return url.replace(/\/+$/, "");
|
package/dist/lib/util.js
CHANGED
|
@@ -53,7 +53,20 @@ export default class Util {
|
|
|
53
53
|
throw new Error(`Failed to init: ${err.message}`);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
+
/** A profile built from the environment: PROJECT_API_TOKEN, API_HOST (required with it) and PROJECT_UUID, the SDK's own names.
|
|
57
|
+
* The token is never printed or logged; errors name the variable only. */
|
|
58
|
+
static envProfile() {
|
|
59
|
+
const host = process.env.API_HOST;
|
|
60
|
+
if (!host)
|
|
61
|
+
throw new Error("PROJECT_API_TOKEN is set but API_HOST is not (API_HOST is required with it)");
|
|
62
|
+
const profile = { name: "env", host, project: process.env.PROJECT_UUID ?? "", current: true };
|
|
63
|
+
Object.defineProperty(profile, "token", { value: process.env.PROJECT_API_TOKEN, enumerable: false });
|
|
64
|
+
return profile;
|
|
65
|
+
}
|
|
56
66
|
static getCurrentProfile() {
|
|
67
|
+
// PROJECT_API_TOKEN (Kiln machines, CI) is used when no profile is chosen with --profile
|
|
68
|
+
if (process.env.PROJECT_API_TOKEN && !process.env.PTKL_ACTIVE_PROFILE)
|
|
69
|
+
return Util.envProfile();
|
|
57
70
|
const profiles = Util.getProfiles();
|
|
58
71
|
// Check if --profile flag was used globally
|
|
59
72
|
const profileNameFromFlag = process.env.PTKL_ACTIVE_PROFILE;
|