@40rty/ams-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,19 @@
1
+ import { fail, readConfig, storeBinding } from '../lib/context.mjs';
2
+ import { call } from '../lib/credentials.mjs';
3
+
4
+ /** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
5
+ export async function connect() {
6
+ const config = await readConfig();
7
+ const { domain, token, shopId } = await storeBinding();
8
+ if (domain === undefined || token === undefined) fail('.env must set PUBLIC_STORE_DOMAIN and PUBLIC_STOREFRONT_API_TOKEN');
9
+ const store = { hosting: { embedded: true, headless: true }, storefrontAccessToken: token };
10
+ // The numeric shop id is how the agent's catalog search is scoped to this store.
11
+ if (shopId !== undefined) store.globalShopId = shopId;
12
+
13
+ const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, {
14
+ platform: 'shopify',
15
+ platformConfig: { platform: 'shopify', domain, config: store },
16
+ vertical: 'ecommerce',
17
+ });
18
+ console.log(`space "${result.slug}" is connected to ${domain} — \`forty dev\` to work on it`);
19
+ }
@@ -0,0 +1,54 @@
1
+ // `forty create <dir>` — start a spacefront package from nothing.
2
+ //
3
+ // Copies the starter (templates/package) into a new directory: a catalog with
4
+ // the types a store needs, a component for each, a shell and a Tailwind build.
5
+ // It writes no forty.config.json: the first `forty dev` signs in, asks which
6
+ // space this is for and writes it (`forty init`).
7
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { cwd, fail } from '../lib/context.mjs';
11
+
12
+ const TEMPLATE = fileURLToPath(new URL('../../templates/package', import.meta.url));
13
+ // The sdk, ui and CLI are released together at one version, so the CLI's own
14
+ // version is the one the starter depends on.
15
+ const CLI_MANIFEST = fileURLToPath(new URL('../../package.json', import.meta.url));
16
+
17
+ /** npm strips a `.gitignore` from a published tarball, so the template carries it unhidden. */
18
+ const RENAMED = { gitignore: '.gitignore' };
19
+
20
+ async function copy(from, to, replace) {
21
+ await mkdir(to, { recursive: true });
22
+ for (const entry of await readdir(from, { withFileTypes: true })) {
23
+ const source = path.join(from, entry.name);
24
+ const target = path.join(to, entry.name in RENAMED ? RENAMED[entry.name] : entry.name);
25
+ if (entry.isDirectory()) await copy(source, target, replace);
26
+ else await writeFile(target, replace(await readFile(source, 'utf8')));
27
+ }
28
+ }
29
+
30
+ export async function create() {
31
+ const dir = process.argv[3];
32
+ if (dir === undefined) fail('usage: forty create <directory>');
33
+ const target = path.resolve(cwd, dir);
34
+ const existing = await readdir(target).catch((err) => {
35
+ if (err.code === 'ENOENT') return [];
36
+ throw err;
37
+ });
38
+ if (existing.length > 0) fail(`${dir} already exists and is not empty`);
39
+
40
+ // The directory names the package: `my-store` → `@my-store/spacefront`, "My Store".
41
+ const slug = path.basename(target).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
42
+ if (slug === '') fail(`cannot make a package name from "${dir}" — use letters, digits and hyphens`);
43
+ const label = slug.split('-').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
44
+ const { version } = JSON.parse(await readFile(CLI_MANIFEST, 'utf8'));
45
+
46
+ await copy(TEMPLATE, target, (text) =>
47
+ text.replaceAll('__PACKAGE__', `@${slug}/spacefront`).replaceAll('__LABEL__', label).replaceAll('__VERSION__', `^${version}`),
48
+ );
49
+
50
+ console.log(`created ${dir} — @${slug}/spacefront\n`);
51
+ console.log(` cd ${dir}`);
52
+ console.log(' npm install');
53
+ console.log(' npm run dev # sign in, pick your space, then every save updates your preview\n');
54
+ }
@@ -0,0 +1,83 @@
1
+ // `forty dev` — work on the project against its space, without touching what
2
+ // the space's visitors see.
3
+ //
4
+ // Every save is built and stored as this developer's DRAFT on the space. The
5
+ // draft is rendered only for a session opened with the preview token this
6
+ // command is given; everyone else keeps seeing the published package, which
7
+ // changes only on `forty publish`.
8
+ //
9
+ // A package the platform hosts is rebuilt whole, and the open preview page
10
+ // swaps it in place. An app that hosts its own spacefront already hot-reloads
11
+ // its components; only its catalog and manifests travel, and the token goes
12
+ // into its `.env`.
13
+ import { watch } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { cwd, deployment, fail, readConfig, readConfigIfPresent, writeDotenv } from '../lib/context.mjs';
16
+ import { call } from '../lib/credentials.mjs';
17
+ import { init } from './init.mjs';
18
+ import { buildRelease } from './publish.mjs';
19
+
20
+ const SETTLE_MS = 150;
21
+
22
+ export async function dev() {
23
+ if ((await readConfigIfPresent()) === null) await init();
24
+ const config = await readConfig();
25
+
26
+ const files = [config.catalog, config.manifests];
27
+ if (config.bundle !== undefined) files.push(path.dirname(config.bundle.entry));
28
+ if (config.bundle !== undefined && typeof config.bundle.css === 'string') files.push(config.bundle.css);
29
+ if (typeof config.seedLayout === 'string') files.push(config.seedLayout);
30
+ if (typeof config.brand === 'string') files.push(config.brand);
31
+ if (typeof config.prompts === 'string') files.push(config.prompts);
32
+ const dirs = new Set(files.map((file) => (path.extname(file) === '' ? file : path.dirname(file))));
33
+
34
+ // The preview credential, from the first draft that lands. It outlives every later save.
35
+ let token;
36
+ let running = false;
37
+ let again = false;
38
+ async function save() {
39
+ if (running) {
40
+ again = true;
41
+ return;
42
+ }
43
+ running = true;
44
+ const started = Date.now();
45
+ try {
46
+ const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/draft`, await buildRelease(config));
47
+ console.log(`${new Date().toLocaleTimeString()} ${result.types.length} types → preview of ${config.spaceSlug} (${Date.now() - started} ms)`);
48
+ if (token === undefined) token = result.token;
49
+ } catch (err) {
50
+ // A save that does not build is the normal case here: report it and keep watching.
51
+ console.error(`forty: ${err.message}`);
52
+ }
53
+ running = false;
54
+ if (again) {
55
+ again = false;
56
+ await save();
57
+ }
58
+ }
59
+
60
+ await save();
61
+ if (token === undefined) fail('the draft was refused — fix the problem above and run `forty dev` again');
62
+
63
+ if (config.bundle === undefined) {
64
+ // This app hosts the spacefront: it presents the token itself.
65
+ await writeDotenv('FORTY_DEV_TOKEN', token);
66
+ console.log('\n wrote FORTY_DEV_TOKEN to .env — your app previews the draft. Keep it out of version control.\n');
67
+ } else {
68
+ console.log(`\n ${deployment(config).consoleUrl}/${config.spaceSlug}?preview=${token}\n`);
69
+ }
70
+ // `--once`: store the draft and stop — for a script, or an agent, that cannot hold a watcher open.
71
+ if (process.argv.includes('--once')) return;
72
+ console.log(`watching ${[...dirs].join(', ')} — visitors see none of this until \`forty publish\``);
73
+
74
+ let timer;
75
+ for (const dir of dirs) {
76
+ watch(path.resolve(cwd, dir), { recursive: true }, () => {
77
+ clearTimeout(timer);
78
+ timer = setTimeout(save, SETTLE_MS);
79
+ });
80
+ }
81
+ // Runs until interrupted.
82
+ await new Promise(() => {});
83
+ }
@@ -0,0 +1,111 @@
1
+ // `forty doctor [dev-server-url]` — the integration's definition of done.
2
+ //
3
+ // Every check names what is wrong in the repo's own terms. Exits non-zero when
4
+ // any fail, so it is the same gate in CI as on a laptop.
5
+ import { access, readFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { loadCatalog } from '../lib/build.mjs';
8
+ import { cwd, readConfig, readDotenv } from '../lib/context.mjs';
9
+ import { findCredential, request } from '../lib/credentials.mjs';
10
+
11
+ /** What the ecommerce vertical requires a source to draw, and what the agent speaks through. */
12
+ const REQUIRED_TYPES = ['productGrid', 'collectionList'];
13
+ const REQUIRED_RENDERERS = ['agentText', 'turn'];
14
+
15
+ async function exists(file) {
16
+ try {
17
+ await access(path.join(cwd, file));
18
+ return true;
19
+ } catch (err) {
20
+ if (err.code === 'ENOENT') return false;
21
+ throw err;
22
+ }
23
+ }
24
+
25
+ /** A status, or 0 when the server cannot be reached at all. */
26
+ async function statusOf(url, init) {
27
+ try {
28
+ return await fetch(url, init);
29
+ } catch (err) {
30
+ console.log(` (${url}: ${err.message})`);
31
+ return { status: 0, ok: false, headers: new Headers() };
32
+ }
33
+ }
34
+
35
+ export async function doctor() {
36
+ const devOrigin = process.argv[3];
37
+ const config = await readConfig();
38
+ const selfHosted = config.bundle === undefined;
39
+ const failures = [];
40
+ const check = (ok, message, fix) => {
41
+ console.log(`${ok ? '✓' : '✗'} ${message}${ok || fix === undefined ? '' : ` — ${fix}`}`);
42
+ if (!ok) failures.push(message);
43
+ };
44
+
45
+ // ── The repo ──
46
+ const hasCatalog = await exists(config.catalog);
47
+ check(hasCatalog, `catalog file ${config.catalog} exists`);
48
+ if (hasCatalog) {
49
+ check(!/from ['"]react['"]/.test(await readFile(path.join(cwd, config.catalog), 'utf8')), 'the catalog file does not import React');
50
+ const types = Object.keys(await loadCatalog(config.catalog));
51
+ for (const type of REQUIRED_TYPES) check(types.includes(type), `the catalog declares "${type}"`);
52
+ }
53
+ if (selfHosted) {
54
+ const componentsFile = path.join(path.dirname(config.catalog), 'components.tsx');
55
+ const text = (await exists(componentsFile)) ? await readFile(path.join(cwd, componentsFile), 'utf8') : '';
56
+ for (const type of REQUIRED_RENDERERS) check(new RegExp(`\\b${type}\\s*:`).test(text), `${componentsFile} draws "${type}"`);
57
+ }
58
+
59
+ // ── The platform ──
60
+ const credential = await findCredential(config.apiUrl);
61
+ check(credential !== null, 'signed in', 'run `forty login`, or set FORTY_API_KEY in CI');
62
+ if (credential !== null) {
63
+ const me = await request(config.apiUrl, 'GET', '/org/me');
64
+ check(me.ok, `the credential from ${credential.source} is accepted by ${config.apiUrl}`);
65
+ const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
66
+ check(space !== undefined, `space "${config.spaceSlug}" belongs to this organization`);
67
+ if (space !== undefined) {
68
+ // Not a failure either way: before the first release a space renders the
69
+ // platform's own components, and the brand's only in a preview.
70
+ const released = space.componentSources.length === 1 && space.componentSources[0] === config.sourceId;
71
+ console.log(released ? `- visitors see ${config.sourceId}` : `- not released yet: visitors see ${space.componentSources.join(', ')} — \`forty publish\` when ready`);
72
+ }
73
+ }
74
+
75
+ // ── A self-hosted app: the visitor credential, the engine, and its own route ──
76
+ if (selfHosted) {
77
+ const token = (await readDotenv(path.join(cwd, '.env'))).FORTY_DEV_TOKEN;
78
+ check(token !== undefined, '.env carries FORTY_DEV_TOKEN', 'run `forty dev`');
79
+ if (token !== undefined) {
80
+ const session = await statusOf(`${config.apiUrl}/s/${config.spaceSlug}/sessions`, {
81
+ method: 'POST',
82
+ headers: { 'content-type': 'application/json', 'x-api-key': token },
83
+ body: JSON.stringify({ visitorId: 'forty-doctor' }),
84
+ });
85
+ check(session.status === 200, 'a session opens on the space with that token', 'it may have expired — run `forty dev`');
86
+ }
87
+
88
+ const sdk = JSON.parse(await readFile(path.join(cwd, 'node_modules/@40rty/ams-sdk/package.json'), 'utf8'));
89
+ const engine = await statusOf(`${config.apiUrl}/embed/engine/${sdk.version}/engine.mjs`, { method: 'HEAD' });
90
+ check(engine.status === 200, `the API serves the engine for sdk ${sdk.version}`);
91
+
92
+ check(typeof config.route === 'string', 'forty.config.json names the spacefront "route"');
93
+ if (typeof config.route === 'string' && devOrigin !== undefined) {
94
+ const served = await statusOf(`${devOrigin}${config.route}`);
95
+ check(served.status === 200, `the dev server at ${devOrigin} serves ${config.route}`);
96
+ const csp = served.headers.get('content-security-policy');
97
+ if (csp !== null) {
98
+ check(csp.includes(config.apiUrl), `CSP on ${config.route} allows ${config.apiUrl}`);
99
+ check(csp.includes(config.apiUrl.replace(/^http/, 'ws')), `CSP on ${config.route} allows ${config.apiUrl.replace(/^http/, 'ws')}`);
100
+ }
101
+ } else if (devOrigin === undefined) {
102
+ console.log('- skipped the route and CSP checks: pass the dev server url, e.g. `forty doctor http://localhost:3000`');
103
+ }
104
+ }
105
+
106
+ if (failures.length > 0) {
107
+ console.error(`\n${failures.length} check(s) failed.`);
108
+ process.exit(1);
109
+ }
110
+ console.log('\nAll checks passed.');
111
+ }
@@ -0,0 +1,58 @@
1
+ // `forty init` — write forty.config.json for this repo.
2
+ //
3
+ // Asks only what it cannot work out: which of the organization's spaces this
4
+ // repo is for. Whether the app hosts itself (a Hydrogen store) or is a UI
5
+ // package the platform hosts is read from package.json.
6
+ import { readFile, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { createInterface } from 'node:readline/promises';
9
+ import { CONFIG_FILE, cwd, deployment, fail, readConfigIfPresent } from '../lib/context.mjs';
10
+ import { call, findCredential } from '../lib/credentials.mjs';
11
+ import { login } from './login.mjs';
12
+
13
+ /** Sources the platform owns; a space still on one has not been given the organization's own yet. */
14
+ const RESERVED = /^@(fourty|forty)\//;
15
+
16
+ async function ask(question, fallback) {
17
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
18
+ const answer = (await rl.question(fallback === undefined ? `${question}: ` : `${question} (${fallback}): `)).trim();
19
+ rl.close();
20
+ if (answer !== '') return answer;
21
+ if (fallback === undefined) fail(`${question} is required`);
22
+ return fallback;
23
+ }
24
+
25
+ async function pickSpace(spaces) {
26
+ if (spaces.length === 0) fail('this organization has no spaces yet — create one in the console, then run `forty init` again');
27
+ if (spaces.length === 1) return spaces[0];
28
+ spaces.forEach((space, i) => console.log(` ${i + 1}. ${space.slug}`));
29
+ const choice = await ask('Which space is this repo for', '1');
30
+ const space = spaces[Number.parseInt(choice, 10) - 1];
31
+ if (space === undefined) fail(`"${choice}" is not one of the spaces above`);
32
+ return space;
33
+ }
34
+
35
+ export async function init() {
36
+ if ((await readConfigIfPresent()) !== null) fail(`${CONFIG_FILE} already exists — edit it, or delete it to start over`);
37
+ const { apiUrl } = deployment(null);
38
+ if ((await findCredential(apiUrl)) === null) await login();
39
+
40
+ const me = await call(apiUrl, 'GET', '/org/me');
41
+ const space = await pickSpace(me.spaces);
42
+
43
+ const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
44
+ const dependencies = manifest.dependencies === undefined ? {} : manifest.dependencies;
45
+ const selfHosted = dependencies['@shopify/hydrogen'] !== undefined;
46
+
47
+ const own = space.componentSources.find((source) => !RESERVED.test(source));
48
+ const named = typeof manifest.name === 'string' && manifest.name.startsWith('@') && !RESERVED.test(manifest.name) ? manifest.name : undefined;
49
+ const sourceId = own !== undefined ? own : await ask('Package id, as @your-org/name', named);
50
+
51
+ const config = selfHosted
52
+ ? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs', route: '/ask' }
53
+ : { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'src/catalog.ts', manifests: 'src/catalogs', bundle: { entry: 'src/index.ts', css: 'dist/package.css' } };
54
+ await writeFile(path.join(cwd, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
55
+
56
+ console.log(`wrote ${CONFIG_FILE} for space "${space.slug}" — ${selfHosted ? 'this app hosts the spacefront' : 'the platform hosts the spacefront from this package'}`);
57
+ console.log(selfHosted ? 'next: forty connect, then forty dev' : 'next: forty dev');
58
+ }
@@ -0,0 +1,74 @@
1
+ // `forty login` — sign in through the browser.
2
+ //
3
+ // The CLI listens on a loopback port and opens the console's approval page.
4
+ // The signed-in person picks an organization; the console creates an API key
5
+ // for it and sends the browser back here with it. Nobody copies a secret, and
6
+ // the key is revocable on the organization's API keys screen.
7
+ import { spawn } from 'node:child_process';
8
+ import { randomBytes } from 'node:crypto';
9
+ import { createServer } from 'node:http';
10
+ import { styleText } from 'node:util';
11
+ import { deployment, fail, readConfigIfPresent } from '../lib/context.mjs';
12
+ import { storeCredential } from '../lib/credentials.mjs';
13
+
14
+ const WAIT_MS = 5 * 60 * 1000;
15
+
16
+ function openBrowser(url) {
17
+ const [bin, args] = process.platform === 'darwin' ? ['open', [url]]
18
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]]
19
+ : ['xdg-open', [url]];
20
+ // A machine with no browser still works: the URL is already printed.
21
+ spawn(bin, args, { stdio: 'ignore', detached: true })
22
+ .on('error', (err) => console.warn(`forty: could not open a browser (${err.message}) — open the link above yourself`))
23
+ .unref();
24
+ }
25
+
26
+ /** Wait for the console to send the browser back with a key for `state`. */
27
+ function awaitApproval(server, state, done) {
28
+ return new Promise((resolve, reject) => {
29
+ const timer = setTimeout(() => reject(new Error('nobody approved the login within 5 minutes')), WAIT_MS);
30
+ server.on('request', (req, res) => {
31
+ const url = new URL(req.url, 'http://127.0.0.1');
32
+ const key = url.searchParams.get('key');
33
+ // Anything that is not our own login coming back is ignored, not trusted.
34
+ if (url.pathname !== '/callback' || url.searchParams.get('state') !== state || key === null) {
35
+ res.writeHead(404).end();
36
+ return;
37
+ }
38
+ // Straight back to the console: the address carrying the key is never
39
+ // the page the person is left on, nor a visible history entry.
40
+ res.writeHead(302, { Location: done }).end();
41
+ clearTimeout(timer);
42
+ resolve({ key, organization: url.searchParams.get('organization'), name: url.searchParams.get('name') });
43
+ });
44
+ });
45
+ }
46
+
47
+ export async function login() {
48
+ const { apiUrl, consoleUrl } = deployment(await readConfigIfPresent());
49
+ const state = randomBytes(24).toString('base64url');
50
+ const server = createServer();
51
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
52
+ const url = `${consoleUrl}/account/cli?port=${server.address().port}&state=${state}`;
53
+
54
+ console.log(`\n Approve this terminal in your browser\n ${styleText('dim', url)}\n`);
55
+ openBrowser(url);
56
+
57
+ let approval;
58
+ try {
59
+ approval = await awaitApproval(server, state, `${consoleUrl}/account/cli?connected=1`);
60
+ } catch (err) {
61
+ fail(err.message);
62
+ } finally {
63
+ server.close();
64
+ server.closeAllConnections();
65
+ }
66
+
67
+ // The key must work against THIS api before it is remembered for it.
68
+ const res = await fetch(`${apiUrl}/org/me`, { headers: { 'x-api-key': approval.key } });
69
+ if (!res.ok) fail(`${consoleUrl} issued a key that ${apiUrl} does not accept (${res.status}) — are the two the same deployment?`);
70
+
71
+ await storeCredential(apiUrl, { key: approval.key, organization: approval.organization, name: approval.name });
72
+ const signedInTo = approval.name === null ? approval.organization : approval.name;
73
+ console.log(` ${styleText('green', '✔')} Signed in to ${styleText('bold', String(signedInTo))}\n ${styleText('dim', 'next:')} forty init\n`);
74
+ }
@@ -0,0 +1,37 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { PackageReleaseSchema, catalogToWire } from '../../dist/wire.js';
4
+ import { buildBundle, loadBrandDefinition, loadCatalog, loadManifests } from '../lib/build.mjs';
5
+ import { cwd, readConfig } from '../lib/context.mjs';
6
+ import { call } from '../lib/credentials.mjs';
7
+
8
+ /** Everything a release carries, built from the repo as it is right now. */
9
+ export async function buildRelease(config) {
10
+ const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
11
+ const release = {
12
+ sourceId: config.sourceId,
13
+ label: config.label,
14
+ version: manifest.version,
15
+ catalog: catalogToWire(await loadCatalog(config.catalog)),
16
+ manifests: await loadManifests(config.manifests),
17
+ };
18
+ if (config.bundle !== undefined) release.bundle = await buildBundle(config.bundle);
19
+ // Optional, for a package the platform hosts: the class its stylesheet styles
20
+ // under, and the canvas a fresh session opens on. A brand in the platform's
21
+ // repository names its `brand.ts` instead, which also carries its prompt
22
+ // sections and vertical config.
23
+ if (typeof config.brand === 'string') Object.assign(release, await loadBrandDefinition(config.brand, config.prompts));
24
+ if (typeof config.theme === 'string') release.theme = { themeClass: config.theme };
25
+ if (typeof config.seedLayout === 'string') release.seedLayout = JSON.parse(await readFile(path.join(cwd, config.seedLayout), 'utf8'));
26
+ return PackageReleaseSchema.parse(release);
27
+ }
28
+
29
+ /** `forty publish` — release: the package changes, and the space's visitors see it. */
30
+ export async function publish() {
31
+ const config = await readConfig();
32
+ const release = await buildRelease(config);
33
+ const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}`, release);
34
+ const built = release.bundle === undefined ? '' : ` + components (${(release.bundle.js.length / 1024).toFixed(0)} KB js, ${(release.bundle.css.length / 1024).toFixed(0)} KB css)`;
35
+ console.log(`released ${result.sourceId} — release ${result.release}: ${result.types.length} types${built} — live on "${result.composed}"`);
36
+ console.log(` undo with \`forty rollback\``);
37
+ }
@@ -0,0 +1,40 @@
1
+ // `forty releases` and `forty rollback` — a package's history, and the pointer
2
+ // that says which release is live.
3
+ //
4
+ // A release is never changed or deleted by publishing: every `forty publish`
5
+ // appends one. Rolling back makes an earlier one live again, and rolling
6
+ // forward is the same command with a later number.
7
+ import { fail, readConfig } from '../lib/context.mjs';
8
+ import { call } from '../lib/credentials.mjs';
9
+
10
+ async function history(config) {
11
+ return call(config.apiUrl, 'GET', `/org/packages/releases?source=${encodeURIComponent(config.sourceId)}`);
12
+ }
13
+
14
+ export async function releases() {
15
+ const config = await readConfig();
16
+ const { active, releases: list } = await history(config);
17
+ for (const release of list) {
18
+ const when = new Date(release.createdAt).toLocaleString();
19
+ console.log(`${release.number === active ? '●' : ' '} release ${release.number} v${release.version} ${release.publishedBy} ${when}`);
20
+ }
21
+ }
22
+
23
+ /** `forty rollback [number]` — without a number, the release before the live one. */
24
+ export async function rollback() {
25
+ const config = await readConfig();
26
+ const { active, releases: list } = await history(config);
27
+ const asked = process.argv[3];
28
+ let target;
29
+ if (asked === undefined) {
30
+ const earlier = list.filter((release) => release.number < active);
31
+ if (earlier.length === 0) fail(`release ${active} is the first — there is nothing to roll back to`);
32
+ target = earlier[0].number;
33
+ } else {
34
+ target = Number.parseInt(asked, 10);
35
+ if (!list.some((release) => release.number === target)) fail(`${config.sourceId} has no release "${asked}" — see \`forty releases\``);
36
+ }
37
+ if (target === active) fail(`release ${target} is already live`);
38
+ await call(config.apiUrl, 'POST', '/org/packages/releases/activate', { sourceId: config.sourceId, release: target });
39
+ console.log(`${config.sourceId}: release ${target} is live (was ${active})`);
40
+ }
package/bin/forty.mjs ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ // forty — connect a repo to its organization's space on the platform.
3
+ //
4
+ // forty create start a new spacefront package from the starter
5
+ // forty login sign in through the browser (once per machine)
6
+ // forty init write forty.config.json for one of the organization's spaces
7
+ // forty dev work on the project: every save becomes your draft on the
8
+ // space, seen only through your preview — visitors keep
9
+ // seeing what is published
10
+ // forty publish release it: the package changes and the space's visitors
11
+ // see it. The catalog + manifests named in the config; with
12
+ // a `bundle` entry the components too, for a hosted spacefront
13
+ // forty releases the package's release history, and which one is live
14
+ // forty rollback make an earlier release live again (`forty rollback 3`)
15
+ // forty connect attach this app's store to the space. The space already
16
+ // exists — it is created in the console
17
+ // forty doctor check the whole integration; non-zero when anything is off
18
+ //
19
+ // Run from the repo's root. The credential is `FORTY_API_KEY` when set (CI),
20
+ // otherwise the login stored by `forty login`.
21
+ import { FortyError } from './lib/context.mjs';
22
+
23
+ const commands = {
24
+ create: () => import('./commands/create.mjs').then((m) => m.create()),
25
+ login: () => import('./commands/login.mjs').then((m) => m.login()),
26
+ init: () => import('./commands/init.mjs').then((m) => m.init()),
27
+ publish: () => import('./commands/publish.mjs').then((m) => m.publish()),
28
+ releases: () => import('./commands/releases.mjs').then((m) => m.releases()),
29
+ rollback: () => import('./commands/releases.mjs').then((m) => m.rollback()),
30
+ connect: () => import('./commands/connect.mjs').then((m) => m.connect()),
31
+ dev: () => import('./commands/dev.mjs').then((m) => m.dev()),
32
+ doctor: () => import('./commands/doctor.mjs').then((m) => m.doctor()),
33
+ };
34
+ try {
35
+ const command = commands[process.argv[2]];
36
+ if (command === undefined) throw new FortyError(`usage: forty <${Object.keys(commands).join('|')}>`);
37
+ await command();
38
+ // Exits outright: a compiled catalog may leave timers of its own running.
39
+ process.exit(0);
40
+ } catch (err) {
41
+ if (!(err instanceof FortyError)) throw err;
42
+ console.error(`forty: ${err.message}`);
43
+ process.exit(1);
44
+ }