@40rty/ams-cli 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,8 @@
1
- import { fail, readConfig, storeBinding } from '../lib/context.mjs';
2
- import { call } from '../lib/credentials.mjs';
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { cwd, fail, option, readConfig, storeBinding } from '../lib/context.mjs';
4
+ import { call, request } from '../lib/credentials.mjs';
5
+ import { displayName, titleCase } from './init.mjs';
3
6
 
4
7
  /** The Storefront API version the store is asked through. */
5
8
  const STOREFRONT_API = '2025-07';
@@ -8,16 +11,17 @@ const SHOP_GID = /^gid:\/\/shopify\/Shop\/(\d+)$/;
8
11
  /**
9
12
  * Ask the store itself, with the app's own token: proves the token works, and
10
13
  * answers the two things the agent needs that `.env` rarely carries — the
11
- * store's numeric id and its market.
14
+ * store's numeric id and its market — plus one product title, the query a
15
+ * search probe can be sure the store sells.
12
16
  */
13
- async function askStore(domain, token) {
17
+ export async function askStore(domain, token) {
14
18
  const url = `https://${domain}/api/${STOREFRONT_API}/graphql.json`;
15
19
  let res;
16
20
  try {
17
21
  res = await fetch(url, {
18
22
  method: 'POST',
19
23
  headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': token },
20
- body: JSON.stringify({ query: '{ shop { id } localization { country { isoCode } } }' }),
24
+ body: JSON.stringify({ query: '{ shop { id name } localization { country { isoCode } } products(first: 1) { nodes { title } } }' }),
21
25
  });
22
26
  } catch (err) {
23
27
  fail(`cannot reach the store at ${url} (${err.message}) — is PUBLIC_STORE_DOMAIN right?`);
@@ -29,19 +33,56 @@ async function askStore(domain, token) {
29
33
  }
30
34
  const match = SHOP_GID.exec(String(body.data.shop.id));
31
35
  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 };
36
+ const first = body.data.products === null || body.data.products === undefined ? undefined : body.data.products.nodes[0];
37
+ return {
38
+ shopId: match === null ? undefined : match[1],
39
+ shopName: typeof body.data.shop.name === 'string' && body.data.shop.name.trim() !== '' ? body.data.shop.name.trim() : undefined,
40
+ marketCountry: typeof country === 'string' && country.length === 2 ? country : undefined,
41
+ sampleTitle: first === undefined || typeof first.title !== 'string' ? undefined : first.title,
42
+ };
33
43
  }
34
44
 
45
+ /**
46
+ * One real catalog search through the space's own agent tools
47
+ * (`POST /org/spaces/:slug/probe-search`) — the store answering its own API
48
+ * does not mean the agent can find its products. `{ ok, count, titles, query }`,
49
+ * or `{ ok: false, error }` when the search could not run.
50
+ */
51
+ export async function probeSearch(config, query) {
52
+ const res = await request(config.apiUrl, 'POST', `/org/spaces/${config.spaceSlug}/probe-search`, query === undefined ? {} : { query });
53
+ if (!res.ok) return { ok: false, error: `${res.status}: ${res.body.error}` };
54
+ return { ok: true, ...res.body };
55
+ }
56
+
57
+ /** The space's current name when `forty init` derived it rather than a person choosing it, else `undefined`. */
58
+ async function derivedName(config) {
59
+ const me = await request(config.apiUrl, 'GET', '/org/me');
60
+ const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
61
+ if (space === undefined) return undefined;
62
+ const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8').catch((err) => {
63
+ if (err.code === 'ENOENT') return '{}';
64
+ throw err;
65
+ }));
66
+ const derived = [config.spaceSlug, titleCase(config.spaceSlug), displayName(manifest.name)];
67
+ return derived.includes(space.name) ? space.name : undefined;
68
+ }
69
+
70
+ /** Why a search that ran found nothing — the one cause we see over and over. */
71
+ export const ZERO_RESULTS_HINT = 'unpublished/dev stores are not in Shopify\'s global catalog, which the agent searches — publish the store (remove its password) and make sure its products are on the Shop channel';
72
+
35
73
  /** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
36
74
  export async function connect() {
37
75
  const config = await readConfig();
38
- const binding = await storeBinding();
76
+ // `--domain` / `--token` / `--shop-id` win over `.env`.
77
+ const env = await storeBinding();
78
+ const pick = (flagName, fromEnv) => (option(flagName) !== undefined ? option(flagName) : fromEnv);
79
+ const binding = { domain: pick('domain', env.domain), token: pick('token', env.token), shopId: pick('shop-id', env.shopId) };
39
80
  // An empty `.env` value is absence: `PUBLIC_STOREFRONT_API_TOKEN=` once
40
81
  // stored `storefrontAccessToken: ""`, which the connector refuses wholesale.
41
82
  const present = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
42
83
  const domain = present(binding.domain);
43
84
  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)');
85
+ if (domain === undefined || token === undefined) fail('no store: set PUBLIC_STORE_DOMAIN and PUBLIC_STOREFRONT_API_TOKEN (or SHOPIFY_STORE_DOMAIN and SHOPIFY_STOREFRONT_ACCESS_TOKEN) in .env, or pass --domain and --token');
45
86
  const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '');
46
87
  // Catalog search runs ONLY through Shopify's Global catalog, scoped by the
47
88
  // store's id — and mock.shop is not in it, so a spacefront on it could never
@@ -58,10 +99,23 @@ export async function connect() {
58
99
  // The store's market: Global search ranks by ship-to country and defaults to the US.
59
100
  if (store.marketCountry !== undefined) settings.marketCountry = store.marketCountry;
60
101
 
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
- });
102
+ const body = { platform: 'shopify', platformConfig: { platform: 'shopify', domain: host, config: settings }, vertical: 'ecommerce' };
103
+ // The agent greets visitors by the space's name: a name `forty init` derived
104
+ // (from the slug or package.json) gives way to the store's own.
105
+ const rename = store.shopName === undefined ? undefined : await derivedName(config);
106
+ if (rename !== undefined && rename !== store.shopName) body.name = store.shopName;
107
+ const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, body);
108
+ if (body.name !== undefined) console.log(`space "${result.slug}" is now named "${body.name}" (was "${rename}", derived by \`forty init\`)`);
66
109
  console.log(`space "${result.slug}" is connected to ${host} (shop ${shopId}${store.marketCountry === undefined ? '' : `, market ${store.marketCountry}`}) — \`forty dev\` to work on it`);
110
+
111
+ // Connected is not searchable: run the agent's own search once, for a product the store just named.
112
+ const probe = await probeSearch(config, store.sampleTitle);
113
+ if (!probe.ok) {
114
+ console.warn(`\n!! WARNING: the agent's catalog search could not run (${probe.error})`);
115
+ } else if (probe.count === 0) {
116
+ console.warn(`\n!! WARNING: the agent's catalog search for "${probe.query}" found NOTHING — visitors will see no products.`);
117
+ console.warn(`!! ${ZERO_RESULTS_HINT}`);
118
+ } else {
119
+ console.log(`search works: "${probe.query}" → ${probe.count} result(s): ${probe.titles.join(', ')}`);
120
+ }
67
121
  }
@@ -1,6 +1,8 @@
1
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.
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.
4
6
  //
5
7
  // forty deploy build, upload, deploy
6
8
  // forty deploy --env KEY also deploy KEY from .env (one that looks secret)
@@ -10,6 +12,7 @@ import path from 'node:path';
10
12
  import { cwd, fail, readConfig, readDotenv } from '../lib/context.mjs';
11
13
  import { request } from '../lib/credentials.mjs';
12
14
  import { detectDeployTarget } from '../lib/deploy-target.mjs';
15
+ import { prepareBasePathBuild } from '../lib/base-path-build.mjs';
13
16
  import { assembleBuildOutput, buildHydrogen, listOutputFiles, pickDeployEnv, uploadFiles } from '../lib/hosted-build.mjs';
14
17
 
15
18
  function optIns(args) {
@@ -41,10 +44,12 @@ export async function deploy() {
41
44
  }
42
45
  const { env, withheld } = pickDeployEnv(await readDotenv(path.join(cwd, '.env')), optIns(args));
43
46
 
44
- buildHydrogen(cwd);
45
- const files = await listOutputFiles(await assembleBuildOutput(cwd));
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));
46
51
  const route = `/org/spaces/${encodeURIComponent(config.spaceSlug)}/deployments`;
47
- const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), env };
52
+ const body = { files: files.map(({ file, sha, size }) => ({ file, sha, size })), basePath: `/${config.spaceSlug}`, env };
48
53
 
49
54
  let res = await request(config.apiUrl, 'POST', route, body);
50
55
  if (res.status === 409 && Array.isArray(res.body.missing)) {
@@ -54,11 +59,12 @@ export async function deploy() {
54
59
  }
55
60
  if (!res.ok) refused(route, res);
56
61
 
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`);
62
+ console.log(`live on 40rty: ${res.body.url} (deployment ${res.body.origin}, this build ${res.body.deploymentUrl} — ready in a few seconds)`);
63
+ console.log(` visitors meet your app at the space's address; a locked space stays locked; \`forty hosting self\` switches back`);
59
64
  if (withheld.length > 0) console.log(` not deployed (looks secret): ${withheld.join(', ')} — add \`--env KEY\` to include one`);
60
65
 
61
66
  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>`);
67
+ const later = 'when it is live, `forty origin add <url>` then `forty hosting self`';
68
+ if (own.target === null) console.log(` your own production target is not set up yet — ${later}`);
69
+ else console.log(` your production deploys to ${own.label} (${own.evidence}) — ${later}`);
64
70
  }
@@ -1,12 +1,18 @@
1
- // `forty doctor [dev-server-url]` — the integration's definition of done.
1
+ // `forty doctor [dev-server-url] [--ask "<question>" | --no-ask]` — the integration's definition of done.
2
+ // When 40rty hosts the app (`forty deploy`), the space's own address is
3
+ // checked too: `<console>/<space><route>`.
2
4
  //
3
5
  // Every check names what is wrong in the repo's own terms. Exits non-zero when
4
6
  // any fail, so it is the same gate in CI as on a laptop.
5
7
  import { access, readFile } from 'node:fs/promises';
6
8
  import path from 'node:path';
9
+ import { catalogToWire } from '../../dist/wire.js';
10
+ import { askSpace, judgeTurn } from '../lib/ask.mjs';
7
11
  import { loadCatalog } from '../lib/build.mjs';
8
- import { cwd, readConfig, readDotenv } from '../lib/context.mjs';
12
+ import { appKind, cwd, FortyError, flag, option, positionals, readConfig, readDotenv, storeBinding } from '../lib/context.mjs';
9
13
  import { findCredential, request } from '../lib/credentials.mjs';
14
+ import { findRootAbsoluteUrls } from '../lib/base-path-build.mjs';
15
+ import { askStore, probeSearch, ZERO_RESULTS_HINT } from './connect.mjs';
10
16
 
11
17
  /** What the ecommerce vertical requires a source to draw, and what the agent speaks through. */
