@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.
- package/LICENSE +21 -0
- package/README.md +147 -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 +56 -0
- package/templates/starter/tsconfig.json +14 -0
- package/types/index.d.ts +1230 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BestCheckout contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bestcheckout/dynamic-component-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Create and develop custom React components for BestCheckout's Checkout, Upsell, Downsell and Thank You pages. The CLI includes project generation, a local Dev Server with HMR, validation and single-file production builds. It works without the Admin, Shop Visual or old Dev Server source repositories.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js >=20.10 and npm. The package has been tested on macOS with Node 22.22.1 and 24.14.1; the minimum Node version, Windows and Linux have not yet been verified.
|
|
8
|
+
- Internet access to install public npm dependencies.
|
|
9
|
+
- Access to a BestCheckout theme editor with custom components and permission to save/publish your target template.
|
|
10
|
+
- Chromium for build validation, including builds requested by Editor Save. Install it as shown below. On macOS, an existing Google Chrome installation can also be detected automatically.
|
|
11
|
+
|
|
12
|
+
## Quick start
|
|
13
|
+
|
|
14
|
+
After the package is published to npm, run:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npx @bestcheckout/dynamic-component-cli@latest init my-components --component-id checkout-card --page-type checkout
|
|
18
|
+
cd my-components
|
|
19
|
+
npm install
|
|
20
|
+
npx playwright install chromium
|
|
21
|
+
npm run dev
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Use a new or empty project directory. No global CLI installation is required. Registry commands require a published version; before the first release, use the archive instructions below.
|
|
25
|
+
|
|
26
|
+
The terminal prints each component's Local URL. For the example above on the default port, it is:
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
http://localhost:5173/src/checkout-card/component.tsx
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Use the exact URL printed by your server. The source URL is a module for the Editor to load, not a standalone checkout webpage; the Editor supplies React and business data.
|
|
33
|
+
|
|
34
|
+
### Connect to the Editor
|
|
35
|
+
|
|
36
|
+
1. Open the target theme's Checkout template and add or select a custom component.
|
|
37
|
+
2. Under **Component source**, paste the source URL into **Local Dev Server source URL** and finish editing the field to connect.
|
|
38
|
+
3. Edit `src/checkout-card/component.tsx`. Change `Component` JSX or the exported `styles` string to see HMR updates in the preview. Edit the right-panel settings to test configuration separately.
|
|
39
|
+
4. Keep the Dev Server running and click **Save** in the Editor. It requests a production build, validates/uploads it and saves the template. Fix build errors and explicitly retry Save when needed.
|
|
40
|
+
5. Click **Publish** to make the saved component/template changes available to the storefront. A local preview alone does not update the storefront.
|
|
41
|
+
6. After a successful publish, stop the Dev Server and refresh the storefront to verify it uses the uploaded artifact.
|
|
42
|
+
|
|
43
|
+
The CLI does not log in to Admin, call resource CRUD APIs or publish templates. These actions remain in the Editor. Local URLs are development inputs and are not the production component source.
|
|
44
|
+
|
|
45
|
+
## Install from a supplied .tgz
|
|
46
|
+
|
|
47
|
+
No source checkout is needed. Replace both archive paths with the actual downloaded file:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npx --yes --package /absolute/path/dynamic-component-cli.tgz dynamic-component init my-components --component-id checkout-card --page-type checkout --cli-package /absolute/path/dynamic-component-cli.tgz
|
|
51
|
+
cd my-components
|
|
52
|
+
npm install
|
|
53
|
+
npx playwright install chromium
|
|
54
|
+
npm run dev
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`--cli-package` copies the archive into `vendor/` and installs that copy instead of fetching an unpublished CLI version from npm. Keep `vendor/` with this project. Installed third-party dependencies still require registry access; a `.tgz` is not a fully offline dependency bundle.
|
|
58
|
+
|
|
59
|
+
## Project files and additional components
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
my-components/
|
|
63
|
+
src/checkout-card/component.tsx
|
|
64
|
+
dynamic.config.json
|
|
65
|
+
package.json
|
|
66
|
+
tsconfig.json
|
|
67
|
+
README.md
|
|
68
|
+
dist/checkout-card.js # generated by npm run build
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Run these commands inside the generated project, after `npm install`:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
npx dynamic-component create offer-card --page-type upsell
|
|
75
|
+
npx dynamic-component create downsell-card --page-type downsell
|
|
76
|
+
npx dynamic-component create order-card --page-type thankYou
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Restart `npm run dev` after adding a component or changing `dynamic.config.json`. Ordinary source edits use HMR.
|
|
80
|
+
|
|
81
|
+
- Page types are exactly `checkout`, `upsell`, `downsell`, `thankYou` (case-sensitive).
|
|
82
|
+
- Component IDs use 1–64 lowercase letters, numbers, underscores or hyphens and must be unique within the project.
|
|
83
|
+
- `dynamic.config.json` registers local entry files. Keep its component ID and page type consistent with each exported `manifest`; mismatches fail validation.
|
|
84
|
+
- Upsell/Downsell starters declare `capabilities.offerRecommendation`. Configure their recommendation rules in the Editor before saving/publishing the offer template.
|
|
85
|
+
|
|
86
|
+
## Component authoring
|
|
87
|
+
|
|
88
|
+
The generated entry exports `manifest`, `schema`, `defaultSettings`, `styles` and a React `Component`, together with a default definition object. Use `settings` for configured values and `runtime` for the capabilities available on the current page. The starter includes a subscribed account example; editor autocomplete exposes the runtime types:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import type { DynamicComponentProps, DynamicComponentDefinition } from "@bestcheckout/dynamic-component-cli/types";
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Supported runtime imports are platform React/ReactDOM imports and relative code imports inside `src`. Arbitrary third-party runtime imports, Node APIs, source symlinks and imports outside `src` are not supported. Use an exported `styles` string and hosted asset URLs instead of importing CSS or image files. The Host provides React/ReactDOM through its bridge.
|
|
95
|
+
|
|
96
|
+
## Commands
|
|
97
|
+
|
|
98
|
+
Run project commands inside the generated project:
|
|
99
|
+
|
|
100
|
+
| Command | Purpose |
|
|
101
|
+
| --- | --- |
|
|
102
|
+
| `npm run dev` | Start the local server; Ctrl+C stops it |
|
|
103
|
+
| `npm run build` | Type-check, validate in a browser and write `dist/<componentId>.js` |
|
|
104
|
+
| `npm run validate` | Run validation without writing production artifacts |
|
|
105
|
+
| `npm run doctor` | Diagnose config, port and browser availability |
|
|
106
|
+
| `npx dynamic-component --help` | Show command options |
|
|
107
|
+
| `npx dynamic-component --version` | Show the installed CLI version |
|
|
108
|
+
|
|
109
|
+
For a manual upload, run `npm run build`, then upload the generated `.js` in the Editor and Save/Publish there. When using Local Save, the Editor requests the build automatically; you do not need to run `build` first. Failed builds do not replace existing output files.
|
|
110
|
+
|
|
111
|
+
## Troubleshooting
|
|
112
|
+
|
|
113
|
+
| Problem | Action |
|
|
114
|
+
| --- | --- |
|
|
115
|
+
| Port 5173 is occupied | Run `npm run dev -- --port 5180` and reconnect using the new printed URL |
|
|
116
|
+
| Editor cannot connect | Keep the server running on the same computer as the browser; check the URL and any browser local-network access prompt |
|
|
117
|
+
| Browser validation is unavailable | Run `npx playwright install chromium` inside the project, then retry |
|
|
118
|
+
| Use an existing browser | For manual builds, use `npm run build -- --browser-executable "/absolute/path/to/browser"`; for Editor-triggered builds, set `DYNAMIC_COMPONENT_BROWSER` in the shell that starts the Dev Server |
|
|
119
|
+
| Unsupported dependency or CSS import | Keep code imports inside `src`, use platform React imports, exported `styles` and hosted asset URLs |
|
|
120
|
+
| Component ID or page type mismatch | Match `dynamic.config.json` with the exported manifest; use a compatible Editor page type |
|
|
121
|
+
| Save fails while preview works | Review the error and run `npm run build`; production type checks and browser validation also apply to Local Save |
|
|
122
|
+
| Build is busy or times out | Wait for the active build to finish, reduce excessive source work if needed, then explicitly retry Save |
|
|
123
|
+
| New component URL is missing | Restart the server after `create` or configuration changes |
|
|
124
|
+
|
|
125
|
+
Builds support up to 500 source files, 1000 source-tree entries, 16 MiB of source and a 1 MiB artifact. Editor-requested builds run one at a time and time out after 45 seconds. Components run in the browser during preview/validation; this is not a sandbox for untrusted code. No platform credentials are stored by the CLI.
|
|
126
|
+
|
|
127
|
+
Windows/Linux, Safari/Firefox and production HTTPS Editor access remain outside the completed compatibility checks. `doctor` cannot change browser permissions.
|
|
128
|
+
|
|
129
|
+
## Upgrade
|
|
130
|
+
|
|
131
|
+
Projects pin the CLI version used to create them. After a newer version is published, stop the Dev Server and run:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
npm install --save-dev --save-exact @bestcheckout/dynamic-component-cli@latest
|
|
135
|
+
npx playwright install chromium
|
|
136
|
+
npm run build
|
|
137
|
+
npm run dev
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Review release changes before upgrading. Installing a new CLI does not overwrite your existing component source or regenerate the Starter. Update the project-local dependency even if you also installed the CLI globally.
|
|
141
|
+
|
|
142
|
+
## Maintainers
|
|
143
|
+
|
|
144
|
+
Source lives in `shop-visual/packages/dynamic-component-cli`. Types and validation are generated from the adjacent Renderer package; installed users do not need to run this synchronization. Tests, protocol synchronization and release steps are documented in `docs/dynamic-component-cli-publishing.md` in the source repository. These maintainer scripts are not shipped in the npm archive.
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT. See [LICENSE](./LICENSE). This license applies to this CLI package; it does not change the licenses of other platform packages or third-party dependencies.
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bestcheckout/dynamic-component-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "CLI and starter project generator for BestCheckout dynamic components",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"dynamic-component": "src/cli.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"types",
|
|
13
|
+
"templates",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test tests/*.test.mjs",
|
|
19
|
+
"pack:check": "npm pack --dry-run",
|
|
20
|
+
"test:integration": "node tests/standalone.integration.mjs",
|
|
21
|
+
"test:editor": "node scripts/test-editor.mjs",
|
|
22
|
+
"sync:protocol": "node scripts/sync-protocol.mjs",
|
|
23
|
+
"check:protocol": "node scripts/sync-protocol.mjs --check"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20.10.0"
|
|
27
|
+
},
|
|
28
|
+
"private": false,
|
|
29
|
+
"exports": {
|
|
30
|
+
"./types": {
|
|
31
|
+
"types": "./types/index.d.ts"
|
|
32
|
+
},
|
|
33
|
+
"./build": "./src/core/build.mjs",
|
|
34
|
+
"./react-bridge": "./src/core/react-bridge.mjs",
|
|
35
|
+
"./source-boundary": "./src/core/source-boundary.mjs"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"acorn": "8.15.0",
|
|
39
|
+
"esbuild": "0.21.5",
|
|
40
|
+
"playwright": "1.56.1",
|
|
41
|
+
"react": "18.3.1",
|
|
42
|
+
"react-dom": "18.3.1",
|
|
43
|
+
"typescript": "5.6.3",
|
|
44
|
+
"vite": "5.4.21"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public",
|
|
48
|
+
"registry": "https://registry.npmjs.org/"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"dts-bundle-generator": "9.5.1"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { initialize, createComponent } from './core/project.mjs';
|
|
6
|
+
|
|
7
|
+
const help = `Usage: dynamic-component <command> [arguments]
|
|
8
|
+
init <directory> --component-id <id> --page-type <checkout|upsell|downsell|thankYou>
|
|
9
|
+
[--cli-package <local.tgz>] Use a local package before registry distribution.
|
|
10
|
+
create <id> --page-type <type> [--project <directory>]
|
|
11
|
+
dev [--project <directory>] [--port <port>]
|
|
12
|
+
validate [--project <directory>] [--browser-executable <path>]
|
|
13
|
+
build [--project <directory>] [--component-id <id>] [--browser-executable <path>]
|
|
14
|
+
doctor [--project <directory>] [--port <port>] [--browser-executable <path>]
|
|
15
|
+
`;
|
|
16
|
+
try {
|
|
17
|
+
const { values, positionals } = parseArgs({
|
|
18
|
+
allowPositionals: true,
|
|
19
|
+
options: {
|
|
20
|
+
help: { type: 'boolean', short: 'h' },
|
|
21
|
+
version: { type: 'boolean' },
|
|
22
|
+
project: { type: 'string' },
|
|
23
|
+
'component-id': { type: 'string' },
|
|
24
|
+
'page-type': { type: 'string' },
|
|
25
|
+
'cli-package': { type: 'string' },
|
|
26
|
+
port: { type: 'string' },
|
|
27
|
+
'browser-executable': { type: 'string' },
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
const [command, argument, ...extra] = positionals;
|
|
31
|
+
if (extra.length) throw new Error('Unexpected positional arguments');
|
|
32
|
+
const accepted = {
|
|
33
|
+
init: ['component-id', 'page-type', 'cli-package'],
|
|
34
|
+
create: ['project', 'page-type'],
|
|
35
|
+
dev: ['project', 'port'],
|
|
36
|
+
validate: ['project', 'browser-executable'],
|
|
37
|
+
build: ['project', 'component-id', 'browser-executable'],
|
|
38
|
+
doctor: ['project', 'port', 'browser-executable'],
|
|
39
|
+
};
|
|
40
|
+
if (accepted[command] && !values.help && !values.version) {
|
|
41
|
+
for (const key of Object.keys(values))
|
|
42
|
+
if (!accepted[command].includes(key))
|
|
43
|
+
throw new Error(`--${key} is not supported by ${command}`);
|
|
44
|
+
if (argument && !['init', 'create'].includes(command))
|
|
45
|
+
throw new Error(`${command} does not accept positional arguments`);
|
|
46
|
+
}
|
|
47
|
+
const root = resolve(values.project || process.cwd());
|
|
48
|
+
if (values.version) console.log(JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version);
|
|
49
|
+
else if (values.help || !command) console.log(help);
|
|
50
|
+
else if (command === 'init') {
|
|
51
|
+
if (!argument) throw new Error('init requires a new directory');
|
|
52
|
+
await initialize(resolve(argument), values);
|
|
53
|
+
} else if (command === 'create') {
|
|
54
|
+
if (!argument) throw new Error('create requires a componentId');
|
|
55
|
+
await createComponent(root, argument, values['page-type'] || 'checkout');
|
|
56
|
+
} else if (command === 'dev') {
|
|
57
|
+
const { serveProject } = await import('./core/server.mjs');
|
|
58
|
+
const server = await serveProject(root, { port: values.port });
|
|
59
|
+
const close = async () => {
|
|
60
|
+
await server.close();
|
|
61
|
+
process.exit(0);
|
|
62
|
+
};
|
|
63
|
+
process.once('SIGINT', close);
|
|
64
|
+
process.once('SIGTERM', close);
|
|
65
|
+
} else if (command === 'build' || command === 'validate') {
|
|
66
|
+
const { validateProject } = await import('./core/validate.mjs');
|
|
67
|
+
await validateProject(root, {
|
|
68
|
+
write: command === 'build',
|
|
69
|
+
componentId: values['component-id'],
|
|
70
|
+
executablePath: values['browser-executable'],
|
|
71
|
+
});
|
|
72
|
+
} else if (command === 'doctor') {
|
|
73
|
+
const { diagnose } = await import('./core/doctor.mjs');
|
|
74
|
+
if (
|
|
75
|
+
!(await diagnose(root, {
|
|
76
|
+
port: values.port,
|
|
77
|
+
executablePath: values['browser-executable'],
|
|
78
|
+
}))
|
|
79
|
+
)
|
|
80
|
+
process.exitCode = 1;
|
|
81
|
+
} else throw new Error(`Unknown command: ${command}`);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
console.error(
|
|
84
|
+
`dynamic-component: ${error instanceof Error ? error.message : String(error)}`,
|
|
85
|
+
);
|
|
86
|
+
process.exitCode = 1;
|
|
87
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { chromium } from 'playwright';
|
|
3
|
+
export function browserPath(explicit) {
|
|
4
|
+
if (explicit) return explicit;
|
|
5
|
+
if (process.env.DYNAMIC_COMPONENT_BROWSER)
|
|
6
|
+
return process.env.DYNAMIC_COMPONENT_BROWSER;
|
|
7
|
+
if (existsSync(chromium.executablePath())) return undefined;
|
|
8
|
+
const chrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
|
9
|
+
if (process.platform === 'darwin' && existsSync(chrome)) return chrome;
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
export async function launchBrowser(explicit) {
|
|
13
|
+
try {
|
|
14
|
+
return await chromium.launch({
|
|
15
|
+
headless: true,
|
|
16
|
+
executablePath: browserPath(explicit),
|
|
17
|
+
});
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error(
|
|
20
|
+
'Browser validation is unavailable. Run npx playwright install chromium, or pass --browser-executable <path>. No validation step was skipped.',
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
/** Fixed tool worker only: merchant modules are transformed, never imported in Node. */
|
|
3
|
+
export async function runBuildWorker(workerUrl, input, { timeoutMs = 45_000 } = {}) {
|
|
4
|
+
const worker = new Worker(workerUrl, {workerData: input, resourceLimits: {maxOldGenerationSizeMb: 256}});
|
|
5
|
+
let timer;
|
|
6
|
+
try {
|
|
7
|
+
return await new Promise((resolve, reject) => {
|
|
8
|
+
timer = setTimeout(() => reject(Object.assign(new Error('Local build timed out. Review source and save again.'), {statusCode: 504})), timeoutMs);
|
|
9
|
+
worker.once('message', value => value.ok ? resolve(value.artifact) : reject(new Error(value.message)));
|
|
10
|
+
worker.once('error', reject);
|
|
11
|
+
worker.once('exit', () => reject(new Error('Local build worker stopped before returning an artifact.')));
|
|
12
|
+
});
|
|
13
|
+
} finally {
|
|
14
|
+
clearTimeout(timer);
|
|
15
|
+
// Wait for termination before releasing the single-build gate, even on timeout.
|
|
16
|
+
await worker.terminate();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export const BUILD_SESSION_TTL_MS = 60_000;
|
|
4
|
+
function failure(statusCode, message) {
|
|
5
|
+
return Object.assign(new Error(message), { statusCode });
|
|
6
|
+
}
|
|
7
|
+
/** Process-local, single-use credentials. Never serialize this store or log headers. */
|
|
8
|
+
export function createBuildSessions({ now = Date.now } = {}) {
|
|
9
|
+
const sessions = new Map();
|
|
10
|
+
let windowStart = now();
|
|
11
|
+
let issued = 0;
|
|
12
|
+
let closed = false;
|
|
13
|
+
function prune() {
|
|
14
|
+
const time = now();
|
|
15
|
+
for (const [token, session] of sessions) if (session.expiresAt <= time) sessions.delete(token);
|
|
16
|
+
if (time - windowStart >= 60_000) { windowStart = time; issued = 0; }
|
|
17
|
+
return time;
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
issue(binding) {
|
|
21
|
+
const time = prune();
|
|
22
|
+
if (closed) throw failure(503, 'Dev Server is closing');
|
|
23
|
+
if (sessions.size >= 64 || issued >= 120)
|
|
24
|
+
throw failure(429, 'Too many build sessions. Wait and retry.');
|
|
25
|
+
const token = randomBytes(32).toString('base64url');
|
|
26
|
+
const expiresAt = time + BUILD_SESSION_TTL_MS;
|
|
27
|
+
sessions.set(token, { sourceUrl: binding.sourceUrl, componentId: binding.componentId, expiresAt });
|
|
28
|
+
issued++;
|
|
29
|
+
return { token, expiresAt };
|
|
30
|
+
},
|
|
31
|
+
consume(authorization, binding) {
|
|
32
|
+
const token = typeof authorization === 'string' && /^Bearer [A-Za-z0-9_-]{43}$/.test(authorization)
|
|
33
|
+
? authorization.slice(7) : '';
|
|
34
|
+
const time = prune();
|
|
35
|
+
const session = sessions.get(token);
|
|
36
|
+
// Any presentation consumes it, including a wrong binding or failed build.
|
|
37
|
+
sessions.delete(token);
|
|
38
|
+
if (closed || !session || session.expiresAt <= time)
|
|
39
|
+
throw failure(401, 'Build session is missing, expired or already used. Save again to retry.');
|
|
40
|
+
if (session.sourceUrl !== binding.sourceUrl || session.componentId !== binding.componentId)
|
|
41
|
+
throw failure(403, 'Build session does not match this source or component.');
|
|
42
|
+
},
|
|
43
|
+
close() { closed = true; sessions.clear(); },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Bound both the bytes and time spent waiting for a local protocol body. */
|
|
48
|
+
export async function readBuildInput(request, {timeoutMs = 10_000} = {}) {
|
|
49
|
+
let timer;
|
|
50
|
+
const body = (async () => {
|
|
51
|
+
const parts = [];
|
|
52
|
+
let length = 0;
|
|
53
|
+
for await (const part of request) {
|
|
54
|
+
length += part.length;
|
|
55
|
+
if (length > 65536) throw failure(413, 'Build request exceeds 64 KiB.');
|
|
56
|
+
parts.push(part);
|
|
57
|
+
}
|
|
58
|
+
return JSON.parse(Buffer.concat(parts).toString('utf8'));
|
|
59
|
+
})();
|
|
60
|
+
try {
|
|
61
|
+
return await Promise.race([body, new Promise((_, reject) => {
|
|
62
|
+
timer = setTimeout(() => {
|
|
63
|
+
reject(failure(408, 'Build request body timed out.'));
|
|
64
|
+
request.destroy();
|
|
65
|
+
}, timeoutMs);
|
|
66
|
+
timer.unref?.();
|
|
67
|
+
})]);
|
|
68
|
+
} finally { clearTimeout(timer); }
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import { buildSingleDynamicArtifact } from './build.mjs';
|
|
3
|
+
try {
|
|
4
|
+
const artifact = await buildSingleDynamicArtifact(workerData.sourceUrl, workerData.componentId, workerData.options);
|
|
5
|
+
parentPort.postMessage({ok: true, artifact});
|
|
6
|
+
} catch (error) {
|
|
7
|
+
parentPort.postMessage({ok: false, message: error instanceof Error ? error.message : 'Local build failed'});
|
|
8
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import { resolve, relative } from 'node:path';
|
|
4
|
+
import { build } from 'esbuild';
|
|
5
|
+
import { assertId, inside, safeFile, sourceFiles } from './config.mjs';
|
|
6
|
+
import { buildBoundary } from './source-boundary.mjs';
|
|
7
|
+
import { validateDynamicArtifactSource } from '../protocol/artifact.mjs';
|
|
8
|
+
export async function sourceFingerprint(src) {
|
|
9
|
+
const hash = createHash('sha256');
|
|
10
|
+
let size = 0;
|
|
11
|
+
const files = await sourceFiles(src);
|
|
12
|
+
if (files.length > 500) throw new Error('Source tree exceeds 500 files');
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
size += (await stat(file)).size;
|
|
15
|
+
if (size > 16 * 1024 * 1024) throw new Error('Source tree exceeds 16 MiB');
|
|
16
|
+
const bytes = await readFile(file);
|
|
17
|
+
if (bytes.length > 16 * 1024 * 1024) throw new Error('Source file exceeds 16 MiB');
|
|
18
|
+
hash.update(relative(src, file)).update('\0').update(bytes).update('\0');
|
|
19
|
+
}
|
|
20
|
+
return hash.digest('hex');
|
|
21
|
+
}
|
|
22
|
+
// Shared by CLI build and Editor Local Save. Transform only; no Node import of merchant source.
|
|
23
|
+
export async function buildArtifact(config, component) {
|
|
24
|
+
assertId(component.componentId);
|
|
25
|
+
const entry = await safeFile(
|
|
26
|
+
config.src,
|
|
27
|
+
resolve(config.root, component.entry),
|
|
28
|
+
);
|
|
29
|
+
const before = await sourceFingerprint(config.src);
|
|
30
|
+
const result = await build({
|
|
31
|
+
absWorkingDir: config.root,
|
|
32
|
+
entryPoints: [entry],
|
|
33
|
+
bundle: true,
|
|
34
|
+
write: false,
|
|
35
|
+
format: 'esm',
|
|
36
|
+
platform: 'browser',
|
|
37
|
+
target: 'es2020',
|
|
38
|
+
jsx: 'automatic',
|
|
39
|
+
logLevel: 'silent',
|
|
40
|
+
tsconfigRaw: { compilerOptions: { jsx: 'react-jsx' } },
|
|
41
|
+
plugins: [buildBoundary(config.src)],
|
|
42
|
+
metafile: true,
|
|
43
|
+
});
|
|
44
|
+
if (result.outputFiles.length !== 1)
|
|
45
|
+
throw new Error(
|
|
46
|
+
'Build must produce one JavaScript file without assets or chunks',
|
|
47
|
+
);
|
|
48
|
+
if (before !== (await sourceFingerprint(config.src)))
|
|
49
|
+
throw new Error('Source changed during build. Review and retry.');
|
|
50
|
+
const sourceText = result.outputFiles[0].text;
|
|
51
|
+
validateDynamicArtifactSource(sourceText);
|
|
52
|
+
return {
|
|
53
|
+
componentId: component.componentId,
|
|
54
|
+
fileName: component.componentId + '.js',
|
|
55
|
+
sourceText,
|
|
56
|
+
sourceHash: createHash('sha256').update(sourceText).digest('hex'),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export async function buildSingleDynamicArtifact(
|
|
60
|
+
sourceUrl,
|
|
61
|
+
componentId,
|
|
62
|
+
options,
|
|
63
|
+
) {
|
|
64
|
+
assertId(componentId);
|
|
65
|
+
const config = options.config;
|
|
66
|
+
const url = new URL(sourceUrl);
|
|
67
|
+
if (
|
|
68
|
+
url.origin !== options.origin ||
|
|
69
|
+
url.username ||
|
|
70
|
+
url.password ||
|
|
71
|
+
url.hash ||
|
|
72
|
+
url.search ||
|
|
73
|
+
!url.pathname.startsWith('/src/')
|
|
74
|
+
)
|
|
75
|
+
throw new Error(
|
|
76
|
+
'sourceUrl must point to a registered entry on this Dev Server',
|
|
77
|
+
);
|
|
78
|
+
const entry = decodeURIComponent(url.pathname.slice(1));
|
|
79
|
+
const component = config.components.find(
|
|
80
|
+
(item) => item.componentId === componentId && item.entry === entry,
|
|
81
|
+
);
|
|
82
|
+
if (!component)
|
|
83
|
+
throw new Error('componentId/sourceUrl does not match dynamic.config.json');
|
|
84
|
+
return buildArtifact(config, component);
|
|
85
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { readFile, realpath, lstat, readdir } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
3
|
+
export const idPattern = /^[a-z0-9_-]{1,64}$/;
|
|
4
|
+
export const pageTypes = ['checkout', 'upsell', 'downsell', 'thankYou'];
|
|
5
|
+
export const configName = 'dynamic.config.json';
|
|
6
|
+
export function inside(root, file) {
|
|
7
|
+
const rel = relative(root, file);
|
|
8
|
+
return (
|
|
9
|
+
rel === '' ||
|
|
10
|
+
(!isAbsolute(rel) &&
|
|
11
|
+
rel !== '..' &&
|
|
12
|
+
!rel.startsWith('../') &&
|
|
13
|
+
!rel.startsWith('..\\'))
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
export function assertId(id) {
|
|
17
|
+
if (typeof id !== 'string' || !idPattern.test(id))
|
|
18
|
+
throw new Error(
|
|
19
|
+
'componentId must use 1–64 lowercase letters, numbers, underscores or hyphens',
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
export function assertPageType(type) {
|
|
23
|
+
if (!pageTypes.includes(type))
|
|
24
|
+
throw new Error(`pageType must be one of ${pageTypes.join(', ')}`);
|
|
25
|
+
}
|
|
26
|
+
export function portNumber(value) {
|
|
27
|
+
const port = Number(value);
|
|
28
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535)
|
|
29
|
+
throw new Error('port must be an integer from 1024 to 65535');
|
|
30
|
+
return port;
|
|
31
|
+
}
|
|
32
|
+
export async function safeFile(base, file) {
|
|
33
|
+
if (!inside(base, file)) throw new Error('Source path must stay inside src');
|
|
34
|
+
const actual = await realpath(file);
|
|
35
|
+
if (!inside(await realpath(base), actual))
|
|
36
|
+
throw new Error('Symlink escapes src');
|
|
37
|
+
return actual;
|
|
38
|
+
}
|
|
39
|
+
export async function readConfig(root, overrides = {}) {
|
|
40
|
+
root = await realpath(root);
|
|
41
|
+
const file = resolve(root, configName);
|
|
42
|
+
if ((await lstat(file)).isSymbolicLink())
|
|
43
|
+
throw new Error('Project config must not be a symlink');
|
|
44
|
+
const config = JSON.parse(await readFile(file, 'utf8'));
|
|
45
|
+
if (
|
|
46
|
+
config.protocolVersion !== 1 ||
|
|
47
|
+
!Array.isArray(config.components) ||
|
|
48
|
+
!config.components.length
|
|
49
|
+
)
|
|
50
|
+
throw new Error(
|
|
51
|
+
'Invalid dynamic.config.json: protocolVersion=1 and components are required',
|
|
52
|
+
);
|
|
53
|
+
const ids = new Set();
|
|
54
|
+
const entries = new Set();
|
|
55
|
+
const src = resolve(root, 'src');
|
|
56
|
+
if ((await lstat(src)).isSymbolicLink())
|
|
57
|
+
throw new Error('src must not be a symlink');
|
|
58
|
+
for (const item of config.components) {
|
|
59
|
+
assertId(item.componentId);
|
|
60
|
+
assertPageType(item.pageType);
|
|
61
|
+
if (ids.has(item.componentId) || entries.has(item.entry))
|
|
62
|
+
throw new Error('Duplicate componentId or entry');
|
|
63
|
+
ids.add(item.componentId);
|
|
64
|
+
entries.add(item.entry);
|
|
65
|
+
if (
|
|
66
|
+
typeof item.entry !== 'string' ||
|
|
67
|
+
!item.entry.startsWith('src/') ||
|
|
68
|
+
!/\.(jsx|tsx)$/.test(item.entry)
|
|
69
|
+
)
|
|
70
|
+
throw new Error('Entry must be JSX/TSX inside src/');
|
|
71
|
+
await safeFile(src, resolve(root, item.entry));
|
|
72
|
+
}
|
|
73
|
+
const outDir = config.outDir || 'dist';
|
|
74
|
+
if (
|
|
75
|
+
!/^[a-zA-Z0-9_-]+$/.test(outDir) ||
|
|
76
|
+
['src', 'node_modules'].includes(outDir)
|
|
77
|
+
)
|
|
78
|
+
throw new Error('outDir must be a separate project subdirectory');
|
|
79
|
+
try {
|
|
80
|
+
if ((await lstat(resolve(root, outDir))).isSymbolicLink())
|
|
81
|
+
throw new Error('outDir must not be a symlink');
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code !== 'ENOENT') throw error;
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
...config,
|
|
87
|
+
root,
|
|
88
|
+
src,
|
|
89
|
+
outDir,
|
|
90
|
+
server: {
|
|
91
|
+
port: portNumber(overrides.port ?? config.server?.port ?? 5173),
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export async function sourceFiles(directory) {
|
|
96
|
+
const files = [];
|
|
97
|
+
let entriesSeen = 0;
|
|
98
|
+
async function visit(dir) {
|
|
99
|
+
for (const item of (await readdir(dir, { withFileTypes: true })).sort(
|
|
100
|
+
(a, b) => a.name.localeCompare(b.name),
|
|
101
|
+
)) {
|
|
102
|
+
if (++entriesSeen > 1000) throw new Error('Source tree exceeds 1000 entries');
|
|
103
|
+
const file = resolve(dir, item.name);
|
|
104
|
+
if (item.isSymbolicLink())
|
|
105
|
+
throw new Error('Symlinks are not supported in component source');
|
|
106
|
+
if (item.isDirectory()) await visit(file);
|
|
107
|
+
else if (item.isFile()) {
|
|
108
|
+
if (files.length >= 500) throw new Error('Source tree exceeds 500 files');
|
|
109
|
+
files.push(file);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
await visit(directory);
|
|
114
|
+
return files;
|
|
115
|
+
}
|