@bestcheckout/dynamic-component-cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +536 -2
- package/package.json +51 -4
- package/src/cli.mjs +87 -0
- package/src/core/browser.mjs +23 -0
- package/src/core/build-runner.mjs +18 -0
- package/src/core/build-session.mjs +69 -0
- package/src/core/build-worker.mjs +8 -0
- package/src/core/build.mjs +85 -0
- package/src/core/config.mjs +115 -0
- package/src/core/doctor.mjs +102 -0
- package/src/core/project.mjs +143 -0
- package/src/core/react-bridge.mjs +65 -0
- package/src/core/server.mjs +191 -0
- package/src/core/source-boundary.mjs +69 -0
- package/src/core/validate.mjs +247 -0
- package/src/protocol/artifact.mjs +88 -0
- package/src/protocol/validation.mjs +96 -0
- package/templates/starter/README.md +58 -0
- package/templates/starter/tsconfig.json +14 -0
- package/types/index.d.ts +1230 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Development modules use the same Host bridge as uploaded artifacts. Keep
|
|
2
|
+
// this in the Dev Server adapter: merchant components still import React normally.
|
|
3
|
+
const modules = {
|
|
4
|
+
react: ['react', ['Children', 'Component', 'Fragment', 'Profiler', 'PureComponent', 'StrictMode', 'Suspense', 'cloneElement', 'createContext', 'createElement', 'createFactory', 'createRef', 'forwardRef', 'isValidElement', 'lazy', 'memo', 'startTransition', 'useCallback', 'useContext', 'useDebugValue', 'useDeferredValue', 'useEffect', 'useId', 'useImperativeHandle', 'useInsertionEffect', 'useLayoutEffect', 'useMemo', 'useReducer', 'useRef', 'useState', 'useSyncExternalStore', 'useTransition', 'version']],
|
|
5
|
+
'react-dom': ['reactDom', ['createPortal', 'flushSync', 'findDOMNode', 'hydrate', 'render', 'unmountComponentAtNode']],
|
|
6
|
+
'react-dom/client': ['reactDomClient', ['createRoot', 'hydrateRoot']],
|
|
7
|
+
'react/jsx-runtime': ['jsxRuntime', ['Fragment', 'jsx', 'jsxs']],
|
|
8
|
+
'react/jsx-dev-runtime': ['jsxDevRuntime', ['Fragment', 'jsxDEV']],
|
|
9
|
+
};
|
|
10
|
+
const prefix = '\0shop-visual-host-runtime:';
|
|
11
|
+
|
|
12
|
+
export function hostReactRuntime() {
|
|
13
|
+
return {
|
|
14
|
+
name: 'shop-visual-host-react-runtime',
|
|
15
|
+
apply: 'serve',
|
|
16
|
+
enforce: 'pre',
|
|
17
|
+
config() {
|
|
18
|
+
// Prevent dependency prebundling from embedding a separate React copy,
|
|
19
|
+
// including imports originating in other dependencies.
|
|
20
|
+
return { optimizeDeps: { exclude: Object.keys(modules) } };
|
|
21
|
+
},
|
|
22
|
+
configResolved(config) {
|
|
23
|
+
// @vitejs/plugin-react adds React to include during config merging. It
|
|
24
|
+
// must not be both an optimizer entry and an external dependency.
|
|
25
|
+
config.optimizeDeps.include = (config.optimizeDeps.include ?? []).filter(name => !Object.hasOwn(modules, name));
|
|
26
|
+
},
|
|
27
|
+
configureServer(server) {
|
|
28
|
+
server.middlewares.use((request, response, next) => {
|
|
29
|
+
const end = response.end.bind(response);
|
|
30
|
+
response.end = (chunk, ...args) => {
|
|
31
|
+
if ((typeof chunk === 'string' || Buffer.isBuffer(chunk)) && String(response.getHeader('Content-Type')).includes('javascript')) {
|
|
32
|
+
// The Host can import fetched entry bytes through a Blob URL. A
|
|
33
|
+
// root-relative virtual module would have no base in that case.
|
|
34
|
+
const origin = `${server.config.server.https ? 'https' : 'http'}://${request.headers.host}`;
|
|
35
|
+
const source = Buffer.from(chunk).toString('utf8').replace(
|
|
36
|
+
/(["'])\/@id\/__x00__shop-visual-host-runtime:([^"']+)\1/g,
|
|
37
|
+
(_match, quote, name) => `${quote}${origin}/@id/__x00__shop-visual-host-runtime:${name}${quote}`,
|
|
38
|
+
);
|
|
39
|
+
response.setHeader('Content-Length', Buffer.byteLength(source));
|
|
40
|
+
return end(Buffer.from(source), ...args);
|
|
41
|
+
}
|
|
42
|
+
return end(chunk, ...args);
|
|
43
|
+
};
|
|
44
|
+
next();
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
resolveId(source) {
|
|
48
|
+
if (Object.hasOwn(modules, source)) return prefix + source;
|
|
49
|
+
if (/^react(?:-dom)?\//.test(source)) {
|
|
50
|
+
throw new Error(`Unsupported Host React runtime import: ${source}`);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
load(id) {
|
|
54
|
+
if (!id.startsWith(prefix)) return;
|
|
55
|
+
const specifier = id.slice(prefix.length);
|
|
56
|
+
const [key, names] = modules[specifier];
|
|
57
|
+
return [
|
|
58
|
+
`const runtime = globalThis.__SHOP_VISUAL_DYNAMIC_RUNTIME__?.[${JSON.stringify(key)}];`,
|
|
59
|
+
`if (!runtime) throw new Error(${JSON.stringify(`Host React runtime is unavailable for ${specifier}. Open this component through the theme editor Local Dev Server preview.`)});`,
|
|
60
|
+
'export default runtime;',
|
|
61
|
+
...names.map(name => `export const ${name} = runtime.${name};`),
|
|
62
|
+
].join('\n');
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createServer } from 'vite';
|
|
2
|
+
import { createBuildSessions, readBuildInput } from './build-session.mjs';
|
|
3
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
4
|
+
import { resolve, relative } from 'node:path';
|
|
5
|
+
import { readConfig, inside } from './config.mjs';
|
|
6
|
+
import { hostReactRuntime } from './react-bridge.mjs';
|
|
7
|
+
import { sourceBoundary } from './source-boundary.mjs';
|
|
8
|
+
import { runBuildWorker } from './build-runner.mjs';
|
|
9
|
+
|
|
10
|
+
function json(response, status, body) {
|
|
11
|
+
response.statusCode = status;
|
|
12
|
+
response.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
13
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
14
|
+
response.end(JSON.stringify(body));
|
|
15
|
+
}
|
|
16
|
+
export async function serveProject(root, options = {}) {
|
|
17
|
+
const config = await readConfig(root, options);
|
|
18
|
+
const port = config.server.port;
|
|
19
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
20
|
+
const canonicalBuildInput = (input) => {
|
|
21
|
+
if (!input || typeof input.sourceUrl !== 'string' || typeof input.componentId !== 'string')
|
|
22
|
+
throw new Error('sourceUrl and componentId are required');
|
|
23
|
+
const url = new URL(input.sourceUrl);
|
|
24
|
+
if (url.origin !== origin && url.origin !== `http://localhost:${port}`)
|
|
25
|
+
throw new Error('sourceUrl origin does not match this Dev Server');
|
|
26
|
+
if (url.username || url.password || url.hash || url.search || !url.pathname.startsWith('/src/'))
|
|
27
|
+
throw new Error('sourceUrl must point to a registered entry on this Dev Server');
|
|
28
|
+
const entry = decodeURIComponent(url.pathname.slice(1));
|
|
29
|
+
const component = config.components.find(item => item.componentId === input.componentId && item.entry === entry);
|
|
30
|
+
if (!component) throw new Error('componentId/sourceUrl does not match dynamic.config.json');
|
|
31
|
+
return { sourceUrl: url.href, componentId: input.componentId };
|
|
32
|
+
};
|
|
33
|
+
const plugin = {
|
|
34
|
+
name: 'dynamic-component-http',
|
|
35
|
+
enforce: 'pre',
|
|
36
|
+
configureServer(server) {
|
|
37
|
+
let busy = false;
|
|
38
|
+
const buildSessions = createBuildSessions();
|
|
39
|
+
server.httpServer?.once('close', () => buildSessions.close());
|
|
40
|
+
server.middlewares.use(async (request, response, next) => {
|
|
41
|
+
const host = request.headers.host;
|
|
42
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host))
|
|
43
|
+
return json(response, 403, { message: 'Invalid Dev Server Host' });
|
|
44
|
+
response.setHeader('Access-Control-Allow-Origin', '*');
|
|
45
|
+
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
|
46
|
+
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
47
|
+
if (request.method === 'OPTIONS') {
|
|
48
|
+
response.statusCode = 204;
|
|
49
|
+
response.end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(request.url || '/', origin);
|
|
54
|
+
const path = decodeURIComponent(url.pathname);
|
|
55
|
+
if (path.startsWith('/.well-known/') && url.search)
|
|
56
|
+
return json(response, 400, { message: 'Protocol query is not permitted' });
|
|
57
|
+
if (path === '/.well-known/dynamic.json') {
|
|
58
|
+
if (request.method !== 'GET')
|
|
59
|
+
return json(response, 405, { message: 'GET is required' });
|
|
60
|
+
return json(response, 200, {
|
|
61
|
+
protocolVersion: 1,
|
|
62
|
+
build: { url: origin + '/.well-known/dynamic-build' },
|
|
63
|
+
buildSession: { url: origin + '/.well-known/dynamic-build-session' },
|
|
64
|
+
hmr: {
|
|
65
|
+
transport: 'websocket',
|
|
66
|
+
url: `ws://127.0.0.1:${port}/`,
|
|
67
|
+
protocol: 'vite-hmr',
|
|
68
|
+
token: server.config.webSocketToken,
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (path === '/.well-known/dynamic-build-session') {
|
|
73
|
+
if (request.method !== 'POST') return json(response, 405, { message: 'POST is required' });
|
|
74
|
+
if (!request.headers['content-type']?.startsWith('application/json'))
|
|
75
|
+
return json(response, 403, { message: 'application/json is required' });
|
|
76
|
+
const input = canonicalBuildInput(await readBuildInput(request));
|
|
77
|
+
return json(response, 200, buildSessions.issue(input));
|
|
78
|
+
}
|
|
79
|
+
if (path === '/.well-known/dynamic-build') {
|
|
80
|
+
if (request.method !== 'POST')
|
|
81
|
+
return json(response, 405, { message: 'POST is required' });
|
|
82
|
+
if (
|
|
83
|
+
!request.headers['content-type']?.startsWith('application/json')
|
|
84
|
+
)
|
|
85
|
+
return json(response, 403, {
|
|
86
|
+
message:
|
|
87
|
+
'application/json is required',
|
|
88
|
+
});
|
|
89
|
+
const input = canonicalBuildInput(await readBuildInput(request));
|
|
90
|
+
buildSessions.consume(request.headers.authorization, input);
|
|
91
|
+
if (busy) return json(response, 409, { message: 'A local build is already running. Save again after it completes.' });
|
|
92
|
+
busy = true;
|
|
93
|
+
try {
|
|
94
|
+
return json(response, 200, await runBuildWorker(new URL('./build-worker.mjs', import.meta.url), {
|
|
95
|
+
...input, options: { config, origin: new URL(input.sourceUrl).origin },
|
|
96
|
+
}));
|
|
97
|
+
} finally { busy = false; }
|
|
98
|
+
}
|
|
99
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
100
|
+
return json(response, 405, { message: 'Read-only route' });
|
|
101
|
+
if (
|
|
102
|
+
['/@vite/client', '/@vite/env'].includes(path) ||
|
|
103
|
+
path.startsWith('/@id/__x00__shop-visual-host-runtime:')
|
|
104
|
+
)
|
|
105
|
+
return next();
|
|
106
|
+
if (path.startsWith('/src/')) {
|
|
107
|
+
const file = await realpath(resolve(root, '.' + path));
|
|
108
|
+
if (
|
|
109
|
+
!inside(config.src, file) ||
|
|
110
|
+
/(?:^|[/\\])\./.test(path) ||
|
|
111
|
+
/(?:^|[/\\])\./.test(relative(config.src, file)) ||
|
|
112
|
+
!/\.(?:[cm]?[jt]sx?|json)$/.test(file) ||
|
|
113
|
+
[...url.searchParams.keys()].some(
|
|
114
|
+
(key) => !['t', 'import', 'v', '__ve_hmr'].includes(key),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
return json(response, 403, {
|
|
118
|
+
message: 'Source path is not permitted',
|
|
119
|
+
});
|
|
120
|
+
return next();
|
|
121
|
+
}
|
|
122
|
+
if (
|
|
123
|
+
path.startsWith(`/${config.outDir}/`) &&
|
|
124
|
+
/^[a-z0-9_-]+\.js$/.test(path.slice(config.outDir.length + 2))
|
|
125
|
+
) {
|
|
126
|
+
const dir = resolve(root, config.outDir);
|
|
127
|
+
const file = await realpath(resolve(root, '.' + path));
|
|
128
|
+
if (!inside(dir, file))
|
|
129
|
+
return json(response, 403, {
|
|
130
|
+
message: 'Artifact path is not permitted',
|
|
131
|
+
});
|
|
132
|
+
response.setHeader(
|
|
133
|
+
'Content-Type',
|
|
134
|
+
'text/javascript; charset=utf-8',
|
|
135
|
+
);
|
|
136
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
137
|
+
response.end(await readFile(file));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
return json(response, 404, {
|
|
141
|
+
message:
|
|
142
|
+
'Only registered component source, build metadata and artifacts are served',
|
|
143
|
+
});
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (response.destroyed) return;
|
|
146
|
+
return json(response, error.statusCode || (error.code === 'ENOENT' ? 404 : 400), {
|
|
147
|
+
message:
|
|
148
|
+
error instanceof Error ? error.message : 'Local request failed',
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
const server = await createServer({
|
|
155
|
+
configFile: false,
|
|
156
|
+
root,
|
|
157
|
+
publicDir: false,
|
|
158
|
+
envFile: false,
|
|
159
|
+
cacheDir: resolve(root, '.dynamic-cache'),
|
|
160
|
+
base: origin + '/',
|
|
161
|
+
logLevel: 'warn',
|
|
162
|
+
plugins: [plugin, hostReactRuntime(), sourceBoundary(config.src)],
|
|
163
|
+
esbuild: { jsx: 'automatic' },
|
|
164
|
+
optimizeDeps: { noDiscovery: true },
|
|
165
|
+
server: {
|
|
166
|
+
host: '127.0.0.1',
|
|
167
|
+
port,
|
|
168
|
+
strictPort: true,
|
|
169
|
+
origin,
|
|
170
|
+
cors: true,
|
|
171
|
+
fs: { strict: true, allow: [config.src] },
|
|
172
|
+
hmr: { host: '127.0.0.1', port },
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
try {
|
|
176
|
+
await server.listen();
|
|
177
|
+
} catch (error) {
|
|
178
|
+
await server.close();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
if (!options.quiet) {
|
|
182
|
+
for (const item of config.components)
|
|
183
|
+
console.log(
|
|
184
|
+
`${item.componentId} (${item.pageType}): ${origin}/${item.entry}`,
|
|
185
|
+
);
|
|
186
|
+
console.log(
|
|
187
|
+
`Metadata: ${origin}/.well-known/dynamic.json\nConnect a Local URL in the Editor. Ctrl+C stops this server.`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return server;
|
|
191
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { inside } from './config.mjs';
|
|
4
|
+
const allowedImports = new Set([
|
|
5
|
+
'react',
|
|
6
|
+
'react-dom',
|
|
7
|
+
'react-dom/client',
|
|
8
|
+
'react/jsx-runtime',
|
|
9
|
+
'react/jsx-dev-runtime',
|
|
10
|
+
]);
|
|
11
|
+
export function assertPublicImport(specifier) {
|
|
12
|
+
if (allowedImports.has(specifier)) return;
|
|
13
|
+
if (!specifier.startsWith('./') && !specifier.startsWith('../'))
|
|
14
|
+
throw new Error(
|
|
15
|
+
`Unsupported dependency: ${specifier}. Only local source and platform React imports are supported.`,
|
|
16
|
+
);
|
|
17
|
+
if (
|
|
18
|
+
/[?#]/.test(specifier) ||
|
|
19
|
+
/\.(css|less|scss|sass|svg|png|jpe?g|gif|webp)$/i.test(specifier)
|
|
20
|
+
)
|
|
21
|
+
throw new Error(
|
|
22
|
+
'Use exported styles and hosted asset URLs; asset/CSS imports are not single-file components',
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
export function sourceBoundary(sourceDirectory) {
|
|
26
|
+
const root = realpathSync(sourceDirectory);
|
|
27
|
+
return {
|
|
28
|
+
name: 'dynamic-component-source-boundary',
|
|
29
|
+
enforce: 'pre',
|
|
30
|
+
async resolveId(source, importer) {
|
|
31
|
+
if (
|
|
32
|
+
!importer ||
|
|
33
|
+
importer.startsWith('\0') ||
|
|
34
|
+
!inside(root, importer.split('?')[0])
|
|
35
|
+
)
|
|
36
|
+
return;
|
|
37
|
+
assertPublicImport(source);
|
|
38
|
+
const result = await this.resolve(source, importer, { skipSelf: true });
|
|
39
|
+
if (result && !result.external && !result.id.startsWith('\0')) {
|
|
40
|
+
const clean = result.id.split('?')[0];
|
|
41
|
+
if (
|
|
42
|
+
isAbsolute(clean) &&
|
|
43
|
+
!allowedImports.has(source) &&
|
|
44
|
+
!inside(root, realpathSync(clean))
|
|
45
|
+
)
|
|
46
|
+
throw new Error('Resolved dependency escapes src');
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export function buildBoundary(sourceDirectory) {
|
|
53
|
+
const root = realpathSync(sourceDirectory);
|
|
54
|
+
return {
|
|
55
|
+
name: 'dynamic-component-source-boundary',
|
|
56
|
+
setup(build) {
|
|
57
|
+
build.onResolve({ filter: /.*/ }, (args) => {
|
|
58
|
+
if (args.kind === 'entry-point') return;
|
|
59
|
+
assertPublicImport(args.path);
|
|
60
|
+
if (allowedImports.has(args.path))
|
|
61
|
+
return { path: args.path, external: true };
|
|
62
|
+
});
|
|
63
|
+
build.onLoad({ filter: /./ }, (args) => {
|
|
64
|
+
if (!inside(root, realpathSync(args.path)))
|
|
65
|
+
throw new Error('Resolved dependency escapes src');
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { readFile, mkdir, writeFile, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { build } from 'esbuild';
|
|
7
|
+
import ts from 'typescript';
|
|
8
|
+
import { readConfig } from './config.mjs';
|
|
9
|
+
import { buildArtifact, sourceFingerprint } from './build.mjs';
|
|
10
|
+
import { launchBrowser } from './browser.mjs';
|
|
11
|
+
import { rewriteProductionReactImports } from '../protocol/artifact.mjs';
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
export function checkTypes(config) {
|
|
14
|
+
const file = ts.findConfigFile(
|
|
15
|
+
config.root,
|
|
16
|
+
ts.sys.fileExists,
|
|
17
|
+
'tsconfig.json',
|
|
18
|
+
);
|
|
19
|
+
if (!file) throw new Error('tsconfig.json is required');
|
|
20
|
+
const raw = ts.readConfigFile(file, ts.sys.readFile);
|
|
21
|
+
if (raw.error)
|
|
22
|
+
throw new Error(
|
|
23
|
+
ts.flattenDiagnosticMessageText(raw.error.messageText, '\n'),
|
|
24
|
+
);
|
|
25
|
+
const parsed = ts.parseJsonConfigFileContent(
|
|
26
|
+
raw.config,
|
|
27
|
+
ts.sys,
|
|
28
|
+
config.root,
|
|
29
|
+
{ noEmit: true, incremental: false },
|
|
30
|
+
file,
|
|
31
|
+
);
|
|
32
|
+
const program = ts.createProgram(parsed.fileNames, {
|
|
33
|
+
...parsed.options,
|
|
34
|
+
noEmit: true,
|
|
35
|
+
incremental: false,
|
|
36
|
+
});
|
|
37
|
+
const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
|
|
38
|
+
if (diagnostics.length)
|
|
39
|
+
throw new Error(
|
|
40
|
+
ts.formatDiagnosticsWithColorAndContext(diagnostics, {
|
|
41
|
+
getCurrentDirectory: () => config.root,
|
|
42
|
+
getCanonicalFileName: (f) => f,
|
|
43
|
+
getNewLine: () => '\n',
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
export async function validateDefinitions(artifacts, components, options = {}) {
|
|
48
|
+
// Compile the platform validator and Host React into an ephemeral browser
|
|
49
|
+
// harness. No Node import of user definitions; no network business actions.
|
|
50
|
+
const protocol = fileURLToPath(
|
|
51
|
+
new URL('../protocol/validation.mjs', import.meta.url),
|
|
52
|
+
);
|
|
53
|
+
const entry = `import * as React from ${JSON.stringify(require.resolve('react'))};
|
|
54
|
+
import * as ReactDOM from ${JSON.stringify(require.resolve('react-dom'))};
|
|
55
|
+
import * as ReactDOMClient from ${JSON.stringify(require.resolve('react-dom/client'))};
|
|
56
|
+
import * as JSX from ${JSON.stringify(require.resolve('react/jsx-runtime'))};
|
|
57
|
+
import * as JSXDev from ${JSON.stringify(require.resolve('react/jsx-dev-runtime'))};
|
|
58
|
+
import {validateDynamicComponentDefinition} from ${JSON.stringify(protocol)};
|
|
59
|
+
globalThis.__SHOP_VISUAL_DYNAMIC_RUNTIME__={react:React,reactDom:ReactDOM,reactDomClient:ReactDOMClient,jsxRuntime:JSX,jsxDevRuntime:JSXDev};
|
|
60
|
+
globalThis.validateDefinition=validateDynamicComponentDefinition;`;
|
|
61
|
+
const built = await build({
|
|
62
|
+
stdin: { contents: entry, resolveDir: configDirectory(), loader: 'js' },
|
|
63
|
+
bundle: true,
|
|
64
|
+
write: false,
|
|
65
|
+
format: 'esm',
|
|
66
|
+
platform: 'browser',
|
|
67
|
+
logLevel: 'silent',
|
|
68
|
+
});
|
|
69
|
+
const bridges = {
|
|
70
|
+
react: 'react',
|
|
71
|
+
'react-dom': 'reactDom',
|
|
72
|
+
'react-dom/client': 'reactDomClient',
|
|
73
|
+
'react/jsx-runtime': 'jsxRuntime',
|
|
74
|
+
'react/jsx-dev-runtime': 'jsxDevRuntime',
|
|
75
|
+
};
|
|
76
|
+
const sources = new Map();
|
|
77
|
+
for (const [name, key] of Object.entries(bridges)) {
|
|
78
|
+
// All wrapper exports share the same browser React object.
|
|
79
|
+
const namespace = await import(name);
|
|
80
|
+
const names = Object.keys(namespace).filter(
|
|
81
|
+
(name) => name !== 'default' && /^[A-Za-z_$][\w$]*$/.test(name),
|
|
82
|
+
);
|
|
83
|
+
sources.set(
|
|
84
|
+
`/bridge/${encodeURIComponent(name)}.js`,
|
|
85
|
+
`const r=globalThis.__SHOP_VISUAL_DYNAMIC_RUNTIME__[${JSON.stringify(key)}];export default r;` +
|
|
86
|
+
names.map((n) => `export const ${n}=r.${n};`).join(''),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
const server = createServer((request, response) => {
|
|
90
|
+
response.setHeader('Content-Type', 'text/javascript');
|
|
91
|
+
if (request.url === '/host.js') response.end(built.outputFiles[0].text);
|
|
92
|
+
else if (sources.has(request.url)) response.end(sources.get(request.url));
|
|
93
|
+
else if (request.url === '/') {
|
|
94
|
+
response.setHeader('Content-Type', 'text/html');
|
|
95
|
+
response.end(
|
|
96
|
+
'<!doctype html><script type="module" src="/host.js"></script>',
|
|
97
|
+
);
|
|
98
|
+
} else {
|
|
99
|
+
response.statusCode = 404;
|
|
100
|
+
response.end();
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
await new Promise((done, reject) => {
|
|
104
|
+
server.once('error', reject);
|
|
105
|
+
server.listen(0, '127.0.0.1', done);
|
|
106
|
+
});
|
|
107
|
+
let browser;
|
|
108
|
+
try {
|
|
109
|
+
browser = await launchBrowser(options.executablePath);
|
|
110
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
111
|
+
const page = await browser.newPage();
|
|
112
|
+
await page.route('**/*', (route) =>
|
|
113
|
+
route
|
|
114
|
+
.request()
|
|
115
|
+
.url()
|
|
116
|
+
.startsWith(origin + '/')
|
|
117
|
+
? route.continue()
|
|
118
|
+
: route.abort(),
|
|
119
|
+
);
|
|
120
|
+
await page.goto(origin);
|
|
121
|
+
await page.waitForFunction(
|
|
122
|
+
() => typeof globalThis.validateDefinition === 'function',
|
|
123
|
+
);
|
|
124
|
+
const manifests = [];
|
|
125
|
+
for (let i = 0; i < artifacts.length; i++) {
|
|
126
|
+
const artifact = artifacts[i];
|
|
127
|
+
const urls = Object.fromEntries(
|
|
128
|
+
Object.entries(bridges).map(([name, key]) => [
|
|
129
|
+
key,
|
|
130
|
+
origin + '/bridge/' + encodeURIComponent(name) + '.js',
|
|
131
|
+
]),
|
|
132
|
+
);
|
|
133
|
+
const source = rewriteProductionReactImports(artifact.sourceText, urls);
|
|
134
|
+
let timer;
|
|
135
|
+
const result = await Promise.race([
|
|
136
|
+
page.evaluate(
|
|
137
|
+
async ({ source, component }) => {
|
|
138
|
+
const url = URL.createObjectURL(
|
|
139
|
+
new Blob([source], { type: 'text/javascript' }),
|
|
140
|
+
);
|
|
141
|
+
try {
|
|
142
|
+
const module = await import(url);
|
|
143
|
+
const checked = globalThis.validateDefinition(
|
|
144
|
+
module.default ?? module.definition,
|
|
145
|
+
);
|
|
146
|
+
if (!checked.ok) return { error: checked.error };
|
|
147
|
+
const definition = checked.definition;
|
|
148
|
+
if (definition.manifest.componentId !== component.componentId)
|
|
149
|
+
return {
|
|
150
|
+
error:
|
|
151
|
+
'Config componentId does not match manifest.componentId',
|
|
152
|
+
};
|
|
153
|
+
if (
|
|
154
|
+
definition.manifest.supportedPageTypes &&
|
|
155
|
+
!definition.manifest.supportedPageTypes.includes(
|
|
156
|
+
component.pageType,
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
return {
|
|
160
|
+
error: 'Manifest does not support configured pageType',
|
|
161
|
+
};
|
|
162
|
+
if (Array.isArray(definition.defaultSettings))
|
|
163
|
+
return {
|
|
164
|
+
error: 'defaultSettings must be an object, not an array',
|
|
165
|
+
};
|
|
166
|
+
return { manifest: definition.manifest };
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return { error: String(error) };
|
|
169
|
+
} finally {
|
|
170
|
+
URL.revokeObjectURL(url);
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
{ source, component: components[i] },
|
|
174
|
+
),
|
|
175
|
+
new Promise((_, reject) => {
|
|
176
|
+
timer = setTimeout(
|
|
177
|
+
() =>
|
|
178
|
+
reject(
|
|
179
|
+
new Error('Component validation timed out after 10 seconds'),
|
|
180
|
+
),
|
|
181
|
+
10000,
|
|
182
|
+
);
|
|
183
|
+
}),
|
|
184
|
+
]).finally(() => clearTimeout(timer));
|
|
185
|
+
if (result.error)
|
|
186
|
+
throw new Error(`${artifact.componentId}: ${result.error}`);
|
|
187
|
+
manifests.push(result.manifest);
|
|
188
|
+
}
|
|
189
|
+
return manifests;
|
|
190
|
+
} finally {
|
|
191
|
+
if (browser) await browser.close();
|
|
192
|
+
await new Promise((done) => server.close(done));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
function configDirectory() {
|
|
196
|
+
return fileURLToPath(new URL('../../', import.meta.url));
|
|
197
|
+
}
|
|
198
|
+
export async function validateProject(root, options = {}) {
|
|
199
|
+
const config = await readConfig(root);
|
|
200
|
+
const before = await sourceFingerprint(config.src);
|
|
201
|
+
const components = options.componentId
|
|
202
|
+
? config.components.filter(
|
|
203
|
+
(item) => item.componentId === options.componentId,
|
|
204
|
+
)
|
|
205
|
+
: config.components;
|
|
206
|
+
if (!components.length)
|
|
207
|
+
throw new Error('Requested componentId is not configured');
|
|
208
|
+
checkTypes(config);
|
|
209
|
+
const artifacts = [];
|
|
210
|
+
for (const item of components)
|
|
211
|
+
artifacts.push(await buildArtifact(config, item));
|
|
212
|
+
const manifests = await validateDefinitions(artifacts, components, options);
|
|
213
|
+
if (before !== (await sourceFingerprint(config.src)))
|
|
214
|
+
throw new Error('Source changed during validation; no files were written');
|
|
215
|
+
const directory = resolve(root, config.outDir);
|
|
216
|
+
const temporary = [];
|
|
217
|
+
try {
|
|
218
|
+
if (options.write) {
|
|
219
|
+
await mkdir(directory, { recursive: true });
|
|
220
|
+
for (const artifact of artifacts) {
|
|
221
|
+
const file = resolve(
|
|
222
|
+
directory,
|
|
223
|
+
artifact.fileName + `.${process.pid}.tmp`,
|
|
224
|
+
);
|
|
225
|
+
temporary.push(file);
|
|
226
|
+
await writeFile(file, artifact.sourceText, { flag: 'wx' });
|
|
227
|
+
}
|
|
228
|
+
for (let i = 0; i < artifacts.length; i++)
|
|
229
|
+
await rename(temporary[i], resolve(directory, artifacts[i].fileName));
|
|
230
|
+
}
|
|
231
|
+
} finally {
|
|
232
|
+
for (const file of temporary) await unlink(file).catch(() => {});
|
|
233
|
+
}
|
|
234
|
+
for (let i = 0; i < artifacts.length; i++)
|
|
235
|
+
console.log(
|
|
236
|
+
JSON.stringify({
|
|
237
|
+
componentId: artifacts[i].componentId,
|
|
238
|
+
manifest: manifests[i],
|
|
239
|
+
bytes: Buffer.byteLength(artifacts[i].sourceText),
|
|
240
|
+
sha256: artifacts[i].sourceHash,
|
|
241
|
+
...(options.write
|
|
242
|
+
? { path: resolve(directory, artifacts[i].fileName) }
|
|
243
|
+
: { validated: true }),
|
|
244
|
+
}),
|
|
245
|
+
);
|
|
246
|
+
return artifacts;
|
|
247
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { parse } from "acorn";
|
|
2
|
+
function validateDynamicArtifactSource(source) {
|
|
3
|
+
if (!source.trim())
|
|
4
|
+
throw new Error("The production component file is empty.");
|
|
5
|
+
if (new TextEncoder().encode(source).byteLength > 1024 * 1024) {
|
|
6
|
+
throw new Error("Component source exceeds 1 MB.");
|
|
7
|
+
}
|
|
8
|
+
let program;
|
|
9
|
+
try {
|
|
10
|
+
program = parse(source, { ecmaVersion: "latest", sourceType: "module" });
|
|
11
|
+
} catch {
|
|
12
|
+
throw new Error("Upload a compiled JavaScript ES module.");
|
|
13
|
+
}
|
|
14
|
+
const allowed = /* @__PURE__ */ new Set([
|
|
15
|
+
"react",
|
|
16
|
+
"react/jsx-runtime",
|
|
17
|
+
"react/jsx-dev-runtime",
|
|
18
|
+
"react-dom",
|
|
19
|
+
"react-dom/client"
|
|
20
|
+
]);
|
|
21
|
+
const dependencyError = () => {
|
|
22
|
+
throw new Error(
|
|
23
|
+
"Component must be a single ESM file with only platform React imports."
|
|
24
|
+
);
|
|
25
|
+
};
|
|
26
|
+
const visit = (node) => {
|
|
27
|
+
const value = node;
|
|
28
|
+
if ([
|
|
29
|
+
"ImportDeclaration",
|
|
30
|
+
"ExportNamedDeclaration",
|
|
31
|
+
"ExportAllDeclaration"
|
|
32
|
+
].includes(node.type) && value.source && !allowed.has(value.source.value))
|
|
33
|
+
dependencyError();
|
|
34
|
+
if (node.type === "ImportExpression" || node.type === "CallExpression" && value.callee?.type === "Identifier" && value.callee.name === "require")
|
|
35
|
+
dependencyError();
|
|
36
|
+
if (node.type === "MemberExpression" && value.object?.type === "MetaProperty" && value.object.meta.name === "import" && value.object.property.name === "meta" && (value.property.name === "hot" || value.property.value === "hot")) {
|
|
37
|
+
throw new Error("Upload a production artifact without HMR.");
|
|
38
|
+
}
|
|
39
|
+
const internalName = node.type === "Identifier" ? value.name : node.type === "Literal" ? value.value : void 0;
|
|
40
|
+
if (typeof internalName === "string" && [
|
|
41
|
+
"__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED",
|
|
42
|
+
"__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE"
|
|
43
|
+
].includes(internalName)) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
"Use platform React imports instead of bundling the React runtime."
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
for (const child of Object.values(value)) {
|
|
49
|
+
if (Array.isArray(child)) {
|
|
50
|
+
for (const item of child)
|
|
51
|
+
if (item && typeof item.type === "string") visit(item);
|
|
52
|
+
} else if (child && typeof child === "object" && typeof child.type === "string")
|
|
53
|
+
visit(child);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
visit(program);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
import { parse as parse2 } from "acorn";
|
|
60
|
+
function rewriteProductionReactImports(source, urls) {
|
|
61
|
+
const bridges = {
|
|
62
|
+
react: urls.react,
|
|
63
|
+
"react-dom": urls.reactDom,
|
|
64
|
+
"react-dom/client": urls.reactDomClient,
|
|
65
|
+
"react/jsx-runtime": urls.jsxRuntime,
|
|
66
|
+
"react/jsx-dev-runtime": urls.jsxDevRuntime
|
|
67
|
+
};
|
|
68
|
+
const program = parse2(source, {
|
|
69
|
+
ecmaVersion: "latest",
|
|
70
|
+
sourceType: "module"
|
|
71
|
+
});
|
|
72
|
+
const replacements = program.body.flatMap(
|
|
73
|
+
(node) => node.source && bridges[node.source.value] ? [
|
|
74
|
+
{
|
|
75
|
+
start: node.source.start,
|
|
76
|
+
end: node.source.end,
|
|
77
|
+
url: bridges[node.source.value]
|
|
78
|
+
}
|
|
79
|
+
] : []
|
|
80
|
+
);
|
|
81
|
+
for (const replacement of replacements.reverse())
|
|
82
|
+
source = source.slice(0, replacement.start) + JSON.stringify(replacement.url) + source.slice(replacement.end);
|
|
83
|
+
return source;
|
|
84
|
+
}
|
|
85
|
+
export {
|
|
86
|
+
rewriteProductionReactImports,
|
|
87
|
+
validateDynamicArtifactSource
|
|
88
|
+
};
|