@40rty/ams-cli 0.1.0 → 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.
@@ -1,19 +1,67 @@
1
1
  import { fail, readConfig, storeBinding } from '../lib/context.mjs';
2
2
  import { call } from '../lib/credentials.mjs';
3
3
 
4
+ /** The Storefront API version the store is asked through. */
5
+ const STOREFRONT_API = '2025-07';
6
+ const SHOP_GID = /^gid:\/\/shopify\/Shop\/(\d+)$/;
7
+
8
+ /**
9
+ * Ask the store itself, with the app's own token: proves the token works, and
10
+ * answers the two things the agent needs that `.env` rarely carries — the
11
+ * store's numeric id and its market.
12
+ */
13
+ async function askStore(domain, token) {
14
+ const url = `https://${domain}/api/${STOREFRONT_API}/graphql.json`;
15
+ let res;
16
+ try {
17
+ res = await fetch(url, {
18
+ method: 'POST',
19
+ headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': token },
20
+ body: JSON.stringify({ query: '{ shop { id } localization { country { isoCode } } }' }),
21
+ });
22
+ } catch (err) {
23
+ fail(`cannot reach the store at ${url} (${err.message}) — is PUBLIC_STORE_DOMAIN right?`);
24
+ }
25
+ const body = await res.json().catch((err) => fail(`the store at ${url} answered ${res.status} with no JSON (${err.message})`));
26
+ if (!res.ok || Array.isArray(body.errors) || body.data === undefined || body.data === null) {
27
+ const reason = Array.isArray(body.errors) ? body.errors.map((e) => e.message).join('; ') : `HTTP ${res.status}`;
28
+ fail(`the store refused PUBLIC_STOREFRONT_API_TOKEN (${reason}) — create a Storefront API token for ${domain} and put it in .env`);
29
+ }
30
+ const match = SHOP_GID.exec(String(body.data.shop.id));
31
+ const country = body.data.localization === null ? undefined : body.data.localization.country.isoCode;
32
+ return { shopId: match === null ? undefined : match[1], marketCountry: typeof country === 'string' && country.length === 2 ? country : undefined };
33
+ }
34
+
4
35
  /** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
5
36
  export async function connect() {
6
37
  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;
38
+ const binding = await storeBinding();
39
+ // An empty `.env` value is absence: `PUBLIC_STOREFRONT_API_TOKEN=` once
40
+ // stored `storefrontAccessToken: ""`, which the connector refuses wholesale.
41
+ const present = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
42
+ const domain = present(binding.domain);
43
+ const token = present(binding.token);
44
+ if (domain === undefined || token === undefined) fail('.env must set PUBLIC_STORE_DOMAIN and PUBLIC_STOREFRONT_API_TOKEN (non-empty)');
45
+ const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '');
46
+ // Catalog search runs ONLY through Shopify's Global catalog, scoped by the
47
+ // store's id — and mock.shop is not in it, so a spacefront on it could never
48
+ // find a product.
49
+ if (host === 'mock.shop') fail('mock.shop is not supported: the agent searches through Shopify\'s Global catalog, which does not index it — connect a real store');
50
+
51
+ const store = await askStore(host, token);
52
+ const shopId = present(binding.shopId) !== undefined ? present(binding.shopId) : store.shopId;
53
+ if (shopId === undefined) {
54
+ fail(`could not work out ${host}'s shop id, and without it the agent cannot search the catalog (search runs through Shopify's Global catalog, by shop id) — set SHOP_ID in .env to the number in gid://shopify/Shop/<n>`);
55
+ }
56
+
57
+ const settings = { hosting: { embedded: true, headless: true }, storefrontAccessToken: token, globalShopId: shopId };
58
+ // The store's market: Global search ranks by ship-to country and defaults to the US.
59
+ if (store.marketCountry !== undefined) settings.marketCountry = store.marketCountry;
12
60
 
13
61
  const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, {
14
62
  platform: 'shopify',
15
- platformConfig: { platform: 'shopify', domain, config: store },
63
+ platformConfig: { platform: 'shopify', domain: host, config: settings },
16
64
  vertical: 'ecommerce',
17
65
  });
18
- console.log(`space "${result.slug}" is connected to ${domain} — \`forty dev\` to work on it`);
66
+ console.log(`space "${result.slug}" is connected to ${host} (shop ${shopId}${store.marketCountry === undefined ? '' : `, market ${store.marketCountry}`}) — \`forty dev\` to work on it`);
19
67
  }
@@ -0,0 +1,64 @@
1
+ // `forty deploy` — host this Hydrogen app on 40rty, now, whatever its own
2
+ // production target is. Builds it, uploads only what the platform has not got,
3
+ // and prints the live URL; run it again to ship a new build to the same URL.
4
+ //
5
+ // forty deploy build, upload, deploy
6
+ // forty deploy --env KEY also deploy KEY from .env (one that looks secret)
7
+ // forty deploy --detect print where this app's OWN production deploys, as JSON
8
+ import { readFile } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { cwd, fail, readConfig, readDotenv } from '../lib/context.mjs';
11
+ import { request } from '../lib/credentials.mjs';
12
+ import { detectDeployTarget } from '../lib/deploy-target.mjs';
13
+ import { assembleBuildOutput, buildHydrogen, listOutputFiles, pickDeployEnv, uploadFiles } from '../lib/hosted-build.mjs';
14
+
15
+ function optIns(args) {
16
+ const keys = [];
17
+ args.forEach((arg, i) => {
18
+ if (arg !== '--env') return;
19
+ if (args[i + 1] === undefined) fail('--env needs a key: `forty deploy --env SANITY_API_TOKEN`');
20
+ keys.push(args[i + 1]);
21
+ });
22
+ return keys;
23
+ }
24
+
25
+ function refused(route, res) {
26
+ const problems = Array.isArray(res.body.problems) ? `\n - ${res.body.problems.join('\n - ')}` : '';
27
+ return fail(`${route} → ${res.status}: ${res.body.error}${problems}`);
28
+ }
29
+
30
+ export async function deploy() {
31
+ const args = process.argv.slice(3);
32
+ if (args.includes('--detect')) {
33
+ console.log(JSON.stringify(await detectDeployTarget(cwd), null, 2));
34
+ return;
35
+ }
36
+
37
+ const config = await readConfig();
38
+ const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
39
+ if (manifest.dependencies === undefined || manifest.dependencies['@shopify/hydrogen'] === undefined) {
40
+ fail('`forty deploy` hosts a Hydrogen app — a package 40rty hosts is already live with `forty publish`');
41
+ }
42
+ const { env, withheld } = pickDeployEnv(await readDotenv(path.join(cwd, '.env')), optIns(args));
43
+
44
+ buildHydrogen(cwd);
45
+ const files = await listOutputFiles(await assembleBuildOutput(cwd));
46
+ const route = `/org/spaces/${encodeURIComponent(config.spaceSlug)}/deployments`;
47
+ const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), env };
48
+
49
+ let res = await request(config.apiUrl, 'POST', route, body);
50
+ if (res.status === 409 && Array.isArray(res.body.missing)) {
51
+ console.log(`uploading ${res.body.missing.length} of ${files.length} files…`);
52
+ await uploadFiles(config.apiUrl, route, files, res.body.missing);
53
+ res = await request(config.apiUrl, 'POST', route, body);
54
+ }
55
+ if (!res.ok) refused(route, res);
56
+
57
+ console.log(`live on 40rty: ${res.body.url} (this deploy: ${res.body.deploymentUrl}, ready in a few seconds)`);
58
+ console.log(` visitors see the space's published release; \`forty dev\` previews stay on localhost`);
59
+ if (withheld.length > 0) console.log(` not deployed (looks secret): ${withheld.join(', ')} — add \`--env KEY\` to include one`);
60
+
61
+ const own = await detectDeployTarget(cwd);
62
+ if (own === null) console.log(' your own production target is not set up yet — add its origin when it is live: forty origin add <url>');
63
+ else console.log(` your production deploys to ${own.label} (${own.evidence}) — add its origin when it is live: forty origin add <url>`);
64
+ }
@@ -32,6 +32,41 @@ async function statusOf(url, init) {
32
32
  }
33
33
  }
34
34
 
35
+ /** A CSP header as directive → its source list (lowercased names; the last policy wins on a repeat, as browsers keep the first — rare enough not to matter here). */
36
+ export function parseCsp(header) {
37
+ const directives = new Map();
38
+ for (const part of header.split(';')) {
39
+ const [name, ...sources] = part.trim().split(/\s+/);
40
+ if (name !== undefined && name !== '' && !directives.has(name.toLowerCase())) directives.set(name.toLowerCase(), sources);
41
+ }
42
+ return directives;
43
+ }
44
+
45
+ /** The list a fetch directive falls back to: its own, else `default-src`, else none (no restriction). */
46
+ function effective(directives, name) {
47
+ if (directives.has(name)) return directives.get(name);
48
+ if (directives.has('default-src')) return directives.get('default-src');
49
+ return null;
50
+ }
51
+
52
+ /** Does a source list admit `origin` (`https://host[:port]` / `wss://…`)? Exact, scheme-only and `*.` host wildcards. */
53
+ export function allowsOrigin(sources, origin) {
54
+ if (sources === null) return true;
55
+ const url = new URL(origin);
56
+ return sources.some((source) => {
57
+ if (source === origin || source === `${url.protocol}`) return true;
58
+ if (source === '*') return url.protocol === 'https:' || url.protocol === 'http:';
59
+ const wildcard = /^([a-z]+:\/\/)?\*\.(.+)$/.exec(source);
60
+ return wildcard !== null && (wildcard[1] === undefined || wildcard[1] === `${url.protocol}//`) && url.host.endsWith(`.${wildcard[2]}`);
61
+ });
62
+ }
63
+
64
+ /** Does the script list let the page run its OWN scripts — Hydrogen's bundle, served from the page's origin? */
65
+ export function allowsOwnScripts(sources, pageOrigin) {
66
+ if (sources === null) return true;
67
+ return sources.includes("'self'") || sources.includes("'strict-dynamic'") || allowsOrigin(sources, pageOrigin);
68
+ }
69
+
35
70
  export async function doctor() {
36
71
  const devOrigin = process.argv[3];
37
72
  const config = await readConfig();
@@ -69,12 +104,23 @@ export async function doctor() {
69
104
  // platform's own components, and the brand's only in a preview.
70
105
  const released = space.componentSources.length === 1 && space.componentSources[0] === config.sourceId;
71
106
  console.log(released ? `- visitors see ${config.sourceId}` : `- not released yet: visitors see ${space.componentSources.join(', ')} — \`forty publish\` when ready`);
107
+ if (selfHosted) {
108
+ // The agent's tools need BOTH: the token for the store, the shop id for catalog search (Shopify's Global catalog).
109
+ const where = space.domain === undefined ? 'no store' : space.domain;
110
+ check(space.hasStorefrontToken === true, `the space's store (${where}) has a storefront token`, 'run `forty connect`');
111
+ check(space.hasGlobalShopId === true, `the space's store (${where}) has a shop id, so catalog search works`, 'run `forty connect`');
112
+ }
72
113
  }
73
114
  }