12
18
  const REQUIRED_TYPES = ['productGrid', 'collectionList'];
@@ -67,8 +73,37 @@ export function allowsOwnScripts(sources, pageOrigin) {
67
73
  return sources.includes("'self'") || sources.includes("'strict-dynamic'") || allowsOrigin(sources, pageOrigin);
68
74
  }
69
75
 
76
+ /** The page at `pageUrl` serves the spacefront route, its CSP lets the engine run, and the api takes calls from it. */
77
+ async function routeChecks(check, config, pageUrl) {
78
+ const page = new URL(pageUrl);
79
+ // Not followed: a locked space answers with a redirect to its gate, which is not the route.
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);
82
+ const csp = served.headers.get('content-security-policy');
83
+ if (csp !== null) {
84
+ const directives = parseCsp(csp);
85
+ const api = new URL(config.apiUrl).origin;
86
+ const socket = api.replace(/^http/, 'ws');
87
+ const scripts = effective(directives, 'script-src');
88
+ const connects = effective(directives, 'connect-src');
89
+ const hint = 'add the origin to defaultSrc, not scriptSrc — scriptSrc replaces Hydrogen\'s defaults';
90
+ check(allowsOwnScripts(scripts, page.origin), `CSP script-src on ${page.pathname} lets the app run its own scripts ('self')`, `without it the app never hydrates — ${hint}`);
91
+ check(allowsOrigin(scripts, api), `CSP script-src on ${page.pathname} allows ${api} (the engine)`, hint);
92
+ check(allowsOrigin(connects, api), `CSP connect-src on ${page.pathname} allows ${api}`, hint);
93
+ check(allowsOrigin(connects, socket), `CSP connect-src on ${page.pathname} allows ${socket}`, hint);
94
+ }
95
+ // A deployed site is refused by the api's CORS until its origin is registered.
96
+ if (page.hostname !== 'localhost' && page.hostname !== '127.0.0.1') {
97
+ const preflight = await statusOf(`${config.apiUrl}/s/${config.spaceSlug}/sessions`, {
98
+ method: 'OPTIONS',
99
+ headers: { Origin: page.origin, 'Access-Control-Request-Method': 'POST' },
100
+ });
101
+ check(preflight.headers.get('access-control-allow-origin') === page.origin, `the api accepts calls from ${page.origin} (CORS)`, `run \`forty origin add ${page.origin}\``);
102
+ }
103
+ }
104
+
70
105
  export async function doctor() {
71
- const devOrigin = process.argv[3];
106
+ const devOrigin = positionals()[0];
72
107
  const config = await readConfig();
73
108
  const selfHosted = config.bundle === undefined;
74
109
  const failures = [];
@@ -92,12 +127,16 @@ export async function doctor() {
92
127
  }
93
128
 
94
129
  // ── The platform ──
130
+ let consoleUrl;
131
+ let hostedAt;
95
132
  const credential = await findCredential(config.apiUrl);
96
133
  check(credential !== null, 'signed in', 'run `forty login`, or set FORTY_API_KEY in CI');
97
134
  if (credential !== null) {
98
135
  const me = await request(config.apiUrl, 'GET', '/org/me');
99
136
  check(me.ok, `the credential from ${credential.source} is accepted by ${config.apiUrl}`);
100
137
  const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
138
+ if (me.ok) consoleUrl = me.body.consoleUrl;
139
+ if (space !== undefined && typeof space.hostedAppOrigin === 'string') hostedAt = space.hostedAppOrigin;
101
140
  check(space !== undefined, `space "${config.spaceSlug}" belongs to this organization`);
102
141
  if (space !== undefined) {
103
142
  // Not a failure either way: before the first release a space renders the
@@ -110,6 +149,7 @@ export async function doctor() {
110
149
  check(space.hasStorefrontToken === true, `the space's store (${where}) has a storefront token`, 'run `forty connect`');
111
150
  check(space.hasGlobalShopId === true, `the space's store (${where}) has a shop id, so catalog search works`, 'run `forty connect`');
112
151
  }
152
+ if (space.domain !== undefined) await searchCheck(config, check);
113
153
  }
114
154
  }
115
155
 
@@ -119,7 +159,8 @@ export async function doctor() {
119
159
  // Hydrogen loads Shopify's Customer Privacy API only with a checkout
120
160
  // domain; without it consent never resolves and the spacefront drops
121
161
  // 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');
162
+ const { hydrogen } = appKind(JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8')));
163
+ if (hydrogen) 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
164
  const token = env.FORTY_DEV_TOKEN;
124
165
  check(token !== undefined, '.env carries FORTY_DEV_TOKEN', 'run `forty dev`');
125
166
  if (token !== undefined) {
@@ -137,39 +178,79 @@ export async function doctor() {
137
178
 
138
179
  check(typeof config.route === 'string', 'forty.config.json names the spacefront "route"');
139
180
  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
- }
181
+ await routeChecks(check, config, `${devOrigin}${config.route}`);
165
182
  } else if (devOrigin === undefined) {
166
183
  console.log('- skipped the route and CSP checks: pass the dev server url, e.g. `forty doctor http://localhost:3000`');
167
184
  }
185
+
186
+ // ── 40rty hosts it (`forty deploy`): the space's own address serves the app ──
187
+ 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 itself does not.
191
+ const absolute = await findRootAbsoluteUrls(cwd);
192
+ if (absolute.length > 0) {
193
+ console.log(`! ${absolute.length} root-absolute URL(s) in the app's markup point outside /${config.spaceSlug}/ when 40rty hosts it — use <Link to> / a relative path:`);
194
+ for (const where of absolute.slice(0, 20)) console.log(` ${where}`);
195
+ }
196
+ }
168
197
  }
169
198
 
199
+ if (!flag('no-ask')) await askCheck(config, check);
200
+
170
201
  if (failures.length > 0) {
171
202
  console.error(`\n${failures.length} check(s) failed.`);
172
203
  process.exit(1);
173
204
  }
174
205
  console.log('\nAll checks passed.');
175
206
  }
