@40rty/ams-cli 0.3.1 → 0.4.2

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,47 @@
1
- // `forty deploy` — host this Hydrogen app on 40rty, now, whatever its own
2
- // production target is. Builds it to answer under `/<space>/`, uploads only
3
- // what the platform has not got, and prints the space's address — the console
4
- // serves the app there (`<console>/<space>`). Run it again to ship a new build;
5
- // `forty hosting self` hands the space back to the app's own deployment.
1
+ // `forty deploy` — host this app on AMS, now, whatever its own production
2
+ // target is: a Hydrogen app or a Next.js app. A hosted space has a site of its
3
+ // own, `<space>.40rty.app`, and the app answers there from `/` exactly as it
4
+ // builds. It builds in a temporary copy (`lib/build-copy.mjs`) with
5
+ // FORTY_AGENTIC=1, as Vercel Build Output, uploads only what the platform has not got, and
6
+ // prints the space's address. Run it again to ship a new build; `forty
7
+ // hosting self` hands the space back to the app's own deployment.
6
8
  //
7
9
  // forty deploy build, upload, deploy
8
10
  // forty deploy --env KEY also deploy KEY from .env (one that looks secret)
9
11
  // forty deploy --detect print where this app's OWN production deploys, as JSON
10
- import { readFile } from 'node:fs/promises';
12
+ //
13
+ // ── The agentic build contract ──────────────────────────────────────────────
14
+ // The agentic webpage is the app itself, built with FORTY_AGENTIC=1: the app's
15
+ // `/` (hosted: `<space>.40rty.app/`) is the agentic page; every other route (products, collections, cart) is the
16
+ // app's own, so links and the cart keep working. Without the flag the app
17
+ // builds exactly as before. `forty doctor` checks the wiring
18
+ // (`lib/agentic.mjs`).
19
+ //
20
+ // Hydrogen / React Router —
21
+ // app/forty/route.tsx the agentic route module: `loader` (preview token),
22
+ // `links` (shell CSS), default component rendering
23
+ // <Spacefront> with the canvas and shell.
24
+ // app/forty/routes.ts export function agenticRoutes(routes) — with
25
+ // FORTY_AGENTIC=1, every index route at the app's root
26
+ // (`_index`, `($locale)._index`) renders
27
+ // forty/route.tsx instead; otherwise `routes` as is.
28
+ // app/routes.ts wraps its list: hydrogenRoutes(agenticRoutes([...])).
29
+ //
30
+ // Next.js (App Router) —
31
+ // app/forty/page.tsx the agentic page (a Server Component reading the
32
+ // preview token, rendering the client <Spacefront>).
33
+ // next.config async rewrites() { return process.env.FORTY_AGENTIC
34
+ // === '1' ? { beforeFiles: [{ source: '/', destination:
35
+ // '/forty' }] } : []; } — merged with any rewrites the
36
+ // app has. `/forty` stays reachable in every build.
37
+ import { readFile, rm } from 'node:fs/promises';
11
38
  import path from 'node:path';
12
39
  import { cwd, fail, readConfig, readDotenv } from '../lib/context.mjs';
13
40
  import { request } from '../lib/credentials.mjs';
14
41
  import { detectDeployTarget } from '../lib/deploy-target.mjs';
15
- import { prepareBasePathBuild } from '../lib/base-path-build.mjs';
16
- import { assembleBuildOutput, buildHydrogen, listOutputFiles, pickDeployEnv, uploadFiles } from '../lib/hosted-build.mjs';
42
+ import { agenticFramework, agenticWiringProblems } from '../lib/agentic.mjs';
43
+ import { prepareBuildCopy } from '../lib/build-copy.mjs';
44
+ import { assembleBuildOutput, buildHydrogen, buildNext, listOutputFiles, pickDeployEnv, uploadFiles } from '../lib/hosted-build.mjs';
17
45
 
