@40rty/ams-cli 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/commands/connect.mjs +67 -13
- package/bin/commands/deploy.mjs +15 -9
- package/bin/commands/doctor.mjs +112 -29
- package/bin/commands/hosting.mjs +14 -0
- package/bin/commands/init.mjs +12 -8
- package/bin/commands/publish.mjs +12 -3
- package/bin/forty.mjs +3 -1
- package/bin/lib/__tests__/app-kind.test.mjs +48 -0
- package/bin/lib/__tests__/ask.test.mjs +52 -0
- package/bin/lib/ask.mjs +111 -0
- package/bin/lib/base-path-build.mjs +149 -0
- package/bin/lib/build.mjs +20 -8
- package/bin/lib/context.mjs +42 -3
- package/bin/lib/deploy-target.mjs +5 -3
- package/bin/lib/hosted-build.mjs +13 -7
- package/dist/wire.js +104 -0
- package/package.json +1 -1
- package/templates/package/package.json +2 -1
- package/templates/package/src/shell.tsx +8 -131
- package/templates/package/src/styles.css +7 -0
package/bin/lib/ask.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// One real visitor turn on the space — what `forty doctor --ask` runs.
|
|
2
|
+
//
|
|
3
|
+
// The same wire the spacefront uses: `POST /s/:slug/sessions` mints a session,
|
|
4
|
+
// `GET /sessions/:id/init` (WebSocket, unlock bearer as `?token=`) carries a
|
|
5
|
+
// `prompt` signal in and the turn's TraceEvents out. The turn is ours from the
|
|
6
|
+
// `agent_ack` that echoes our `messageId`, and over at its `done` or `error`.
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { applySinglePatch, EMPTY_SPEC } from '../../dist/wire.js';
|
|
9
|
+
|
|
10
|
+
/** A wire props-schema node, past the wrappers that do not change what it holds. */
|
|
11
|
+
function unwrap(node) {
|
|
12
|
+
let current = node;
|
|
13
|
+
while (current !== undefined && current.resolved === undefined && (current.t === 'optional' || current.t === 'nullable' || current.t === 'default')) current = current.inner;
|
|
14
|
+
return current;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Each catalog type → its top-level props that carry entity refs (`resolved()`), read off the wire catalog. */
|
|
18
|
+
export function resolvedProps(wireCatalog) {
|
|
19
|
+
const out = new Map();
|
|
20
|
+
for (const [type, entry] of Object.entries(wireCatalog)) {
|
|
21
|
+
const shape = entry.propsSchema !== undefined && entry.propsSchema.t === 'object' ? entry.propsSchema.shape : {};
|
|
22
|
+
const props = Object.entries(shape).filter(([, node]) => {
|
|
23
|
+
const inner = unwrap(node);
|
|
24
|
+
return inner !== undefined && (inner.resolved !== undefined || (inner.t === 'array' && unwrap(inner.element) !== undefined && unwrap(inner.element).resolved !== undefined));
|
|
25
|
+
}).map(([prop]) => prop);
|
|
26
|
+
if (props.length > 0) out.set(type, props);
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** How many entities a resolved prop's value names: an array's length, else one for a present value. */
|
|
32
|
+
function entityCount(value) {
|
|
33
|
+
if (Array.isArray(value)) return value.length;
|
|
34
|
+
return value === undefined || value === null || value === '' ? 0 : 1;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Did the turn compose something real? It passes when an element the turn
|
|
39
|
+
* wrote (differs from the layout it started on) is a catalog type with ≥1
|
|
40
|
+
* entity in a resolved prop — a productGrid with a product, not an empty grid.
|
|
41
|
+
*/
|
|
42
|
+
export function judgeTurn(before, after, wireCatalog) {
|
|
43
|
+
const props = resolvedProps(wireCatalog);
|
|
44
|
+
const composed = Object.entries(after.elements).filter(([key, element]) => JSON.stringify(element) !== JSON.stringify(before.elements[key]));
|
|
45
|
+
const elementTypes = composed.map(([, element]) => element.type);
|
|
46
|
+
const evidence = [];
|
|
47
|
+
for (const [, element] of composed) {
|
|
48
|
+
for (const prop of props.has(element.type) ? props.get(element.type) : []) {
|
|
49
|
+
const count = entityCount(element.props === undefined ? undefined : element.props[prop]);
|
|
50
|
+
if (count > 0) evidence.push(`${element.type}.${prop} (${count})`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { pass: evidence.length > 0, elementTypes, evidence };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isSpec(value) {
|
|
57
|
+
return value !== null && typeof value === 'object' && typeof value.root === 'string' && value.elements !== null && typeof value.elements === 'object';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Ask the space one question as a visitor. Resolves (never rejects) with what
|
|
62
|
+
* the turn produced: `{ before, layout, text, error }` — `error` is the
|
|
63
|
+
* session's own words when it refused or failed.
|
|
64
|
+
*/
|
|
65
|
+
export async function askSpace({ apiUrl, slug, token, question, timeoutMs = 60_000 }) {
|
|
66
|
+
const headers = { 'content-type': 'application/json' };
|
|
67
|
+
if (token !== undefined) headers['x-api-key'] = token;
|
|
68
|
+
let res;
|
|
69
|
+
try {
|
|
70
|
+
res = await fetch(`${apiUrl}/s/${encodeURIComponent(slug)}/sessions`, { method: 'POST', headers, body: JSON.stringify({ visitorId: 'forty-doctor', forceFresh: true }) });
|
|
71
|
+
} catch (err) {
|
|
72
|
+
return { error: `cannot reach ${apiUrl} (${err.message})` };
|
|
73
|
+
}
|
|
74
|
+
const session = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
|
|
75
|
+
if (!res.ok) return { error: `the session was refused (${res.status}: ${session.error})` };
|
|
76
|
+
|
|
77
|
+
const start = isSpec(session.layout) ? session.layout : isSpec(session.seedLayout) ? session.seedLayout : EMPTY_SPEC;
|
|
78
|
+
const url = new URL(`${apiUrl.replace(/^http/, 'ws')}/sessions/${encodeURIComponent(session.sessionId)}/init`);
|
|
79
|
+
if (token !== undefined) url.searchParams.set('token', token);
|
|
80
|
+
const messageId = `msg-doctor-${randomUUID()}`;
|
|
81
|
+
|
|
82
|
+
return new Promise((resolve) => {
|
|
83
|
+
let layout = start;
|
|
84
|
+
let committed = null;
|
|
85
|
+
let turnId = null;
|
|
86
|
+
let text = '';
|
|
87
|
+
const ws = new WebSocket(url);
|
|
88
|
+
const finish = (outcome) => {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
ws.onclose = null;
|
|
91
|
+
ws.close();
|
|
92
|
+
resolve({ before: start, layout: committed === null ? layout : committed, text, ...outcome });
|
|
93
|
+
};
|
|
94
|
+
const timer = setTimeout(() => finish({ error: `no answer within ${timeoutMs / 1000}s` }), timeoutMs);
|
|
95
|
+
ws.onopen = () => ws.send(JSON.stringify({ type: 'prompt', timestamp: Date.now(), payload: { text: question, messageId } }));
|
|
96
|
+
ws.onerror = (evt) => finish({ error: `the session socket failed${evt.message === undefined ? '' : ` (${evt.message})`}` });
|
|
97
|
+
ws.onclose = (evt) => finish({ error: `the session socket closed (${evt.code}${evt.reason === '' ? '' : `: ${evt.reason}`})` });
|
|
98
|
+
ws.onmessage = (evt) => {
|
|
99
|
+
const frame = JSON.parse(String(evt.data));
|
|
100
|
+
if (frame.type === 'agent_ack' && frame.messageId === messageId) turnId = frame.turnId;
|
|
101
|
+
// An error with no turn is the socket's own refusal; one with a turn is ours only if it is ours.
|
|
102
|
+
if (frame.type === 'error' && (frame.turnId === undefined || frame.turnId === turnId)) return finish({ error: frame.message });
|
|
103
|
+
if (turnId === null || frame.turnId !== turnId) return;
|
|
104
|
+
if (frame.type === 'response_text_delta') text += frame.text;
|
|
105
|
+
if (frame.type === 'response_text') text = frame.text;
|
|
106
|
+
if (frame.type === 'layout_patch_op') layout = applySinglePatch(layout, frame.patch);
|
|
107
|
+
if (frame.type === 'layout_committed' && isSpec(frame.layout)) committed = frame.layout;
|
|
108
|
+
if (frame.type === 'done') finish({});
|
|
109
|
+
};
|
|
110
|
+
});
|
|
111
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
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
|
+
}
|
package/bin/lib/build.mjs
CHANGED
|
@@ -76,6 +76,15 @@ export async function loadCatalog(file) {
|
|
|
76
76
|
*/
|
|
77
77
|
const SHARED = /^(react|react-dom|react\/jsx-runtime|framer-motion|zod|@40rty\/ams-sdk|@40rty\/ams-ui(\/.+)?|@fourty\/.+)$/;
|
|
78
78
|
|
|
79
|
+
/** With a named stylesheet, the components' OWN css imports are empty — the named sheet carries them; a package's are bundled. */
|
|
80
|
+
const ownCssIsNamedPlugin = {
|
|
81
|
+
name: 'forty-own-css',
|
|
82
|
+
setup(pluginBuild) {
|
|
83
|
+
pluginBuild.onResolve({ filter: /\.css$/ }, (args) => (args.path.startsWith('.') || path.isAbsolute(args.path) ? { path: args.path, namespace: 'forty-own-css' } : undefined));
|
|
84
|
+
pluginBuild.onLoad({ filter: /.*/, namespace: 'forty-own-css' }, () => ({ contents: '', loader: 'css' }));
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
|
|
79
88
|
const sharedModulesPlugin = {
|
|
80
89
|
name: 'forty-shared-modules',
|
|
81
90
|
setup(pluginBuild) {
|
|
@@ -94,7 +103,11 @@ const sharedModulesPlugin = {
|
|
|
94
103
|
* The stylesheet is either named (`bundle.css`, bundled so a file of `@import`s
|
|
95
104
|
* arrives whole) or, when it is not, every CSS file the components themselves
|
|
96
105
|
* import — so a package whose entry already pulls in its styles needs no
|
|
97
|
-
* second list of them.
|
|
106
|
+
* second list of them. With a named sheet, a stylesheet the components import
|
|
107
|
+
* from a PACKAGE (`@40rty/ams-ui/island.css`) is still bundled and appended:
|
|
108
|
+
* the named sheet is a Tailwind build, whose `@import` cannot resolve a
|
|
109
|
+
* package's `exports`. Their own relative CSS is the named sheet's to carry.
|
|
110
|
+
* Fonts and images stay where their `url()` points.
|
|
98
111
|
*/
|
|
99
112
|
export async function buildBundle(bundle) {
|
|
100
113
|
if (typeof bundle.entry !== 'string') fail('forty.config.json "bundle" needs an "entry"');
|
|
@@ -109,19 +122,18 @@ export async function buildBundle(bundle) {
|
|
|
109
122
|
minify: true,
|
|
110
123
|
jsx: 'automatic',
|
|
111
124
|
define: { 'process.env.NODE_ENV': '"production"' },
|
|
112
|
-
loader: { '.css':
|
|
125
|
+
loader: { '.css': 'css' },
|
|
113
126
|
external: CSS_EXTERNAL,
|
|
114
|
-
plugins: [sharedModulesPlugin],
|
|
127
|
+
plugins: typeof bundle.css === 'string' ? [ownCssIsNamedPlugin, sharedModulesPlugin] : [sharedModulesPlugin],
|
|
115
128
|
logLevel: 'error',
|
|
116
129
|
});
|
|
117
130
|
const js = result.outputFiles.find((file) => file.path.endsWith('.js'));
|
|
118
131
|
if (js === undefined) fail(`${bundle.entry} produced no module`);
|
|
119
132
|
// The package's own Tailwind utilities, appended to its stylesheet (`lib/tailwind.mjs`).
|
|
120
133
|
const utilities = typeof bundle.tailwind === 'string' ? await compileTailwind(bundle.tailwind) : '';
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
134
|
+
const importedSheet = result.outputFiles.find((file) => file.path.endsWith('.css'));
|
|
135
|
+
const imported = importedSheet === undefined ? '' : importedSheet.text;
|
|
136
|
+
if (typeof bundle.css !== 'string') return { js: js.text, css: imported + utilities };
|
|
125
137
|
let css;
|
|
126
138
|
try {
|
|
127
139
|
const sheet = await build({
|
|
@@ -136,7 +148,7 @@ export async function buildBundle(bundle) {
|
|
|
136
148
|
} catch (err) {
|
|
137
149
|
fail(`cannot build the stylesheet ${bundle.css} — ${err.message}`);
|
|
138
150
|
}
|
|
139
|
-
return { js: js.text, css: css + utilities };
|
|
151
|
+
return { js: js.text, css: css + imported + utilities };
|
|
140
152
|
}
|
|
141
153
|
|
|
142
154
|
/** What a stylesheet points at rather than carries. */
|
package/bin/lib/context.mjs
CHANGED
|
@@ -77,10 +77,41 @@ export async function readDotenv(file) {
|
|
|
77
77
|
return out;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
/** The
|
|
80
|
+
/** The first of `names` set (non-empty) in `env`. */
|
|
81
|
+
function firstOf(env, names) {
|
|
82
|
+
const name = names.find((candidate) => typeof env[candidate] === 'string' && env[candidate].trim() !== '');
|
|
83
|
+
return name === undefined ? undefined : env[name];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The store this app sells from, read from its own `.env` — Hydrogen's names
|
|
88
|
+
* first, then Next.js Commerce's (`SHOPIFY_STORE_DOMAIN`, `SHOPIFY_STOREFRONT_ACCESS_TOKEN`).
|
|
89
|
+
*/
|
|
81
90
|
export async function storeBinding() {
|
|
82
91
|
const env = await readDotenv(path.join(cwd, '.env'));
|
|
83
|
-
return {
|
|
92
|
+
return {
|
|
93
|
+
domain: firstOf(env, ['PUBLIC_STORE_DOMAIN', 'SHOPIFY_STORE_DOMAIN']),
|
|
94
|
+
token: firstOf(env, ['PUBLIC_STOREFRONT_API_TOKEN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN']),
|
|
95
|
+
shopId: env.SHOP_ID,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Frameworks whose app serves its own pages — and so hosts the spacefront itself. */
|
|
100
|
+
const APP_FRAMEWORKS = ['@shopify/hydrogen', 'next', 'react-router', '@remix-run/react', '@remix-run/node'];
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What a repo is, from its package.json: `{ selfHosted, hydrogen, framework }`.
|
|
104
|
+
* An app (Hydrogen, Next.js, React Router, Remix, or Vite + React) hosts the
|
|
105
|
+
* spacefront in its own pages; anything else is a package the platform hosts.
|
|
106
|
+
* `--self-hosted` / `--package` override the guess.
|
|
107
|
+
*/
|
|
108
|
+
export function appKind(manifest) {
|
|
109
|
+
const deps = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
110
|
+
const has = (name) => deps[name] !== undefined;
|
|
111
|
+
let framework = APP_FRAMEWORKS.find(has);
|
|
112
|
+
if (framework === undefined && has('vite') && has('react') && has('react-dom')) framework = 'vite';
|
|
113
|
+
const forced = process.argv.includes('--self-hosted') ? true : process.argv.includes('--package') ? false : undefined;
|
|
114
|
+
return { selfHosted: forced === undefined ? framework !== undefined : forced, hydrogen: has('@shopify/hydrogen'), framework };
|
|
84
115
|
}
|
|
85
116
|
|
|
86
117
|
/** Set one key in the app's `.env`, replacing it in place or appending it. */
|
|
@@ -115,13 +146,21 @@ export function option(name) {
|
|
|
115
146
|
return undefined;
|
|
116
147
|
}
|
|
117
148
|
|
|
149
|
+
/** Is the valueless switch `--name` on the command line? Switches are spelled `--no-…` or listed in SWITCHES. */
|
|
150
|
+
export function flag(name) {
|
|
151
|
+
return process.argv.slice(3).includes(`--${name}`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Valueless switches that do not start with `--no-` — every other flag takes a value. */
|
|
155
|
+
const SWITCHES = new Set(['--detect', '--keep-locked', '--self-hosted', '--package']);
|
|
156
|
+
|
|
118
157
|
/** The command's arguments that are not flags or flag values, in order. */
|
|
119
158
|
export function positionals() {
|
|
120
159
|
const args = process.argv.slice(3);
|
|
121
160
|
const out = [];
|
|
122
161
|
for (let i = 0; i < args.length; i += 1) {
|
|
123
162
|
if (args[i].startsWith('--')) {
|
|
124
|
-
if (!args[i].includes('=')) i += 1;
|
|
163
|
+
if (!args[i].includes('=') && !args[i].startsWith('--no-') && !SWITCHES.has(args[i])) i += 1;
|
|
125
164
|
continue;
|
|
126
165
|
}
|
|
127
166
|
out.push(args[i]);
|
|
@@ -35,8 +35,8 @@ async function upToRepoRoot(cwd) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
/**
|
|
38
|
-
* The developer's own deploy target: `{ target, label, evidence }
|
|
39
|
-
* when the repository names none. `target` is one of oxygen, vercel, netlify,
|
|
38
|
+
* The developer's own deploy target: `{ target, label, evidence }` —
|
|
39
|
+
* `target: null` (label "none detected") when the repository names none. `target` is one of oxygen, vercel, netlify,
|
|
40
40
|
* cloudflare, fly, docker. Explicit signals win; Hydrogen's default `oxygen()`
|
|
41
41
|
* vite plugin is the last resort, because every Hydrogen app starts with it.
|
|
42
42
|
*/
|
|
@@ -82,5 +82,7 @@ export async function detectDeployTarget(cwd) {
|
|
|
82
82
|
});
|
|
83
83
|
if (/\boxygen\(/.test(text)) return found('oxygen', 'Shopify Oxygen', `${config} uses the oxygen() plugin (Hydrogen's default)`);
|
|
84
84
|
}
|
|
85
|
-
|
|
85
|
+
// A Next.js app that names no other target almost always ships to Vercel.
|
|
86
|
+
if (deps.next !== undefined) return found('vercel', 'Vercel (likely)', 'package.json depends on next, and no other target is configured');
|
|
87
|
+
return found(null, 'none detected', 'no deploy config, CI workflow or adapter in the repository');
|
|
86
88
|
}
|
package/bin/lib/hosted-build.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { createHash } from 'node:crypto';
|
|
|
6
6
|
import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { fail } from './context.mjs';
|
|
9
|
+
import { ASSET_BASE_ENV } from './base-path-build.mjs';
|
|
9
10
|
import { findCredential } from './credentials.mjs';
|
|
10
11
|
|
|
11
12
|
/** Inside `dist/`, which a Hydrogen app already ignores — never the developer's own `.vercel/`. */
|
|
@@ -22,23 +23,28 @@ export default function handler(request, context) {
|
|
|
22
23
|
}
|
|
23
24
|
`;
|
|
24
25
|
|
|
25
|
-
/** `shopify hydrogen build
|
|
26
|
-
export function buildHydrogen(cwd) {
|
|
27
|
-
const
|
|
26
|
+
/** `shopify hydrogen build` in `cwd` (the app's base-path copy), its assets served from `assetBase`, with its output on the terminal. */
|
|
27
|
+
export function buildHydrogen(cwd, assetBase) {
|
|
28
|
+
const env = { ...process.env, [ASSET_BASE_ENV]: assetBase };
|
|
29
|
+
const run = spawnSync('npx', ['--no-install', 'shopify', 'hydrogen', 'build', '--no-lockfile-check'], { cwd, stdio: 'inherit', env });
|
|
28
30
|
if (run.error !== undefined) fail(`could not run \`shopify hydrogen build\` (${run.error.message})`);
|
|
29
31
|
if (run.status !== 0) fail('`shopify hydrogen build` failed — fix the build, then run `forty deploy` again');
|
|
30
32
|
}
|
|
31
33
|
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
+
/**
|
|
35
|
+
* Lay a build's `dist/client` + `dist/server` out as a Build Output under
|
|
36
|
+
* `cwd`'s OUTPUT_DIR. The app answers under `/<slug>/`, so its client files are
|
|
37
|
+
* served from there too (`static/<slug>/assets/…`).
|
|
38
|
+
*/
|
|
39
|
+
export async function assembleBuildOutput(cwd, buildDir, slug) {
|
|
34
40
|
const out = path.join(cwd, OUTPUT_DIR);
|
|
35
41
|
const func = path.join(out, 'functions', 'index.func');
|
|
36
42
|
await rm(out, { recursive: true, force: true });
|
|
37
43
|
await mkdir(func, { recursive: true });
|
|
38
|
-
await cp(path.join(
|
|
44
|
+
await cp(path.join(buildDir, 'dist', 'client'), path.join(out, 'static', slug), { recursive: true });
|
|
39
45
|
// The worker and any chunk or wasm it imports — not its source map, metafile or bundle report. Its entry becomes server.js.
|
|
40
46
|
const runtime = (src) => !/\.[a-z]+$/.test(src) || /\.(m?js|wasm)$/.test(src);
|
|
41
|
-
await cp(path.join(
|
|
47
|
+
await cp(path.join(buildDir, 'dist', 'server'), func, { recursive: true, filter: runtime });
|
|
42
48
|
await rename(path.join(func, 'index.js'), path.join(func, 'server.js'));
|
|
43
49
|
await writeFile(path.join(func, 'index.js'), EDGE_ENTRY);
|
|
44
50
|
await writeFile(path.join(func, '.vc-config.json'), JSON.stringify({ runtime: 'edge', entrypoint: 'index.js' }));
|
package/dist/wire.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// ../spacestation/src/layout/layout.ts
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
var JSON_PATCH_OPS = ["add", "remove", "replace", "move"];
|
|
4
|
+
var EMPTY_SPEC = {
|
|
5
|
+
root: "page",
|
|
6
|
+
elements: { page: { type: "page", props: {}, children: [] } }
|
|
7
|
+
};
|
|
4
8
|
var UIElementSchema = z.object({
|
|
5
9
|
type: z.string(),
|
|
6
10
|
props: z.record(z.unknown()).default({}),
|
|
@@ -523,6 +527,104 @@ import { z as z15 } from "zod";
|
|
|
523
527
|
// ../spacestation/src/catalog/function-props.ts
|
|
524
528
|
import { z as z16 } from "zod";
|
|
525
529
|
|
|
530
|
+
// ../spacestation/src/layout/apply-patch.ts
|
|
531
|
+
function arrayAdd(arr, key, value) {
|
|
532
|
+
if (key === "-") {
|
|
533
|
+
arr.push(value);
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
const idx = Number(key);
|
|
537
|
+
if (!Number.isInteger(idx) || idx < 0 || idx > arr.length) return false;
|
|
538
|
+
arr.splice(idx, 0, value);
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
541
|
+
function arrayIndex(arr, key) {
|
|
542
|
+
const idx = Number(key);
|
|
543
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= arr.length) return null;
|
|
544
|
+
return idx;
|
|
545
|
+
}
|
|
546
|
+
function applySinglePatch(doc, patch) {
|
|
547
|
+
const segments = patch.path.split("/").filter(Boolean);
|
|
548
|
+
if (segments.length === 0) {
|
|
549
|
+
if (patch.op === "replace" || patch.op === "add") {
|
|
550
|
+
if (patch.value === void 0 || patch.value === null) return doc;
|
|
551
|
+
if (typeof patch.value !== "object") return doc;
|
|
552
|
+
return patch.value;
|
|
553
|
+
}
|
|
554
|
+
return doc;
|
|
555
|
+
}
|
|
556
|
+
if (patch.op === "move") {
|
|
557
|
+
if (!patch.from) return doc;
|
|
558
|
+
const read = readAtPath(doc, patch.from);
|
|
559
|
+
if (!read.found) return doc;
|
|
560
|
+
const removed = applySinglePatch(doc, { op: "remove", path: patch.from });
|
|
561
|
+
if (removed === doc) return doc;
|
|
562
|
+
return applySinglePatch(removed, { op: "add", path: patch.path, value: read.value });
|
|
563
|
+
}
|
|
564
|
+
const result = { ...doc };
|
|
565
|
+
let target = result;
|
|
566
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
567
|
+
const seg = segments[i];
|
|
568
|
+
const child = target[seg];
|
|
569
|
+
if (child === void 0 || child === null) return doc;
|
|
570
|
+
if (Array.isArray(child)) {
|
|
571
|
+
target[seg] = [...child];
|
|
572
|
+
} else if (typeof child === "object") {
|
|
573
|
+
target[seg] = { ...child };
|
|
574
|
+
} else {
|
|
575
|
+
return doc;
|
|
576
|
+
}
|
|
577
|
+
target = target[seg];
|
|
578
|
+
}
|
|
579
|
+
const key = segments[segments.length - 1];
|
|
580
|
+
switch (patch.op) {
|
|
581
|
+
case "add":
|
|
582
|
+
if (Array.isArray(target)) {
|
|
583
|
+
if (!arrayAdd(target, key, patch.value)) return doc;
|
|
584
|
+
} else {
|
|
585
|
+
target[key] = patch.value;
|
|
586
|
+
}
|
|
587
|
+
break;
|
|
588
|
+
case "replace":
|
|
589
|
+
if (Array.isArray(target)) {
|
|
590
|
+
const idx = arrayIndex(target, key);
|
|
591
|
+
if (idx === null) return doc;
|
|
592
|
+
target[idx] = patch.value;
|
|
593
|
+
} else {
|
|
594
|
+
target[key] = patch.value;
|
|
595
|
+
}
|
|
596
|
+
break;
|
|
597
|
+
case "remove":
|
|
598
|
+
if (Array.isArray(target)) {
|
|
599
|
+
const idx = arrayIndex(target, key);
|
|
600
|
+
if (idx === null) return doc;
|
|
601
|
+
target.splice(idx, 1);
|
|
602
|
+
} else {
|
|
603
|
+
delete target[key];
|
|
604
|
+
}
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
return result;
|
|
608
|
+
}
|
|
609
|
+
function readAtPath(doc, path) {
|
|
610
|
+
const segments = path.split("/").filter(Boolean);
|
|
611
|
+
let cursor = doc;
|
|
612
|
+
for (const seg of segments) {
|
|
613
|
+
if (Array.isArray(cursor)) {
|
|
614
|
+
const idx = Number(seg);
|
|
615
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= cursor.length) return { found: false };
|
|
616
|
+
cursor = cursor[idx];
|
|
617
|
+
} else if (typeof cursor === "object" && cursor !== null) {
|
|
618
|
+
const rec = { ...cursor };
|
|
619
|
+
if (!(seg in rec)) return { found: false };
|
|
620
|
+
cursor = rec[seg];
|
|
621
|
+
} else {
|
|
622
|
+
return { found: false };
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return { found: true, value: cursor };
|
|
626
|
+
}
|
|
627
|
+
|
|
526
628
|
// ../spacestation/src/catalog/wire/wire-schema.ts
|
|
527
629
|
import { z as z17 } from "zod";
|
|
528
630
|
var common = {
|
|
@@ -1480,6 +1582,8 @@ var FileBugInputSchema = z31.object({
|
|
|
1480
1582
|
payload: z31.record(z31.unknown())
|
|
1481
1583
|
});
|
|
1482
1584
|
export {
|
|
1585
|
+
EMPTY_SPEC,
|
|
1483
1586
|
PackageReleaseSchema,
|
|
1587
|
+
applySinglePatch,
|
|
1484
1588
|
catalogToWire
|
|
1485
1589
|
};
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"version": "0.1.0",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
|
-
"description": "__LABEL__'s spacefront components
|
|
6
|
+
"description": "__LABEL__'s spacefront components \u2014 published to 40rty, which hosts the page.",
|
|
7
7
|
"scripts": {
|
|
8
8
|
"build:css": "tailwindcss -i src/styles.css -o dist/package.css --minify",
|
|
9
9
|
"dev": "npm run build:css && (tailwindcss -i src/styles.css -o dist/package.css --watch & forty dev)",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
15
|
"@40rty/ams-sdk": "__VERSION__",
|
|
16
|
+
"@40rty/ams-ui": "__VERSION__",
|
|
16
17
|
"react": "^18.3.1",
|
|
17
18
|
"react-dom": "^18.3.1"
|
|
18
19
|
},
|