@40rty/ams-cli 0.5.19 → 0.5.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/commands/__tests__/connect.test.mjs +57 -0
- package/bin/commands/connect.mjs +86 -128
- package/bin/commands/doctor.mjs +6 -16
- package/bin/forty.mjs +5 -5
- package/bin/lib/context.mjs +3 -22
- package/package.json +1 -1
- package/templates/package/README.md +1 -1
- package/bin/lib/__tests__/store-page.test.mjs +0 -26
- package/bin/lib/store-page.d.mts +0 -14
- package/bin/lib/store-page.mjs +0 -82
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// `forty connect <id> --<field> <value>` — the CLI maps flags onto the fields a
|
|
2
|
+
// connector declares and knows nothing else about it.
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
import { describeConnector, flagName, valuesFor } from '../connect.mjs';
|
|
5
|
+
|
|
6
|
+
const STORE = {
|
|
7
|
+
id: 'acme-store',
|
|
8
|
+
label: 'Acme',
|
|
9
|
+
blurb: 'A store.',
|
|
10
|
+
dataSource: true,
|
|
11
|
+
fields: [
|
|
12
|
+
{ key: 'domain', label: 'Domain', hint: 'Where it is.', optional: false, env: ['STORE_DOMAIN', 'OTHER_DOMAIN'] },
|
|
13
|
+
{ key: 'accessToken', label: 'Token', hint: 'Its key.', optional: false, env: ['STORE_TOKEN'] },
|
|
14
|
+
{ key: 'savedCatalog', label: 'Saved catalog', hint: 'A view.', optional: true, env: [] },
|
|
15
|
+
],
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe('flagName', () => {
|
|
19
|
+
it('is the field key in kebab case', () => {
|
|
20
|
+
expect(flagName('storefrontAccessToken')).toBe('storefront-access-token');
|
|
21
|
+
expect(flagName('domain')).toBe('domain');
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe('valuesFor', () => {
|
|
26
|
+
it('maps each flag onto the field it names, in both spellings, skipping the connector id', () => {
|
|
27
|
+
expect(valuesFor(STORE, ['acme-store', '--domain', 'a.example', '--access-token=t0k', '--saved-catalog', ''], {})).toEqual({
|
|
28
|
+
domain: 'a.example',
|
|
29
|
+
accessToken: 't0k',
|
|
30
|
+
savedCatalog: '',
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('reads a field left off the command line from `.env`, by the names the connector declares', () => {
|
|
35
|
+
expect(valuesFor(STORE, ['acme-store', '--access-token', 'flag'], { OTHER_DOMAIN: 'b.example', STORE_TOKEN: 'env' })).toEqual({
|
|
36
|
+
domain: 'b.example',
|
|
37
|
+
accessToken: 'flag',
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('refuses a flag the connector does not declare, naming the ones it does', () => {
|
|
42
|
+
expect(() => valuesFor(STORE, ['--token', 'x'], {})).toThrow(/--domain, --access-token, --saved-catalog/);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('refuses a flag with no value', () => {
|
|
46
|
+
expect(() => valuesFor(STORE, ['--domain', '--access-token', 'x'], {})).toThrow(/--domain needs a value/);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('describeConnector', () => {
|
|
51
|
+
it('prints each field as the flag it is given by', () => {
|
|
52
|
+
const text = describeConnector(STORE);
|
|
53
|
+
expect(text).toContain('acme-store — Acme: A store.');
|
|
54
|
+
expect(text).toContain('--access-token Token — Its key. [.env: STORE_TOKEN]');
|
|
55
|
+
expect(text).toContain('--saved-catalog (optional)');
|
|
56
|
+
});
|
|
57
|
+
});
|
package/bin/commands/connect.mjs
CHANGED
|
@@ -1,53 +1,72 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { cwd, fail, flag,
|
|
3
|
+
import { cwd, deployment, fail, flag, positionals, readConfig, readConfigIfPresent, readDotenv } from '../lib/context.mjs';
|
|
4
4
|
import { call, request } from '../lib/credentials.mjs';
|
|
5
|
-
import { resolveStorePage } from '../lib/store-page.mjs';
|
|
6
5
|
import { displayName, titleCase } from './init.mjs';
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
// `forty connect` names no connector. What a deployment carries, and what each
|
|
8
|
+
// asks for, comes from the api (`GET /org/connectors`, the connector
|
|
9
|
+
// definitions the console draws its cards from); the values become what is
|
|
10
|
+
// stored on the server, by the connector's own definition.
|
|
11
|
+
|
|
12
|
+
/** The flag a field key is given as: `storefrontAccessToken` → `storefront-access-token`. */
|
|
13
|
+
export function flagName(key) {
|
|
14
|
+
return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
15
|
+
}
|
|
11
16
|
|
|
12
17
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
18
|
+
* The values `args` (the command line after `connect`) and `env` (the app's
|
|
19
|
+
* `.env`) give `connector`'s declared fields. A flag wins over `.env`, which is
|
|
20
|
+
* read only by the names the connector declares for a field. A flag the
|
|
21
|
+
* connector does not declare is a mistake, not something to ignore.
|
|
17
22
|
*/
|
|
18
|
-
export
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
export function valuesFor(connector, args, env) {
|
|
24
|
+
const byFlag = new Map(connector.fields.map((field) => [flagName(field.key), field]));
|
|
25
|
+
const values = {};
|
|
26
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
27
|
+
if (!args[i].startsWith('--')) continue;
|
|
28
|
+
const eq = args[i].indexOf('=');
|
|
29
|
+
const name = args[i].slice(2, eq === -1 ? undefined : eq);
|
|
30
|
+
const field = byFlag.get(name);
|
|
31
|
+
if (field === undefined) {
|
|
32
|
+
const known = [...byFlag.keys()].map((known) => `--${known}`).join(', ');
|
|
33
|
+
fail(`${connector.id} has no --${name} — it takes ${known === '' ? 'no values' : known}`);
|
|
34
|
+
}
|
|
35
|
+
let value;
|
|
36
|
+
if (eq !== -1) {
|
|
37
|
+
value = args[i].slice(eq + 1);
|
|
38
|
+
} else {
|
|
39
|
+
value = args[i + 1];
|
|
40
|
+
if (value === undefined || value.startsWith('--')) fail(`--${name} needs a value`);
|
|
41
|
+
i += 1;
|
|
42
|
+
}
|
|
43
|
+
values[field.key] = value;
|
|
44
|
+
}
|
|
45
|
+
for (const field of connector.fields) {
|
|
46
|
+
if (field.key in values) continue;
|
|
47
|
+
const name = field.env.find((candidate) => typeof env[candidate] === 'string' && env[candidate].trim() !== '');
|
|
48
|
+
if (name !== undefined) values[field.key] = env[name];
|
|
29
49
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
50
|
+
return values;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One connector as `--list` prints it: what it is, then each flag it takes. */
|
|
54
|
+
export function describeConnector(connector) {
|
|
55
|
+
const lines = [`${connector.id} — ${connector.label}: ${connector.blurb}${connector.dataSource ? ' (the space\'s data source)' : ''}`];
|
|
56
|
+
for (const field of connector.fields) {
|
|
57
|
+
const from = field.env.length === 0 ? '' : ` [.env: ${field.env.join(' | ')}]`;
|
|
58
|
+
lines.push(` --${flagName(field.key)}${field.optional ? ' (optional)' : ''} ${field.label} — ${field.hint}${from}`);
|
|
34
59
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const first = body.data.products === null || body.data.products === undefined ? undefined : body.data.products.nodes[0];
|
|
38
|
-
return {
|
|
39
|
-
shopId: match === null ? undefined : match[1],
|
|
40
|
-
shopName: typeof body.data.shop.name === 'string' && body.data.shop.name.trim() !== '' ? body.data.shop.name.trim() : undefined,
|
|
41
|
-
marketCountry: typeof country === 'string' && country.length === 2 ? country : undefined,
|
|
42
|
-
sampleTitle: first === undefined || typeof first.title !== 'string' ? undefined : first.title,
|
|
43
|
-
};
|
|
60
|
+
if (connector.fields.length === 0) lines.push(' (nothing to fill in)');
|
|
61
|
+
return lines.join('\n');
|
|
44
62
|
}
|
|
45
63
|
|
|
46
64
|
/**
|
|
47
65
|
* One real catalog search through the space's own agent tools
|
|
48
|
-
* (`POST /org/spaces/:slug/probe-search`) —
|
|
49
|
-
* does not mean the agent can find
|
|
50
|
-
*
|
|
66
|
+
* (`POST /org/spaces/:slug/probe-search`) — a connected data source answering
|
|
67
|
+
* its own API does not mean the agent can find anything in it. With no query,
|
|
68
|
+
* the server searches for something the data source says it holds.
|
|
69
|
+
* `{ ok, count, titles, query }`, or `{ ok: false, error }` when it could not run.
|
|
51
70
|
*/
|
|
52
71
|
export async function probeSearch(config, query) {
|
|
53
72
|
const res = await request(config.apiUrl, 'POST', `/org/spaces/${config.spaceSlug}/probe-search`, query === undefined ? {} : { query });
|
|
@@ -55,108 +74,47 @@ export async function probeSearch(config, query) {
|
|
|
55
74
|
return { ok: true, ...res.body };
|
|
56
75
|
}
|
|
57
76
|
|
|
58
|
-
/**
|
|
59
|
-
async function
|
|
77
|
+
/** Whether the space's current name is one `forty init` derived rather than a person chose. */
|
|
78
|
+
async function nameIsDerived(config) {
|
|
60
79
|
const me = await request(config.apiUrl, 'GET', '/org/me');
|
|
61
80
|
const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
|
|
62
|
-
if (space === undefined) return
|
|
81
|
+
if (space === undefined) return false;
|
|
63
82
|
const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8').catch((err) => {
|
|
64
83
|
if (err.code === 'ENOENT') return '{}';
|
|
65
84
|
throw err;
|
|
66
85
|
}));
|
|
67
|
-
|
|
68
|
-
return derived.includes(space.name) ? space.name : undefined;
|
|
86
|
+
return [config.spaceSlug, titleCase(config.spaceSlug), displayName(manifest.name)].includes(space.name);
|
|
69
87
|
}
|
|
70
88
|
|
|
71
|
-
/**
|
|
72
|
-
export const ZERO_RESULTS_HINT = 'unpublished/dev stores are not in Shopify\'s global catalog — publish the store (remove its password) and put its products on the Shop channel, or search the store\'s own catalog instead: `forty connect --search storefront`';
|
|
73
|
-
|
|
74
|
-
/** Where the agent's catalog search runs: Shopify's Global catalog (by shop id), or the store's own Storefront search. */
|
|
75
|
-
const SEARCH_MODES = ['global', 'storefront'];
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* `forty connect --catalog` — bind the space to no store: Shopify's whole
|
|
79
|
-
* catalog through Shop's MCP server (`shopify-catalog`), for a marketplace
|
|
80
|
-
* space whose products come from every store. `--country` / `--currency` set
|
|
81
|
-
* the market prices and availability are read for (default US / USD).
|
|
82
|
-
*/
|
|
83
|
-
async function connectCatalog(config) {
|
|
84
|
-
const country = option('country') === undefined ? 'US' : option('country').toUpperCase();
|
|
85
|
-
const currency = option('currency') === undefined ? 'USD' : option('currency').toUpperCase();
|
|
86
|
-
if (!/^[A-Z]{2}$/.test(country)) fail(`--country must be an ISO 3166-1 alpha-2 code like US (got "${country}")`);
|
|
87
|
-
if (!/^[A-Z]{3}$/.test(currency)) fail(`--currency must be an ISO 4217 code like USD (got "${currency}")`);
|
|
88
|
-
const platform = 'shopify-catalog';
|
|
89
|
-
const body = { platform, platformConfig: { platform, domain: 'mcp.shop.com', config: { marketCountry: country, currency } }, vertical: 'ecommerce' };
|
|
90
|
-
const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, body);
|
|
91
|
-
console.log(`space "${result.slug}" is connected to the Shopify catalog — every store, market ${country}, prices in ${currency}`);
|
|
92
|
-
const probe = await probeSearch(config, 'backpack');
|
|
93
|
-
if (!probe.ok) console.warn(`\n!! WARNING: the agent's catalog search could not run (${probe.error})`);
|
|
94
|
-
else console.log(`search works: "${probe.query}" → ${probe.count} result(s): ${probe.titles.join(', ')}`);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
|
|
89
|
+
/** `forty connect --list` | `forty connect <connector> [--<field> <value> ...]` */
|
|
98
90
|
export async function connect() {
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
// `--domain` / `--token` / `--shop-id` win over `--from`, which wins over `.env`.
|
|
107
|
-
const env = page === undefined ? await storeBinding() : { ...(await storeBinding()), domain: page.domain, token: page.token };
|
|
108
|
-
const pick = (flagName, fromEnv) => (option(flagName) !== undefined ? option(flagName) : fromEnv);
|
|
109
|
-
const binding = { domain: pick('domain', env.domain), token: pick('token', env.token), shopId: pick('shop-id', env.shopId) };
|
|
110
|
-
// An empty `.env` value is absence: `PUBLIC_STOREFRONT_API_TOKEN=` once
|
|
111
|
-
// stored `storefrontAccessToken: ""`, which the connector refuses wholesale.
|
|
112
|
-
const present = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
|
|
113
|
-
const domain = present(binding.domain);
|
|
114
|
-
const token = present(binding.token);
|
|
115
|
-
if (domain === undefined || token === undefined) fail('no store: pass --from <the store\'s live URL> (reads its public Storefront token), or 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');
|
|
116
|
-
const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '');
|
|
117
|
-
// `--search global` (default): Shopify's Global catalog, scoped by the
|
|
118
|
-
// store's shop id, with the store's own search beside it. `--search
|
|
119
|
-
// storefront`: the store's own Storefront search only — for a store Global
|
|
120
|
-
// does not index (a dev store, mock.shop, a Storefront-shaped mock API).
|
|
121
|
-
const search = option('search') === undefined ? 'global' : option('search');
|
|
122
|
-
if (!SEARCH_MODES.includes(search)) fail(`--search must be one of ${SEARCH_MODES.join(', ')} (got "${search}")`);
|
|
123
|
-
if (host === 'mock.shop' && search === 'global') fail('mock.shop is not in Shopify\'s Global catalog — connect it with `--search storefront`');
|
|
124
|
-
|
|
125
|
-
const store = await askStore(host, token);
|
|
126
|
-
const settings = { hosting: { embedded: true, headless: true }, storefrontAccessToken: token };
|
|
127
|
-
let shopId;
|
|
128
|
-
if (search === 'global') {
|
|
129
|
-
shopId = present(binding.shopId) !== undefined ? present(binding.shopId) : store.shopId;
|
|
130
|
-
if (shopId === undefined) {
|
|
131
|
-
fail(`could not work out ${host}'s shop id, which Global catalog search is scoped by — set SHOP_ID in .env to the number in gid://shopify/Shop/<n>, or search the store's own catalog: \`--search storefront\``);
|
|
132
|
-
}
|
|
133
|
-
settings.globalShopId = shopId;
|
|
134
|
-
// The store's market: Global search ranks by ship-to country and defaults to the US.
|
|
135
|
-
if (store.marketCountry !== undefined) settings.marketCountry = store.marketCountry;
|
|
136
|
-
} else {
|
|
137
|
-
// An empty value removes a shop id an earlier `forty connect` stored, so
|
|
138
|
-
// catalog search routes to the store's own search.
|
|
139
|
-
settings.globalShopId = '';
|
|
91
|
+
const listing = flag('list');
|
|
92
|
+
const config = listing ? await readConfigIfPresent() : await readConfig();
|
|
93
|
+
const { apiUrl } = listing ? deployment(config) : config;
|
|
94
|
+
const { connectors } = await call(apiUrl, 'GET', '/org/connectors');
|
|
95
|
+
if (listing) {
|
|
96
|
+
console.log(connectors.map(describeConnector).join('\n\n'));
|
|
97
|
+
return;
|
|
140
98
|
}
|
|
141
99
|
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
if (
|
|
147
|
-
const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, body);
|
|
148
|
-
if (body.name !== undefined) console.log(`space "${result.slug}" is now named "${body.name}" (was "${rename}", derived by \`forty init\`)`);
|
|
149
|
-
const how = search === 'global' ? `shop ${shopId}, Global catalog search${store.marketCountry === undefined ? '' : `, market ${store.marketCountry}`}` : 'the store\'s own catalog search';
|
|
150
|
-
console.log(`space "${result.slug}" is connected to ${host} (${how}) — \`forty dev\` to work on it`);
|
|
100
|
+
const ids = connectors.map((connector) => connector.id).join('|');
|
|
101
|
+
const [id] = positionals();
|
|
102
|
+
if (id === undefined) fail(`usage: forty connect <${ids}> [--<field> <value> ...] — \`forty connect --list\` shows what each takes`);
|
|
103
|
+
const connector = connectors.find((candidate) => candidate.id === id);
|
|
104
|
+
if (connector === undefined) fail(`this deployment has no connector "${id}" — it has ${ids}`);
|
|
151
105
|
|
|
152
|
-
|
|
153
|
-
const
|
|
154
|
-
if (!
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
106
|
+
const values = valuesFor(connector, process.argv.slice(3), await readDotenv(path.join(cwd, '.env')));
|
|
107
|
+
const res = await request(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/connectors/${connector.id}`, { values, adoptName: await nameIsDerived(config) });
|
|
108
|
+
if (!res.ok) fail(`${connector.label} was not connected (${res.status}): ${res.body.error} — \`forty connect --list\` shows its fields`);
|
|
109
|
+
const result = res.body;
|
|
110
|
+
const shown = Object.entries(result.values).map(([key, value]) => `${flagName(key)} ${value}`).join(', ');
|
|
111
|
+
console.log(`space "${config.spaceSlug}" is connected to ${connector.label}${shown === '' ? '' : ` (${shown})`}`);
|
|
112
|
+
if (result.name !== undefined) console.log(`space "${config.spaceSlug}" is now named "${result.name}" (its name was derived by \`forty init\`)`);
|
|
113
|
+
if (!result.dataSource) return;
|
|
114
|
+
|
|
115
|
+
// Connected is not searchable: run the agent's own search once.
|
|
116
|
+
const probe = await probeSearch(config);
|
|
117
|
+
if (!probe.ok) console.warn(`\n!! WARNING: the agent's search could not run (${probe.error})`);
|
|
118
|
+
else if (probe.count === 0) console.warn(`\n!! WARNING: the agent's search for "${probe.query}" found NOTHING — visitors will be shown nothing from ${connector.label}.`);
|
|
119
|
+
else console.log(`search works: "${probe.query}" → ${probe.count} result(s): ${probe.titles.join(', ')}`);
|
|
162
120
|
}
|
package/bin/commands/doctor.mjs
CHANGED
|
@@ -11,10 +11,10 @@ import path from 'node:path';
|
|
|
11
11
|
import { catalogToWire } from '../../dist/wire.js';
|
|
12
12
|
import { askSpace, judgeTurn } from '../lib/ask.mjs';
|
|
13
13
|
import { loadCatalog } from '../lib/build.mjs';
|
|
14
|
-
import { appKind, cwd,
|
|
14
|
+
import { appKind, cwd, flag, option, positionals, readConfig, readDotenv } from '../lib/context.mjs';
|
|
15
15
|
import { findCredential, request } from '../lib/credentials.mjs';
|
|
16
16
|
import { agenticFramework, agenticWiringProblems } from '../lib/agentic.mjs';
|
|
17
|
-
import {
|
|
17
|
+
import { probeSearch } from './connect.mjs';
|
|
18
18
|
|
|
19
19
|
/** What a space bound to a store requires a source to draw, and what the agent speaks through. */
|
|
20
20
|
const STORE_TYPES = ['productGrid', 'collectionList'];
|
|
@@ -241,24 +241,14 @@ async function askCheck(config, check, linkToken) {
|
|
|
241
241
|
|
|
242
242
|
/**
|
|
243
243
|
* The agent's own catalog search, run once (`POST /org/spaces/:slug/probe-search`)
|
|
244
|
-
* for
|
|
245
|
-
* be missing from the index the agent searches.
|
|
244
|
+
* for something the space's data source says it holds — a source whose API
|
|
245
|
+
* answers can still be missing from the index the agent searches.
|
|
246
246
|
*/
|
|
247
247
|
async function searchCheck(config, check) {
|
|
248
|
-
const
|
|
249
|
-
let query;
|
|
250
|
-
if (typeof binding.domain === 'string' && binding.domain !== '' && typeof binding.token === 'string' && binding.token !== '') {
|
|
251
|
-
try {
|
|
252
|
-
query = (await askStore(binding.domain.replace(/^https?:\/\//, '').replace(/\/+$/, ''), binding.token)).sampleTitle;
|
|
253
|
-
} catch (err) {
|
|
254
|
-
if (!(err instanceof FortyError)) throw err;
|
|
255
|
-
console.log(` (could not ask the store for a product to search for: ${err.message})`);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
const probe = await probeSearch(config, query);
|
|
248
|
+
const probe = await probeSearch(config);
|
|
259
249
|
if (!probe.ok) {
|
|
260
250
|
check(false, 'the agent\'s catalog search runs', probe.error);
|
|
261
251
|
return;
|
|
262
252
|
}
|
|
263
|
-
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(', ')}`})`,
|
|
253
|
+
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(', ')}`})`, 'check what the space is connected to — `forty connect --list`, then reconnect it');
|
|
264
254
|
}
|
package/bin/forty.mjs
CHANGED
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
// `--message "…"` (required, one line) says what the release changed
|
|
17
17
|
// forty releases the package's release history, and which one is live
|
|
18
18
|
// forty rollback make an earlier release live again (`forty rollback 3`)
|
|
19
|
-
// forty connect
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
19
|
+
// forty connect connect the space to one of the connectors this deployment
|
|
20
|
+
// carries: `forty connect --list` prints each one and the
|
|
21
|
+
// fields it takes; `forty connect <id> --<field> <value> …`
|
|
22
|
+
// connects it (a field left out is read from `.env` by the
|
|
23
|
+
// names the connector declares), then runs a real search
|
|
24
24
|
// forty origin add let a deployed site's origin call the api (CORS)
|
|
25
25
|
// forty domain add serve the space on your own domain; prints the DNS records
|
|
26
26
|
// forty feedback report a problem to the 40rty team
|
package/bin/lib/context.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// What every command shares: where it is running, the config file,
|
|
2
|
-
//
|
|
1
|
+
// What every command shares: where it is running, the config file, and which
|
|
2
|
+
// 40rty deployment it talks to.
|
|
3
3
|
import { readFile, writeFile } from 'node:fs/promises';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
|
|
@@ -80,25 +80,6 @@ export async function readDotenv(file) {
|
|
|
80
80
|
return out;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
/** The first of `names` set (non-empty) in `env`. */
|
|
84
|
-
function firstOf(env, names) {
|
|
85
|
-
const name = names.find((candidate) => typeof env[candidate] === 'string' && env[candidate].trim() !== '');
|
|
86
|
-
return name === undefined ? undefined : env[name];
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* The store this app sells from, read from its own `.env` — Hydrogen's names
|
|
91
|
-
* first, then Next.js Commerce's (`SHOPIFY_STORE_DOMAIN`, `SHOPIFY_STOREFRONT_ACCESS_TOKEN`).
|
|
92
|
-
*/
|
|
93
|
-
export async function storeBinding() {
|
|
94
|
-
const env = await readDotenv(path.join(cwd, '.env'));
|
|
95
|
-
return {
|
|
96
|
-
domain: firstOf(env, ['PUBLIC_STORE_DOMAIN', 'SHOPIFY_STORE_DOMAIN']),
|
|
97
|
-
token: firstOf(env, ['PUBLIC_STOREFRONT_API_TOKEN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN']),
|
|
98
|
-
shopId: env.SHOP_ID,
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
|
|
102
83
|
/** Frameworks whose app serves its own pages — and so hosts the spacefront itself. */
|
|
103
84
|
const APP_FRAMEWORKS = ['@shopify/hydrogen', 'next', 'react-router', '@remix-run/react', '@remix-run/node'];
|
|
104
85
|
|
|
@@ -155,7 +136,7 @@ export function flag(name) {
|
|
|
155
136
|
}
|
|
156
137
|
|
|
157
138
|
/** Valueless switches that do not start with `--no-` — every other flag takes a value. */
|
|
158
|
-
const SWITCHES = new Set(['--detect', '--keep-locked', '--self-hosted', '--package']);
|
|
139
|
+
const SWITCHES = new Set(['--detect', '--keep-locked', '--self-hosted', '--package', '--list']);
|
|
159
140
|
|
|
160
141
|
/** The command's arguments that are not flags or flag values, in order. */
|
|
161
142
|
export function positionals() {
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ tells it which blocks answer which question.
|
|
|
8
8
|
```bash
|
|
9
9
|
npm install
|
|
10
10
|
npx forty init # sign in, pick (or --create) your space
|
|
11
|
-
npx forty connect --
|
|
11
|
+
npx forty connect shopify --domain your-store.myshopify.com --storefront-access-token <token> # `forty connect --list` for the rest
|
|
12
12
|
npm run dev # sign in, pick your space, then every save updates your preview
|
|
13
13
|
npm run release # publish a new release — visitors see it
|
|
14
14
|
```
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
// Where a storefront ships its public Storefront token — what `forty connect --from` reads.
|
|
2
|
-
import { describe, expect, it } from 'vitest';
|
|
3
|
-
import { findShopDomains, findTokenCandidates } from '../store-page.mjs';
|
|
4
|
-
|
|
5
|
-
describe('findTokenCandidates', () => {
|
|
6
|
-
it('reads the token Hydrogen serializes into its consent config (acme.example shape)', () => {
|
|
7
|
-
const html = String.raw`\"checkoutDomain\",\"checkout.acme.example\",\"storefrontAccessToken\",\"2efed5e20dc72ac998fdbbc55ae0649e\",\"withPrivacyBanner\"`;
|
|
8
|
-
expect(findTokenCandidates(html)).toEqual(['2efed5e20dc72ac998fdbbc55ae0649e']);
|
|
9
|
-
});
|
|
10
|
-
|
|
11
|
-
it('reads it from JSON and from an Online Store theme meta tag', () => {
|
|
12
|
-
expect(findTokenCandidates('{"storefrontAccessToken":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}')).toEqual(['a'.repeat(32)]);
|
|
13
|
-
expect(findTokenCandidates('<meta name="shopify-checkout-api-token" content="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">')).toEqual(['b'.repeat(32)]);
|
|
14
|
-
expect(findTokenCandidates('<script id="shopify-features" type="application/json">{"accessToken":"cccccccccccccccccccccccccccccccc","betas":[]}</script>')).toEqual(['c'.repeat(32)]);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('finds nothing on a page that ships no token', () => {
|
|
18
|
-
expect(findTokenCandidates('<html>469e4518231869be4ba940a1dcefec4b</html>')).toEqual([]);
|
|
19
|
-
});
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
describe('findShopDomains', () => {
|
|
23
|
-
it('ranks the store domain the page mentions most', () => {
|
|
24
|
-
expect(findShopDomains('x.myshopify.com acmebody.myshopify.com acmebody.myshopify.com')).toEqual(['acmebody.myshopify.com', 'x.myshopify.com']);
|
|
25
|
-
});
|
|
26
|
-
});
|
package/bin/lib/store-page.d.mts
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/** Types for `store-page.mjs`, for the TypeScript tooling that reads a storefront the way `forty connect --from` does (scripts/create-space/resolve.ts). */
|
|
2
|
-
export const STOREFRONT_API_VERSION: string;
|
|
3
|
-
|
|
4
|
-
/** Every myshopify domain the page names, most-mentioned first. */
|
|
5
|
-
export function findShopDomains(html: string): string[];
|
|
6
|
-
|
|
7
|
-
/** Public Storefront token candidates the page ships, most trusted first. */
|
|
8
|
-
export function findTokenCandidates(html: string): string[];
|
|
9
|
-
|
|
10
|
-
/** Does the Storefront API at `domain` accept `token`? */
|
|
11
|
-
export function acceptsToken(domain: string, token: string): Promise<boolean>;
|
|
12
|
-
|
|
13
|
-
/** The store behind a storefront URL (or its page saved from a browser), or why there is none. */
|
|
14
|
-
export function resolveStorePage(source: string): Promise<{ domain: string; token: string } | { error: string }>;
|
package/bin/lib/store-page.mjs
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
// Which Shopify store is behind a storefront URL, and a Storefront token that
|
|
2
|
-
// answers for it — read from the page every visitor's browser already gets.
|
|
3
|
-
//
|
|
4
|
-
// A storefront's Storefront token is PUBLIC by design: it ships to every
|
|
5
|
-
// browser so the page can query products. Where it ships depends on the stack:
|
|
6
|
-
// - Hydrogen renders it into its consent config (`storefrontAccessToken`
|
|
7
|
-
// beside `checkoutDomain`);
|
|
8
|
-
// - Online Store themes publish it as `<meta name="shopify-checkout-api-token">`
|
|
9
|
-
// or as the `shopify-features` script's `accessToken`.
|
|
10
|
-
// A candidate only counts once the Storefront API accepts it for the store's
|
|
11
|
-
// own domain. `forty connect --from <url>` and create-space's resolve stage
|
|
12
|
-
// both read the page through this module.
|
|
13
|
-
|
|
14
|
-
import { readFile } from 'node:fs/promises';
|
|
15
|
-
|
|
16
|
-
export const STOREFRONT_API_VERSION = '2025-07';
|
|
17
|
-
|
|
18
|
-
/** Every myshopify domain the page names, most-mentioned first. */
|
|
19
|
-
export function findShopDomains(html) {
|
|
20
|
-
const counts = new Map();
|
|
21
|
-
for (const m of html.matchAll(/\b([a-z0-9][a-z0-9-]*)\.myshopify\.com\b/g)) {
|
|
22
|
-
const domain = `${m[1]}.myshopify.com`;
|
|
23
|
-
counts.set(domain, (counts.has(domain) ? counts.get(domain) : 0) + 1);
|
|
24
|
-
}
|
|
25
|
-
return [...counts].sort((a, b) => b[1] - a[1]).map(([d]) => d);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** Token candidates in the order the places above are trusted. */
|
|
29
|
-
export function findTokenCandidates(html) {
|
|
30
|
-
const found = [];
|
|
31
|
-
const patterns = [
|
|
32
|
-
// Hydrogen, serialized either as JSON or as a flat turbo-stream array (\"key\",\"value\").
|
|
33
|
-
/storefrontAccessToken\\?"\s*[:,]\s*\\?"([a-f0-9]{32})/g,
|
|
34
|
-
/<meta[^>]+name="shopify-checkout-api-token"[^>]+content="([a-f0-9]{32})"/g,
|
|
35
|
-
/<meta[^>]+content="([a-f0-9]{32})"[^>]+name="shopify-checkout-api-token"/g,
|
|
36
|
-
/<script[^>]+id="shopify-features"[^>]*>\s*\{"accessToken":"([a-f0-9]{32})"/g,
|
|
37
|
-
];
|
|
38
|
-
for (const pattern of patterns) for (const m of html.matchAll(pattern)) if (!found.includes(m[1])) found.push(m[1]);
|
|
39
|
-
return found;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Does the Storefront API at `domain` accept `token`? */
|
|
43
|
-
export async function acceptsToken(domain, token) {
|
|
44
|
-
const res = await fetch(`https://${domain}/api/${STOREFRONT_API_VERSION}/graphql.json`, {
|
|
45
|
-
method: 'POST',
|
|
46
|
-
headers: { 'content-type': 'application/json', 'x-shopify-storefront-access-token': token },
|
|
47
|
-
body: JSON.stringify({ query: '{ shop { id } }' }),
|
|
48
|
-
});
|
|
49
|
-
if (!res.ok) return false;
|
|
50
|
-
const body = await res.json().catch((err) => {
|
|
51
|
-
console.warn(`${domain} answered ${res.status} with no JSON (${err.message}) — treating the token as refused`);
|
|
52
|
-
return null;
|
|
53
|
-
});
|
|
54
|
-
return body !== null && body.data !== undefined && body.data !== null && body.data.shop !== null;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** The page's HTML: fetched for a URL, read from disk for a page a real browser saved (a bot wall lets only browsers through). */
|
|
58
|
-
async function pageHtml(source) {
|
|
59
|
-
if (!/^https?:\/\//.test(source)) {
|
|
60
|
-
return readFile(source, 'utf8').then((html) => ({ html }), (err) => ({ error: `cannot read ${source} (${err.message}) — pass the store's URL, or a page saved from it` }));
|
|
61
|
-
}
|
|
62
|
-
const res = await fetch(source, { headers: { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36' } });
|
|
63
|
-
if (!res.ok) return { error: `${source} answered ${res.status} — a bot wall lets only a real browser through: open the store there, save the page (or copy its HTML into a file) and pass that file to --from` };
|
|
64
|
-
return { html: await res.text() };
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* `{ domain, token }` for the store behind `source` — a storefront URL, or its
|
|
69
|
-
* page saved from a browser — or `{ error }` saying why there is none.
|
|
70
|
-
*/
|
|
71
|
-
export async function resolveStorePage(source) {
|
|
72
|
-
const page = await pageHtml(source);
|
|
73
|
-
if ('error' in page) return page;
|
|
74
|
-
const domains = findShopDomains(page.html);
|
|
75
|
-
if (domains.length === 0) return { error: `${source} names no *.myshopify.com domain — not a Shopify storefront page` };
|
|
76
|
-
const tokens = findTokenCandidates(page.html);
|
|
77
|
-
if (tokens.length === 0) return { error: `${source} ships no public Storefront token in its page` };
|
|
78
|
-
for (const domain of domains) {
|
|
79
|
-
for (const token of tokens) if (await acceptsToken(domain, token)) return { domain, token };
|
|
80
|
-
}
|
|
81
|
-
return { error: `none of the ${tokens.length} token(s) on ${source} is accepted by ${domains.join(', ')}` };
|
|
82
|
-
}
|