74
115
 
75
116
  // ── A self-hosted app: the visitor credential, the engine, and its own route ──
76
117
  if (selfHosted) {
77
- const token = (await readDotenv(path.join(cwd, '.env'))).FORTY_DEV_TOKEN;
118
+ const env = await readDotenv(path.join(cwd, '.env'));
119
+ // Hydrogen loads Shopify's Customer Privacy API only with a checkout
120
+ // domain; without it consent never resolves and the spacefront drops
121
+ // every message, silently.
122
+ check(typeof env.PUBLIC_CHECKOUT_DOMAIN === 'string' && env.PUBLIC_CHECKOUT_DOMAIN !== '', '.env sets PUBLIC_CHECKOUT_DOMAIN', 'set it to the store\'s checkout domain (e.g. checkout.example.com, or the *.myshopify.com domain) — without it consent never resolves and messages are dropped');
123
+ const token = env.FORTY_DEV_TOKEN;
78
124
  check(token !== undefined, '.env carries FORTY_DEV_TOKEN', 'run `forty dev`');
79
125
  if (token !== undefined) {
80
126
  const session = await statusOf(`${config.apiUrl}/s/${config.spaceSlug}/sessions`, {
@@ -95,8 +141,26 @@ export async function doctor() {
95
141
  check(served.status === 200, `the dev server at ${devOrigin} serves ${config.route}`);
96
142
  const csp = served.headers.get('content-security-policy');
97
143
  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')}`);
144
+ const directives = parseCsp(csp);
145
+ const api = new URL(config.apiUrl).origin;
146
+ const socket = api.replace(/^http/, 'ws');
147
+ const pageOrigin = new URL(devOrigin).origin;
148
+ const scripts = effective(directives, 'script-src');
149
+ const connects = effective(directives, 'connect-src');
150
+ const hint = 'add the origin to defaultSrc, not scriptSrc — scriptSrc replaces Hydrogen\'s defaults';
151
+ check(allowsOwnScripts(scripts, pageOrigin), `CSP script-src on ${config.route} lets the app run its own scripts ('self')`, `without it the app never hydrates — ${hint}`);
152
+ check(allowsOrigin(scripts, api), `CSP script-src on ${config.route} allows ${api} (the engine)`, hint);
153
+ check(allowsOrigin(connects, api), `CSP connect-src on ${config.route} allows ${api}`, hint);
154
+ check(allowsOrigin(connects, socket), `CSP connect-src on ${config.route} allows ${socket}`, hint);
155
+ }
156
+ // A deployed site is refused by the api's CORS until its origin is registered.
157
+ const site = new URL(devOrigin);
158
+ if (site.hostname !== 'localhost' && site.hostname !== '127.0.0.1') {
159
+ const preflight = await statusOf(`${config.apiUrl}/s/${config.spaceSlug}/sessions`, {
160
+ method: 'OPTIONS',
161
+ headers: { Origin: site.origin, 'Access-Control-Request-Method': 'POST' },
162
+ });
163
+ check(preflight.headers.get('access-control-allow-origin') === site.origin, `the api accepts calls from ${site.origin} (CORS)`, `run \`forty origin add ${site.origin}\``);
100
164
  }
101
165
  } else if (devOrigin === undefined) {
102
166
  console.log('- skipped the route and CSP checks: pass the dev server url, e.g. `forty doctor http://localhost:3000`');
@@ -0,0 +1,54 @@
1
+ // `forty feedback "<text>"` (or the text on stdin) — tell the 40rty team what
2
+ // went wrong. Sent under the organization's key with what the team needs to
3
+ // reproduce it: versions, framework, space, and the last command that failed.
4
+ // The api strips anything shaped like a secret before anyone sees it.
5
+ import { readFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { cwd, deployment, fail, positionals, readConfigIfPresent } from '../lib/context.mjs';
8
+ import { call } from '../lib/credentials.mjs';
9
+ import { readLastFailure } from '../lib/last-failure.mjs';
10
+
11
+ async function readJson(file) {
12
+ try {
13
+ return JSON.parse(await readFile(file, 'utf8'));
14
+ } catch (err) {
15
+ if (err.code === 'ENOENT') return null;
16
+ throw err;
17
+ }
18
+ }
19
+
20
+ async function readStdin() {
21
+ const chunks = [];
22
+ for await (const chunk of process.stdin) chunks.push(chunk);
23
+ return Buffer.concat(chunks).toString('utf8');
24
+ }
25
+
26
+ /** The app's framework, from its dependencies — what a report most often needs first. */
27
+ function frameworkOf(manifest) {
28
+ if (manifest === null) return 'unknown';
29
+ const deps = Object.assign({}, manifest.dependencies, manifest.devDependencies);
30
+ for (const [dep, name] of [['@shopify/hydrogen', 'hydrogen'], ['next', 'next'], ['@remix-run/react', 'remix'], ['react-router', 'react-router'], ['vite', 'vite']]) {
31
+ if (deps[dep] !== undefined) return name;
32
+ }
33
+ return 'unknown';
34
+ }
35
+
36
+ export async function feedback() {
37
+ const args = positionals();
38
+ const text = (args.length > 0 ? args.join(' ') : process.stdin.isTTY ? '' : await readStdin()).trim();
39
+ if (text === '') fail('usage: forty feedback "<what went wrong>" (or pipe the text in)');
40
+
41
+ const config = await readConfigIfPresent();
42
+ const { apiUrl } = deployment(config);
43
+ const cli = await readJson(new URL('../../package.json', import.meta.url));
44
+ const sdk = await readJson(path.join(cwd, 'node_modules/@40rty/ams-sdk/package.json'));
45
+ const context = { nodeVersion: process.version, framework: frameworkOf(await readJson(path.join(cwd, 'package.json'))) };
46
+ if (cli !== null) context.cliVersion = String(cli.version);
47
+ if (sdk !== null) context.sdkVersion = String(sdk.version);
48
+ if (config !== null && typeof config.spaceSlug === 'string') context.spaceSlug = config.spaceSlug;
49
+ const last = await readLastFailure();
50
+ if (last !== null) context.lastCommand = `forty ${last.command} → ${last.message}`.slice(0, 2000);
51
+
52
+ await call(apiUrl, 'POST', '/org/feedback', { text: text.slice(0, 8000), context });
53
+ console.log('sent to the 40rty team — thank you');
54
+ }
@@ -1,52 +1,130 @@
1
1
  // `forty init` — write forty.config.json for this repo.
2
2
  //
3
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.
4
+ // repo is for, and the package id. Whether the app hosts itself (a Hydrogen
5
+ // store) or is a UI package the platform hosts is read from package.json.
6
+ //
7
+ // Runs unattended too — a coding agent setting a project up has no terminal to
8
+ // answer in:
9
+ // --space <slug> use that existing space
10
+ // --create <slug> create a new space in the organization
11
+ // --source <@org/name> the package id, instead of asking
12
+ // An organization with no space yet gets one, named after the app. A question
13
+ // that would need a terminal when there is none fails naming the flag that
14
+ // answers it, rather than waiting on input that will never come.
6
15
  import { readFile, writeFile } from 'node:fs/promises';
7
16
  import path from 'node:path';
8
- import { createInterface } from 'node:readline/promises';
9
- import { CONFIG_FILE, cwd, deployment, fail, readConfigIfPresent } from '../lib/context.mjs';
17
+ import { createInterface } from 'node:readline';
18
+ import { CONFIG_FILE, cwd, deployment, fail, option, readConfigIfPresent } from '../lib/context.mjs';
10
19
  import { call, findCredential } from '../lib/credentials.mjs';
11
20
  import { login } from './login.mjs';
12
21
 
13
22
  /** Sources the platform owns; a space still on one has not been given the organization's own yet. */
14
23
  const RESERVED = /^@(fourty|forty)\//;
15
24
 
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();
25
+ /**
26
+ * ONE readline interface for the whole command, read as a line iterator.
27
+ *
28
+ * An interface per question loses input: each one reads ahead from stdin into
29
+ * its own buffer, and closing it throws away whatever it had buffered beyond
30
+ * its own line — so a second answer typed (or pasted) ahead was gone. The
31
+ * iterator queues every line until a question takes it.
32
+ */
33
+ let lines = null;
34
+ let rl = null;
35
+
36
+ async function ask(question, flag, fallback) {
37
+ if (!process.stdin.isTTY) {
38
+ if (fallback !== undefined) return fallback;
39
+ fail(`${question}? — no terminal to ask in; pass ${flag}`);
40
+ }
41
+ if (rl === null) {
42
+ rl = createInterface({ input: process.stdin, output: process.stdout });
43
+ lines = rl[Symbol.asyncIterator]();
44
+ }
45
+ process.stdout.write(fallback === undefined ? `${question}: ` : `${question} (${fallback}): `);
46
+ const next = await lines.next();
47
+ const answer = next.done ? '' : next.value.trim();
20
48
  if (answer !== '') return answer;
21
- if (fallback === undefined) fail(`${question} is required`);
49
+ if (fallback === undefined) fail(`${question} is required (or pass ${flag})`);
22
50
  return fallback;
23
51
  }
24
52
 
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];
53
+ /** A url-safe slug, as a suggestion — the api's `validateSlug` decides. */
54
+ function slugify(text) {
55
+ return text.toLowerCase().replace(/^@[^/]+\//, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48);
56
+ }
57
+
58
+ /**
59
+ * Create a space in the organization — or take it back, if it is already ours.
60
+ * Called LAST, once every question is answered, so a run that fails on a
61
+ * missing answer leaves nothing behind.
62
+ */
63
+ async function createSpace(apiUrl, { slug, name }) {
64
+ const created = await call(apiUrl, 'POST', '/org/spaces', { name, slug });
65
+ console.log(created.created ? `created space "${created.slug}"` : `space "${created.slug}" already exists in this organization — using it`);
66
+ return { slug: created.slug, name: created.name, componentSources: [] };
67
+ }
68
+
69
+ /** An existing space, or `{ create: { slug, name } }` for one to make once everything else is known. */
70
+ async function pickSpace(spaces, appName) {
71
+ const wanted = option('space');
72
+ const create = option('create');
73
+ if (wanted !== undefined && create !== undefined) fail('pass --space OR --create, not both');
74
+ if (create !== undefined) return { create: { slug: create, name: appName === undefined ? create : appName } };
75
+ if (wanted !== undefined) {
76
+ const space = spaces.find((candidate) => candidate.slug === wanted);
77
+ const has = spaces.length === 0 ? 'none' : spaces.map((candidate) => candidate.slug).join(', ');
78
+ if (space === undefined) fail(`no space "${wanted}" in this organization (it has: ${has}) — \`--create ${wanted}\` makes it`);
79
+ return space;
80
+ }
81
+
82
+ const name = appName === undefined ? 'spacefront' : appName;
83
+ if (spaces.length === 0) return { create: { slug: slugify(name), name } };
84
+ if (!process.stdin.isTTY) {
85
+ if (spaces.length === 1) {
86
+ console.log(`using the organization's only space, "${spaces[0].slug}" — \`--create <slug>\` for a new one`);
87
+ return spaces[0];
88
+ }
89
+ fail(`this organization has ${spaces.length} spaces (${spaces.map((s) => s.slug).join(', ')}) — pass --space <slug>, or --create <slug> for a new one`);
90
+ }
91
+
28
92
  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`);
93
+ console.log(` ${spaces.length + 1}. create a new space`);
94
+ const choice = await ask('Which space is this repo for', '--space <slug>', '1');
95
+ const index = Number.parseInt(choice, 10) - 1;
96
+ if (index === spaces.length) return { create: { slug: await ask('Address for the new space', '--create <slug>', slugify(name)), name } };
97
+ const space = spaces[index];
98
+ if (space === undefined) fail(`"${choice}" is not one of the choices above`);
32
99
  return space;
33
100
  }
34
101
 
35
102
  export async function init() {
103
+ try {
104
+ await run();
105
+ } finally {
106
+ if (rl !== null) rl.close();
107
+ }
108
+ }
109
+
110
+ async function run() {
36
111
  if ((await readConfigIfPresent()) !== null) fail(`${CONFIG_FILE} already exists — edit it, or delete it to start over`);
37
112
  const { apiUrl } = deployment(null);
38
113
  if ((await findCredential(apiUrl)) === null) await login();
39
114
 
40
- const me = await call(apiUrl, 'GET', '/org/me');
41
- const space = await pickSpace(me.spaces);
42
-
43
115
  const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
44
116
  const dependencies = manifest.dependencies === undefined ? {} : manifest.dependencies;
45
117
  const selfHosted = dependencies['@shopify/hydrogen'] !== undefined;
118
+ const appName = typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name.replace(/^@[^/]+\//, '') : undefined;
119
+
120
+ const me = await call(apiUrl, 'GET', '/org/me');
121
+ const picked = await pickSpace(me.spaces, appName);
46
122
 
47
- const own = space.componentSources.find((source) => !RESERVED.test(source));
123
+ const own = picked.create === undefined ? picked.componentSources.find((source) => !RESERVED.test(source)) : undefined;
48
124
  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);
125
+ const flagged = option('source');
126
+ const sourceId = own !== undefined ? own : flagged !== undefined ? flagged : await ask('Package id, as @your-org/name', '--source <@org/name>', named);
127
+ const space = picked.create === undefined ? picked : await createSpace(apiUrl, picked.create);
50
128
 
51
129
  const config = selfHosted
52
130
  ? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs', route: '/ask' }
@@ -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
+ }
@@ -2,8 +2,9 @@ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { PackageReleaseSchema, catalogToWire } from '../../dist/wire.js';
4
4
  import { buildBundle, loadBrandDefinition, loadCatalog, loadManifests } from '../lib/build.mjs';
5
- import { cwd, readConfig } from '../lib/context.mjs';
5
+ import { cwd, option, readConfig } from '../lib/context.mjs';
6
6
  import { call } from '../lib/credentials.mjs';
7
+ import { registerOrigin } from './origin.mjs';
7
8
 
8
9
  /** Everything a release carries, built from the repo as it is right now. */
9
10
  export async function buildRelease(config) {
@@ -34,4 +35,7 @@ export async function publish() {
34
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)`;
35
36
  console.log(`released ${result.sourceId} — release ${result.release}: ${result.types.length} types${built} — live on "${result.composed}"`);
36
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);
37
41
  }
package/bin/forty.mjs CHANGED
@@ -3,7 +3,8 @@
3
3
  //
4
4
  // forty create start a new spacefront package from the starter
5
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
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
7
8
  // forty dev work on the project: every save becomes your draft on the
8
9
  // space, seen only through your preview — visitors keep
9
10
  // seeing what is published
@@ -12,13 +13,17 @@
12
13
  // a `bundle` entry the components too, for a hosted spacefront
13
14
  // forty releases the package's release history, and which one is live
14
15
  // 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
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
17
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)
18
22
  //
19
23
  // Run from the repo's root. The credential is `FORTY_API_KEY` when set (CI),
20
24
  // otherwise the login stored by `forty login`.
21
25
  import { FortyError } from './lib/context.mjs';
26
+ import { recordFailure } from './lib/last-failure.mjs';
22
27
 
23
28
  const commands = {
24
29
  create: () => import('./commands/create.mjs').then((m) => m.create()),
@@ -30,6 +35,9 @@ const commands = {
30
35
  connect: () => import('./commands/connect.mjs').then((m) => m.connect()),
31
36
  dev: () => import('./commands/dev.mjs').then((m) => m.dev()),
32
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()),
33
41
  };
34
42
  try {
35
43
  const command = commands[process.argv[2]];
@@ -40,5 +48,6 @@ try {
40
48
  } catch (err) {
41
49
  if (!(err instanceof FortyError)) throw err;
42
50
  console.error(`forty: ${err.message}`);
51
+ if (process.argv[2] !== 'feedback') await recordFailure(process.argv[2], err.message);
43
52
  process.exit(1);
44
53
  }
@@ -97,3 +97,34 @@ export async function writeDotenv(key, value) {
97
97
  const next = existing.test(text) ? text.replace(existing, line) : `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}${line}\n`;
98
98
  await writeFile(file, next);
99
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,86 @@
1
+ // Where this app's OWN production deploys to, read from the repository.
2
+ //
3
+ // `forty deploy` hosts the app on 40rty right away; this says where it will
4
+ // live once the developer ships it themselves, so the CLI can tell them which
5
+ // origin to allow then. Exported for `forty doctor` and the setup skill.
6
+ import { access, readdir, readFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+
9
+ async function exists(file) {
10
+ try {
11
+ await access(file);
12
+ return true;
13
+ } catch (err) {
14
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return false;
15
+ throw err;
16
+ }
17
+ }
18
+
19
+ async function list(dir) {
20
+ try {
21
+ return await readdir(dir);
22
+ } catch (err) {
23
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return [];
24
+ throw err;
25
+ }
26
+ }
27
+
28
+ /** This directory and its parents up to the repository root — an app may sit in a monorepo's subfolder, its CI at the root. */
29
+ async function upToRepoRoot(cwd) {
30
+ const dirs = [];
31
+ for (let dir = cwd; ; dir = path.dirname(dir)) {
32
+ dirs.push(dir);
33
+ if ((await exists(path.join(dir, '.git'))) || path.dirname(dir) === dir) return dirs;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The developer's own deploy target: `{ target, label, evidence }`, or `null`
39
+ * when the repository names none. `target` is one of oxygen, vercel, netlify,
40
+ * cloudflare, fly, docker. Explicit signals win; Hydrogen's default `oxygen()`
41
+ * vite plugin is the last resort, because every Hydrogen app starts with it.
42
+ */
43
+ export async function detectDeployTarget(cwd) {
44
+ let manifest = {};
45
+ try {
46
+ manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
47
+ } catch (err) {
48
+ if (err.code !== 'ENOENT') throw err;
49
+ }
50
+ const deps = { ...manifest.dependencies, ...manifest.devDependencies };
51
+ const scripts = Object.values(manifest.scripts === undefined ? {} : manifest.scripts).join('\n');
52
+ const found = (target, label, evidence) => ({ target, label, evidence });
53
+
54
+ for (const dir of await upToRepoRoot(cwd)) {
55
+ const workflows = (await list(path.join(dir, '.github', 'workflows'))).filter((f) => /^oxygen-deployment-.*\.ya?ml$/.test(f));
56
+ if (workflows.length > 0) return found('oxygen', 'Shopify Oxygen', path.relative(cwd, path.join(dir, '.github', 'workflows', workflows[0])));
57
+ }
58
+ if (/hydrogen deploy/.test(scripts)) return found('oxygen', 'Shopify Oxygen', 'package.json script runs `shopify hydrogen deploy`');
59
+
60
+ const files = [
61
+ ['vercel.json', 'vercel', 'Vercel'],
62
+ ['.vercel/project.json', 'vercel', 'Vercel'],
63
+ ['netlify.toml', 'netlify', 'Netlify'],
64
+ ['wrangler.toml', 'cloudflare', 'Cloudflare Workers'],
65
+ ['wrangler.json', 'cloudflare', 'Cloudflare Workers'],
66
+ ['wrangler.jsonc', 'cloudflare', 'Cloudflare Workers'],
67
+ ['fly.toml', 'fly', 'Fly.io'],
68
+ ];
69
+ for (const [file, target, label] of files) if (await exists(path.join(cwd, file))) return found(target, label, file);
70
+ for (const [dep, target, label] of [
71
+ ['@vercel/remix', 'vercel', 'Vercel'],
72
+ ['@vercel/react-router', 'vercel', 'Vercel'],
73
+ ['@netlify/remix-adapter', 'netlify', 'Netlify'],
74
+ ['@netlify/vite-plugin-react-router', 'netlify', 'Netlify'],
75
+ ]) if (deps[dep] !== undefined) return found(target, label, `package.json depends on ${dep}`);
76
+ if (await exists(path.join(cwd, 'Dockerfile'))) return found('docker', 'a container (Dockerfile)', 'Dockerfile');
77
+
78
+ for (const config of ['vite.config.ts', 'vite.config.js', 'vite.config.mts']) {
79
+ const text = await readFile(path.join(cwd, config), 'utf8').catch((err) => {
80
+ if (err.code === 'ENOENT') return '';
81
+ throw err;
82
+ });
83
+ if (/\boxygen\(/.test(text)) return found('oxygen', 'Shopify Oxygen', `${config} uses the oxygen() plugin (Hydrogen's default)`);
84
+ }
85
+ return null;
86
+ }
@@ -0,0 +1,116 @@
1
+ // `forty deploy`'s build: a Hydrogen app as Vercel's Build Output (v3) — the
2
+ // client as static files, the Oxygen worker as one Edge Function — plus the
3
+ // env the hosted site runs with.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { fail } from './context.mjs';
9
+ import { findCredential } from './credentials.mjs';
10
+
11
+ /** Inside `dist/`, which a Hydrogen app already ignores — never the developer's own `.vercel/`. */
12
+ const OUTPUT_DIR = path.join('dist', 'forty-output');
13
+
14
+ // The Oxygen worker (`export default { fetch(request, env, ctx) }`) as a Vercel
15
+ // Edge Function. Vercel Edge has no Cache API, so Hydrogen's cache is a no-op
16
+ // there: every storefront query goes to Shopify uncached.
17
+ const EDGE_ENTRY = `import worker from './server.js';
18
+ const noCache = {match: async () => undefined, put: async () => {}, delete: async () => false};
19
+ globalThis.caches ??= {open: async () => noCache, default: noCache};
20
+ export default function handler(request, context) {
21
+ return worker.fetch(request, process.env, {waitUntil: (p) => context?.waitUntil?.(p), passThroughOnException() {}});
22
+ }
23
+ `;
24
+
25
+ /** `shopify hydrogen build`, in this app, with its output on the terminal. */
26
+ export function buildHydrogen(cwd) {
27
+ const run = spawnSync('npx', ['--no-install', 'shopify', 'hydrogen', 'build', '--no-lockfile-check'], { cwd, stdio: 'inherit' });
28
+ if (run.error !== undefined) fail(`could not run \`shopify hydrogen build\` (${run.error.message})`);
29
+ if (run.status !== 0) fail('`shopify hydrogen build` failed — fix the build, then run `forty deploy` again');
30
+ }
31
+
32
+ /** Lay `dist/client` + `dist/server` out as a Build Output under OUTPUT_DIR. */
33
+ export async function assembleBuildOutput(cwd) {
34
+ const out = path.join(cwd, OUTPUT_DIR);
35
+ const func = path.join(out, 'functions', 'index.func');
36
+ await rm(out, { recursive: true, force: true });
37
+ await mkdir(func, { recursive: true });
38
+ await cp(path.join(cwd, 'dist', 'client'), path.join(out, 'static'), { recursive: true });
39
+ // The worker and any chunk or wasm it imports — not its source map, metafile or bundle report. Its entry becomes server.js.
40
+ const runtime = (src) => !/\.[a-z]+$/.test(src) || /\.(m?js|wasm)$/.test(src);
41
+ await cp(path.join(cwd, 'dist', 'server'), func, { recursive: true, filter: runtime });
42
+ await rename(path.join(func, 'index.js'), path.join(func, 'server.js'));
43
+ await writeFile(path.join(func, 'index.js'), EDGE_ENTRY);
44
+ await writeFile(path.join(func, '.vc-config.json'), JSON.stringify({ runtime: 'edge', entrypoint: 'index.js' }));
45
+ await writeFile(path.join(out, 'config.json'), JSON.stringify({ version: 3, routes: [{ handle: 'filesystem' }, { src: '/(.*)', dest: '/index' }] }));
46
+ return out;
47
+ }
48
+
49
+ /** Every file under `dir` as `{ file, sha, size, abs }`, `file` relative with forward slashes. */
50
+ export async function listOutputFiles(dir) {
51
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
52
+ const files = [];
53
+ for (const entry of entries) {
54
+ if (!entry.isFile()) continue;
55
+ const abs = path.join(entry.parentPath, entry.name);
56
+ const bytes = await readFile(abs);
57
+ files.push({ file: path.relative(dir, abs).split(path.sep).join('/'), sha: createHash('sha1').update(bytes).digest('hex'), size: bytes.byteLength, abs });
58
+ }
59
+ return files;
60
+ }
61
+
62
+ /** What a Hydrogen app cannot start without. */
63
+ const REQUIRED = ['SESSION_SECRET', 'PUBLIC_STORE_DOMAIN', 'PUBLIC_STOREFRONT_API_TOKEN'];
64
+ /** Read by Hydrogen when present; public by Shopify's own naming. */
65
+ const KNOWN = ['PUBLIC_CHECKOUT_DOMAIN', 'SHOP_ID', 'PUBLIC_STOREFRONT_ID'];
66
+ const LOOKS_SECRET = /SECRET|TOKEN|PRIVATE|PASSWORD|PASSWD|CREDENTIAL|(^|_)KEY$|(^|_)AUTH/;
67
+
68
+ /**
69
+ * The env the hosted site runs with, from the app's `.env`: what Hydrogen
70
+ * needs, anything `PUBLIC_`, anything that does not look like a secret, and
71
+ * whatever the developer opted in with `--env KEY`. `FORTY_*` never — the site
72
+ * is the space's published face, and `FORTY_DEV_TOKEN` would turn it into a
73
+ * developer's preview.
74
+ */
75
+ export function pickDeployEnv(dotenv, optIn) {
76
+ for (const key of REQUIRED) if (typeof dotenv[key] !== 'string' || dotenv[key] === '') fail(`.env must set ${key} — the app cannot start without it`);
77
+ const env = {};
78
+ const withheld = [];
79
+ for (const [key, value] of Object.entries(dotenv)) {
80
+ if (key.startsWith('FORTY_')) continue;
81
+ if (REQUIRED.includes(key) || KNOWN.includes(key) || key.startsWith('PUBLIC_') || optIn.includes(key) || !LOOKS_SECRET.test(key)) env[key] = value;
82
+ else withheld.push(key);
83
+ }
84
+ for (const key of optIn) {
85
+ if (key.startsWith('FORTY_')) fail(`--env ${key}: 40rty credentials are never deployed`);
86
+ if (env[key] === undefined) fail(`--env ${key}: not set in .env`);
87
+ }
88
+ return { env, withheld };
89
+ }
90
+
91
+ /** PUT one file's bytes to the api. */
92
+ async function putFile(apiUrl, route, key, file) {
93
+ const bytes = await readFile(file.abs);
94
+ const res = await fetch(`${apiUrl}${route}/files/${file.sha}`, {
95
+ method: 'PUT',
96
+ headers: { 'content-type': 'application/octet-stream', 'x-api-key': key },
97
+ body: bytes,
98
+ });
99
+ if (!res.ok) {
100
+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
101
+ fail(`uploading ${file.file} → ${res.status}: ${body.error}`);
102
+ }
103
+ }
104
+
105
+ /** Upload the files the api asked for, a few at a time. */
106
+ export async function uploadFiles(apiUrl, route, files, shas) {
107
+ const credential = await findCredential(apiUrl);
108
+ if (credential === null) fail('not signed in — run `forty login`, or set FORTY_API_KEY in CI');
109
+ const wanted = new Set(shas);
110
+ // One upload per sha, even when two paths share content.
111
+ const queue = [...new Map(files.filter((f) => wanted.has(f.sha)).map((f) => [f.sha, f])).values()];
112
+ const worker = async () => {
113
+ for (let file = queue.shift(); file !== undefined; file = queue.shift()) await putFile(apiUrl, route, credential.key, file);
114
+ };
115
+ await Promise.all(Array.from({ length: 6 }, worker));
116
+ }
@@ -0,0 +1,28 @@
1
+ // The last command that failed on this machine, so `forty feedback` can say
2
+ // what broke without the reporter retyping it. Kept beside the credentials;
3
+ // holds the error message only — never arguments, which may carry secrets.
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ const FILE = path.join(os.homedir(), '.config', 'forty', 'last-failure.json');
9
+
10
+ export async function recordFailure(command, message) {
11
+ try {
12
+ await mkdir(path.dirname(FILE), { recursive: true, mode: 0o700 });
13
+ await writeFile(FILE, `${JSON.stringify({ command, message, at: new Date().toISOString() })}\n`, { mode: 0o600 });
14
+ } catch (err) {
15
+ // Bookkeeping for a later report: never worth failing the command over.
16
+ console.warn(`forty: could not record the failure (${err.message})`);
17
+ }
18
+ }
19
+
20
+ export async function readLastFailure() {
21
+ try {
22
+ return JSON.parse(await readFile(FILE, 'utf8'));
23
+ } catch (err) {
24
+ if (err.code === 'ENOENT') return null;
25
+ console.warn(`forty: could not read the last failure (${err.message})`);
26
+ return null;
27
+ }
28
+ }
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "peerDependencies": {
16
16
  "zod": "^3.25.0"
17
17
  },
18
- "version": "0.1.0",
18
+ "version": "0.2.0",
19
19
  "homepage": "https://docs.40rty.ai",
20
20
  "license": "UNLICENSED",
21
21
  "engines": {