@40rty/ams-cli 0.3.1 → 0.3.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,48 @@
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. The console serves a hosted
3
+ // space at `<console>/<space>/`, so the app is built to answer under
4
+ // `/<space>/` (Hydrogen: React Router's basename + asset base; Next.js:
5
+ // `basePath`). It builds in a temporary copy (`lib/build-copy.mjs`) with
6
+ // FORTY_AGENTIC=1, as Vercel Build Output, uploads only what the platform has not got, and
7
+ // prints the space's address. Run it again to ship a new build; `forty
8
+ // hosting self` hands the space back to the app's own deployment.
6
9
  //
7
10
  // forty deploy build, upload, deploy
8
11
  // forty deploy --env KEY also deploy KEY from .env (one that looks secret)
9
12
  // forty deploy --detect print where this app's OWN production deploys, as JSON
10
- import { readFile } from 'node:fs/promises';
13
+ //
14
+ // ── The agentic build contract ──────────────────────────────────────────────
15
+ // The agentic webpage is the app itself, built with FORTY_AGENTIC=1: the app's
16
+ // `/` (hosted: `<console>/<space>/`) is the agentic page; every other route (products, collections, cart) is the
17
+ // app's own, so links and the cart keep working. Without the flag the app
18
+ // builds exactly as before. `forty doctor` checks the wiring
19
+ // (`lib/agentic.mjs`).
20
+ //
21
+ // Hydrogen / React Router —
22
+ // app/forty/route.tsx the agentic route module: `loader` (preview token),
23
+ // `links` (shell CSS), default component rendering
24
+ // <Spacefront> with the canvas and shell.
25
+ // app/forty/routes.ts export function agenticRoutes(routes) — with
26
+ // FORTY_AGENTIC=1, every index route at the app's root
27
+ // (`_index`, `($locale)._index`) renders
28
+ // forty/route.tsx instead; otherwise `routes` as is.
29
+ // app/routes.ts wraps its list: hydrogenRoutes(agenticRoutes([...])).
30
+ //
31
+ // Next.js (App Router) —
32
+ // app/forty/page.tsx the agentic page (a Server Component reading the
33
+ // preview token, rendering the client <Spacefront>).
34
+ // next.config async rewrites() { return process.env.FORTY_AGENTIC
35
+ // === '1' ? { beforeFiles: [{ source: '/', destination:
36
+ // '/forty' }] } : []; } — merged with any rewrites the
37
+ // app has. `/forty` stays reachable in every build.
38
+ import { readFile, rm } from 'node:fs/promises';
11
39
  import path from 'node:path';
12
40
  import { cwd, fail, readConfig, readDotenv } from '../lib/context.mjs';
13
41
  import { request } from '../lib/credentials.mjs';
14
42
  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';
43
+ import { agenticFramework, agenticWiringProblems } from '../lib/agentic.mjs';
44
+ import { prepareBuildCopy } from '../lib/build-copy.mjs';
45
+ import { assembleBuildOutput, buildHydrogen, buildNext, listOutputFiles, pickDeployEnv, uploadFiles } from '../lib/hosted-build.mjs';
17
46
 
