@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,67 @@
|
|
|
1
|
+
import { fail, readConfig, storeBinding } from '../lib/context.mjs';
|
|
2
|
+
import { call } from '../lib/credentials.mjs';
|
|
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
|
+
|
|
35
|
+
/** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
|
|
36
|
+
export async function connect() {
|
|
37
|
+
const config = await readConfig();
|
|
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;
|
|
60
|
+
|
|
61
|
+
const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, {
|
|
62
|
+
platform: 'shopify',
|
|
63
|
+
platformConfig: { platform: 'shopify', domain: host, config: settings },
|
|
64
|
+
vertical: 'ecommerce',
|
|
65
|
+
});
|
|
66
|
+
console.log(`space "${result.slug}" is connected to ${host} (shop ${shopId}${store.marketCountry === undefined ? '' : `, market ${store.marketCountry}`}) — \`forty dev\` to work on it`);
|
|
67
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// `forty create <dir>` — start a spacefront package from nothing.
|
|
2
|
+
//
|
|
3
|
+
// Copies the starter (templates/package) into a new directory: a catalog with
|
|
4
|
+
// the types a store needs, a component for each, a shell and a Tailwind build.
|
|
5
|
+
// It writes no forty.config.json: the first `forty dev` signs in, asks which
|
|
6
|
+
// space this is for and writes it (`forty init`).
|
|
7
|
+
import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { cwd, fail } from '../lib/context.mjs';
|
|
11
|
+
|
|
12
|
+
const TEMPLATE = fileURLToPath(new URL('../../templates/package', import.meta.url));
|
|
13
|
+
// The sdk, ui and CLI are released together at one version, so the CLI's own
|
|
14
|
+
// version is the one the starter depends on.
|
|
15
|
+
const CLI_MANIFEST = fileURLToPath(new URL('../../package.json', import.meta.url));
|
|
16
|
+
|
|
17
|
+
/** npm strips a `.gitignore` from a published tarball, so the template carries it unhidden. */
|
|
18
|
+
const RENAMED = { gitignore: '.gitignore' };
|
|
19
|
+
|
|
20
|
+
async function copy(from, to, replace) {
|
|
21
|
+
await mkdir(to, { recursive: true });
|
|
22
|
+
for (const entry of await readdir(from, { withFileTypes: true })) {
|
|
23
|
+
const source = path.join(from, entry.name);
|
|
24
|
+
const target = path.join(to, entry.name in RENAMED ? RENAMED[entry.name] : entry.name);
|
|
25
|
+
if (entry.isDirectory()) await copy(source, target, replace);
|
|
26
|
+
else await writeFile(target, replace(await readFile(source, 'utf8')));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function create() {
|
|
31
|
+
const dir = process.argv[3];
|
|
32
|
+
if (dir === undefined) fail('usage: forty create <directory>');
|
|
33
|
+
const target = path.resolve(cwd, dir);
|
|
34
|
+
const existing = await readdir(target).catch((err) => {
|
|
35
|
+
if (err.code === 'ENOENT') return [];
|
|
36
|
+
throw err;
|
|
37
|
+
});
|
|
38
|
+
if (existing.length > 0) fail(`${dir} already exists and is not empty`);
|
|
39
|
+
|
|
40
|
+
// The directory names the package: `my-store` → `@my-store/spacefront`, "My Store".
|
|
41
|
+
const slug = path.basename(target).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
42
|
+
if (slug === '') fail(`cannot make a package name from "${dir}" — use letters, digits and hyphens`);
|
|
43
|
+
const label = slug.split('-').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
|
|
44
|
+
const { version } = JSON.parse(await readFile(CLI_MANIFEST, 'utf8'));
|
|
45
|
+
|
|
46
|
+
await copy(TEMPLATE, target, (text) =>
|
|
47
|
+
text.replaceAll('__PACKAGE__', `@${slug}/spacefront`).replaceAll('__LABEL__', label).replaceAll('__VERSION__', `^${version}`),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
console.log(`created ${dir} — @${slug}/spacefront\n`);
|
|
51
|
+
console.log(` cd ${dir}`);
|
|
52
|
+
console.log(' npm install');
|
|
53
|
+
console.log(' npm run dev # sign in, pick your space, then every save updates your preview\n');
|
|
54
|
+
}
|
|
@@ -0,0 +1,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
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// `forty dev` — work on the project against its space, without touching what
|
|
2
|
+
// the space's visitors see.
|
|
3
|
+
//
|
|
4
|
+
// Every save is built and stored as this developer's DRAFT on the space. The
|
|
5
|
+
// draft is rendered only for a session opened with the preview token this
|
|
6
|
+
// command is given; everyone else keeps seeing the published package, which
|
|
7
|
+
// changes only on `forty publish`.
|
|
8
|
+
//
|
|
9
|
+
// A package the platform hosts is rebuilt whole, and the open preview page
|
|
10
|
+
// swaps it in place. An app that hosts its own spacefront already hot-reloads
|
|
11
|
+
// its components; only its catalog and manifests travel, and the token goes
|
|
12
|
+
// into its `.env`.
|
|
13
|
+
import { watch } from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { cwd, deployment, fail, readConfig, readConfigIfPresent, writeDotenv } from '../lib/context.mjs';
|
|
16
|
+
import { call } from '../lib/credentials.mjs';
|
|
17
|
+
import { init } from './init.mjs';
|
|
18
|
+
import { buildRelease } from './publish.mjs';
|
|
19
|
+
|
|
20
|
+
const SETTLE_MS = 150;
|
|
21
|
+
|
|
22
|
+
export async function dev() {
|
|
23
|
+
if ((await readConfigIfPresent()) === null) await init();
|
|
24
|
+
const config = await readConfig();
|
|
25
|
+
|
|
26
|
+
const files = [config.catalog, config.manifests];
|
|
27
|
+
if (config.bundle !== undefined) files.push(path.dirname(config.bundle.entry));
|
|
28
|
+
if (config.bundle !== undefined && typeof config.bundle.css === 'string') files.push(config.bundle.css);
|
|
29
|
+
if (typeof config.seedLayout === 'string') files.push(config.seedLayout);
|
|
30
|
+
if (typeof config.brand === 'string') files.push(config.brand);
|
|
31
|
+
if (typeof config.prompts === 'string') files.push(config.prompts);
|
|
32
|
+
const dirs = new Set(files.map((file) => (path.extname(file) === '' ? file : path.dirname(file))));
|
|
33
|
+
|
|
34
|
+
// The preview credential, from the first draft that lands. It outlives every later save.
|
|
35
|
+
let token;
|
|
36
|
+
let running = false;
|
|
37
|
+
let again = false;
|
|
38
|
+
async function save() {
|
|
39
|
+
if (running) {
|
|
40
|
+
again = true;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
running = true;
|
|
44
|
+
const started = Date.now();
|
|
45
|
+
try {
|
|
46
|
+
const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/draft`, await buildRelease(config));
|
|
47
|
+
console.log(`${new Date().toLocaleTimeString()} ${result.types.length} types → preview of ${config.spaceSlug} (${Date.now() - started} ms)`);
|
|
48
|
+
if (token === undefined) token = result.token;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
// A save that does not build is the normal case here: report it and keep watching.
|
|
51
|
+
console.error(`forty: ${err.message}`);
|
|
52
|
+
}
|
|
53
|
+
running = false;
|
|
54
|
+
if (again) {
|
|
55
|
+
again = false;
|
|
56
|
+
await save();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
await save();
|
|
61
|
+
if (token === undefined) fail('the draft was refused — fix the problem above and run `forty dev` again');
|
|
62
|
+
|
|
63
|
+
if (config.bundle === undefined) {
|
|
64
|
+
// This app hosts the spacefront: it presents the token itself.
|
|
65
|
+
await writeDotenv('FORTY_DEV_TOKEN', token);
|
|
66
|
+
console.log('\n wrote FORTY_DEV_TOKEN to .env — your app previews the draft. Keep it out of version control.\n');
|
|
67
|
+
} else {
|
|
68
|
+
console.log(`\n ${deployment(config).consoleUrl}/${config.spaceSlug}?preview=${token}\n`);
|
|
69
|
+
}
|
|
70
|
+
// `--once`: store the draft and stop — for a script, or an agent, that cannot hold a watcher open.
|
|
71
|
+
if (process.argv.includes('--once')) return;
|
|
72
|
+
console.log(`watching ${[...dirs].join(', ')} — visitors see none of this until \`forty publish\``);
|
|
73
|
+
|
|
74
|
+
let timer;
|
|
75
|
+
for (const dir of dirs) {
|
|
76
|
+
watch(path.resolve(cwd, dir), { recursive: true }, () => {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
timer = setTimeout(save, SETTLE_MS);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
// Runs until interrupted.
|
|
82
|
+
await new Promise(() => {});
|
|
83
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// `forty doctor [dev-server-url]` — the integration's definition of done.
|
|
2
|
+
//
|
|
3
|
+
// Every check names what is wrong in the repo's own terms. Exits non-zero when
|
|
4
|
+
// any fail, so it is the same gate in CI as on a laptop.
|
|
5
|
+
import { access, readFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { loadCatalog } from '../lib/build.mjs';
|
|
8
|
+
import { cwd, readConfig, readDotenv } from '../lib/context.mjs';
|
|
9
|
+
import { findCredential, request } from '../lib/credentials.mjs';
|
|
10
|
+
|
|
11
|
+
/** What the ecommerce vertical requires a source to draw, and what the agent speaks through. */
|
|
12
|
+
const REQUIRED_TYPES = ['productGrid', 'collectionList'];
|
|
13
|
+
const REQUIRED_RENDERERS = ['agentText', 'turn'];
|
|
14
|
+
|
|
15
|
+
async function exists(file) {
|
|
16
|
+
try {
|
|
17
|
+
await access(path.join(cwd, file));
|
|
18
|
+
return true;
|
|
19
|
+
} catch (err) {
|
|
20
|
+
if (err.code === 'ENOENT') return false;
|
|
21
|
+
throw err;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A status, or 0 when the server cannot be reached at all. */
|
|
26
|
+
async function statusOf(url, init) {
|
|
27
|
+
try {
|
|
28
|
+
return await fetch(url, init);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
console.log(` (${url}: ${err.message})`);
|
|
31
|
+
return { status: 0, ok: false, headers: new Headers() };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 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
|
+
|
|
70
|
+
export async function doctor() {
|
|
71
|
+
const devOrigin = process.argv[3];
|
|
72
|
+
const config = await readConfig();
|
|
73
|
+
const selfHosted = config.bundle === undefined;
|
|
74
|
+
const failures = [];
|
|
75
|
+
const check = (ok, message, fix) => {
|
|
76
|
+
console.log(`${ok ? '✓' : '✗'} ${message}${ok || fix === undefined ? '' : ` — ${fix}`}`);
|
|
77
|
+
if (!ok) failures.push(message);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// ── The repo ──
|
|
81
|
+
const hasCatalog = await exists(config.catalog);
|
|
82
|
+
check(hasCatalog, `catalog file ${config.catalog} exists`);
|
|
83
|
+
if (hasCatalog) {
|
|
84
|
+
check(!/from ['"]react['"]/.test(await readFile(path.join(cwd, config.catalog), 'utf8')), 'the catalog file does not import React');
|
|
85
|
+
const types = Object.keys(await loadCatalog(config.catalog));
|
|
86
|
+
for (const type of REQUIRED_TYPES) check(types.includes(type), `the catalog declares "${type}"`);
|
|
87
|
+
}
|
|
88
|
+
if (selfHosted) {
|
|
89
|
+
const componentsFile = path.join(path.dirname(config.catalog), 'components.tsx');
|
|
90
|
+
const text = (await exists(componentsFile)) ? await readFile(path.join(cwd, componentsFile), 'utf8') : '';
|
|
91
|
+
for (const type of REQUIRED_RENDERERS) check(new RegExp(`\\b${type}\\s*:`).test(text), `${componentsFile} draws "${type}"`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── The platform ──
|
|
95
|
+
const credential = await findCredential(config.apiUrl);
|
|
96
|
+
check(credential !== null, 'signed in', 'run `forty login`, or set FORTY_API_KEY in CI');
|
|
97
|
+
if (credential !== null) {
|
|
98
|
+
const me = await request(config.apiUrl, 'GET', '/org/me');
|
|
99
|
+
check(me.ok, `the credential from ${credential.source} is accepted by ${config.apiUrl}`);
|
|
100
|
+
const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
|
|
101
|
+
check(space !== undefined, `space "${config.spaceSlug}" belongs to this organization`);
|
|
102
|
+
if (space !== undefined) {
|
|
103
|
+
// Not a failure either way: before the first release a space renders the
|
|
104
|
+
// platform's own components, and the brand's only in a preview.
|
|
105
|
+
const released = space.componentSources.length === 1 && space.componentSources[0] === config.sourceId;
|
|
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
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── A self-hosted app: the visitor credential, the engine, and its own route ──
|
|
117
|
+
if (selfHosted) {
|
|
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;
|
|
124
|
+
check(token !== undefined, '.env carries FORTY_DEV_TOKEN', 'run `forty dev`');
|
|
125
|
+
if (token !== undefined) {
|
|
126
|
+
const session = await statusOf(`${config.apiUrl}/s/${config.spaceSlug}/sessions`, {
|
|
127
|
+
method: 'POST',
|
|
128
|
+
headers: { 'content-type': 'application/json', 'x-api-key': token },
|
|
129
|
+
body: JSON.stringify({ visitorId: 'forty-doctor' }),
|
|
130
|
+
});
|
|
131
|
+
check(session.status === 200, 'a session opens on the space with that token', 'it may have expired — run `forty dev`');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const sdk = JSON.parse(await readFile(path.join(cwd, 'node_modules/@40rty/ams-sdk/package.json'), 'utf8'));
|
|
135
|
+
const engine = await statusOf(`${config.apiUrl}/embed/engine/${sdk.version}/engine.mjs`, { method: 'HEAD' });
|
|
136
|
+
check(engine.status === 200, `the API serves the engine for sdk ${sdk.version}`);
|
|
137
|
+
|
|
138
|
+
check(typeof config.route === 'string', 'forty.config.json names the spacefront "route"');
|
|
139
|
+
if (typeof config.route === 'string' && devOrigin !== undefined) {
|
|
140
|
+
const served = await statusOf(`${devOrigin}${config.route}`);
|
|
141
|
+
check(served.status === 200, `the dev server at ${devOrigin} serves ${config.route}`);
|
|
142
|
+
const csp = served.headers.get('content-security-policy');
|
|
143
|
+
if (csp !== null) {
|
|
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}\``);
|
|
164
|
+
}
|
|
165
|
+
} else if (devOrigin === undefined) {
|
|
166
|
+
console.log('- skipped the route and CSP checks: pass the dev server url, e.g. `forty doctor http://localhost:3000`');
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (failures.length > 0) {
|
|
171
|
+
console.error(`\n${failures.length} check(s) failed.`);
|
|
172
|
+
process.exit(1);
|
|
173
|
+
}
|
|
174
|
+
console.log('\nAll checks passed.');
|
|
175
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// `forty init` — write forty.config.json for this repo.
|
|
2
|
+
//
|
|
3
|
+
// Asks only what it cannot work out: which of the organization's spaces this
|
|
4
|
+
// repo is for, 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.
|
|
15
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { createInterface } from 'node:readline';
|
|
18
|
+
import { CONFIG_FILE, cwd, deployment, fail, option, readConfigIfPresent } from '../lib/context.mjs';
|
|
19
|
+
import { call, findCredential } from '../lib/credentials.mjs';
|
|
20
|
+
import { login } from './login.mjs';
|
|
21
|
+
|
|
22
|
+
/** Sources the platform owns; a space still on one has not been given the organization's own yet. */
|
|
23
|
+
const RESERVED = /^@(fourty|forty)\//;
|
|
24
|
+
|
|
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();
|
|
48
|
+
if (answer !== '') return answer;
|
|
49
|
+
if (fallback === undefined) fail(`${question} is required (or pass ${flag})`);
|
|
50
|
+
return fallback;
|
|
51
|
+
}
|
|
52
|
+
|
|
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
|
+
|
|
92
|
+
spaces.forEach((space, i) => console.log(` ${i + 1}. ${space.slug}`));
|
|
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`);
|
|
99
|
+
return space;
|
|
100
|
+
}
|
|
101
|
+
|
|
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() {
|
|
111
|
+
if ((await readConfigIfPresent()) !== null) fail(`${CONFIG_FILE} already exists — edit it, or delete it to start over`);
|
|
112
|
+
const { apiUrl } = deployment(null);
|
|
113
|
+
if ((await findCredential(apiUrl)) === null) await login();
|
|
114
|
+
|
|
115
|
+
const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
|
|
116
|
+
const dependencies = manifest.dependencies === undefined ? {} : manifest.dependencies;
|
|
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);
|
|
122
|
+
|
|
123
|
+
const own = picked.create === undefined ? picked.componentSources.find((source) => !RESERVED.test(source)) : undefined;
|
|
124
|
+
const named = typeof manifest.name === 'string' && manifest.name.startsWith('@') && !RESERVED.test(manifest.name) ? manifest.name : undefined;
|
|
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);
|
|
128
|
+
|
|
129
|
+
const config = selfHosted
|
|
130
|
+
? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs', route: '/ask' }
|
|
131
|
+
: { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'src/catalog.ts', manifests: 'src/catalogs', bundle: { entry: 'src/index.ts', css: 'dist/package.css' } };
|
|
132
|
+
await writeFile(path.join(cwd, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
|
|
133
|
+
|
|
134
|
+
console.log(`wrote ${CONFIG_FILE} for space "${space.slug}" — ${selfHosted ? 'this app hosts the spacefront' : 'the platform hosts the spacefront from this package'}`);
|
|
135
|
+
console.log(selfHosted ? 'next: forty connect, then forty dev' : 'next: forty dev');
|
|
136
|
+
}
|