207
+
208
+ /** The question doctor asks when `--ask` names none. */
209
+ const DEFAULT_QUESTION = 'what do you sell?';
210
+
211
+ /**
212
+ * The end-to-end check: one real visitor turn, through the same socket the
213
+ * spacefront uses. Passes when the agent composed a catalog element carrying
214
+ * at least one entity. Skipped with `--no-ask`.
215
+ */
216
+ async function askCheck(config, check) {
217
+ const asked = option('ask');
218
+ const question = asked === undefined ? DEFAULT_QUESTION : asked;
219
+ const env = await readDotenv(path.join(cwd, '.env'));
220
+ // The preview credential `forty dev` wrote opens a locked space, and its draft.
221
+ const token = typeof env.FORTY_DEV_TOKEN === 'string' && env.FORTY_DEV_TOKEN !== '' ? env.FORTY_DEV_TOKEN : undefined;
222
+ console.log(`\n- asking "${question}"${token === undefined ? '' : ' (with FORTY_DEV_TOKEN)'}…`);
223
+ const turn = await askSpace({ apiUrl: config.apiUrl, slug: config.spaceSlug, token, question });
224
+ if (turn.error !== undefined) {
225
+ check(false, `the agent answered "${question}"`, turn.error);
226
+ return;
227
+ }
228
+ const verdict = judgeTurn(turn.before, turn.layout, catalogToWire(await loadCatalog(config.catalog)));
229
+ console.log(` composed: ${verdict.elementTypes.length === 0 ? '(nothing)' : verdict.elementTypes.join(', ')}`);
230
+ console.log(` said: ${turn.text === '' ? '(nothing)' : turn.text}`);
231
+ check(verdict.pass, `the agent answered "${question}" with ${verdict.pass ? verdict.evidence.join(', ') : 'catalog entities'}`, 'no composed element carries an entity — run `forty connect` to probe search, and check the space\'s store');
232
+ }
233
+
234
+ /**
235
+ * The agent's own catalog search, run once (`POST /org/spaces/:slug/probe-search`)
236
+ * for a product the store itself names — a store whose API answers can still
237
+ * be missing from the index the agent searches.
238
+ */
239
+ async function searchCheck(config, check) {
240
+ const binding = await storeBinding();
241
+ let query;
242
+ if (typeof binding.domain === 'string' && binding.domain !== '' && typeof binding.token === 'string' && binding.token !== '') {
243
+ try {
244
+ query = (await askStore(binding.domain.replace(/^https?:\/\//, '').replace(/\/+$/, ''), binding.token)).sampleTitle;
245
+ } catch (err) {
246
+ if (!(err instanceof FortyError)) throw err;
247
+ console.log(` (could not ask the store for a product to search for: ${err.message})`);
248
+ }
249
+ }
250
+ const probe = await probeSearch(config, query);
251
+ if (!probe.ok) {
252
+ check(false, 'the agent\'s catalog search runs', probe.error);
253
+ return;
254
+ }
255
+ check(probe.count > 0, `the agent's catalog search finds "${probe.query}" (${probe.count} result(s)${probe.titles.length === 0 ? '' : `: ${probe.titles.slice(0, 3).join(', ')}`})`, ZERO_RESULTS_HINT);
256
+ }
@@ -0,0 +1,14 @@
1
+ // `forty hosting self` — the space's spacefront is the app's OWN deployment
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
4
+ // its origin stay, so `forty deploy` switches back in one step.
5
+ import { fail, positionals, readConfig } from '../lib/context.mjs';
6
+ import { call } from '../lib/credentials.mjs';
7
+
8
+ export async function hosting() {
9
+ const [mode] = positionals();
10
+ if (mode !== 'self') fail('usage: forty hosting self (`forty deploy` makes it 40rty-hosted)');
11
+ const config = await readConfig();
12
+ await call(config.apiUrl, 'DELETE', `/org/spaces/${encodeURIComponent(config.spaceSlug)}/hosted-app`);
13
+ console.log(`"${config.spaceSlug}" is self-hosted: register your site with \`forty origin add <url>\` if you have not`);
14
+ }
@@ -8,14 +8,15 @@
8
8
  // answer in:
9
9
  // --space <slug> use that existing space
10
10
  // --create <slug> create a new space in the organization
11
- // --source <@org/name> the package id, instead of asking
11
+ // --source <@org/name> the package id (default `@<space>/storefront`)
12
+ // --self-hosted / --package override what package.json says this repo is
12
13
  // An organization with no space yet gets one, named after the app. A question
13
14
  // that would need a terminal when there is none fails naming the flag that
14
15
  // answers it, rather than waiting on input that will never come.
15
16
  import { readFile, writeFile } from 'node:fs/promises';
16
17
  import path from 'node:path';
17
18
  import { createInterface } from 'node:readline';
18
- import { CONFIG_FILE, cwd, deployment, fail, option, readConfigIfPresent } from '../lib/context.mjs';
19
+ import { appKind, CONFIG_FILE, cwd, deployment, fail, option, readConfigIfPresent } from '../lib/context.mjs';
19
20
  import { call, findCredential } from '../lib/credentials.mjs';
20
21
  import { login } from './login.mjs';
21
22
 
@@ -67,10 +68,10 @@ async function createSpace(apiUrl, { slug, name }) {
67
68
  }
68
69
 
69
70
  /** An existing space, or `{ create: { slug, name } }` for one to make once everything else is known. */
70
- const titleCase = (words) => words.split(/[-_\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(' ');
71
+ export const titleCase = (words) => words.split(/[-_\s]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join(' ');
71
72
 
72
73
  /** A person-readable name from package.json: `@hosted-test/spacefront` → "Hosted Test", not "spacefront". */
73
- function displayName(name) {
74
+ export function displayName(name) {
74
75
  if (typeof name !== 'string' || name === '') return undefined;
75
76
  const match = /^@([^/]+)\/(.+)$/.exec(name);
76
77
  if (match === null) return titleCase(name);
@@ -124,8 +125,7 @@ async function run() {
124
125
  if ((await findCredential(apiUrl)) === null) await login();
125
126
 
126
127
  const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
127
- const dependencies = manifest.dependencies === undefined ? {} : manifest.dependencies;
128
- const selfHosted = dependencies['@shopify/hydrogen'] !== undefined;
128
+ const { selfHosted, framework } = appKind(manifest);
129
129
  const appName = displayName(manifest.name);
130
130
 
131
131
  const me = await call(apiUrl, 'GET', '/org/me');
@@ -134,7 +134,10 @@ async function run() {
134
134
  const own = picked.create === undefined ? picked.componentSources.find((source) => !RESERVED.test(source)) : undefined;
135
135
  const named = typeof manifest.name === 'string' && manifest.name.startsWith('@') && !RESERVED.test(manifest.name) ? manifest.name : undefined;
136
136
  const flagged = option('source');
137
- const sourceId = own !== undefined ? own : flagged !== undefined ? flagged : await ask('Package id, as @your-org/name', '--source <@org/name>', named);
137
+ // Without a terminal the default stands: `@<space>/storefront`, unless package.json names one.
138
+ const slug = picked.create === undefined ? picked.slug : picked.create.slug;
139
+ const fallbackId = named !== undefined ? named : `@${slug}/storefront`;
140
+ const sourceId = own !== undefined ? own : flagged !== undefined ? flagged : await ask('Package id, as @your-org/name', '--source <@org/name>', fallbackId);
138
141
  const space = picked.create === undefined ? picked : await createSpace(apiUrl, picked.create);
139
142
 
140
143
  const config = selfHosted
@@ -142,6 +145,7 @@ async function run() {
142
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' } };
143
146
  await writeFile(path.join(cwd, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
144
147
 
145
- console.log(`wrote ${CONFIG_FILE} for space "${space.slug}" — ${selfHosted ? 'this app hosts the spacefront' : 'the platform hosts the spacefront from this package'}`);
148
+ const kind = selfHosted ? `this app hosts the spacefront${framework === undefined ? '' : ` (${framework})`}` : 'the platform hosts the spacefront from this package';
149
+ console.log(`wrote ${CONFIG_FILE} for space "${space.slug}" — ${kind}; \`--self-hosted\` / \`--package\` override`);
146
150
  console.log(selfHosted ? 'next: forty connect, then forty dev' : 'next: forty dev');
147
151
  }
@@ -2,17 +2,23 @@ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { PackageReleaseSchema, catalogToWire } from '../../dist/wire.js';
4
4
  import { buildBundle, loadBrandDefinition, loadCatalog, loadManifests } from '../lib/build.mjs';
5
- import { cwd, option, readConfig } from '../lib/context.mjs';
5
+ import { cwd, flag, option, readConfig } from '../lib/context.mjs';
6
6
  import { call } from '../lib/credentials.mjs';
7
7
  import { registerOrigin } from './origin.mjs';
8
8
 
9
9
  /** Everything a release carries, built from the repo as it is right now. */
10
10
  export async function buildRelease(config) {
11
11
  const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
12
+ // A release records the package's version; an app that never set one releases as 0.0.0.
13
+ let version = manifest.version;
14
+ if (typeof version !== 'string' || version === '') {
15
+ version = '0.0.0';
16
+ console.log('package.json has no "version" — releasing as 0.0.0');
17
+ }
12
18
  const release = {
13
19
  sourceId: config.sourceId,
14
20
  label: config.label,
15
- version: manifest.version,
21
+ version,
16
22
  catalog: catalogToWire(await loadCatalog(config.catalog)),
17
23
  manifests: await loadManifests(config.manifests),
18
24
  };
@@ -31,9 +37,12 @@ export async function buildRelease(config) {
31
37
  export async function publish() {
32
38
  const config = await readConfig();
33
39
  const release = await buildRelease(config);
34
- const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}`, release);
40
+ // `--keep-locked`: a space `forty init` created opens to visitors on its first release — unless asked not to.
41
+ const keepLocked = flag('keep-locked') ? '&keepLocked=true' : '';
42
+ const result = await call(config.apiUrl, 'PUT', `/org/packages/releases?space=${encodeURIComponent(config.spaceSlug)}${keepLocked}`, release);
35
43
  const built = release.bundle === undefined ? '' : ` + components (${(release.bundle.js.length / 1024).toFixed(0)} KB js, ${(release.bundle.css.length / 1024).toFixed(0)} KB css)`;
36
44
  console.log(`released ${result.sourceId} — release ${result.release}: ${result.types.length} types${built} — live on "${result.composed}"`);
45
+ if (typeof result.openedAt === 'string') console.log(` now public at ${result.openedAt}`);
37
46
  console.log(` undo with \`forty rollback\``);
38
47
  // `--origin <url>`: the site this release is deployed to, allowed to call the api.
39
48
  const origin = option('origin');
package/bin/forty.mjs CHANGED
@@ -17,8 +17,9 @@
17
17
  // forty origin add let a deployed site's origin call the api (CORS)
18
18
  // forty feedback report a problem to the 40rty team
19
19
  // forty doctor check the whole integration; non-zero when anything is off
20
- // forty deploy host this Hydrogen app on 40rty now and print its live URL
20
+ // forty deploy host this Hydrogen app on 40rty, at the space's address
21
21
  // (`--detect` prints where the app's own production deploys)
22
+ // forty hosting self the app's own deployment serves the space again
22
23
  //
23
24
  // Run from the repo's root. The credential is `FORTY_API_KEY` when set (CI),
24
25
  // otherwise the login stored by `forty login`.
@@ -38,6 +39,7 @@ const commands = {
38
39
  origin: () => import('./commands/origin.mjs').then((m) => m.origin()),
39
40
  feedback: () => import('./commands/feedback.mjs').then((m) => m.feedback()),
40
41
  deploy: () => import('./commands/deploy.mjs').then((m) => m.deploy()),
42
+ hosting: () => import('./commands/hosting.mjs').then((m) => m.hosting()),
41
43
  };
42
44
  try {
43
45
  const command = commands[process.argv[2]];
@@ -0,0 +1,48 @@
1
+ // What a repo is (an app hosting its own spacefront, or a package the platform
2
+ // hosts), and where its own production deploys — both read from the repo alone.
3
+ import { mkdtemp, writeFile } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { afterEach, describe, it, expect } from 'vitest';
7
+ import { appKind } from '../context.mjs';
8
+ import { detectDeployTarget } from '../deploy-target.mjs';
9
+
10
+ const argv = process.argv;
11
+ afterEach(() => {
12
+ process.argv = argv;
13
+ });
14
+
15
+ describe('appKind', () => {
16
+ it('reads Hydrogen, Next.js, React Router and Vite + React as apps that host the spacefront', () => {
17
+ expect(appKind({ dependencies: { '@shopify/hydrogen': '1' } })).toEqual({ selfHosted: true, hydrogen: true, framework: '@shopify/hydrogen' });
18
+ expect(appKind({ dependencies: { next: '15', react: '19' } })).toMatchObject({ selfHosted: true, hydrogen: false, framework: 'next' });
19
+ expect(appKind({ dependencies: { 'react-router': '7' } })).toMatchObject({ selfHosted: true });
20
+ expect(appKind({ dependencies: { react: '18', 'react-dom': '18' }, devDependencies: { vite: '6' } })).toMatchObject({ selfHosted: true, framework: 'vite' });
21
+ });
22
+
23
+ it('reads a React library with no app framework as a package — and the flags override either way', () => {
24
+ const starter = { dependencies: { '@40rty/ams-sdk': '0.2.2', react: '18', 'react-dom': '18' }, devDependencies: { tailwindcss: '3' } };
25
+ expect(appKind(starter)).toMatchObject({ selfHosted: false, framework: undefined });
26
+ process.argv = ['node', 'forty', 'init', '--self-hosted'];
27
+ expect(appKind(starter).selfHosted).toBe(true);
28
+ process.argv = ['node', 'forty', 'init', '--package'];
29
+ expect(appKind({ dependencies: { next: '15' } }).selfHosted).toBe(false);
30
+ });
31
+ });
32
+
33
+ describe('detectDeployTarget', () => {
34
+ const repo = async (manifest) => {
35
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'forty-target-'));
36
+ await writeFile(path.join(dir, '.git'), '');
37
+ await writeFile(path.join(dir, 'package.json'), JSON.stringify(manifest));
38
+ return dir;
39
+ };
40
+
41
+ it('names Vercel as likely for a Next.js app with no other target', async () => {
42
+ expect(await detectDeployTarget(await repo({ dependencies: { next: '15' } }))).toMatchObject({ target: 'vercel', label: 'Vercel (likely)' });
43
+ });
44
+
45
+ it('answers "none detected" rather than null', async () => {
46
+ expect(await detectDeployTarget(await repo({ dependencies: { react: '18' } }))).toMatchObject({ target: null, label: 'none detected' });
47
+ });
48
+ });
@@ -0,0 +1,52 @@
1
+ // `forty doctor --ask`'s verdict: a turn passes only when it COMPOSED a catalog
2
+ // element carrying an entity — not an empty grid, not the seed layout it opened on.
3
+ import { describe, it, expect } from 'vitest';
4
+ import { z } from 'zod';
5
+ import { applySinglePatch, catalogToWire, EMPTY_SPEC, resolved } from '@fourty/spacestation';
6
+ import { judgeTurn, resolvedProps } from '../ask.mjs';
7
+
8
+ const product = z.object({ id: z.string() });
9
+ const catalog = catalogToWire({
10
+ productGrid: { type: 'productGrid', propsSchema: z.object({ title: z.string().optional(), products: resolved(product, 'product', { min: 1 }) }) },
11
+ productDetail: { type: 'productDetail', propsSchema: z.object({ product: resolved(product, 'product', { max: 1 }).optional() }) },
12
+ hero: { type: 'hero', propsSchema: z.object({ title: z.string() }) },
13
+ });
14
+
15
+ /** A layout with one element under the page, built the way the turn builds it — by patches. */
16
+ function compose(base, key, element) {
17
+ const withElement = applySinglePatch(base, { op: 'add', path: `/elements/${key}`, value: element });
18
+ return applySinglePatch(withElement, { op: 'add', path: '/elements/page/children/-', value: key });
19
+ }
20
+
21
+ describe('resolvedProps', () => {
22
+ it('reads the entity-ref props off the wire catalog, array and singular, through optional', () => {
23
+ expect(Object.fromEntries(resolvedProps(catalog))).toEqual({ productGrid: ['products'], productDetail: ['product'] });
24
+ });
25
+ });
26
+
27
+ describe('judgeTurn', () => {
28
+ it('passes on a composed productGrid with a product', () => {
29
+ const after = compose(EMPTY_SPEC, 'grid', { type: 'productGrid', props: { products: ['gid://shopify/Product/1'] }, children: [] });
30
+ expect(judgeTurn(EMPTY_SPEC, after, catalog)).toEqual({ pass: true, elementTypes: ['page', 'productGrid'], evidence: ['productGrid.products (1)'] });
31
+ });
32
+
33
+ it('fails on an empty grid, and on elements with no entity props', () => {
34
+ const empty = compose(EMPTY_SPEC, 'grid', { type: 'productGrid', props: { products: [] }, children: [] });
35
+ expect(judgeTurn(EMPTY_SPEC, empty, catalog).pass).toBe(false);
36
+ const hero = compose(EMPTY_SPEC, 'hero', { type: 'hero', props: { title: 'Hi' }, children: [] });
37
+ expect(judgeTurn(EMPTY_SPEC, hero, catalog)).toMatchObject({ pass: false, elementTypes: ['page', 'hero'] });
38
+ });
39
+
40
+ it('does not credit the turn with what the layout already held', () => {
41
+ const seeded = compose(EMPTY_SPEC, 'grid', { type: 'productGrid', props: { products: ['gid://shopify/Product/1'] }, children: [] });
42
+ const after = compose(seeded, 'hero', { type: 'hero', props: { title: 'Hi' }, children: [] });
43
+ expect(judgeTurn(seeded, after, catalog)).toMatchObject({ pass: false, elementTypes: ['page', 'hero'] });
44
+ });
45
+
46
+ it('counts a singular entity ref, and ignores a type outside the catalog', () => {
47
+ const detail = compose(EMPTY_SPEC, 'pdp', { type: 'productDetail', props: { product: 'gid://shopify/Product/2' }, children: [] });
48
+ expect(judgeTurn(EMPTY_SPEC, detail, catalog).evidence).toEqual(['productDetail.product (1)']);
49
+ const foreign = compose(EMPTY_SPEC, 'x', { type: 'mystery', props: { products: ['a'] }, children: [] });
50
+ expect(judgeTurn(EMPTY_SPEC, foreign, catalog).pass).toBe(false);
51
+ });
52
+ });