18
47
  function optIns(args) {
19
48
  const keys = [];
@@ -39,15 +68,32 @@ export async function deploy() {
39
68
 
40
69
  const config = await readConfig();
41
70
  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`');
71
+ const framework = agenticFramework(manifest);
72
+ if (framework === null) {
73
+ 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
74
  }
45
- const { env, withheld } = pickDeployEnv(await readDotenv(path.join(cwd, '.env')), optIns(args));
75
+ const problems = await agenticWiringProblems(cwd, framework);
76
+ if (problems.length > 0) fail(`the app is not wired for an agentic build:\n - ${problems.map(([what, fix]) => `${what} — ${fix}`).join('\n - ')}`);
77
+ const dotenv = await readDotenv(path.join(cwd, '.env'));
78
+ const { env, withheld } = framework === 'hydrogen' ? pickDeployEnv(dotenv, optIns(args)) : pickDeployEnv(dotenv, optIns(args), []);
46
79
 
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));
80
+ const buildDir = await prepareBuildCopy(cwd, framework, config.spaceSlug);
81
+ console.log(`building with FORTY_AGENTIC=1 to answer under /${config.spaceSlug}/ (in a temporary copy; your files are untouched)`);
82
+ let files;
83
+ try {
84
+ if (framework === 'hydrogen') {
85
+ buildHydrogen(buildDir, `/${config.spaceSlug}/`);
86
+ files = await listOutputFiles(await assembleBuildOutput(cwd, buildDir, config.spaceSlug));
87
+ } else {
88
+ files = await listOutputFiles(await buildNext(cwd, buildDir));
89
+ }
90
+ } finally {
91
+ // The copy only exists to build from. Left in the app it is a second copy
92
+ // of the source that the app's own `tsc` / linters then walk (swag-store:
93
+ // hundreds of errors from dist/forty-build). The output lives beside it
94
+ // (dist/ or .next/forty-output), which the upload reads.
95
+ await rm(buildDir, { recursive: true, force: true });
96
+ }
51
97
  const route = `/org/spaces/${encodeURIComponent(config.spaceSlug)}/deployments`;
52
98
  const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), basePath: `/${config.spaceSlug}`, env };
53
99
 
@@ -59,7 +105,7 @@ export async function deploy() {
59
105
  }
60
106
  if (!res.ok) refused(route, res);
61
107
 
62
- console.log(`live on 40rty: ${res.body.url} (deployment ${res.body.origin}, this build ${res.body.deploymentUrl} — ready in a few seconds)`);
108
+ console.log(`live on AMS: ${res.body.url} (deployment ${res.body.origin}, this build ${res.body.deploymentUrl} — ready in a few seconds)`);
63
109
  console.log(` visitors meet your app at the space's address; a locked space stays locked; \`forty hosting self\` switches back`);
64
110
  if (withheld.length > 0) console.log(` not deployed (looks secret): ${withheld.join(', ')} — add \`--env KEY\` to include one`);
65
111
 
@@ -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);
@@ -176,25 +176,23 @@ export async function doctor() {
176
176
  const engine = await statusOf(`${config.apiUrl}/embed/engine/${sdk.version}/engine.mjs`, { method: 'HEAD' });
177
177
  check(engine.status === 200, `the API serves the engine for sdk ${sdk.version}`);
178
178
 
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`');
179
+ // The agentic webpage is the app built with FORTY_AGENTIC=1 (`forty deploy`'s contract): `/` is the agentic page.
180
+ const framework = agenticFramework(JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8')));
181
+ if (framework !== null) {
182
+ const problems = await agenticWiringProblems(cwd, framework);
183
+ if (problems.length === 0) check(true, `the app is wired for an agentic build (FORTY_AGENTIC=1 makes / the agentic page)`);
184
+ for (const [what, fix] of problems) check(false, what, fix);
185
+ }
186
+ if (devOrigin !== undefined) {
187
+ await routeChecks(check, config, `${devOrigin}/`);
188
+ } else {
189
+ 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
190
  }
185
191
 
186
- // ── 40rty hosts it (`forty deploy`): the space's own address serves the app ──
192
+ // ── AMS hosts it (`forty deploy`) ──
187
193
  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
- }
194
+ console.log(`- AMS hosts this app (${hostedAt}), served at ${consoleUrl}/${config.spaceSlug}/ — \`forty hosting self\` hands it back`);
195
+ if (typeof consoleUrl === 'string') await routeChecks(check, config, `${consoleUrl}/${config.spaceSlug}/`);
198
196
  }
199
197
  }
200
198
 