18
46
  function optIns(args) {
19
47
  const keys = [];
@@ -39,17 +67,34 @@ export async function deploy() {
39
67
 
40
68
  const config = await readConfig();
41
69
  const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
42
- if (manifest.dependencies === undefined || manifest.dependencies['@shopify/hydrogen'] === undefined) {
43
- fail('`forty deploy` hosts a Hydrogen app — a package 40rty hosts is already live with `forty publish`');
70
+ const framework = agenticFramework(manifest);
71
+ if (framework === null) {
72
+ fail('`forty deploy` hosts a Hydrogen or Next.js app — for another framework, host it yourself; a component package is already live with `forty publish`');
44
73
  }
45
- const { env, withheld } = pickDeployEnv(await readDotenv(path.join(cwd, '.env')), optIns(args));
74
+ const problems = await agenticWiringProblems(cwd, framework);
75
+ if (problems.length > 0) fail(`the app is not wired for an agentic build:\n - ${problems.map(([what, fix]) => `${what} — ${fix}`).join('\n - ')}`);
76
+ const dotenv = await readDotenv(path.join(cwd, '.env'));
77
+ const { env, withheld } = framework === 'hydrogen' ? pickDeployEnv(dotenv, optIns(args)) : pickDeployEnv(dotenv, optIns(args), []);
46
78
 
47
- const buildDir = await prepareBasePathBuild(cwd, config.spaceSlug);
48
- console.log(`building to answer under /${config.spaceSlug}/ (in ${path.relative(cwd, buildDir)}; your files are untouched)`);
49
- buildHydrogen(buildDir, `/${config.spaceSlug}/`);
50
- const files = await listOutputFiles(await assembleBuildOutput(cwd, buildDir, config.spaceSlug));
79
+ const buildDir = await prepareBuildCopy(cwd, framework);
80
+ console.log('building with FORTY_AGENTIC=1 (in a temporary copy; your files are untouched)');
81
+ let files;
82
+ try {
83
+ if (framework === 'hydrogen') {
84
+ buildHydrogen(buildDir);
85
+ files = await listOutputFiles(await assembleBuildOutput(cwd, buildDir));
86
+ } else {
87
+ files = await listOutputFiles(await buildNext(cwd, buildDir));
88
+ }
89
+ } finally {
90
+ // The copy only exists to build from. Left in the app it is a second copy
91
+ // of the source that the app's own `tsc` / linters then walk (swag-store:
92
+ // hundreds of errors from dist/forty-build). The output lives beside it
93
+ // (dist/ or .next/forty-output), which the upload reads.
94
+ await rm(buildDir, { recursive: true, force: true });
95
+ }
51
96
  const route = `/org/spaces/${encodeURIComponent(config.spaceSlug)}/deployments`;
52
- const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), basePath: `/${config.spaceSlug}`, env };
97
+ const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), basePath: '/', env };
53
98
 
54
99
  let res = await request(config.apiUrl, 'POST', route, body);
