@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,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,99 @@
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
+ }
@@ -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
+ }
@@ -0,0 +1,41 @@
1
+ // A package's own Tailwind utilities, for its published bundle.
2
+ //
3
+ // A bundle is loaded into a page the package's author does not control, so the
4
+ // utility classes its components use have to travel with it. With
5
+ // `bundle.tailwind` in forty.config.json naming the package's Tailwind input
6
+ // CSS, that file is compiled here — with the Tailwind the PACKAGE depends on,
7
+ // resolved from the package itself — and the result is appended to the bundle's
8
+ // stylesheet. The input decides what is emitted: theme variables and utilities,
9
+ // never a preflight, because base styles belong to the page that hosts it.
10
+ //
11
+ // Tailwind is resolved from the INPUT FILE's location (as its own `@import`s
12
+ // are), and sources are detected from the package being published — so one
13
+ // shared input can serve many packages.
14
+ import { createRequire } from 'node:module';
15
+ import { readFile } from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { cwd, fail } from './context.mjs';
18
+
19
+ const NEEDS = ['postcss', '@tailwindcss/postcss'];
20
+
21
+ export async function compileTailwind(input) {
22
+ const file = path.resolve(cwd, input);
23
+ const require = createRequire(file);
24
+ const modules = {};
25
+ for (const name of NEEDS) {
26
+ try {
27
+ modules[name] = require(name);
28
+ } catch (err) {
29
+ fail(`bundle.tailwind needs "${name}" installed where ${input} lives (${err.code})`);
30
+ }
31
+ }
32
+ let source;
33
+ try {
34
+ source = await readFile(file, 'utf8');
35
+ } catch (err) {
36
+ fail(`cannot read bundle.tailwind ${input} (${err.code})`);
37
+ }
38
+ const plugin = modules['@tailwindcss/postcss']({ base: cwd, optimize: { minify: true } });
39
+ const result = await modules.postcss([plugin]).process(source, { from: file });
40
+ return result.css;
41
+ }