@@ -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
+ }
@@ -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 {}
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,180 @@
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) to
4
+ // answer under `/<slug>/` — the path the console serves a hosted space at —
5
+ // set outside the developer's files:
6
+ //
7
+ // Hydrogen React Router's `basename` (the copy's react-router.config.*
8
+ // wraps the original; Hydrogen's preset refuses a basename, see
9
+ // the wrapper), and every built asset URL through
10
+ // HYDROGEN_ASSET_BASE_URL (`ASSET_BASE_ENV`), which `shopify
11
+ // hydrogen build` sets Vite's `base` from.
12
+ // Next.js `basePath` (the copy's next.config wraps the original).
13
+ //
14
+ // A URL the app spells out itself — `<a href="/cart">` — knows nothing of the
15
+ // base; the console follows it back under `/<slug>/` (a same-site Referer redirect).
16
+ import { spawnSync } from 'node:child_process';
17
+ import { constants } from 'node:fs';
18
+ import { access, cp, mkdir, readdir, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
19
+ import path from 'node:path';
20
+
21
+ /** Where each framework's copy lives: inside the output folder the app already ignores. */
22
+ export const BUILD_COPY_DIR = { hydrogen: path.join('dist', 'forty-build'), next: path.join('.next', 'forty-build') };
23
+
24
+ /** What the copy leaves behind: dependencies are linked, outputs and VCS state are not the app. */
25
+ const NOT_COPIED = new Set(['node_modules', 'dist', '.next', '.git', '.vercel', '.cache', '.turbo']);
26
+
27
+ /** Caches a tool writes inside `node_modules`: the copy keeps its own, never the app's. */
28
+ const OWN_CACHES = new Set(['.vite', '.cache']);
29
+
30
+ async function exists(file) {
31
+ try {
32
+ await access(file);
33
+ return true;
34
+ } catch (err) {
35
+ if (err.code === 'ENOENT') return false;
36
+ throw err;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * `to` as a directory of links to what `from` holds, each to its REAL path.
42
+ * Not one link to `from` itself: a pnpm app's packages are relative links
43
+ * (`../../node_modules/.pnpm/…`), and a tool that joins them onto the path it
44
+ * came through — Tailwind's resolver does — lands outside the store from a
45
+ * directory at another depth.
46
+ */
47
+ async function linkDependencies(from, to) {
48
+ await mkdir(to, { recursive: true });
49
+ for (const entry of await readdir(from)) {
50
+ if (OWN_CACHES.has(entry)) continue;
51
+ const source = path.join(from, entry);
52
+ if (entry.startsWith('@')) await linkDependencies(source, path.join(to, entry));
53
+ else await symlink(await realpath(source), path.join(to, entry));
54
+ }
55
+ }
56
+
57
+ /**
58
+ * A copy of the app at `cwd` to build `framework` in, answering under
59
+ * `/<slug>/`; returns its directory.
60
+ * A Hydrogen copy links the app's packages (nothing installed twice). A
61
+ * Next.js copy needs them inside it — Turbopack refuses a link out of the
62
+ * project root — and flat for its functions (`hoistedPnpmInstall`); an npm or
63
+ * yarn app's are cloned, copy-on-write where the filesystem can. `FORTY_*` lines are dropped from the copy's
64
+ * `.env*`: a build may prerender a page that reads `FORTY_DEV_TOKEN`, and the
65
+ * site is the space's published face, never a developer's preview.
66
+ */
67
+ export async function prepareBuildCopy(cwd, framework, slug) {
68
+ const dir = path.join(cwd, BUILD_COPY_DIR[framework]);
69
+ await rm(dir, { recursive: true, force: true });
70
+ await mkdir(dir, { recursive: true });
71
+ for (const entry of await readdir(cwd)) {
72
+ if (NOT_COPIED.has(entry)) continue;
73
+ await cp(path.join(cwd, entry), path.join(dir, entry), { recursive: true, filter: (src) => !path.relative(cwd, src).split(path.sep).includes('node_modules') });
74
+ }
75
+ const modules = path.join(cwd, 'node_modules');
76
+ if (await exists(modules)) {
77
+ if (framework === 'hydrogen') await linkDependencies(modules, path.join(dir, 'node_modules'));
78
+ else if (!(await hoistedPnpmInstall(modules, dir))) await cp(modules, path.join(dir, 'node_modules'), { recursive: true, verbatimSymlinks: true, mode: constants.COPYFILE_FICLONE });
79
+ }
80
+ for (const entry of await readdir(dir)) {
81
+ if (!/^\.env(\..+)?$/.test(entry)) continue;
82
+ const file = path.join(dir, entry);
83
+ const kept = (await readFile(file, 'utf8')).split('\n').filter((line) => !/^\s*(export\s+)?FORTY_/.test(line));
84
+ await writeFile(file, kept.join('\n'));
85
+ }
86
+ if (framework === 'hydrogen') await wrapConfig(dir, 'react-router.config', routerConfigWrapper(`/${slug}/`, null), (original) => routerConfigWrapper(`/${slug}/`, original));
87
+ else await wrapConfig(dir, 'next.config', nextConfigWrapper(`/${slug}`, null), (original) => nextConfigWrapper(`/${slug}`, original), 'mjs');
88
+ return dir;
89
+ }
90
+
91
+ const EXTENSIONS = ['ts', 'mts', 'js', 'mjs'];
92
+
93
+ /**
94
+ * A pnpm app's packages are links into `.pnpm/`. A Vercel function ships files,
95
+ * not links, and Node resolves a package's own dependencies through those
96
+ * links — so a Next.js copy of a pnpm app gets a FLAT (hoisted) node_modules
97
+ * instead, installed offline from the app's own store with the app's own pnpm
98
+ * version: nothing is downloaded. `false` when the app is not a pnpm app (npm
99
+ * and yarn already lay packages out flat).
100
+ */
101
+ async function hoistedPnpmInstall(modules, dir) {
102
+ let meta;
103
+ try {
104
+ meta = JSON.parse(await readFile(path.join(modules, '.modules.yaml'), 'utf8'));
105
+ } catch {
106
+ return false;
107
+ }
108
+ if (typeof meta.packageManager !== 'string' || !meta.packageManager.startsWith('pnpm@')) return false;
109
+ // pnpm 11 reads the linker from pnpm-workspace.yaml, not from a flag; older pnpm from .npmrc. The copy gets both.
110
+ const workspace = path.join(dir, 'pnpm-workspace.yaml');
111
+ const current = (await exists(workspace)) ? await readFile(workspace, 'utf8') : '';
112
+ await writeFile(workspace, `${current.replace(/^nodeLinker:.*$/m, '')}\nnodeLinker: hoisted\n`);
113
+ const npmrc = path.join(dir, '.npmrc');
114
+ await writeFile(npmrc, `${(await exists(npmrc)) ? await readFile(npmrc, 'utf8') : ''}\nnode-linker=hoisted\n`);
115
+ const args = ['--yes', meta.packageManager, 'install', '--offline', '--frozen-lockfile', '--config.minimum-release-age=0', '--ignore-scripts'];
116
+ if (typeof meta.storeDir === 'string') args.push(`--store-dir=${meta.storeDir}`);
117
+ const run = spawnSync('npx', args, { cwd: dir, stdio: 'inherit' });
118
+ 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})`);
119
+ return true;
120
+ }
121
+
122
+ /** In `dir`: the config `<stem>.*` renamed aside and wrapped by `wrapper(originalName)`, or `fresh` written when there is none. */
123
+ async function wrapConfig(dir, stem, fresh, wrapper, freshExt = 'ts') {
124
+ for (const ext of EXTENSIONS) {
125
+ const file = `${stem}.${ext}`;
126
+ if (!(await exists(path.join(dir, file)))) continue;
127
+ const original = `${stem}.forty-original.${ext}`;
128
+ await rename(path.join(dir, file), path.join(dir, original));
129
+ await writeFile(path.join(dir, file), wrapper(original));
130
+ return;
131
+ }
132
+ await writeFile(path.join(dir, `${stem}.${freshExt}`), fresh);
133
+ }
134
+
135
+ /**
136
+ * The React Router config that wraps `original` (a file name beside it), or a
137
+ * fresh one when it is `null`.
138
+ *
139
+ * Hydrogen's preset refuses any basename outright ("use a reverse proxy or CDN
140
+ * path rewriting") because ITS dev and preview servers serve from `/`. The
141
+ * console is that reverse proxy, and the build runs nowhere else, so the
142
+ * preset's own checks still run — on the config as it reads without a
143
+ * basename.
144
+ */
145
+ export function routerConfigWrapper(basename, original) {
146
+ if (original === null) return `export default { basename: ${JSON.stringify(basename)} };\n`;
147
+ return `import config from './${original}';
148
+ const unbased = (preset) => typeof preset.reactRouterConfigResolved !== 'function' ? preset : {
149
+ ...preset,
150
+ reactRouterConfigResolved: (args) => preset.reactRouterConfigResolved({ ...args, reactRouterConfig: { ...args.reactRouterConfig, basename: '/' } }),
151
+ };
152
+ export default { ...config, presets: (Array.isArray(config.presets) ? config.presets : []).map(unbased), basename: ${JSON.stringify(basename)} };
153
+ `;
154
+ }
155
+
156
+ /** The environment `shopify hydrogen build` takes the asset base from. */
157
+ export const ASSET_BASE_ENV = 'HYDROGEN_ASSET_BASE_URL';
158
+
159
+ /**
160
+ * The next.config that wraps `original` (a file name beside it, or `null`) with
161
+ * `basePath`. A config may be an object or a function of the build phase.
162
+ *
163
+ * `skipTrailingSlashRedirect`: the console serves a hosted space's subtree at
164
+ * `/<slug>/…` and sends the bare `/<slug>` there; Next's own `/<slug>/` →
165
+ * `/<slug>` redirect would loop against it.
166
+ */
167
+ export function nextConfigWrapper(basePath, original) {
168
+ const forty = `basePath: ${JSON.stringify(basePath)}, skipTrailingSlashRedirect: true`;
169
+ if (original === null) return `export default { ${forty} };\n`;
170
+ // A TypeScript config is imported without its extension (the app's own
171
+ // tsconfig may refuse `.ts` imports); the wrapper is not the app's code to check.
172
+ const from = original.replace(/\.m?ts$/, '');
173
+ return `// @ts-nocheck
174
+ import config from './${from}';
175
+ export default async function fortyConfig(...args) {
176
+ const resolved = typeof config === 'function' ? await config(...args) : config;
177
+ return { ...resolved, ${forty} };
178
+ }
179
+ `;
180
+ }
@@ -1,16 +1,19 @@
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.
1
+ // `forty deploy`'s build, as Vercel's Build Output (v3), plus the env the
2
+ // hosted site runs with. A Hydrogen app: the client as static files, the
3
+ // Oxygen worker as one Edge Function. A Next.js app: whatever `vercel build`
4
+ // makes of it — the same output a Vercel deploy of the app would serve.
4
5
  import { spawnSync } from 'node:child_process';
5
6
  import { createHash } from 'node:crypto';
6
7
  import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
8
  import path from 'node:path';
8
9
  import { fail } from './context.mjs';
9
- import { ASSET_BASE_ENV } from './base-path-build.mjs';
10
10
  import { findCredential } from './credentials.mjs';
11
+ import { ASSET_BASE_ENV } from './build-copy.mjs';
11
12
 
12
13
  /** Inside `dist/`, which a Hydrogen app already ignores — never the developer's own `.vercel/`. */
13
14
  const OUTPUT_DIR = path.join('dist', 'forty-output');
15
+ /** Inside `.next/`, which a Next.js app already ignores. */
16
+ const NEXT_OUTPUT_DIR = path.join('.next', 'forty-output');
14
17
 
15
18
  // The Oxygen worker (`export default { fetch(request, env, ctx) }`) as a Vercel
16
19
  // Edge Function. Vercel Edge has no Cache API, so Hydrogen's cache is a no-op
@@ -23,18 +26,69 @@ export default function handler(request, context) {
23
26
  }
24
27
  `;
25
28
 
26
- /** `shopify hydrogen build` in `cwd` (the app's base-path copy), its assets served from `assetBase`, with its output on the terminal. */
29
+ /** The build env that makes `/` the agentic webpage (the contract in `deploy.mjs`). */
30
+ const AGENTIC = { FORTY_AGENTIC: '1' };
31
+
32
+ /** `shopify hydrogen build` in `cwd` (the app's build copy), agentic, its assets served from `assetBase`, with its output on the terminal. */
27
33
  export function buildHydrogen(cwd, assetBase) {
28
- const env = { ...process.env, [ASSET_BASE_ENV]: assetBase };
34
+ const env = { ...process.env, ...AGENTIC, [ASSET_BASE_ENV]: assetBase };
29
35
  const run = spawnSync('npx', ['--no-install', 'shopify', 'hydrogen', 'build', '--no-lockfile-check'], { cwd, stdio: 'inherit', env });
30
36
  if (run.error !== undefined) fail(`could not run \`shopify hydrogen build\` (${run.error.message})`);
31
37
  if (run.status !== 0) fail('`shopify hydrogen build` failed — fix the build, then run `forty deploy` again');
32
38
  }
33
39
 
40
+ /**
41
+ * `vercel build` in `dir` (the app's build copy), agentic, offline: a local project
42
+ * file stands in for `vercel pull`, so no Vercel login or project is needed;
43
+ * its no-op install keeps the copy's flat node_modules (`build-copy.mjs`).
44
+ * Each function names the project files it needs in its `filePathMap`
45
+ * (node_modules, mostly) instead of holding them. Those files are copied ONCE
46
+ * into the output's `_deps/` and the maps pointed there, so the upload — which
47
+ * sends only the output, deduplicated by content — carries them. (`vercel
48
+ * build --standalone` inlines them per function instead: a GB for 76 functions.)
49
+ * Then its `.vercel/output` is copied under `cwd`'s NEXT_OUTPUT_DIR with
50
+ * symlinks resolved — the build links functions that share files, and the
51
+ * upload sends files, not links. Returns the output directory.
52
+ */
53
+ export async function buildNext(cwd, dir) {
54
+ await mkdir(path.join(dir, '.vercel'), { recursive: true });
55
+ await writeFile(path.join(dir, '.vercel', 'project.json'), JSON.stringify({ projectId: 'forty-deploy', orgId: 'forty-deploy', settings: { framework: 'nextjs', installCommand: 'true' } }));
56
+ const run = spawnSync('npx', ['--yes', 'vercel@latest', 'build', '--prod', '--yes'], { cwd: dir, stdio: 'inherit', env: { ...process.env, ...AGENTIC, VERCEL_TELEMETRY_DISABLED: '1' } });
57
+ if (run.error !== undefined) fail(`could not run \`vercel build\` (${run.error.message})`);
58
+ if (run.status !== 0) fail('`vercel build` failed — fix the build, then run `forty deploy` again');
59
+ const out = path.join(cwd, NEXT_OUTPUT_DIR);
60
+ await rm(out, { recursive: true, force: true });
61
+ await cp(path.join(dir, '.vercel', 'output'), out, { recursive: true, dereference: true });
62
+ const copied = new Set();
63
+ for (const entry of await readdir(path.join(out, 'functions'), { recursive: true, withFileTypes: true })) {
64
+ if (!entry.isFile() || entry.name !== '.vc-config.json') continue;
65
+ const file = path.join(entry.parentPath, entry.name);
66
+ const config = JSON.parse(await readFile(file, 'utf8'));
67
+ if (config.filePathMap === undefined) continue;
68
+ const map = {};
69
+ for (const [key, from] of Object.entries(config.filePathMap)) {
70
+ const source = path.join(dir, from);
71
+ if (!copied.has(from)) {
72
+ await mkdir(path.dirname(path.join(out, '_deps', from)), { recursive: true });
73
+ await cp(source, path.join(out, '_deps', from), { dereference: true, recursive: true });
74
+ copied.add(from);
75
+ }
76
+ map[key] = `${DEPLOYED_OUTPUT}/_deps/${from}`;
77
+ }
78
+ config.filePathMap = map;
79
+ await writeFile(file, JSON.stringify(config));
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /** Where the api places the output inside the deployment (`spacefront-hosting.ts`); `filePathMap` is relative to the deployment root. */
85
+ const DEPLOYED_OUTPUT = '.vercel/output';
86
+
34
87
  /**
35
88
  * Lay a build's `dist/client` + `dist/server` out as a Build Output under
36
89
  * `cwd`'s OUTPUT_DIR. The app answers under `/<slug>/`, so its client files are
37
- * served from there too (`static/<slug>/assets/…`).
90
+ * served from there too (`static/<slug>/assets/…`); the worker is the one
91
+ * function every other path falls through to.
38
92
  */
39
93
  export async function assembleBuildOutput(cwd, buildDir, slug) {
40
94
  const out = path.join(cwd, OUTPUT_DIR);
@@ -66,25 +120,28 @@ export async function listOutputFiles(dir) {
66
120
  }
67
121
 
68
122
  /** What a Hydrogen app cannot start without. */
69
- const REQUIRED = ['SESSION_SECRET', 'PUBLIC_STORE_DOMAIN', 'PUBLIC_STOREFRONT_API_TOKEN'];
70
- /** Read by Hydrogen when present; public by Shopify's own naming. */
71
- const KNOWN = ['PUBLIC_CHECKOUT_DOMAIN', 'SHOP_ID', 'PUBLIC_STOREFRONT_ID'];
123
+ export const HYDROGEN_REQUIRED = ['SESSION_SECRET', 'PUBLIC_STORE_DOMAIN', 'PUBLIC_STOREFRONT_API_TOKEN'];
124
+ /**
125
+ * Deployed even though the name looks secret: Shopify's own public values
126
+ * (Hydrogen's, and Next.js Commerce's names for the same Storefront token).
127
+ */
128
+ const KNOWN = ['PUBLIC_CHECKOUT_DOMAIN', 'SHOP_ID', 'PUBLIC_STOREFRONT_ID', 'SHOPIFY_STORE_DOMAIN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN'];
72
129
  const LOOKS_SECRET = /SECRET|TOKEN|PRIVATE|PASSWORD|PASSWD|CREDENTIAL|(^|_)KEY$|(^|_)AUTH/;
73
130
 
74
131
  /**
75
- * The env the hosted site runs with, from the app's `.env`: what Hydrogen
76
- * needs, anything `PUBLIC_`, anything that does not look like a secret, and
132
+ * The env the hosted site runs with, from the app's `.env`: what the app
133
+ * needs (`required`), anything `PUBLIC_`, anything that does not look like a secret, and
77
134
  * whatever the developer opted in with `--env KEY`. `FORTY_*` never — the site
78
135
  * is the space's published face, and `FORTY_DEV_TOKEN` would turn it into a
79
136
  * developer's preview.
80
137
  */
81
- export function pickDeployEnv(dotenv, optIn) {
82
- for (const key of REQUIRED) if (typeof dotenv[key] !== 'string' || dotenv[key] === '') fail(`.env must set ${key} — the app cannot start without it`);
138
+ export function pickDeployEnv(dotenv, optIn, required = HYDROGEN_REQUIRED) {
139
+ for (const key of required) if (typeof dotenv[key] !== 'string' || dotenv[key] === '') fail(`.env must set ${key} — the app cannot start without it`);
83
140
  const env = {};
84
141
  const withheld = [];
85
142
  for (const [key, value] of Object.entries(dotenv)) {
86
143
  if (key.startsWith('FORTY_')) continue;
87
- if (REQUIRED.includes(key) || KNOWN.includes(key) || key.startsWith('PUBLIC_') || optIn.includes(key) || !LOOKS_SECRET.test(key)) env[key] = value;
144
+ if (required.includes(key) || KNOWN.includes(key) || key.startsWith('PUBLIC_') || optIn.includes(key) || !LOOKS_SECRET.test(key)) env[key] = value;
88
145
  else withheld.push(key);
89
146
  }
90
147
  for (const key of optIn) {
package/dist/wire.js CHANGED
@@ -527,6 +527,15 @@ import { z as z15 } from "zod";
527
527
  // ../spacestation/src/catalog/function-props.ts
528
528
  import { z as z16 } from "zod";
529
529
 
530
+ // ../spacestation/src/catalog/shape-tokens.ts
531
+ var SHAPE_TOKEN = /<(?![/!])[^<>=]*\s[^<>=]*(?<!\/)>/;
532
+ function carriesShapeToken(value) {
533
+ if (typeof value === "string") return SHAPE_TOKEN.test(value);
534
+ if (Array.isArray(value)) return value.some(carriesShapeToken);
535
+ if (typeof value === "object" && value !== null) return Object.values(value).some(carriesShapeToken);
536
+ return false;
537
+ }
538
+
530
539
  // ../spacestation/src/layout/apply-patch.ts
531
540
  function arrayAdd(arr, key, value) {
532
541
  if (key === "-") {
@@ -818,6 +827,8 @@ var PackageReleaseSchema = z21.object({
818
827
  label: z21.string().min(1).max(120),
819
828
  /** The package's own version, as its repository states it — shown in the console. */
820
829
  version: z21.string().min(1).max(40),
830
+ /** What this release changed, in the publisher's words (`forty publish --message`) — shown in the console's version list. */
831
+ description: z21.string().min(1).max(500).optional(),
821
832
  catalog: WireCatalogSchema,
822
833
  /** Component manifests by path under `catalogs/`, e.g. `catalogs/product/productGrid.md`. */
823
834
  manifests: z21.record(z21.string().regex(/^catalogs\/.+\.md$/, "a manifest path is catalogs/<\u2026>.md"), z21.string()),
@@ -1585,5 +1596,6 @@ export {
1585
1596
  EMPTY_SPEC,
1586
1597
  PackageReleaseSchema,
1587
1598
  applySinglePatch,
1599
+ carriesShapeToken,
1588
1600
  catalogToWire
1589
1601
  };
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "peerDependencies": {
16
16
  "zod": "^3.25.0"
17
17
  },
18
- "version": "0.3.1",
18
+ "version": "0.3.2",
19
19
  "homepage": "https://docs.40rty.ai",
20
20
  "license": "UNLICENSED",
21
21
  "engines": {
@@ -1,149 +0,0 @@
1
- // `forty deploy` builds the app to answer under `/<slug>/` — the path the
2
- // console serves a 40rty-hosted space at — WITHOUT touching the developer's
3
- // files. Two settings, both made outside them:
4
- //
5
- // basename '/<slug>/' React Router's. The build runs in a COPY whose
6
- // react-router.config.* wraps the original (Hydrogen's
7
- // preset refuses a basename; see the wrapper). Routes,
8
- // <Link>, <Form>/CartForm actions, redirects and lazy
9
- // route discovery honour it; an optional `($locale)`
10
- // segment matches after it.
11
- // asset base '/<slug>/' Every built asset URL. `shopify hydrogen build` sets
12
- // Vite's `base` itself, over the app's vite.config, from
13
- // HYDROGEN_ASSET_BASE_URL (how Oxygen points assets at
14
- // its CDN) — so that is what is set (`ASSET_BASE_ENV`).
15
- //
16
- // A URL the app spells out itself — `<a href="/cart">`, `src="/logo.svg"` —
17
- // knows nothing of the base; `forty doctor` lists them.
18
- import { access, cp, mkdir, readdir, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
19
- import path from 'node:path';
20
-
21
- /** Inside `dist/`, which a Hydrogen app already ignores. */
22
- export const BUILD_COPY_DIR = path.join('dist', 'forty-build');
23
-
24
- const EXTENSIONS = ['ts', 'mts', 'js', 'mjs'];
25
- /** What the copy leaves behind: dependencies are linked, outputs and VCS state are not the app. */
26
- const NOT_COPIED = new Set(['node_modules', 'dist', '.git', '.vercel', '.cache', '.turbo']);
27
-
28
- async function exists(file) {
29
- try {
30
- await access(file);
31
- return true;
32
- } catch (err) {
33
- if (err.code === 'ENOENT') return false;
34
- throw err;
35
- }
36
- }
37
-
38
- /** Caches a tool writes inside `node_modules`: the copy keeps its own, never the app's. */
39
- const OWN_CACHES = new Set(['.vite', '.cache']);
40
-
41
- /**
42
- * `to` as a directory of links to what `from` holds, each to its REAL path.
43
- * Not one link to `from` itself: a pnpm app's packages are relative links
44
- * (`../../node_modules/.pnpm/…`), and a tool that joins them onto the path it
45
- * came through — Tailwind's resolver does — lands outside the store from a
46
- * directory at another depth.
47
- */
48
- async function linkDependencies(from, to) {
49
- await mkdir(to, { recursive: true });
50
- for (const entry of await readdir(from)) {
51
- if (OWN_CACHES.has(entry)) continue;
52
- const source = path.join(from, entry);
53
- if (entry.startsWith('@')) await linkDependencies(source, path.join(to, entry));
54
- else await symlink(await realpath(source), path.join(to, entry));
55
- }
56
- }
57
-
58
- /** `react-router.config.ts` → `react-router.config.forty-original.ts` */
59
- function originalName(file) {
60
- const ext = path.extname(file);
61
- return `${path.basename(file, ext)}.forty-original${ext}`;
62
- }
63
-
64
- /**
65
- * The React Router config that wraps `original` (a file name beside it), or a
66
- * fresh one when the app has none.
67
- *
68
- * Hydrogen's preset refuses any basename outright ("use a reverse proxy or CDN
69
- * path rewriting") because ITS dev and preview servers serve from `/`. The
70
- * console is that reverse proxy, and the build runs nowhere else, so the
71
- * preset's own checks still run — on the config as it reads without a
72
- * basename.
73
- */
74
- export function routerConfigWrapper(basename, original) {
75
- if (original === null) return `export default { basename: ${JSON.stringify(basename)} };\n`;
76
- return `import config from './${original}';
77
- const unbased = (preset) => typeof preset.reactRouterConfigResolved !== 'function' ? preset : {
78
- ...preset,
79
- reactRouterConfigResolved: (args) => preset.reactRouterConfigResolved({ ...args, reactRouterConfig: { ...args.reactRouterConfig, basename: '/' } }),
80
- };
81
- export default { ...config, presets: (Array.isArray(config.presets) ? config.presets : []).map(unbased), basename: ${JSON.stringify(basename)} };
82
- `;
83
- }
84
-
85
- /** The environment `shopify hydrogen build` takes the asset base from. */
86
- export const ASSET_BASE_ENV = 'HYDROGEN_ASSET_BASE_URL';
87
-
88
- /** The first `<stem>.<ext>` present in `dir`, or `null`. */
89
- async function find(dir, stem) {
90
- for (const ext of EXTENSIONS) {
91
- const file = `${stem}.${ext}`;
92
- if (await exists(path.join(dir, file))) return file;
93
- }
94
- return null;
95
- }
96
-
97
- /**
98
- * A copy of the app at `cwd`, configured to answer under `/<slug>/`. Returns
99
- * the copy's directory; build it there. Its `node_modules` links to the app's
100
- * own packages, so nothing is installed twice.
101
- */
102
- export async function prepareBasePathBuild(cwd, slug) {
103
- const base = `/${slug}/`;
104
- const dir = path.join(cwd, BUILD_COPY_DIR);
105
- await rm(dir, { recursive: true, force: true });
106
- await mkdir(dir, { recursive: true });
107
- for (const entry of await readdir(cwd)) {
108
- if (NOT_COPIED.has(entry)) continue;
109
- await cp(path.join(cwd, entry), path.join(dir, entry), { recursive: true, filter: (src) => !path.relative(cwd, src).split(path.sep).includes('node_modules') });
110
- }
111
- if (await exists(path.join(cwd, 'node_modules'))) await linkDependencies(path.join(cwd, 'node_modules'), path.join(dir, 'node_modules'));
112
-
113
- const router = await find(dir, 'react-router.config');
114
- if (router === null) {
115
- await writeFile(path.join(dir, 'react-router.config.ts'), routerConfigWrapper(base, null));
116
- } else {
117
- await rename(path.join(dir, router), path.join(dir, originalName(router)));
118
- await writeFile(path.join(dir, router), routerConfigWrapper(base, originalName(router)));
119
- }
120
- return dir;
121
- }
122
-
123
- /**
124
- * Root-absolute URLs written into the app's markup — `href="/…"`, `src="/…"`,
125
- * `action="/…"`, and `href: '/…'` in a `links()` export — as `file:line`. Under `/<slug>/` each points outside the
126
- * store. `<Link to>` and `<Form action>` through React Router are fine; a
127
- * plain attribute is not.
128
- */
129
- export async function findRootAbsoluteUrls(cwd, appDir = 'app') {
130
- const found = [];
131
- const pattern = /\b(href|src|action)\s*(=\s*\{?|:\s*)["'`]\/(?!\/)/g;
132
- let entries;
133
- try {
134
- entries = await readdir(path.join(cwd, appDir), { recursive: true, withFileTypes: true });
135
- } catch (err) {
136
- if (err.code === 'ENOENT') return found;
137
- throw err;
138
- }
139
- for (const entry of entries) {
140
- if (!entry.isFile() || !/\.(tsx|jsx)$/.test(entry.name)) continue;
141
- const abs = path.join(entry.parentPath, entry.name);
142
- const lines = (await readFile(abs, 'utf8')).split('\n');
143
- lines.forEach((line, i) => {
144
- if (pattern.test(line)) found.push(`${path.relative(cwd, abs)}:${i + 1}`);
145
- pattern.lastIndex = 0;
146
- });
147
- }
148
- return found;
149
- }