@bestcheckout/dynamic-component-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ };
@@ -0,0 +1,96 @@
1
+ var offerRecommendationKeys = [
2
+ "recommendationRule",
3
+ "maximumProducts",
4
+ "specificProducts",
5
+ "defaultProducts",
6
+ "productMappings",
7
+ "fillDefaultProducts",
8
+ "discountType",
9
+ "discountValue"
10
+ ];
11
+
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null;
14
+ }
15
+ function isPageType(value) {
16
+ return value === "checkout" || value === "upsell" || value === "downsell" || value === "thankYou";
17
+ }
18
+ function validateDynamicManifest(value) {
19
+ if (!isRecord(value))
20
+ return { ok: false, error: "manifest must be an object" };
21
+ if (typeof value.componentId !== "string" || !/^[a-z0-9_-]{1,64}$/.test(value.componentId)) {
22
+ return {
23
+ ok: false,
24
+ error: "manifest.componentId must use 1\u201364 lowercase letters, numbers, underscores or hyphens"
25
+ };
26
+ }
27
+ if (typeof value.name !== "string" || !value.name.trim() || [...value.name.trim()].length > 128) {
28
+ return { ok: false, error: "manifest.name is required" };
29
+ }
30
+ if ("dataRequirements" in value) {
31
+ return {
32
+ ok: false,
33
+ error: "manifest.dataRequirements is not supported; use runtime snapshots and subscriptions"
34
+ };
35
+ }
36
+ if ("errorContent" in value) {
37
+ return {
38
+ ok: false,
39
+ error: "manifest.errorContent is not supported"
40
+ };
41
+ }
42
+ if (value.supportedPageTypes !== void 0 && (!Array.isArray(value.supportedPageTypes) || value.supportedPageTypes.some((item) => !isPageType(item)))) {
43
+ return { ok: false, error: "manifest.supportedPageTypes is invalid" };
44
+ }
45
+ if (value.capabilities !== void 0 && (!isRecord(value.capabilities) || Array.isArray(value.capabilities) || value.capabilities.offerRecommendation !== void 0 && typeof value.capabilities.offerRecommendation !== "boolean")) {
46
+ return {
47
+ ok: false,
48
+ error: "manifest.capabilities.offerRecommendation must be a boolean"
49
+ };
50
+ }
51
+ return { ok: true, manifest: value };
52
+ }
53
+ function validateDynamicComponentDefinition(value) {
54
+ if (!isRecord(value))
55
+ return { ok: false, error: "definition must be an object" };
56
+ const manifestResult = validateDynamicManifest(value.manifest);
57
+ if (!manifestResult.ok) return manifestResult;
58
+ if (!isRecord(value.defaultSettings)) {
59
+ return { ok: false, error: "defaultSettings must be an object" };
60
+ }
61
+ if (!isRecord(value.schema) && !Array.isArray(value.schema)) {
62
+ return { ok: false, error: "schema must be an object or array" };
63
+ }
64
+ if (manifestResult.manifest.capabilities?.offerRecommendation) {
65
+ const fields = Array.isArray(value.schema) ? value.schema : value.schema.fields;
66
+ if (Array.isArray(fields) && fields.some(
67
+ (field) => isRecord(field) && offerRecommendationKeys.includes(
68
+ field.key
69
+ )
70
+ ))
71
+ return {
72
+ ok: false,
73
+ error: "Offer recommendation fields are provided by the platform; remove duplicate schema keys"
74
+ };
75
+ }
76
+ const hasComponent = typeof value.Component === "function";
77
+ if (!hasComponent) {
78
+ return {
79
+ ok: false,
80
+ error: "Component must be a function"
81
+ };
82
+ }
83
+ if ("renderError" in value) {
84
+ return { ok: false, error: "renderError is not supported" };
85
+ }
86
+ if (value.styles !== void 0 && typeof value.styles !== "string") {
87
+ return { ok: false, error: "styles must be a string" };
88
+ }
89
+ return {
90
+ ok: true,
91
+ definition: value
92
+ };
93
+ }
94
+ export {
95
+ validateDynamicComponentDefinition
96
+ };
@@ -0,0 +1,56 @@
1
+ # Dynamic component project
2
+
3
+ ## Start development
4
+
5
+ Use Node.js >=20.10 and npm. From this project directory:
6
+
7
+ ```bash
8
+ npm install
9
+ npx playwright install chromium
10
+ npm run dev
11
+ ```
12
+
13
+ Chromium is required for build validation, including Editor Save. If a suitable browser is already installed, the browser download can be skipped; macOS Chrome can be detected automatically.
14
+
15
+ 1. Open the matching page type in the BestCheckout theme editor and add/select a custom component.
16
+ 2. Paste the terminal's component URL into **Component source → Local Dev Server source URL** and finish editing the field. The URL is a source module, not a standalone page.
17
+ 3. Edit the registered `src/<componentId>/component.tsx`. JSX and exported `styles` changes update the preview through HMR.
18
+ 4. Keep the server running and click **Save** in the Editor to build, validate and upload the artifact and save template configuration. Fix errors before retrying.
19
+ 5. Click **Publish** to apply the saved changes to the storefront. Stop the local server and refresh the storefront to check the published artifact.
20
+
21
+ For a custom port, run `npm run dev -- --port 5180` and reconnect using the newly printed URL. Ctrl+C stops the server.
22
+
23
+ ## Add components
24
+
25
+ ```bash
26
+ npx dynamic-component create offer-card --page-type upsell
27
+ npx dynamic-component create downsell-card --page-type downsell
28
+ npx dynamic-component create order-card --page-type thankYou
29
+ ```
30
+
31
+ Supported page types are exactly `checkout`, `upsell`, `downsell`, `thankYou`. IDs use 1–64 lowercase letters, digits, underscores or hyphens. Restart the server after adding components or changing `dynamic.config.json`.
32
+
33
+ The config registers local entry files; each entry's exported manifest must have the matching component ID and support its page type. Upsell/Downsell starters declare `offerRecommendation`; configure recommendation rules in the Editor.
34
+
35
+ ## Build and diagnose
36
+
37
+ ```bash
38
+ npm run build
39
+ npm run validate
40
+ npm run doctor
41
+ npx dynamic-component --help
42
+ ```
43
+
44
+ `build` type-checks and validates the components in a browser, then writes `dist/<componentId>.js` for manual upload. `validate` checks without writing artifacts. `doctor` diagnoses setup; it is optional. Editor Local Save calls the build automatically. Save/Publish remain Editor operations.
45
+
46
+ If Chromium is unavailable, install it using the command above. A manual build can use `npm run build -- --browser-executable "/absolute/path/to/browser"`; Editor-triggered builds can use `DYNAMIC_COMPONENT_BROWSER` set before starting the server.
47
+
48
+ ## Authoring and dependencies
49
+
50
+ Use `settings` for configured values and `runtime` for page capabilities. Public types come from `@bestcheckout/dynamic-component-cli/types`. Host React/ReactDOM and relative source-code imports inside `src` are supported. Arbitrary third-party runtime dependencies, source symlinks and imports outside `src` are not supported. Use exported `styles` and hosted URLs instead of CSS/image imports.
51
+
52
+ If initialized from a local archive, keep `vendor/dynamic-component-cli.tgz`; this project's dependency references it. Public dependencies still require registry access.
53
+
54
+ After a new CLI release, stop the server and explicitly upgrade the project dependency with `npm install --save-dev --save-exact @bestcheckout/dynamic-component-cli@latest`, install its Chromium if needed, then build and restart. Existing component source is not regenerated.
55
+
56
+ The CLI package uses the MIT license; your generated project does not automatically receive a license declaration. No platform credentials are stored by the CLI. Preview and validation execute component code in a browser and are not a sandbox. Windows/Linux, Safari/Firefox and production HTTPS Editor compatibility have not yet been fully verified.
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "jsx": "react-jsx",
7
+ "strict": true,
8
+ "noEmit": true,
9
+ "skipLibCheck": false,
10
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
11
+ "types": ["react", "react-dom"]
12
+ },
13
+ "include": ["src/**/*.tsx", "src/**/*.ts", "src/**/*.jsx"]
14
+ }