55
100
  if (res.status === 409 && Array.isArray(res.body.missing)) {
@@ -59,7 +104,7 @@ export async function deploy() {
59
104
  }
60
105
  if (!res.ok) refused(route, res);
61
106
 
62
- console.log(`live on 40rty: ${res.body.url} (deployment ${res.body.origin}, this build ${res.body.deploymentUrl} — ready in a few seconds)`);
107
+ console.log(`live on AMS: ${res.body.url} (deployment ${res.body.origin}, this build ${res.body.deploymentUrl} — ready in a few seconds)`);
63
108
  console.log(` visitors meet your app at the space's address; a locked space stays locked; \`forty hosting self\` switches back`);
64
109
  if (withheld.length > 0) console.log(` not deployed (looks secret): ${withheld.join(', ')} — add \`--env KEY\` to include one`);
65
110
 
@@ -12,20 +12,13 @@
12
12
  // into its `.env`.
13
13
  import { watch } from 'node:fs';
14
14
  import path from 'node:path';
15
- import { cwd, deployment, fail, readConfig, readConfigIfPresent, writeDotenv } from '../lib/context.mjs';
16
- import { call, request } from '../lib/credentials.mjs';
15
+ import { cwd, fail, readConfig, readConfigIfPresent, writeDotenv } from '../lib/context.mjs';
16
+ import { call } from '../lib/credentials.mjs';
17
17
  import { init } from './init.mjs';
18
18
  import { buildRelease } from './publish.mjs';
19
19
 
20
20
  const SETTLE_MS = 150;
21
21
 
22
- /** The console of the deployment this space lives on: `FORTY_CONSOLE_URL`, else the one the api names. */
23
- async function previewConsole(config) {
24
- if (process.env.FORTY_CONSOLE_URL) return deployment(config).consoleUrl;
25
- const me = await request(config.apiUrl, 'GET', '/org/me');
26
- return me.ok && typeof me.body.consoleUrl === 'string' ? me.body.consoleUrl : deployment(config).consoleUrl;
27
- }
28
-
29
22
  export async function dev() {
30
23
  if ((await readConfigIfPresent()) === null) await init();
31
24
  const config = await readConfig();
@@ -40,6 +33,8 @@ export async function dev() {
40
33
 
41
34
  // The preview credential, from the first draft that lands. It outlives every later save.
42
35
  let token;
36
+ // Where the draft opens: the space's own site, carrying the token.
37
+ let previewUrl;
43
38
  let running = false;
44
39
  let again = false;
45
40
  async function save() {
@@ -52,7 +47,10 @@ export async function dev() {
52
47
  try {
53
48
  const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/draft`, await buildRelease(config));
54
49
  console.log(`${new Date().toLocaleTimeString()} ${result.types.length} types → preview of ${config.spaceSlug} (${Date.now() - started} ms)`);
55
- if (token === undefined) token = result.token;
50
+ if (token === undefined) {
51
+ token = result.token;
52
+ previewUrl = result.previewUrl;
53
+ }
56
54
  } catch (err) {
57
55
  // A save that does not build is the normal case here: report it and keep watching.
58
56
  console.error(`forty: ${err.message}`);
@@ -72,7 +70,8 @@ export async function dev() {
72
70
  await writeDotenv('FORTY_DEV_TOKEN', token);
73
71
  console.log('\n wrote FORTY_DEV_TOKEN to .env — your app previews the draft. Keep it out of version control.\n');
74
72
  } else {
75
- console.log(`\n ${await previewConsole(config)}/${config.spaceSlug}?preview=${token}\n`);
73
+ if (typeof previewUrl !== 'string') fail('the platform did not say where the draft opens — update the platform (its API answers `previewUrl`)');
74
+ console.log(`\n ${previewUrl}\n`);
76
75
  }
77
76
  // `--once`: store the draft and stop — for a script, or an agent, that cannot hold a watcher open.
78
77
  if (process.argv.includes('--once')) return;
@@ -1,6 +1,6 @@
1
1
  // `forty doctor [dev-server-url] [--ask "<question>" | --no-ask]` — the integration's definition of done.
2
2
  // When 40rty hosts the app (`forty deploy`), the space's own address is
3
- // checked too: `<console>/<space><route>`.
3
+ // checked too: its own site, `https://<space>.40rty.app<route>`.
4
4
  //
5
5
  // Every check names what is wrong in the repo's own terms. Exits non-zero when
6
6
  // any fail, so it is the same gate in CI as on a laptop.
@@ -11,7 +11,7 @@ import { askSpace, judgeTurn } from '../lib/ask.mjs';
11
11
  import { loadCatalog } from '../lib/build.mjs';
12
12
  import { appKind, cwd, FortyError, flag, option, positionals, readConfig, readDotenv, storeBinding } from '../lib/context.mjs';
13
13
  import { findCredential, request } from '../lib/credentials.mjs';
14
- import { findRootAbsoluteUrls } from '../lib/base-path-build.mjs';
14
+ import { agenticFramework, agenticWiringProblems } from '../lib/agentic.mjs';
15
15
  import { askStore, probeSearch, ZERO_RESULTS_HINT } from './connect.mjs';
16
16
 
17
17
  /** What the ecommerce vertical requires a source to draw, and what the agent speaks through. */
@@ -78,7 +78,7 @@ async function routeChecks(check, config, pageUrl) {
78
78
  const page = new URL(pageUrl);
79
79
  // Not followed: a locked space answers with a redirect to its gate, which is not the route.
80
80
  const served = await statusOf(pageUrl, { redirect: 'manual' });
81
- check(served.status === 200, `${pageUrl} serves the spacefront route`, served.status >= 300 && served.status < 400 ? `it redirects to ${served.headers.get('location')} — a locked space shows its gate until it is opened to visitors` : undefined);
81
+ check(served.status === 200, `${pageUrl} serves the agentic page`, served.status >= 300 && served.status < 400 ? `it redirects to ${served.headers.get('location')} — a locked space shows its gate until it is opened to visitors` : undefined);
82
82
  const csp = served.headers.get('content-security-policy');
83
83
  if (csp !== null) {
84
84
  const directives = parseCsp(csp);
@@ -127,7 +127,6 @@ export async function doctor() {
127
127
  }
128
128
 
129
129
  // ── The platform ──
130
- let consoleUrl;
131
130
  let hostedAt;
132
131
  const credential = await findCredential(config.apiUrl);
133
132
  check(credential !== null, 'signed in', 'run `forty login`, or set FORTY_API_KEY in CI');
@@ -135,7 +134,6 @@ export async function doctor() {
135
134
  const me = await request(config.apiUrl, 'GET', '/org/me');
136
135
  check(me.ok, `the credential from ${credential.source} is accepted by ${config.apiUrl}`);
137
136
  const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
138
- if (me.ok) consoleUrl = me.body.consoleUrl;
139
137
  if (space !== undefined && typeof space.hostedAppOrigin === 'string') hostedAt = space.hostedAppOrigin;
140
138
  check(space !== undefined, `space "${config.spaceSlug}" belongs to this organization`);
141
139
  if (space !== undefined) {
@@ -176,25 +174,24 @@ export async function doctor() {
176
174
  const engine = await statusOf(`${config.apiUrl}/embed/engine/${sdk.version}/engine.mjs`, { method: 'HEAD' });
177
175
  check(engine.status === 200, `the API serves the engine for sdk ${sdk.version}`);
178
176
 
179
- check(typeof config.route === 'string', 'forty.config.json names the spacefront "route"');
180
- if (typeof config.route === 'string' && devOrigin !== undefined) {
181
- await routeChecks(check, config, `${devOrigin}${config.route}`);
182
- } else if (devOrigin === undefined) {
183
- console.log('- skipped the route and CSP checks: pass the dev server url, e.g. `forty doctor http://localhost:3000`');
177
+ // The agentic webpage is the app built with FORTY_AGENTIC=1 (`forty deploy`'s contract): `/` is the agentic page.
178
+ const framework = agenticFramework(JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8')));
179
+ if (framework !== null) {
180
+ const problems = await agenticWiringProblems(cwd, framework);
181
+ if (problems.length === 0) check(true, `the app is wired for an agentic build (FORTY_AGENTIC=1 makes / the agentic page)`);
182
+ for (const [what, fix] of problems) check(false, what, fix);
183
+ }
184
+ if (devOrigin !== undefined) {
185
+ await routeChecks(check, config, `${devOrigin}/`);
186
+ } else {
187
+ console.log('- skipped the page and CSP checks: start the dev server with FORTY_AGENTIC=1 and pass its url, e.g. `forty doctor http://localhost:3000`');
184
188
  }
185
189
 
186
- // ── 40rty hosts it (`forty deploy`): the space's own address serves the app ──
190
+ // ── AMS hosts it (`forty deploy`) ──
187
191
  if (hostedAt !== undefined) {
188
- console.log(`- 40rty hosts this app (${hostedAt}), served at ${consoleUrl}/${config.spaceSlug} — \`forty hosting self\` hands it back`);
189
- if (typeof config.route === 'string') await routeChecks(check, config, `${consoleUrl}/${config.spaceSlug}${config.route}`);
190
- // The app answers under /<space>/. A URL it spells out from the root
191
- // (`href="/pages/…"`, `/images/…`) is followed back under /<space>/ by the
192
- // console (a same-site Referer redirect), so it works — one extra hop.
193
- const absolute = await findRootAbsoluteUrls(cwd);
194
- if (absolute.length > 0) {
195
- console.log(`- ${absolute.length} root-absolute URL(s) in the app's markup reach /${config.spaceSlug}/ through one redirect when 40rty hosts it — fine; <Link to> or a relative path skips the hop${flag('verbose') ? ':' : ' (--verbose lists them)'}`);
196
- if (flag('verbose')) for (const where of absolute.slice(0, 20)) console.log(` ${where}`);
197
- }
192
+ const site = `https://${config.spaceSlug}.40rty.app/`;
193
+ console.log(`- AMS hosts this app (${hostedAt}), served at ${site} — \`forty hosting self\` hands it back`);
194
+ await routeChecks(check, config, site);
198
195
  }
199
196
  }
200
197
 
@@ -0,0 +1,42 @@
1
+ import { fail, positionals, readConfig } from '../lib/context.mjs';
2
+ import { call } from '../lib/credentials.mjs';
3
+
4
+ /** The DNS records a domain still needs, one line each — or why there are none to show. */
5
+ function describe(status) {
6
+ const { hostname } = status.domain;
7
+ const lines = [];
8
+ if (status.vercel.state !== 'ok') return [` ${hostname}: status unavailable (${status.vercel.state})`];
9
+ const vercel = status.vercel.status;
10
+ if (vercel.verified && !vercel.misconfigured) return [` ${hostname}: live`];
11
+ lines.push(` ${hostname}: waiting for DNS — create:`);
12
+ for (const r of vercel.records) lines.push(` ${r.type.padEnd(5)} ${r.name.padEnd(24)} ${r.value}`);
13
+ if (vercel.aliasTarget !== null) lines.push(` (or, at the apex, ALIAS/ANAME → ${vercel.aliasTarget})`);
14
+ for (const c of vercel.challenges) lines.push(` ${c.type.padEnd(5)} ${c.domain.padEnd(24)} ${c.value}`);
15
+ return lines;
16
+ }
17
+
18
+ /**
19
+ * `forty domain add <host>` — serve this repo's space on the customer's own
20
+ * domain (its hosted app or package, as on `<console>/<space>`), and print the
21
+ * DNS records to create. `forty domain` lists the space's domains and what each
22
+ * still needs. Serving starts once DNS resolves to us; certificates are automatic.
23
+ */
24
+ export async function domain() {
25
+ const [action, host] = positionals();
26
+ const config = await readConfig();
27
+ const route = `/org/spaces/${config.spaceSlug}/domains`;
28
+ if (action === undefined || action === 'list') {
29
+ const statuses = await call(config.apiUrl, 'GET', route);
30
+ if (statuses.length === 0) return console.log(`"${config.spaceSlug}" has no custom domain — \`forty domain add shop.example.com\``);
31
+ for (const status of statuses) for (const line of describe(status)) console.log(line);
32
+ return;
33
+ }
34
+ if (action !== 'add' || host === undefined) fail('usage: forty domain add <shop.example.com> | forty domain');
35
+ const result = await call(config.apiUrl, 'POST', route, { hostname: host });
36
+ console.log(`${result.domain.hostname} now serves "${config.spaceSlug}"`);
37
+ if (result.attach.state !== 'attached') {
38
+ const why = result.attach.state === 'error' ? result.attach.message : result.attach.reason;
39
+ console.log(` not attached yet (${result.attach.state}: ${why}) — tell the 40rty team`);
40
+ }
41
+ for (const line of describe(result)) console.log(line);
42
+ }
@@ -1,6 +1,6 @@
1
1
  // `forty hosting self` — the space's spacefront is the app's OWN deployment
2
2
  // again (Oxygen, Vercel, …), not the one `forty deploy` put on 40rty. The
3
- // console stops serving `<console>/<space>/` from 40rty's copy; the copy and
3
+ // console stops serving `<space>.40rty.app` from 40rty's copy; the copy and
4
4
  // its origin stay, so `forty deploy` switches back in one step.
5
5
  import { fail, positionals, readConfig } from '../lib/context.mjs';
6
6
  import { call } from '../lib/credentials.mjs';
@@ -141,7 +141,7 @@ async function run() {
141
141
  const space = picked.create === undefined ? picked : await createSpace(apiUrl, picked.create);
142
142
 
143
143
  const config = selfHosted
144
- ? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs', route: '/ask' }
144
+ ? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs' }
145
145
  : { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'src/catalog.ts', manifests: 'src/catalogs', bundle: { entry: 'src/index.ts', css: 'dist/package.css' } };
146
146
  await writeFile(path.join(cwd, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
147
147
 
@@ -1,6 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { PackageReleaseSchema, catalogToWire } from '../../dist/wire.js';
3
+ import { PackageReleaseSchema, carriesShapeToken, catalogToWire } from '../../dist/wire.js';
4
4
  import { buildBundle, loadBrandDefinition, loadCatalog, loadManifests } from '../lib/build.mjs';
5
5
  import { cwd, flag, option, readConfig } from '../lib/context.mjs';
6
6
  import { call } from '../lib/credentials.mjs';
@@ -30,13 +30,31 @@ export async function buildRelease(config) {
30
30
  if (typeof config.brand === 'string') Object.assign(release, await loadBrandDefinition(config.brand, config.prompts));
31
31
  if (typeof config.theme === 'string') release.theme = { themeClass: config.theme };
32
32
  if (typeof config.seedLayout === 'string') release.seedLayout = JSON.parse(await readFile(path.join(cwd, config.seedLayout), 'utf8'));
33
+ warnShapeTokenExamples(release.catalog);
33
34
  return PackageReleaseSchema.parse(release);
34
35
  }
35
36
 
37
+ /**
38
+ * A component whose only examples are a shared contract's `<...>` shape tokens
39
+ * has nothing the console can preview — it shows "ships no example of its own".
40
+ * Said here, where the fix is one `examples:` option on `catalogComponentFrom`.
41
+ */
42
+ function warnShapeTokenExamples(catalog) {
43
+ const types = Object.entries(catalog)
44
+ .filter(([, entry]) => Array.isArray(entry.examples) && entry.examples.some(carriesShapeToken))
45
+ .map(([type]) => type);
46
+ if (types.length === 0) return;
47
+ console.warn(`no example of their own (only <...> placeholders), so the console cannot preview: ${types.join(', ')}`);
48
+ console.warn(' pass `examples` to catalogComponentFrom(...) for each');
49
+ }
50
+
36
51
  /** `forty publish` — release: the package changes, and the space's visitors see it. */
37
52
  export async function publish() {
38
53
  const config = await readConfig();
39
54
  const release = await buildRelease(config);
55
+ // `--message "…"`: what this release changed — the console's version list shows it.
56
+ const message = option('message');
57
+ if (message !== undefined) release.description = message;
40
58
  // `--keep-locked`: a space `forty init` created opens to visitors on its first release — unless asked not to.
41
59
  const keepLocked = flag('keep-locked') ? '&keepLocked=true' : '';
42
60
  const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}${keepLocked}`, release);
package/bin/forty.mjs CHANGED
@@ -10,11 +10,13 @@
10
10
  // seeing what is published
11
11
  // forty publish release it: the package changes and the space's visitors
12
12
  // see it. The catalog + manifests named in the config; with
13
- // a `bundle` entry the components too, for a hosted spacefront
13
+ // a `bundle` entry the components too, for a hosted spacefront.
14
+ // `--message "…"` says what the release changed
14
15
  // forty releases the package's release history, and which one is live
15
16
  // forty rollback make an earlier release live again (`forty rollback 3`)
16
17
  // forty connect attach this app's store to the space
17
18
  // forty origin add let a deployed site's origin call the api (CORS)
19
+ // forty domain add serve the space on your own domain; prints the DNS records
18
20
  // forty feedback report a problem to the 40rty team
19
21
  // forty doctor check the whole integration; non-zero when anything is off
20
22
  // forty deploy host this Hydrogen app on 40rty, at the space's address
@@ -37,6 +39,7 @@ const commands = {
37
39
  dev: () => import('./commands/dev.mjs').then((m) => m.dev()),
38
40
  doctor: () => import('./commands/doctor.mjs').then((m) => m.doctor()),
39
41
  origin: () => import('./commands/origin.mjs').then((m) => m.origin()),
42
+ domain: () => import('./commands/domain.mjs').then((m) => m.domain()),
40
43
  feedback: () => import('./commands/feedback.mjs').then((m) => m.feedback()),
41
44
  deploy: () => import('./commands/deploy.mjs').then((m) => m.deploy()),
42
45
  hosting: () => import('./commands/hosting.mjs').then((m) => m.hosting()),
@@ -0,0 +1,48 @@
1
+ // The agentic build contract (documented in `commands/deploy.mjs`): what in the
2
+ // app makes `/` the agentic webpage when it is built with FORTY_AGENTIC=1.
3
+ import { access, readFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ async function read(file) {
7
+ try {
8
+ return await readFile(file, 'utf8');
9
+ } catch (err) {
10
+ if (err.code === 'ENOENT') return null;
11
+ throw err;
12
+ }
13
+ }
14
+
15
+ async function firstOf(cwd, files) {
16
+ for (const file of files) {
17
+ try {
18
+ await access(path.join(cwd, file));
19
+ return file;
20
+ } catch { /* not there — try the next one */ }
21
+ }
22
+ return null;
23
+ }
24
+
25
+ /** `'hydrogen' | 'next' | null` from package.json's dependencies. */
26
+ export function agenticFramework(manifest) {
27
+ const deps = { ...manifest.dependencies, ...manifest.devDependencies };
28
+ if (deps['@shopify/hydrogen'] !== undefined) return 'hydrogen';
29
+ if (deps.next !== undefined) return 'next';
30
+ return null;
31
+ }
32
+
33
+ /** What is missing from the app's agentic wiring for `framework`, as `[problem, fix]` pairs; empty when it is wired. */
34
+ export async function agenticWiringProblems(cwd, framework) {
35
+ const problems = [];
36
+ if (framework === 'hydrogen') {
37
+ if ((await firstOf(cwd, ['app/forty/route.tsx', 'app/forty/route.jsx'])) === null) problems.push(['app/forty/route.tsx exists (the agentic page)', 'move the agentic route module there']);
38
+ const routes = await read(path.join(cwd, 'app/routes.ts'));
39
+ if (routes === null || !routes.includes('agenticRoutes(')) problems.push(['app/routes.ts wraps its routes in agenticRoutes()', 'import { agenticRoutes } from "./forty/routes" and wrap the route list']);
40
+ if ((await firstOf(cwd, ['app/forty/routes.ts'])) === null) problems.push(['app/forty/routes.ts exists (agenticRoutes)', 'add it — see the contract in `forty deploy`']);
41
+ } else if (framework === 'next') {
42
+ if ((await firstOf(cwd, ['app/forty/page.tsx', 'app/forty/page.jsx', 'src/app/forty/page.tsx'])) === null) problems.push(['app/forty/page.tsx exists (the agentic page)', 'move the agentic page there']);
43
+ const configFile = await firstOf(cwd, ['next.config.ts', 'next.config.mjs', 'next.config.js']);
44
+ const config = configFile === null ? null : await read(path.join(cwd, configFile));
45
+ if (config === null || !config.includes('FORTY_AGENTIC')) problems.push(['next.config rewrites / to /forty when FORTY_AGENTIC=1', 'add the beforeFiles rewrite — see the contract in `forty deploy`']);
46
+ }
47
+ return problems;
48
+ }
@@ -0,0 +1,105 @@
1
+ // `forty deploy` builds the app in a COPY — never in the developer's tree, whose
2
+ // `dist/` / `.next/` and config stay theirs. The copy is built with
3
+ // `FORTY_AGENTIC=1` (see `deploy.mjs` for the contract that flag switches),
4
+ // exactly as the app builds itself: a hosted app has its own site
5
+ // (`<slug>.40rty.app`) and answers from `/`, so nothing in its config moves.
6
+ import { spawnSync } from 'node:child_process';
7
+ import { constants } from 'node:fs';
8
+ import { access, cp, mkdir, readdir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+
11
+ /** Where each framework's copy lives: inside the output folder the app already ignores. */
12
+ export const BUILD_COPY_DIR = { hydrogen: path.join('dist', 'forty-build'), next: path.join('.next', 'forty-build') };
13
+
14
+ /** What the copy leaves behind: dependencies are linked, outputs and VCS state are not the app. */
15
+ const NOT_COPIED = new Set(['node_modules', 'dist', '.next', '.git', '.vercel', '.cache', '.turbo']);
16
+
17
+ /** Caches a tool writes inside `node_modules`: the copy keeps its own, never the app's. */
18
+ const OWN_CACHES = new Set(['.vite', '.cache']);
19
+
20
+ async function exists(file) {
21
+ try {
22
+ await access(file);
23
+ return true;
24
+ } catch (err) {
25
+ if (err.code === 'ENOENT') return false;
26
+ throw err;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * `to` as a directory of links to what `from` holds, each to its REAL path.
32
+ * Not one link to `from` itself: a pnpm app's packages are relative links
33
+ * (`../../node_modules/.pnpm/…`), and a tool that joins them onto the path it
34
+ * came through — Tailwind's resolver does — lands outside the store from a
35
+ * directory at another depth.
36
+ */
37
+ async function linkDependencies(from, to) {
38
+ await mkdir(to, { recursive: true });
39
+ for (const entry of await readdir(from)) {
40
+ if (OWN_CACHES.has(entry)) continue;
41
+ const source = path.join(from, entry);
42
+ if (entry.startsWith('@')) await linkDependencies(source, path.join(to, entry));
43
+ else await symlink(await realpath(source), path.join(to, entry));
44
+ }
45
+ }
46
+
47
+ /**
48
+ * A copy of the app at `cwd` to build `framework` in; returns its directory.
49
+ * A Hydrogen copy links the app's packages (nothing installed twice). A
50
+ * Next.js copy needs them inside it — Turbopack refuses a link out of the
51
+ * project root — and flat for its functions (`hoistedPnpmInstall`); an npm or
52
+ * yarn app's are cloned, copy-on-write where the filesystem can. `FORTY_*` lines are dropped from the copy's
53
+ * `.env*`: a build may prerender a page that reads `FORTY_DEV_TOKEN`, and the
54
+ * site is the space's published face, never a developer's preview.
55
+ */
56
+ export async function prepareBuildCopy(cwd, framework) {
57
+ const dir = path.join(cwd, BUILD_COPY_DIR[framework]);
58
+ await rm(dir, { recursive: true, force: true });
59
+ await mkdir(dir, { recursive: true });
60
+ for (const entry of await readdir(cwd)) {
61
+ if (NOT_COPIED.has(entry)) continue;
62
+ await cp(path.join(cwd, entry), path.join(dir, entry), { recursive: true, filter: (src) => !path.relative(cwd, src).split(path.sep).includes('node_modules') });
63
+ }
64
+ const modules = path.join(cwd, 'node_modules');
65
+ if (await exists(modules)) {
66
+ if (framework === 'hydrogen') await linkDependencies(modules, path.join(dir, 'node_modules'));
67
+ else if (!(await hoistedPnpmInstall(modules, dir))) await cp(modules, path.join(dir, 'node_modules'), { recursive: true, verbatimSymlinks: true, mode: constants.COPYFILE_FICLONE });
68
+ }
69
+ for (const entry of await readdir(dir)) {
70
+ if (!/^\.env(\..+)?$/.test(entry)) continue;
71
+ const file = path.join(dir, entry);
72
+ const kept = (await readFile(file, 'utf8')).split('\n').filter((line) => !/^\s*(export\s+)?FORTY_/.test(line));
73
+ await writeFile(file, kept.join('\n'));
74
+ }
75
+ return dir;
76
+ }
77
+
78
+ /**
79
+ * A pnpm app's packages are links into `.pnpm/`. A Vercel function ships files,
80
+ * not links, and Node resolves a package's own dependencies through those
81
+ * links — so a Next.js copy of a pnpm app gets a FLAT (hoisted) node_modules
82
+ * instead, installed offline from the app's own store with the app's own pnpm
83
+ * version: nothing is downloaded. `false` when the app is not a pnpm app (npm
84
+ * and yarn already lay packages out flat).
85
+ */
86
+ async function hoistedPnpmInstall(modules, dir) {
87
+ let meta;
88
+ try {
89
+ meta = JSON.parse(await readFile(path.join(modules, '.modules.yaml'), 'utf8'));
90
+ } catch {
91
+ return false;
92
+ }
93
+ if (typeof meta.packageManager !== 'string' || !meta.packageManager.startsWith('pnpm@')) return false;
94
+ // pnpm 11 reads the linker from pnpm-workspace.yaml, not from a flag; older pnpm from .npmrc. The copy gets both.
95
+ const workspace = path.join(dir, 'pnpm-workspace.yaml');
96
+ const current = (await exists(workspace)) ? await readFile(workspace, 'utf8') : '';
97
+ await writeFile(workspace, `${current.replace(/^nodeLinker:.*$/m, '')}\nnodeLinker: hoisted\n`);
98
+ const npmrc = path.join(dir, '.npmrc');
99
+ await writeFile(npmrc, `${(await exists(npmrc)) ? await readFile(npmrc, 'utf8') : ''}\nnode-linker=hoisted\n`);
100
+ const args = ['--yes', meta.packageManager, 'install', '--offline', '--frozen-lockfile', '--config.minimum-release-age=0', '--ignore-scripts'];
101
+ if (typeof meta.storeDir === 'string') args.push(`--store-dir=${meta.storeDir}`);
102
+ const run = spawnSync('npx', args, { cwd: dir, stdio: 'inherit' });
103
+ if (run.error !== undefined || run.status !== 0) throw new Error(`could not lay out a flat node_modules for the build (\`pnpm install --offline\`, nodeLinker hoisted, in ${dir})`);
104
+ return true;
105
+ }
package/bin/lib/build.mjs CHANGED
@@ -107,7 +107,9 @@ const sharedModulesPlugin = {
107
107
  * from a PACKAGE (`@40rty/ams-ui/island.css`) is still bundled and appended:
108
108
  * the named sheet is a Tailwind build, whose `@import` cannot resolve a
109
109
  * package's `exports`. Their own relative CSS is the named sheet's to carry.
110
- * Fonts and images stay where their `url()` points.
110
+ * A font or image the stylesheet points at by a local path ships with it, as
111
+ * `assets/<content hash>.<ext>` beside the stylesheet (`assets`, base64); a
112
+ * remote one stays where its `url()` points.
111
113
  */
112
114
  export async function buildBundle(bundle) {
113
115
  if (typeof bundle.entry !== 'string') fail('forty.config.json "bundle" needs an "entry"');
@@ -122,7 +124,8 @@ export async function buildBundle(bundle) {
122
124
  minify: true,
123
125
  jsx: 'automatic',
124
126
  define: { 'process.env.NODE_ENV': '"production"' },
125
- loader: { '.css': 'css' },
127
+ loader: { '.css': 'css', ...ASSET_LOADERS },
128
+ assetNames: ASSET_NAMES,
126
129
  external: CSS_EXTERNAL,
127
130
  plugins: typeof bundle.css === 'string' ? [ownCssIsNamedPlugin, sharedModulesPlugin] : [sharedModulesPlugin],
128
131
  logLevel: 'error',
@@ -133,26 +136,51 @@ export async function buildBundle(bundle) {
133
136
  const utilities = typeof bundle.tailwind === 'string' ? await compileTailwind(bundle.tailwind) : '';
134
137
  const importedSheet = result.outputFiles.find((file) => file.path.endsWith('.css'));
135
138
  const imported = importedSheet === undefined ? '' : importedSheet.text;
136
- if (typeof bundle.css !== 'string') return { js: js.text, css: imported + utilities };
137
- let css;
138
- try {
139
- const sheet = await build({
140
- entryPoints: [path.resolve(cwd, bundle.css)],
141
- bundle: true,
142
- write: false,
143
- minify: true,
144
- external: CSS_EXTERNAL,
145
- logLevel: 'error',
146
- });
147
- css = sheet.outputFiles[0].text;
148
- } catch (err) {
149
- fail(`cannot build the stylesheet ${bundle.css} — ${err.message}`);
139
+ const outputs = [...result.outputFiles];
140
+ let css = '';
141
+ if (typeof bundle.css === 'string') {
142
+ try {
143
+ const sheet = await build({
144
+ entryPoints: [path.resolve(cwd, bundle.css)],
145
+ bundle: true,
146
+ write: false,
147
+ minify: true,
148
+ outdir: path.join(cwd, 'node_modules', '.forty', 'bundle'),
149
+ loader: ASSET_LOADERS,
150
+ assetNames: ASSET_NAMES,
151
+ external: CSS_EXTERNAL,
152
+ logLevel: 'error',
153
+ });
154
+ const built = sheet.outputFiles.find((file) => file.path.endsWith('.css'));
155
+ if (built === undefined) fail(`${bundle.css} produced no stylesheet`);
156
+ css = built.text;
157
+ outputs.push(...sheet.outputFiles);
158
+ } catch (err) {
159
+ fail(`cannot build the stylesheet ${bundle.css} — ${err.message}`);
160
+ }
150
161
  }
151
- return { js: js.text, css: css + imported + utilities };
162
+ const out = { js: js.text, css: css + imported + utilities };
163
+ const assets = bundleAssets(outputs);
164
+ if (Object.keys(assets).length > 0) out.assets = assets;
165
+ return out;
152
166
  }
153
167
 
154
- /** What a stylesheet points at rather than carries. */
155
- const CSS_EXTERNAL = ['http://*', 'https://*', 'data:*', '*.woff', '*.woff2', '*.ttf', '*.otf', '*.png', '*.jpg', '*.jpeg', '*.svg', '*.gif', '*.webp'];
168
+ /** What a stylesheet points at rather than carries: only what is already somewhere else. */
169
+ const CSS_EXTERNAL = ['http://*', 'https://*', 'data:*'];
170
+
171
+ /** What a stylesheet carries as a file of its own, under `assets/` beside it. */
172
+ const ASSET_LOADERS = Object.fromEntries(['.woff', '.woff2', '.ttf', '.otf', '.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp'].map((ext) => [ext, 'file']));
173
+ const ASSET_NAMES = 'assets/[hash]';
174
+
175
+ /** The built asset files, base64, by their path beside the stylesheet. */
176
+ function bundleAssets(outputs) {
177
+ const assets = {};
178
+ for (const file of outputs) {
179
+ const rel = path.relative(path.join(cwd, 'node_modules', '.forty', 'bundle'), file.path).split(path.sep).join('/');
180
+ if (rel.startsWith('assets/')) assets[rel] = Buffer.from(file.contents).toString('base64');
181
+ }
182
+ return assets;
183
+ }
156
184
 
157
185
  export async function loadManifests(dir) {
158
186
  const root = path.resolve(cwd, dir);