@40rty/ams-cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/commands/connect.mjs +67 -0
- package/bin/commands/create.mjs +54 -0
- package/bin/commands/deploy.mjs +64 -0
- package/bin/commands/dev.mjs +83 -0
- package/bin/commands/doctor.mjs +175 -0
- package/bin/commands/feedback.mjs +54 -0
- package/bin/commands/init.mjs +136 -0
- package/bin/commands/login.mjs +74 -0
- package/bin/commands/origin.mjs +20 -0
- package/bin/commands/publish.mjs +41 -0
- package/bin/commands/releases.mjs +40 -0
- package/bin/forty.mjs +53 -0
- package/bin/lib/build.mjs +193 -0
- package/bin/lib/context.mjs +130 -0
- package/bin/lib/credentials.mjs +80 -0
- package/bin/lib/deploy-target.mjs +86 -0
- package/bin/lib/hosted-build.mjs +116 -0
- package/bin/lib/last-failure.mjs +28 -0
- package/bin/lib/tailwind.mjs +41 -0
- package/dist/wire.js +1485 -0
- package/package.json +33 -4
- package/templates/package/README.md +13 -0
- package/templates/package/gitignore +3 -0
- package/templates/package/package.json +26 -0
- package/templates/package/src/blocks.tsx +94 -0
- package/templates/package/src/catalog.ts +39 -0
- package/templates/package/src/catalogs/collectionList.md +11 -0
- package/templates/package/src/catalogs/hero.md +11 -0
- package/templates/package/src/catalogs/productGrid.md +11 -0
- package/templates/package/src/index.ts +20 -0
- package/templates/package/src/shell.tsx +81 -0
- package/templates/package/src/styles.css +10 -0
- package/templates/package/tailwind.config.js +13 -0
- package/templates/package/tsconfig.json +13 -0
- package/README.md +0 -3
|
@@ -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,20 @@
|
|
|
1
|
+
import { fail, positionals, readConfig } from '../lib/context.mjs';
|
|
2
|
+
import { call } from '../lib/credentials.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Let a deployed site call the api for this repo's space. The api refuses a
|
|
6
|
+
* browser origin it does not know (CORS), so a spacefront served from its own
|
|
7
|
+
* domain stays silent until its origin is registered. `localhost` needs none:
|
|
8
|
+
* it is allowed while `forty dev` has a draft on the space.
|
|
9
|
+
*/
|
|
10
|
+
export async function registerOrigin(config, url) {
|
|
11
|
+
const result = await call(config.apiUrl, 'POST', `/org/spaces/${config.spaceSlug}/origins`, { origin: url });
|
|
12
|
+
console.log(result.created ? `${result.origin} may now call the api for "${config.spaceSlug}"` : `${result.origin} was already registered for "${config.spaceSlug}"`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** `forty origin add <url>` */
|
|
16
|
+
export async function origin() {
|
|
17
|
+
const [action, url] = positionals();
|
|
18
|
+
if (action !== 'add' || url === undefined) fail('usage: forty origin add <https://your-site.example>');
|
|
19
|
+
await registerOrigin(await readConfig(), url);
|
|
20
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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, option, readConfig } from '../lib/context.mjs';
|
|
6
|
+
import { call } from '../lib/credentials.mjs';
|
|
7
|
+
import { registerOrigin } from './origin.mjs';
|
|
8
|
+
|
|
9
|
+
/** Everything a release carries, built from the repo as it is right now. */
|
|
10
|
+
export async function buildRelease(config) {
|
|
11
|
+
const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
|
|
12
|
+
const release = {
|
|
13
|
+
sourceId: config.sourceId,
|
|
14
|
+
label: config.label,
|
|
15
|
+
version: manifest.version,
|
|
16
|
+
catalog: catalogToWire(await loadCatalog(config.catalog)),
|
|
17
|
+
manifests: await loadManifests(config.manifests),
|
|
18
|
+
};
|
|
19
|
+
if (config.bundle !== undefined) release.bundle = await buildBundle(config.bundle);
|
|
20
|
+
// Optional, for a package the platform hosts: the class its stylesheet styles
|
|
21
|
+
// under, and the canvas a fresh session opens on. A brand in the platform's
|
|
22
|
+
// repository names its `brand.ts` instead, which also carries its prompt
|
|
23
|
+
// sections and vertical config.
|
|
24
|
+
if (typeof config.brand === 'string') Object.assign(release, await loadBrandDefinition(config.brand, config.prompts));
|
|
25
|
+
if (typeof config.theme === 'string') release.theme = { themeClass: config.theme };
|
|
26
|
+
if (typeof config.seedLayout === 'string') release.seedLayout = JSON.parse(await readFile(path.join(cwd, config.seedLayout), 'utf8'));
|
|
27
|
+
return PackageReleaseSchema.parse(release);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `forty publish` — release: the package changes, and the space's visitors see it. */
|
|
31
|
+
export async function publish() {
|
|
32
|
+
const config = await readConfig();
|
|
33
|
+
const release = await buildRelease(config);
|
|
34
|
+
const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}`, release);
|
|
35
|
+
const built = release.bundle === undefined ? '' : ` + components (${(release.bundle.js.length / 1024).toFixed(0)} KB js, ${(release.bundle.css.length / 1024).toFixed(0)} KB css)`;
|
|
36
|
+
console.log(`released ${result.sourceId} — release ${result.release}: ${result.types.length} types${built} — live on "${result.composed}"`);
|
|
37
|
+
console.log(` undo with \`forty rollback\``);
|
|
38
|
+
// `--origin <url>`: the site this release is deployed to, allowed to call the api.
|
|
39
|
+
const origin = option('origin');
|
|
40
|
+
if (origin !== undefined) await registerOrigin(config, origin);
|
|
41
|
+
}
|
|
@@ -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,53 @@
|
|
|
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
|
+
// creating one when asked (--create <slug>) or when there is none
|
|
8
|
+
// forty dev work on the project: every save becomes your draft on the
|
|
9
|
+
// space, seen only through your preview — visitors keep
|
|
10
|
+
// seeing what is published
|
|
11
|
+
// forty publish release it: the package changes and the space's visitors
|
|
12
|
+
// see it. The catalog + manifests named in the config; with
|
|
13
|
+
// a `bundle` entry the components too, for a hosted spacefront
|
|
14
|
+
// forty releases the package's release history, and which one is live
|
|
15
|
+
// forty rollback make an earlier release live again (`forty rollback 3`)
|
|
16
|
+
// forty connect attach this app's store to the space
|
|
17
|
+
// forty origin add let a deployed site's origin call the api (CORS)
|
|
18
|
+
// forty feedback report a problem to the 40rty team
|
|
19
|
+
// forty doctor check the whole integration; non-zero when anything is off
|
|
20
|
+
// forty deploy host this Hydrogen app on 40rty now and print its live URL
|
|
21
|
+
// (`--detect` prints where the app's own production deploys)
|
|
22
|
+
//
|
|
23
|
+
// Run from the repo's root. The credential is `FORTY_API_KEY` when set (CI),
|
|
24
|
+
// otherwise the login stored by `forty login`.
|
|
25
|
+
import { FortyError } from './lib/context.mjs';
|
|
26
|
+
import { recordFailure } from './lib/last-failure.mjs';
|
|
27
|
+
|
|
28
|
+
const commands = {
|
|
29
|
+
create: () => import('./commands/create.mjs').then((m) => m.create()),
|
|
30
|
+
login: () => import('./commands/login.mjs').then((m) => m.login()),
|
|
31
|
+
init: () => import('./commands/init.mjs').then((m) => m.init()),
|
|
32
|
+
publish: () => import('./commands/publish.mjs').then((m) => m.publish()),
|
|
33
|
+
releases: () => import('./commands/releases.mjs').then((m) => m.releases()),
|
|
34
|
+
rollback: () => import('./commands/releases.mjs').then((m) => m.rollback()),
|
|
35
|
+
connect: () => import('./commands/connect.mjs').then((m) => m.connect()),
|
|
36
|
+
dev: () => import('./commands/dev.mjs').then((m) => m.dev()),
|
|
37
|
+
doctor: () => import('./commands/doctor.mjs').then((m) => m.doctor()),
|
|
38
|
+
origin: () => import('./commands/origin.mjs').then((m) => m.origin()),
|
|
39
|
+
feedback: () => import('./commands/feedback.mjs').then((m) => m.feedback()),
|
|
40
|
+
deploy: () => import('./commands/deploy.mjs').then((m) => m.deploy()),
|
|
41
|
+
};
|
|
42
|
+
try {
|
|
43
|
+
const command = commands[process.argv[2]];
|
|
44
|
+
if (command === undefined) throw new FortyError(`usage: forty <${Object.keys(commands).join('|')}>`);
|
|
45
|
+
await command();
|
|
46
|
+
// Exits outright: a compiled catalog may leave timers of its own running.
|
|
47
|
+
process.exit(0);
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (!(err instanceof FortyError)) throw err;
|
|
50
|
+
console.error(`forty: ${err.message}`);
|
|
51
|
+
if (process.argv[2] !== 'feedback') await recordFailure(process.argv[2], err.message);
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Turning the app's source into what gets published: the catalog (data), the
|
|
2
|
+
// manifests, and — for a spacefront the platform hosts — the component bundle.
|
|
3
|
+
//
|
|
4
|
+
// TypeScript is compiled with esbuild — no build step in the host app, and no
|
|
5
|
+
// dependency on which bundler it uses.
|
|
6
|
+
import { mkdir, readFile, readdir } from 'node:fs/promises';
|
|
7
|
+
import { builtinModules } from 'node:module';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
import { build } from 'esbuild';
|
|
11
|
+
import { cwd, fail } from './context.mjs';
|
|
12
|
+
import { compileTailwind } from './tailwind.mjs';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What the compiled catalog imports by NAME, so the app's one copy is used:
|
|
16
|
+
* zod, because the wire serializer recognises schemas by `instanceof`, and the
|
|
17
|
+
* sdk, the ui and React, because they are the app's.
|
|
18
|
+
*/
|
|
19
|
+
const CATALOG_SHARED = /^(zod|react|react-dom|react\/jsx-runtime|@40rty\/ams-sdk|@40rty\/ams-ui(\/[a-z-]+)?)$/;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The catalog file's own source is compiled; what it installs is not.
|
|
23
|
+
*
|
|
24
|
+
* A catalog may import its declarations from beside its components, and — for
|
|
25
|
+
* a brand in the platform's repository — from `@fourty/*` workspace source
|
|
26
|
+
* that node cannot load as it is. So relative and `@fourty/*` imports are
|
|
27
|
+
* compiled in. Every other package stays a real import, pinned to the file the
|
|
28
|
+
* importing source resolves it to, because the compiled catalog sits in the
|
|
29
|
+
* app's root `node_modules` and could not find a dependency of a dependency
|
|
30
|
+
* from there.
|
|
31
|
+
*/
|
|
32
|
+
const catalogImportsPlugin = {
|
|
33
|
+
name: 'forty-catalog-imports',
|
|
34
|
+
setup(pluginBuild) {
|
|
35
|
+
pluginBuild.onResolve({ filter: /^[^./]/ }, async (args) => {
|
|
36
|
+
if (args.pluginData !== undefined && args.pluginData.resolving === true) return undefined;
|
|
37
|
+
if (CATALOG_SHARED.test(args.path) || args.path.startsWith('node:') || builtinModules.includes(args.path)) return { path: args.path, external: true };
|
|
38
|
+
if (args.path.startsWith('@fourty/')) return undefined;
|
|
39
|
+
const found = await pluginBuild.resolve(args.path, { resolveDir: args.resolveDir, kind: args.kind, pluginData: { resolving: true } });
|
|
40
|
+
if (found.errors.length > 0) return { errors: found.errors };
|
|
41
|
+
return { path: found.path, external: true };
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Import the catalog module. It is compiled to a file inside the app's own
|
|
48
|
+
* `node_modules`, so what it leaves external resolves exactly as it does in
|
|
49
|
+
* the app.
|
|
50
|
+
*/
|
|
51
|
+
export async function loadCatalog(file) {
|
|
52
|
+
const outfile = path.join(cwd, 'node_modules', '.forty', 'catalog.mjs');
|
|
53
|
+
await mkdir(path.dirname(outfile), { recursive: true });
|
|
54
|
+
await build({
|
|
55
|
+
entryPoints: [path.resolve(cwd, file)],
|
|
56
|
+
outfile,
|
|
57
|
+
bundle: true,
|
|
58
|
+
format: 'esm',
|
|
59
|
+
platform: 'node',
|
|
60
|
+
jsx: 'automatic',
|
|
61
|
+
loader: { '.css': 'empty' },
|
|
62
|
+
plugins: [catalogImportsPlugin],
|
|
63
|
+
logLevel: 'error',
|
|
64
|
+
});
|
|
65
|
+
const mod = await import(`${pathToFileURL(outfile).href}?t=${Date.now()}`);
|
|
66
|
+
if (mod.catalog === undefined) fail(`${file} does not export \`catalog\``);
|
|
67
|
+
return mod.catalog;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* What a published bundle takes from the page that loads it, never bundles
|
|
72
|
+
* itself: React, the sdk and — when the package builds on it — `@40rty/ams-ui`,
|
|
73
|
+
* whose contexts and stores must be the page's one copy. `@fourty/*` is the
|
|
74
|
+
* platform's own code: only a brand that lives in the platform's repository
|
|
75
|
+
* imports it, and only a page the platform hosts provides it.
|
|
76
|
+
*/
|
|
77
|
+
const SHARED = /^(react|react-dom|react\/jsx-runtime|framer-motion|zod|@40rty\/ams-sdk|@40rty\/ams-ui(\/.+)?|@fourty\/.+)$/;
|
|
78
|
+
|
|
79
|
+
const sharedModulesPlugin = {
|
|
80
|
+
name: 'forty-shared-modules',
|
|
81
|
+
setup(pluginBuild) {
|
|
82
|
+
// A stylesheet a package imports from the platform (`@40rty/ams-ui/motion.css`) is CSS to bundle, not a module to share.
|
|
83
|
+
pluginBuild.onResolve({ filter: SHARED }, (args) => (args.path.endsWith('.css') ? undefined : { path: args.path, namespace: 'forty-host' }));
|
|
84
|
+
pluginBuild.onLoad({ filter: /.*/, namespace: 'forty-host' }, (args) => ({
|
|
85
|
+
contents: `module.exports = globalThis.__forty_host__[${JSON.stringify(args.path)}];`,
|
|
86
|
+
loader: 'js',
|
|
87
|
+
}));
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Build the brand's components into one browser module, plus its stylesheet.
|
|
93
|
+
*
|
|
94
|
+
* The stylesheet is either named (`bundle.css`, bundled so a file of `@import`s
|
|
95
|
+
* arrives whole) or, when it is not, every CSS file the components themselves
|
|
96
|
+
* import — so a package whose entry already pulls in its styles needs no
|
|
97
|
+
* second list of them. Fonts and images stay where their `url()` points.
|
|
98
|
+
*/
|
|
99
|
+
export async function buildBundle(bundle) {
|
|
100
|
+
if (typeof bundle.entry !== 'string') fail('forty.config.json "bundle" needs an "entry"');
|
|
101
|
+
const result = await build({
|
|
102
|
+
entryPoints: [path.resolve(cwd, bundle.entry)],
|
|
103
|
+
bundle: true,
|
|
104
|
+
write: false,
|
|
105
|
+
outdir: path.join(cwd, 'node_modules', '.forty', 'bundle'),
|
|
106
|
+
format: 'esm',
|
|
107
|
+
platform: 'browser',
|
|
108
|
+
target: 'es2020',
|
|
109
|
+
minify: true,
|
|
110
|
+
jsx: 'automatic',
|
|
111
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
112
|
+
loader: { '.css': typeof bundle.css === 'string' ? 'empty' : 'css' },
|
|
113
|
+
external: CSS_EXTERNAL,
|
|
114
|
+
plugins: [sharedModulesPlugin],
|
|
115
|
+
logLevel: 'error',
|
|
116
|
+
});
|
|
117
|
+
const js = result.outputFiles.find((file) => file.path.endsWith('.js'));
|
|
118
|
+
if (js === undefined) fail(`${bundle.entry} produced no module`);
|
|
119
|
+
// The package's own Tailwind utilities, appended to its stylesheet (`lib/tailwind.mjs`).
|
|
120
|
+
const utilities = typeof bundle.tailwind === 'string' ? await compileTailwind(bundle.tailwind) : '';
|
|
121
|
+
if (typeof bundle.css !== 'string') {
|
|
122
|
+
const imported = result.outputFiles.find((file) => file.path.endsWith('.css'));
|
|
123
|
+
return { js: js.text, css: (imported === undefined ? '' : imported.text) + utilities };
|
|
124
|
+
}
|
|
125
|
+
let css;
|
|
126
|
+
try {
|
|
127
|
+
const sheet = await build({
|
|
128
|
+
entryPoints: [path.resolve(cwd, bundle.css)],
|
|
129
|
+
bundle: true,
|
|
130
|
+
write: false,
|
|
131
|
+
minify: true,
|
|
132
|
+
external: CSS_EXTERNAL,
|
|
133
|
+
logLevel: 'error',
|
|
134
|
+
});
|
|
135
|
+
css = sheet.outputFiles[0].text;
|
|
136
|
+
} catch (err) {
|
|
137
|
+
fail(`cannot build the stylesheet ${bundle.css} — ${err.message}`);
|
|
138
|
+
}
|
|
139
|
+
return { js: js.text, css: css + utilities };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** What a stylesheet points at rather than carries. */
|
|
143
|
+
const CSS_EXTERNAL = ['http://*', 'https://*', 'data:*', '*.woff', '*.woff2', '*.ttf', '*.otf', '*.png', '*.jpg', '*.jpeg', '*.svg', '*.gif', '*.webp'];
|
|
144
|
+
|
|
145
|
+
export async function loadManifests(dir) {
|
|
146
|
+
const root = path.resolve(cwd, dir);
|
|
147
|
+
const out = {};
|
|
148
|
+
for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) {
|
|
149
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
|
|
150
|
+
const abs = path.join(entry.parentPath, entry.name);
|
|
151
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
152
|
+
out[`catalogs/${rel}`] = await readFile(abs, 'utf8');
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* A brand that lives in the platform's repository already declares its theme,
|
|
159
|
+
* home layout, prompt sections and vertical config in its `BrandDefinition`
|
|
160
|
+
* (`src/brand.ts`). Read them from there rather than restating them in
|
|
161
|
+
* forty.config.json, so there is one place they are defined.
|
|
162
|
+
*/
|
|
163
|
+
export async function loadBrandDefinition(file, promptsDir) {
|
|
164
|
+
const outfile = path.join(cwd, 'node_modules', '.forty', 'brand.mjs');
|
|
165
|
+
await mkdir(path.dirname(outfile), { recursive: true });
|
|
166
|
+
await build({
|
|
167
|
+
entryPoints: [path.resolve(cwd, file)],
|
|
168
|
+
outfile,
|
|
169
|
+
bundle: true,
|
|
170
|
+
format: 'esm',
|
|
171
|
+
platform: 'node',
|
|
172
|
+
jsx: 'automatic',
|
|
173
|
+
loader: { '.css': 'empty' },
|
|
174
|
+
plugins: [catalogImportsPlugin],
|
|
175
|
+
logLevel: 'error',
|
|
176
|
+
});
|
|
177
|
+
const mod = await import(`${pathToFileURL(outfile).href}?t=${Date.now()}`);
|
|
178
|
+
if (mod.brand === undefined) fail(`${file} does not export \`brand\``);
|
|
179
|
+
const brand = mod.brand;
|
|
180
|
+
const out = {};
|
|
181
|
+
if (brand.theme !== undefined) out.theme = { themeClass: brand.theme.themeClass };
|
|
182
|
+
if (brand.defaultLayout !== undefined) out.seedLayout = brand.defaultLayout;
|
|
183
|
+
if (brand.config !== undefined) out.config = brand.config;
|
|
184
|
+
if (brand.promptSections !== undefined) {
|
|
185
|
+
// Prompt files live under forty.config.json's `prompts` directory.
|
|
186
|
+
if (typeof promptsDir !== 'string') fail(`${file} declares promptSections but forty.config.json has no "prompts" directory`);
|
|
187
|
+
out.promptSections = [];
|
|
188
|
+
for (const section of brand.promptSections) {
|
|
189
|
+
out.promptSections.push({ id: section.id, order: section.order, requires: section.requires, content: await readFile(path.join(cwd, promptsDir, section.file), 'utf8') });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// What every command shares: where it is running, the config file, the store
|
|
2
|
+
// binding, and which 40rty deployment it talks to.
|
|
3
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
export const cwd = process.cwd();
|
|
7
|
+
export const CONFIG_FILE = 'forty.config.json';
|
|
8
|
+
|
|
9
|
+
/** The production deployment, used when neither the config nor the environment names another. */
|
|
10
|
+
const PRODUCTION = { apiUrl: 'https://40rty-ams-production.up.railway.app', consoleUrl: 'https://app.40rty.ai' };
|
|
11
|
+
|
|
12
|
+
/** A problem the person can act on — printed without a stack. */
|
|
13
|
+
export class FortyError extends Error {}
|
|
14
|
+
|
|
15
|
+
/** End the command with that problem. Thrown, so `forty dev` can survive a bad save. */
|
|
16
|
+
export function fail(message) {
|
|
17
|
+
throw new FortyError(message);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function fromEnv(name) {
|
|
21
|
+
const value = process.env[name];
|
|
22
|
+
return typeof value === 'string' && value !== '' ? value.replace(/\/+$/, '') : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The config file as written, or `null` when there is none yet. */
|
|
26
|
+
export async function readConfigIfPresent() {
|
|
27
|
+
let raw;
|
|
28
|
+
try {
|
|
29
|
+
raw = await readFile(path.join(cwd, CONFIG_FILE), 'utf8');
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (err.code === 'ENOENT') return null;
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
return JSON.parse(raw);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The config file, complete — a command that needs it cannot run without it. */
|
|
38
|
+
export async function readConfig() {
|
|
39
|
+
const config = await readConfigIfPresent();
|
|
40
|
+
if (config === null) fail(`no ${CONFIG_FILE} in ${cwd} — run \`forty init\``);
|
|
41
|
+
// `FORTY_API_URL` points a repo at another deployment (a local stack, staging) without editing the file.
|
|
42
|
+
const override = fromEnv('FORTY_API_URL');
|
|
43
|
+
if (override !== undefined) config.apiUrl = override;
|
|
44
|
+
// Slugs are per deployment too: `FORTY_SPACE` names this repo's space on the one `FORTY_API_URL` points at.
|
|
45
|
+
const space = fromEnv('FORTY_SPACE');
|
|
46
|
+
if (space !== undefined) config.spaceSlug = space;
|
|
47
|
+
for (const key of ['apiUrl', 'spaceSlug', 'sourceId', 'label', 'catalog', 'manifests']) {
|
|
48
|
+
if (typeof config[key] !== 'string' || config[key] === '') fail(`${CONFIG_FILE} is missing "${key}"`);
|
|
49
|
+
}
|
|
50
|
+
return config;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Which deployment: the environment's, else the config's, else production. */
|
|
54
|
+
export function deployment(config) {
|
|
55
|
+
const envApi = fromEnv('FORTY_API_URL');
|
|
56
|
+
const envConsole = fromEnv('FORTY_CONSOLE_URL');
|
|
57
|
+
const apiUrl = envApi !== undefined ? envApi : config !== null && typeof config.apiUrl === 'string' ? config.apiUrl : PRODUCTION.apiUrl;
|
|
58
|
+
const consoleUrl = envConsole !== undefined ? envConsole : PRODUCTION.consoleUrl;
|
|
59
|
+
return { apiUrl, consoleUrl };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Parse a dotenv file into a plain object; a missing file is an empty binding. */
|
|
63
|
+
export async function readDotenv(file) {
|
|
64
|
+
let text;
|
|
65
|
+
try {
|
|
66
|
+
text = await readFile(file, 'utf8');
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (err.code === 'ENOENT') return {};
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const line of text.split('\n')) {
|
|
73
|
+
const match = /^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/.exec(line);
|
|
74
|
+
if (match === null) continue;
|
|
75
|
+
out[match[1]] = match[2].replace(/^["']|["']$/g, '');
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The store this app sells from, read from its own `.env`. */
|
|
81
|
+
export async function storeBinding() {
|
|
82
|
+
const env = await readDotenv(path.join(cwd, '.env'));
|
|
83
|
+
return { domain: env.PUBLIC_STORE_DOMAIN, token: env.PUBLIC_STOREFRONT_API_TOKEN, shopId: env.SHOP_ID };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Set one key in the app's `.env`, replacing it in place or appending it. */
|
|
87
|
+
export async function writeDotenv(key, value) {
|
|
88
|
+
const file = path.join(cwd, '.env');
|
|
89
|
+
let text = '';
|
|
90
|
+
try {
|
|
91
|
+
text = await readFile(file, 'utf8');
|
|
92
|
+
} catch (err) {
|
|
93
|
+
if (err.code !== 'ENOENT') throw err;
|
|
94
|
+
}
|
|
95
|
+
const line = `${key}=${value}`;
|
|
96
|
+
const existing = new RegExp(`^${key}=.*$`, 'm');
|
|
97
|
+
const next = existing.test(text) ? text.replace(existing, line) : `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${line}\n`;
|
|
98
|
+
await writeFile(file, next);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The value of `--name <value>` / `--name=value` on the command line, or
|
|
103
|
+
* `undefined` when absent. A flag given with no value is a mistake, not absence.
|
|
104
|
+
*/
|
|
105
|
+
export function option(name) {
|
|
106
|
+
const args = process.argv.slice(3);
|
|
107
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
108
|
+
if (args[i].startsWith(`--${name}=`)) return args[i].slice(name.length + 3);
|
|
109
|
+
if (args[i] === `--${name}`) {
|
|
110
|
+
const value = args[i + 1];
|
|
111
|
+
if (value === undefined || value.startsWith('--')) fail(`--${name} needs a value`);
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The command's arguments that are not flags or flag values, in order. */
|
|
119
|
+
export function positionals() {
|
|
120
|
+
const args = process.argv.slice(3);
|
|
121
|
+
const out = [];
|
|
122
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
123
|
+
if (args[i].startsWith('--')) {
|
|
124
|
+
if (!args[i].includes('=')) i += 1;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
out.push(args[i]);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Who the CLI acts as.
|
|
2
|
+
//
|
|
3
|
+
// Two credentials, one rule: `FORTY_API_KEY` when it is set (CI), otherwise the
|
|
4
|
+
// key `forty login` stored for this deployment (a person's machine). Both are
|
|
5
|
+
// organization API keys, so every command works the same with either.
|
|
6
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fail } from './context.mjs';
|
|
10
|
+
|
|
11
|
+
const STORE = path.join(os.homedir(), '.config', 'forty', 'credentials.json');
|
|
12
|
+
|
|
13
|
+
async function readStore() {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(await readFile(STORE, 'utf8'));
|
|
16
|
+
} catch (err) {
|
|
17
|
+
if (err.code === 'ENOENT') return {};
|
|
18
|
+
throw err;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Remember a login for one deployment. Readable by this user only. */
|
|
23
|
+
export async function storeCredential(apiUrl, credential) {
|
|
24
|
+
const store = await readStore();
|
|
25
|
+
store[apiUrl] = credential;
|
|
26
|
+
await mkdir(path.dirname(STORE), { recursive: true, mode: 0o700 });
|
|
27
|
+
await writeFile(STORE, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The key to send, and where it came from — `null` when there is none. */
|
|
31
|
+
export async function findCredential(apiUrl) {
|
|
32
|
+
const fromEnv = process.env.FORTY_API_KEY;
|
|
33
|
+
if (typeof fromEnv === 'string' && fromEnv !== '') return { key: fromEnv, source: 'FORTY_API_KEY' };
|
|
34
|
+
const stored = (await readStore())[apiUrl];
|
|
35
|
+
if (stored !== undefined && typeof stored.key === 'string') return { key: stored.key, source: 'forty login', organization: stored.name };
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function requireCredential(apiUrl) {
|
|
40
|
+
const credential = await findCredential(apiUrl);
|
|
41
|
+
if (credential === null) fail('not signed in — run `forty login`, or set FORTY_API_KEY in CI');
|
|
42
|
+
return credential;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const RETRIES = 4;
|
|
46
|
+
const RETRY_MS = 1500;
|
|
47
|
+
|
|
48
|
+
/** `fetch`, tried again when the api cannot be reached at all — a deploy or restart is seconds long. */
|
|
49
|
+
async function reach(url, init) {
|
|
50
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
51
|
+
try {
|
|
52
|
+
return await fetch(url, init);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (attempt === RETRIES) fail(`cannot reach ${new URL(url).origin} (${err.message})`);
|
|
55
|
+
await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One request to the api as the organization. Returns `{ status, body }`; never throws on a refusal. */
|
|
61
|
+
export async function request(apiUrl, method, route, body) {
|
|
62
|
+
const { key } = await requireCredential(apiUrl);
|
|
63
|
+
const res = await reach(`${apiUrl}${route}`, {
|
|
64
|
+
method,
|
|
65
|
+
headers: { 'Content-Type': 'application/json', 'x-api-key': key },
|
|
66
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
67
|
+
});
|
|
68
|
+
const payload = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
|
|
69
|
+
return { status: res.status, ok: res.ok, body: payload };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** As `request`, but a refusal ends the command with the api's own reason. */
|
|
73
|
+
export async function call(apiUrl, method, route, body) {
|
|
74
|
+
const res = await request(apiUrl, method, route, body);
|
|
75
|
+
if (!res.ok) {
|
|
76
|
+
const problems = Array.isArray(res.body.problems) ? `\n - ${res.body.problems.join('\n - ')}` : '';
|
|
77
|
+
fail(`${route} → ${res.status}: ${res.body.error}${problems}`);
|
|
78
|
+
}
|
|
79
|
+
return res.body;
|
|
80
|
+
}
|