@sbuilder/cli 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/README.md +49 -0
- package/dist/bin/wb.js +129 -0
- package/dist/bin/wb.js.map +1 -0
- package/dist/src/deploy.js +215 -0
- package/dist/src/deploy.js.map +1 -0
- package/dist/src/dev.js +184 -0
- package/dist/src/dev.js.map +1 -0
- package/dist/src/init.js +86 -0
- package/dist/src/init.js.map +1 -0
- package/dist/src/scaffold.js +238 -0
- package/dist/src/scaffold.js.map +1 -0
- package/dist/src/types.js +15 -0
- package/dist/src/types.js.map +1 -0
- package/package.json +25 -0
package/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# @sbuilder/cli
|
|
2
|
+
|
|
3
|
+
`wb` — scaffold, run and deploy an app for the Store Builder platform.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
wb init [name] [--port 3000] scaffold an app that runs, registers, and opens
|
|
7
|
+
inside a merchant's admin
|
|
8
|
+
wb dev upload an island's code to your DRAFT version
|
|
9
|
+
every time you save it. Reads wb.json; needs WB_TOKEN.
|
|
10
|
+
wb deploy [--submit] push the version's payload in dependency order.
|
|
11
|
+
--submit then sends it for review.
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Node 20 or newer. Written in TypeScript, published compiled — an installed copy
|
|
15
|
+
has no dependencies and nothing to build.
|
|
16
|
+
|
|
17
|
+
## The reference is served, not kept here
|
|
18
|
+
|
|
19
|
+
**Every command, every flag, the `wb.json` shape and every refusal are on the
|
|
20
|
+
`/cli-docs` page of your Store Builder deployment** — the same place as
|
|
21
|
+
`/app-docs` (building an app) and `/block-docs` (blocks and islands). That page
|
|
22
|
+
is the one this repository tests against: its commands are extracted from its own
|
|
23
|
+
bytes and run against `bin/wb.js`, so it cannot document a flag the CLI rejects.
|
|
24
|
+
|
|
25
|
+
This file deliberately does not repeat it. A second copy of a reference is two
|
|
26
|
+
documents that disagree by next month, and only one of them is checked.
|
|
27
|
+
|
|
28
|
+
## Not on npm yet
|
|
29
|
+
|
|
30
|
+
`@sbuilder/cli` has a complete publish workflow (`.github/workflows/publish-cli.yml`)
|
|
31
|
+
and no npm credential, so nothing has been published and `npx` will not find it.
|
|
32
|
+
Run it from a checkout instead — from the repository root:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm ci
|
|
36
|
+
npm run build --workspace cli
|
|
37
|
+
node cli/dist/bin/wb.js --help
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Working on it
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm run typecheck --prefix cli # tsc over bin, src AND tests
|
|
44
|
+
npm test --prefix cli # builds first, then vitest
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`npm test` builds before it runs, on purpose: the unit suites import `src/`, but
|
|
48
|
+
every test that spawns the command runs `dist/`, so what is proved is what
|
|
49
|
+
ships.
|
package/dist/bin/wb.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `wb` — the Store Builder app CLI.
|
|
4
|
+
*
|
|
5
|
+
* Dispatch only: every command's behaviour lives in src/ so it can be tested
|
|
6
|
+
* without spawning a process. This file's whole job is to turn argv into a call
|
|
7
|
+
* and an exit code.
|
|
8
|
+
*/
|
|
9
|
+
import { init, nextSteps, InitError } from '../src/init.js';
|
|
10
|
+
import { readConfig, watchAndUpload, DevError } from '../src/dev.js';
|
|
11
|
+
import { deploy, submit, DeployStopped } from '../src/deploy.js';
|
|
12
|
+
const USAGE = `wb — build an app for Store Builder
|
|
13
|
+
|
|
14
|
+
wb init [name] [--port 3000] scaffold an app that runs, registers, and opens
|
|
15
|
+
inside a merchant's admin
|
|
16
|
+
wb dev upload an island's code to your DRAFT version
|
|
17
|
+
every time you save it (not hot reload — you
|
|
18
|
+
refresh). Reads wb.json; needs WB_TOKEN.
|
|
19
|
+
wb deploy [--submit] push the version's payload in dependency order.
|
|
20
|
+
Not one write: if it stops it says where, and
|
|
21
|
+
running it again is safe. --submit then sends
|
|
22
|
+
it for review.
|
|
23
|
+
|
|
24
|
+
Docs: /cli-docs (this tool) · /app-docs (building an app) · /block-docs (contributing
|
|
25
|
+
to the editor)`;
|
|
26
|
+
function parse(argv) {
|
|
27
|
+
const args = { _: [], port: 3000 };
|
|
28
|
+
for (let i = 0; i < argv.length; i++) {
|
|
29
|
+
const a = argv[i];
|
|
30
|
+
if (a === '--port') {
|
|
31
|
+
args.port = Number(argv[++i]);
|
|
32
|
+
}
|
|
33
|
+
else if (a === '--submit') {
|
|
34
|
+
args.submit = true;
|
|
35
|
+
}
|
|
36
|
+
else if (a === '-h' || a === '--help') {
|
|
37
|
+
args.help = true;
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
args._.push(a);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return args;
|
|
44
|
+
}
|
|
45
|
+
async function main(argv) {
|
|
46
|
+
const args = parse(argv);
|
|
47
|
+
const cmd = args._[0];
|
|
48
|
+
if (args.help || !cmd) {
|
|
49
|
+
console.log(USAGE);
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
if (cmd === 'dev') {
|
|
53
|
+
try {
|
|
54
|
+
const cfg = await readConfig();
|
|
55
|
+
const api = process.env.WB_API ?? 'http://localhost:8080';
|
|
56
|
+
const token = process.env.WB_TOKEN ?? '';
|
|
57
|
+
if (!token) {
|
|
58
|
+
console.error('WB_TOKEN is not set — it needs a token for the organization that owns this app.');
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
const w = watchAndUpload({ ...cfg, api, token });
|
|
62
|
+
console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
|
|
63
|
+
console.log('This is not hot reload: after each upload, refresh the page.');
|
|
64
|
+
await w.send(); // upload once now rather than waiting for the first save
|
|
65
|
+
// Runs until interrupted. No resolve: the watcher IS the program.
|
|
66
|
+
await new Promise(() => { });
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
if (err instanceof DevError) {
|
|
71
|
+
console.error(err.message);
|
|
72
|
+
return 1;
|
|
73
|
+
}
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (cmd === 'deploy') {
|
|
78
|
+
try {
|
|
79
|
+
const cfg = await readConfig();
|
|
80
|
+
const api = process.env.WB_API ?? 'http://localhost:8080';
|
|
81
|
+
const token = process.env.WB_TOKEN ?? '';
|
|
82
|
+
if (!token) {
|
|
83
|
+
console.error('WB_TOKEN is not set — it needs a token for the organization that owns this app.');
|
|
84
|
+
return 1;
|
|
85
|
+
}
|
|
86
|
+
console.log(`deploying to version ${cfg.versionId}:`);
|
|
87
|
+
await deploy({ api, token, cfg, log: (l) => console.log(l) });
|
|
88
|
+
console.log('done.');
|
|
89
|
+
if (args.submit) {
|
|
90
|
+
await submit({ api, token, cfg });
|
|
91
|
+
console.log('submitted for review.');
|
|
92
|
+
}
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
if (err instanceof DeployStopped || err instanceof DevError) {
|
|
97
|
+
console.error(err.message);
|
|
98
|
+
return 1;
|
|
99
|
+
}
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (cmd !== 'init') {
|
|
104
|
+
console.error(`unknown command: ${cmd}\n`);
|
|
105
|
+
console.error(USAGE);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
if (!Number.isFinite(args.port) || args.port <= 0) {
|
|
109
|
+
console.error('--port must be a number');
|
|
110
|
+
return 1;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const res = await init({ name: args._[1], port: args.port });
|
|
114
|
+
console.log(nextSteps({ name: res.name, port: args.port }));
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
// An InitError is a refusal the developer can act on — print it plainly.
|
|
119
|
+
// Anything else is a bug in this tool and gets its stack, because a
|
|
120
|
+
// scaffolder that swallows its own failures is one nobody can report.
|
|
121
|
+
if (err instanceof InitError) {
|
|
122
|
+
console.error(err.message);
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
129
|
+
//# sourceMappingURL=wb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wb.js","sourceRoot":"","sources":["../../bin/wb.ts"],"names":[],"mappings":";AACA;;;;;;GAMG;AACH,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjE,MAAM,KAAK,GAAG;;;;;;;;;;;;;eAaC,CAAC;AAiBhB,SAAS,KAAK,CAAC,IAAc;IAC3B,MAAM,IAAI,GAAS,EAAE,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;YACnB,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAChC,CAAC;aAAM,IAAI,CAAC,KAAK,UAAU,EAAE,CAAC;YAC5B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;aAAM,IAAI,CAA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,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve, dirname } from 'node:path';
|
|
3
|
+
import { explain, DevError, messageOf } from './dev.js';
|
|
4
|
+
/**
|
|
5
|
+
* `wb deploy` — push a version's payload, in dependency order.
|
|
6
|
+
*
|
|
7
|
+
* # IT IS NOT ATOMIC, AND IT MUST NOT SAY IT IS
|
|
8
|
+
*
|
|
9
|
+
* A version's payload is written through five doors — fields, images, blocks,
|
|
10
|
+
* island declarations, and one module upload per island — and no single call
|
|
11
|
+
* carries it. A tool that sequenced them and called the result atomic would be
|
|
12
|
+
* making a promise in the one place a developer would rely on it, about a
|
|
13
|
+
* guarantee that does not exist.
|
|
14
|
+
*
|
|
15
|
+
* # And it does not need to be
|
|
16
|
+
*
|
|
17
|
+
* A DRAFT IS DESIGNED TO BE INCOHERENT BETWEEN WRITES. The platform says so
|
|
18
|
+
* itself, beside ValidateIslandModules: *"A draft legitimately holds a named
|
|
19
|
+
* island with nothing uploaded yet — that is a developer partway through — and
|
|
20
|
+
* only the gate before a reviewer's queue can insist the pair is complete."*
|
|
21
|
+
* Both coherence checks live in SubmitVersion, not on the individual writes.
|
|
22
|
+
*
|
|
23
|
+
* So a half-finished deploy is not a damaged version. It is an unfinished one,
|
|
24
|
+
* and the cost is precise: it cannot be submitted until it is finished, and the
|
|
25
|
+
* submit refusal already names exactly what is missing. Refusing to start would
|
|
26
|
+
* refuse the normal case, and a tool that treats unfinished as unsafe teaches
|
|
27
|
+
* its user to ignore it.
|
|
28
|
+
*
|
|
29
|
+
* What this owes the developer instead is to say EXACTLY where it stopped, so
|
|
30
|
+
* resuming is obvious — and every write here is idempotent, so resuming is
|
|
31
|
+
* simply running it again.
|
|
32
|
+
*/
|
|
33
|
+
/** One step of a deploy: what it is called, and what it does. */
|
|
34
|
+
async function put(url, token, body, contentType = 'application/json') {
|
|
35
|
+
const res = await fetch(url, {
|
|
36
|
+
method: 'PUT',
|
|
37
|
+
headers: { 'Content-Type': contentType, Authorization: `Bearer ${token}` },
|
|
38
|
+
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
39
|
+
});
|
|
40
|
+
if (res.ok)
|
|
41
|
+
return;
|
|
42
|
+
let parsed = {};
|
|
43
|
+
try {
|
|
44
|
+
parsed = (await res.json());
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
throw new DevError(`HTTP ${res.status}`);
|
|
48
|
+
}
|
|
49
|
+
throw new DevError(explain(res.status, parsed));
|
|
50
|
+
}
|
|
51
|
+
async function post(url, token, body, contentType = 'application/json') {
|
|
52
|
+
const res = await fetch(url, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: { 'Content-Type': contentType, Authorization: `Bearer ${token}` },
|
|
55
|
+
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
56
|
+
});
|
|
57
|
+
if (res.ok)
|
|
58
|
+
return res;
|
|
59
|
+
let parsed = {};
|
|
60
|
+
try {
|
|
61
|
+
parsed = (await res.json());
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new DevError(`HTTP ${res.status}`);
|
|
65
|
+
}
|
|
66
|
+
throw new DevError(explain(res.status, parsed));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* steps builds the ordered plan for a config.
|
|
70
|
+
*
|
|
71
|
+
* DEPENDENCY ORDER, and the order is the whole design: declarations before the
|
|
72
|
+
* modules that fill them, because code uploaded for an island the version does
|
|
73
|
+
* not declare is refused (`island_not_found`), while a declaration with no code
|
|
74
|
+
* yet is a state the platform expects. A failure part-way therefore leaves the
|
|
75
|
+
* SHAPE of what was intended rather than orphaned bytes.
|
|
76
|
+
*
|
|
77
|
+
* Exported so a test can assert the ORDER without performing it — the property
|
|
78
|
+
* is the sequence, and a test that only watched a successful run would pass on
|
|
79
|
+
* any order that happened to work.
|
|
80
|
+
*/
|
|
81
|
+
export function steps(cfg) {
|
|
82
|
+
const base = `/api/orgs/${encodeURIComponent(cfg.orgId)}/apps/${encodeURIComponent(cfg.appId)}/versions/${encodeURIComponent(cfg.versionId)}`;
|
|
83
|
+
const out = [];
|
|
84
|
+
if (cfg.version) {
|
|
85
|
+
out.push({ name: 'version fields', method: 'PUT', path: base, body: cfg.version });
|
|
86
|
+
}
|
|
87
|
+
if (cfg.blocks) {
|
|
88
|
+
out.push({ name: 'blocks', method: 'PUT', path: `${base}/blocks`, file: cfg.blocks });
|
|
89
|
+
}
|
|
90
|
+
const islands = cfg.islands ?? [];
|
|
91
|
+
if (islands.length > 0) {
|
|
92
|
+
out.push({
|
|
93
|
+
name: 'island declarations',
|
|
94
|
+
method: 'PUT',
|
|
95
|
+
path: `${base}/islands`,
|
|
96
|
+
body: { islands: islands.map((i) => ({ name: i.name })) },
|
|
97
|
+
});
|
|
98
|
+
for (const island of islands) {
|
|
99
|
+
out.push({
|
|
100
|
+
name: `island "${island.name}"`,
|
|
101
|
+
method: 'POST',
|
|
102
|
+
path: `${base}/islands/module?name=${encodeURIComponent(island.name)}`,
|
|
103
|
+
file: island.entry,
|
|
104
|
+
contentType: 'application/javascript',
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* deploy runs the plan and reports where it got to.
|
|
112
|
+
*
|
|
113
|
+
* @returns {{done: string[]}} on success
|
|
114
|
+
* @throws {DeployStopped} naming the completed steps and the one that failed
|
|
115
|
+
*/
|
|
116
|
+
export async function deploy({ api, token, cfg, dir = process.cwd(), log = () => { }, }) {
|
|
117
|
+
const plan = steps(cfg);
|
|
118
|
+
const done = [];
|
|
119
|
+
for (const step of plan) {
|
|
120
|
+
let body = step.body;
|
|
121
|
+
if (step.file) {
|
|
122
|
+
body = await readFile(resolve(dir, step.file), 'utf8');
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const url = `${api}${step.path}`;
|
|
126
|
+
if (step.method === 'PUT') {
|
|
127
|
+
await put(url, token, body, step.contentType);
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
await post(url, token, body, step.contentType);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
throw new DeployStopped(step, done, messageOf(err));
|
|
135
|
+
}
|
|
136
|
+
done.push(step.name);
|
|
137
|
+
log(` ${step.name}`);
|
|
138
|
+
}
|
|
139
|
+
return { done };
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* DeployStopped says where it stopped, in the terms resuming needs.
|
|
143
|
+
*
|
|
144
|
+
* Not "deploy failed": that tells the developer nothing they can act on. What
|
|
145
|
+
* they need is which steps landed, which one did not, and the fact that running
|
|
146
|
+
* it again is safe — because every write here is idempotent and a partial draft
|
|
147
|
+
* is unfinished rather than broken.
|
|
148
|
+
*/
|
|
149
|
+
export class DeployStopped extends Error {
|
|
150
|
+
step;
|
|
151
|
+
done;
|
|
152
|
+
constructor(step, done, reason) {
|
|
153
|
+
const lines = [
|
|
154
|
+
`Stopped at: ${step.name}`,
|
|
155
|
+
'',
|
|
156
|
+
reason,
|
|
157
|
+
'',
|
|
158
|
+
done.length > 0 ? `Already applied: ${done.join(', ')}` : 'Nothing was applied.',
|
|
159
|
+
'',
|
|
160
|
+
'This left the version UNFINISHED, not broken — a draft is allowed to be',
|
|
161
|
+
'partway through, and it simply cannot be submitted until the rest lands.',
|
|
162
|
+
'Fix the cause and run wb deploy again; every step is safe to repeat.',
|
|
163
|
+
];
|
|
164
|
+
super(lines.join('\n'));
|
|
165
|
+
this.step = step;
|
|
166
|
+
this.done = done;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* loopbackURLs returns the version fields that still point at localhost.
|
|
171
|
+
*
|
|
172
|
+
* THE COURTESY CHECK, and it lives HERE — at submit — because that is exactly
|
|
173
|
+
* where the server's own asymmetry falls: a draft may pin loopback (checkURLs
|
|
174
|
+
* with allowLoopback true at create and update) and SubmitVersion passes false.
|
|
175
|
+
* A client check that fired anywhere else would be a SECOND rule, drifting from
|
|
176
|
+
* the first, tested against nothing.
|
|
177
|
+
*
|
|
178
|
+
* It is a courtesy and never the authority. The server's refusal is the one that
|
|
179
|
+
* counts, and if the two ever disagree the server wins — this only exists to
|
|
180
|
+
* fail earlier, with more context than the server has room for.
|
|
181
|
+
*/
|
|
182
|
+
export function loopbackURLs(version = {}) {
|
|
183
|
+
const isLoopback = (raw) => {
|
|
184
|
+
if (!raw)
|
|
185
|
+
return false;
|
|
186
|
+
try {
|
|
187
|
+
const u = new URL(raw);
|
|
188
|
+
return (u.protocol === 'http:' &&
|
|
189
|
+
(u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]' || u.hostname === '::1'));
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return false;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const out = [];
|
|
196
|
+
if (isLoopback(version.embedUrl))
|
|
197
|
+
out.push(`embedUrl (${version.embedUrl})`);
|
|
198
|
+
if (isLoopback(version.redirectUri))
|
|
199
|
+
out.push(`redirectUri (${version.redirectUri})`);
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
/** `wb deploy --submit` — the coherence gate, walked into deliberately. */
|
|
203
|
+
export async function submit({ api, token, cfg }) {
|
|
204
|
+
const stillLocal = loopbackURLs(cfg.version);
|
|
205
|
+
if (stillLocal.length > 0) {
|
|
206
|
+
throw new DevError(`This version still points at your own machine: ${stillLocal.join(', ')}.\n` +
|
|
207
|
+
'Review needs public https URLs — the loopback allowance covers development only.\n' +
|
|
208
|
+
'Update the version to its real addresses, deploy again, then submit.');
|
|
209
|
+
}
|
|
210
|
+
const url = `${api}/api/orgs/${encodeURIComponent(cfg.orgId)}/apps/${encodeURIComponent(cfg.appId)}` +
|
|
211
|
+
`/versions/${encodeURIComponent(cfg.versionId)}/submit`;
|
|
212
|
+
await post(url, token, {});
|
|
213
|
+
}
|
|
214
|
+
export { dirname };
|
|
215
|
+
//# sourceMappingURL=deploy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deploy.js","sourceRoot":"","sources":["../../src/deploy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAGxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,iEAAiE;AACjE,KAAK,UAAU,GAAG,CAAC,GAAW,EAAE,KAAa,EAAE,IAAa,EAAE,WAAW,GAAG,kBAAkB;IAC5F,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;QAC3B,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE;QAC1E,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;KAC7D,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,EAAE;QAAE,OAAO;IACnB,IAAI,MAAM,GAAgB,EAAE,CAAC;IAC7B,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAgB,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,QAAQ,CAAC,QAAQ,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAClD,CAAC;A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,CAAC;AAED,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAqD;IACjG,MAAM,UAAU,GAAG,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7C,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,QAAQ,CAChB,kDAAkD,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK;YAC1E,oFAAoF;YACpF,sEAAsE,CACzE,CAAC;IACJ,CAAC;IACD,MAAM,GAAG,GACP,GAAG,GAAG,aAAa,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;QACxF,aAAa,kBAAkB,CAAC,GAAG,CAAC,SAAS,CAAC,SAAS,CAAC;IAC1D,MAAM,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED,OAAO,EAAE,OAAO,EAAE,CAAC"}
|
package/dist/src/dev.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { watch } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* `wb dev` — save, upload, refresh.
|
|
6
|
+
*
|
|
7
|
+
* # IT IS NOT HOT RELOAD, AND IT MUST NEVER SAY IT IS
|
|
8
|
+
*
|
|
9
|
+
* An island's code on a rendered page always comes from the platform's object
|
|
10
|
+
* store: `ModuleURL` is produced in exactly one place, as
|
|
11
|
+
* `store.PublicURL(is.ModuleKey)`, because the platform hosts the bundle rather
|
|
12
|
+
* than shipping a URL shape a developer supplies. That was decided deliberately
|
|
13
|
+
* and this tool does not reopen it — so a page cannot be pointed at
|
|
14
|
+
* `localhost:5173`, and there is no live-patching to be had.
|
|
15
|
+
*
|
|
16
|
+
* What is left is still most of the friction: the developer stops hunting for
|
|
17
|
+
* an endpoint. Save the file, this uploads it, they refresh. Three words, said
|
|
18
|
+
* in the terminal in those words, because the developer reads the terminal and
|
|
19
|
+
* a name that overpromises there will be believed there.
|
|
20
|
+
*
|
|
21
|
+
* # It uploads to a DRAFT
|
|
22
|
+
*
|
|
23
|
+
* A version that has left draft refuses the write — approval pins a payload, and
|
|
24
|
+
* an island swapped after review is code running on merchants' pages that nobody
|
|
25
|
+
* looked at. When that happens this says so in the terms the developer is
|
|
26
|
+
* standing in, rather than repeating the server's sentence about a status field.
|
|
27
|
+
*/
|
|
28
|
+
/** How long to wait after a change before uploading, in milliseconds.
|
|
29
|
+
*
|
|
30
|
+
* An editor writing a file produces several events — truncate, then write, then
|
|
31
|
+
* a rename on some platforms — and uploading on each would send a half-written
|
|
32
|
+
* file first. Small enough to feel immediate, large enough to coalesce a save. */
|
|
33
|
+
const SETTLE_MS = 120;
|
|
34
|
+
export class DevError extends Error {
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The message off a thrown value.
|
|
38
|
+
*
|
|
39
|
+
* `catch` binds `unknown`, and the JS this replaced reached straight for
|
|
40
|
+
* `.message` — which on a non-Error throw printed the literal word "undefined"
|
|
41
|
+
* and told the developer nothing. Naming the fallback is the whole reason the
|
|
42
|
+
* types were worth adding here.
|
|
43
|
+
*/
|
|
44
|
+
export function messageOf(err) {
|
|
45
|
+
return err instanceof Error ? err.message : String(err);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* uploadModule PUTs one island's code to a draft version.
|
|
49
|
+
*
|
|
50
|
+
* Exported so the watcher and the tests drive the same function — a test that
|
|
51
|
+
* exercised a copy of this would prove the copy.
|
|
52
|
+
*/
|
|
53
|
+
export async function uploadModule({ api, token, orgId, appId, versionId, island, source, }) {
|
|
54
|
+
const url = `${api}/api/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}` +
|
|
55
|
+
`/versions/${encodeURIComponent(versionId)}/islands/module?name=${encodeURIComponent(island)}`;
|
|
56
|
+
const res = await fetch(url, {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: {
|
|
59
|
+
// The module is JavaScript, sent as itself. The platform validates that it
|
|
60
|
+
// is text and caps its size; it stores the bytes under a digest of them.
|
|
61
|
+
'Content-Type': 'application/javascript',
|
|
62
|
+
Authorization: `Bearer ${token}`,
|
|
63
|
+
},
|
|
64
|
+
body: source,
|
|
65
|
+
});
|
|
66
|
+
if (res.ok)
|
|
67
|
+
return;
|
|
68
|
+
let body = {};
|
|
69
|
+
try {
|
|
70
|
+
body = (await res.json());
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// A non-JSON body from this endpoint means something in front of the server
|
|
74
|
+
// answered — a proxy, a login page. Say the status rather than pretending to
|
|
75
|
+
// have parsed a reason.
|
|
76
|
+
throw new DevError(`upload failed: HTTP ${res.status}`);
|
|
77
|
+
}
|
|
78
|
+
throw new DevError(explain(res.status, body));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* explain turns the server's refusal into the sentence the developer needs.
|
|
82
|
+
*
|
|
83
|
+
* THE SERVER'S WORDS ARE FOR THE SERVER'S AUDIENCE. `not_draft` says "this
|
|
84
|
+
* version has left draft", which is accurate and describes a status field; the
|
|
85
|
+
* developer is standing in a terminal wondering why their save did nothing, and
|
|
86
|
+
* what they need is the next action. Every branch here keeps the machine code
|
|
87
|
+
* intact and adds the step.
|
|
88
|
+
*
|
|
89
|
+
* Unknown codes fall through to the server's own message rather than a generic
|
|
90
|
+
* one: a refusal this tool has not been taught is still better read in the
|
|
91
|
+
* server's words than in a shrug.
|
|
92
|
+
*/
|
|
93
|
+
export function explain(status, body) {
|
|
94
|
+
const code = body?.code ?? '';
|
|
95
|
+
const message = body?.error ?? `HTTP ${status}`;
|
|
96
|
+
switch (code) {
|
|
97
|
+
case 'not_draft':
|
|
98
|
+
return ('This version is in review or already approved, so its code is frozen.\n' +
|
|
99
|
+
'Create a new draft version and point wb dev at that one.\n' +
|
|
100
|
+
`(server: ${message})`);
|
|
101
|
+
case 'island_not_found':
|
|
102
|
+
return ('This version does not declare an island by that name.\n' +
|
|
103
|
+
'Declare it on the version first — code can only be uploaded for an island that exists.\n' +
|
|
104
|
+
`(server: ${message})`);
|
|
105
|
+
case 'island_module_not_text':
|
|
106
|
+
return `That file is not text. An island module is JavaScript.\n(server: ${message})`;
|
|
107
|
+
case 'island_module_too_large':
|
|
108
|
+
return `That file is too large to upload as an island module.\n(server: ${message})`;
|
|
109
|
+
case 'unauthorized':
|
|
110
|
+
return 'Not signed in. Set WB_TOKEN to a token for the organization that owns this app.';
|
|
111
|
+
default:
|
|
112
|
+
if (status === 401 || status === 403) {
|
|
113
|
+
return ('Refused: this token cannot edit that app.\n' +
|
|
114
|
+
'Check WB_TOKEN, and that the app belongs to the organization you named.\n' +
|
|
115
|
+
`(server: ${message})`);
|
|
116
|
+
}
|
|
117
|
+
return message;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* watchAndUpload watches one file and uploads it on every settled change.
|
|
122
|
+
*
|
|
123
|
+
* The return type is written out rather than inferred: `send` is the half a
|
|
124
|
+
* caller drives directly, and an inferred shape would let a rename slip past
|
|
125
|
+
* every call site that only uses `close`.
|
|
126
|
+
*/
|
|
127
|
+
export function watchAndUpload(opts) {
|
|
128
|
+
const { entry, log = console.log, onError = console.error } = opts;
|
|
129
|
+
const file = resolve(entry);
|
|
130
|
+
let timer;
|
|
131
|
+
let busy = false;
|
|
132
|
+
const send = async () => {
|
|
133
|
+
if (busy)
|
|
134
|
+
return; // a save during an upload is picked up by the next event
|
|
135
|
+
busy = true;
|
|
136
|
+
try {
|
|
137
|
+
const source = await readFile(file, 'utf8');
|
|
138
|
+
await uploadModule({ ...opts, source });
|
|
139
|
+
// THE THREE WORDS. Not "hot reload", not "live", not "synced" — the
|
|
140
|
+
// developer has to refresh, and the terminal is where they learn that.
|
|
141
|
+
log(`uploaded ${opts.island} — refresh the page to see it`);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
onError(err instanceof DevError ? err.message : `upload failed: ${messageOf(err)}`);
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
busy = false;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const watcher = watch(file, () => {
|
|
151
|
+
clearTimeout(timer);
|
|
152
|
+
timer = setTimeout(send, SETTLE_MS);
|
|
153
|
+
});
|
|
154
|
+
return {
|
|
155
|
+
close() {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
watcher.close();
|
|
158
|
+
},
|
|
159
|
+
// Exposed so a caller can do the first upload without waiting for a save,
|
|
160
|
+
// and so a test can drive one deterministically rather than racing the
|
|
161
|
+
// filesystem.
|
|
162
|
+
send,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** Reads wb.json beside the project, which is where `wb dev` gets its ids. */
|
|
166
|
+
export async function readConfig(dir = process.cwd()) {
|
|
167
|
+
const path = resolve(dir, 'wb.json');
|
|
168
|
+
try {
|
|
169
|
+
await stat(path);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw new DevError('No wb.json here. It needs orgId, appId, versionId, island and entry — the ids\n' +
|
|
173
|
+
'come from the app and the DRAFT version you created.');
|
|
174
|
+
}
|
|
175
|
+
// `as` and not a validator: the five checks below ARE the validation, and
|
|
176
|
+
// they run on the parsed object before it is handed to anyone.
|
|
177
|
+
const cfg = JSON.parse(await readFile(path, 'utf8'));
|
|
178
|
+
for (const key of ['orgId', 'appId', 'versionId', 'island', 'entry']) {
|
|
179
|
+
if (!cfg[key])
|
|
180
|
+
throw new DevError(`wb.json is missing "${key}".`);
|
|
181
|
+
}
|
|
182
|
+
return cfg;
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=dev.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/dev.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AAM,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IACrC,IAAI,CAAC;QACH,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,QAAQ,CAChB,iFAAiF;YAC/E,sDAAsD,CACzD,CAAC;IACJ,CAAC;IACD,0EAA0E;IAC1E,+DAA+D;IAC/D,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAsB,CAAC;IAC1E,KAAK,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,OAAO,CAAU,EAAE,CAAC;QAC9E,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,QAAQ,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,GAAe,CAAC;AACzB,CAAC"}
|
package/dist/src/init.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { mkdir, readdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { files } from './scaffold.js';
|
|
5
|
+
/**
|
|
6
|
+
* `wb init` — write the scaffold into a directory.
|
|
7
|
+
*
|
|
8
|
+
* # It never overwrites, and it never half-writes
|
|
9
|
+
*
|
|
10
|
+
* A scaffold that clobbers is a scaffold that can destroy work on its FIRST
|
|
11
|
+
* command, before the developer has any reason to trust it. So the whole file
|
|
12
|
+
* set is checked against the target before anything is written, and a single
|
|
13
|
+
* collision refuses the lot — a partial scaffold is worse than none, because it
|
|
14
|
+
* leaves a directory that looks initialised and is not.
|
|
15
|
+
*/
|
|
16
|
+
/** A directory name a developer can type, and npm will accept as a package. */
|
|
17
|
+
export function normalizeName(raw) {
|
|
18
|
+
const name = String(raw ?? '')
|
|
19
|
+
.trim()
|
|
20
|
+
.toLowerCase()
|
|
21
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
22
|
+
.replace(/^[-_.]+|[-_.]+$/g, '');
|
|
23
|
+
return name || 'my-app';
|
|
24
|
+
}
|
|
25
|
+
export class InitError extends Error {
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* plan resolves what would be written, without writing it.
|
|
29
|
+
*
|
|
30
|
+
* Separate from the write so the refusal above can be decided before any file
|
|
31
|
+
* exists, and so a test can assert the contents without a temp directory.
|
|
32
|
+
*/
|
|
33
|
+
export function plan({ name, dir, port = 3000 }) {
|
|
34
|
+
const pkgName = normalizeName(name);
|
|
35
|
+
const target = resolve(dir ?? pkgName);
|
|
36
|
+
return { pkgName, target, files: files(pkgName, port) };
|
|
37
|
+
}
|
|
38
|
+
/** init writes the scaffold and returns what it wrote. */
|
|
39
|
+
export async function init(opts = {}) {
|
|
40
|
+
const { pkgName, target, files: out } = plan(opts);
|
|
41
|
+
// An EXISTING directory is fine as long as it is empty of the things we would
|
|
42
|
+
// write — running `wb init` inside a fresh git clone is a normal thing to do,
|
|
43
|
+
// and refusing it because `.git` exists would be refusing the common case.
|
|
44
|
+
if (existsSync(target)) {
|
|
45
|
+
const existing = new Set(await readdir(target));
|
|
46
|
+
const clashes = Object.keys(out).filter((f) => existing.has(f));
|
|
47
|
+
if (clashes.length > 0) {
|
|
48
|
+
throw new InitError(`${target} already contains ${clashes.join(', ')} — refusing to overwrite. ` +
|
|
49
|
+
`Pick an empty directory, or move those files aside.`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
await mkdir(target, { recursive: true });
|
|
53
|
+
for (const [file, contents] of Object.entries(out)) {
|
|
54
|
+
await writeFile(join(target, file), contents, 'utf8');
|
|
55
|
+
}
|
|
56
|
+
return { name: pkgName, target, written: Object.keys(out).sort() };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The words printed after a successful init.
|
|
60
|
+
*
|
|
61
|
+
* Four steps, in the order they are done, and the one fact that saves an hour:
|
|
62
|
+
* NO TUNNEL. The platform allows a draft version and a sandbox install to point
|
|
63
|
+
* at localhost, so the whole development loop runs on the developer's machine —
|
|
64
|
+
* and that is discoverable nowhere else at the moment they need it.
|
|
65
|
+
*/
|
|
66
|
+
export function nextSteps({ name, port = 3000 }) {
|
|
67
|
+
return [
|
|
68
|
+
`Created ${name}.`,
|
|
69
|
+
'',
|
|
70
|
+
'Next:',
|
|
71
|
+
` cd ${name}`,
|
|
72
|
+
' cp .env.example .env # fill in WB_CLIENT_ID and WB_CLIENT_SECRET',
|
|
73
|
+
' npm start',
|
|
74
|
+
'',
|
|
75
|
+
`Your app runs at http://localhost:${port} — no tunnel needed. A draft version`,
|
|
76
|
+
'may point at localhost and a sandbox install may frame it, so the whole loop',
|
|
77
|
+
'is local. A tunnel is only for checking the PUBLIC urls before you submit.',
|
|
78
|
+
'',
|
|
79
|
+
'Then create a draft version pointing at:',
|
|
80
|
+
` embed URL http://localhost:${port}/embed`,
|
|
81
|
+
` redirect URI http://localhost:${port}/oauth/callback`,
|
|
82
|
+
'',
|
|
83
|
+
'The full walkthrough, including every error code, is at /app-docs.',
|
|
84
|
+
].join('\n');
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=init.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.js","sourceRoot":"","sources":["../../src/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAoBtC;;;;;;;;;;GAUG;AAEH,+EAA+E;AAC/E,MAAM,UAAU,aAAa,CAAC,GAAY;IACxC,MAAM,IAAI,G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IAAI,CAAC,IAAI,CAAC,4BAA4B;gBAC1E,qDAAqD,CACxD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,MAAM,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,KAAK,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACnD,MAAM,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AACrE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,SAAS,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,EAAmC;IAC9E,OAAO;QACL,WAAW,IAAI,GAAG;QAClB,EAAE;QACF,OAAO;QACP,QAAQ,IAAI,EAAE;QACd,yEAAyE;QACzE,aAAa;QACb,EAAE;QACF,qCAAqC,IAAI,sCAAsC;QAC/E,8EAA8E;QAC9E,4EAA4E;QAC5E,EAAE;QACF,0CAA0C;QAC1C,oCAAoC,IAAI,QAAQ;QAChD,oCAAoC,IAAI,iBAAiB;QACzD,EAAE;QACF,oEAAoE;KACrE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SCAFFOLD: the guide's fastest working example, and nothing else.
|
|
3
|
+
*
|
|
4
|
+
* Every file below is one a developer needs on DAY ONE. Anything extra is
|
|
5
|
+
* something they must read and decide about before they have seen the thing
|
|
6
|
+
* work at all — so there are no blocks here, no islands, no app-data, and no
|
|
7
|
+
* framework. Those are all documented at /block-docs and none of them belong in
|
|
8
|
+
* a first success.
|
|
9
|
+
*
|
|
10
|
+
* WHAT IT DOES: starts, serves the embedded screen a merchant opens, and
|
|
11
|
+
* completes the OAuth exchange. That is the whole of it, and it is enough to see
|
|
12
|
+
* the app appear inside a real merchant's admin.
|
|
13
|
+
*
|
|
14
|
+
* # No dependencies, and no build
|
|
15
|
+
*
|
|
16
|
+
* `node:http` rather than a framework, and plain ESM rather than TypeScript.
|
|
17
|
+
* Both for the same reason: the first `npm install` a developer runs should not
|
|
18
|
+
* be the first thing that can fail. A scaffold whose dependencies do not resolve
|
|
19
|
+
* on their machine has taught them nothing about this platform.
|
|
20
|
+
*/
|
|
21
|
+
/** The scaffolded app's package.json. */
|
|
22
|
+
function pkg(name) {
|
|
23
|
+
return (JSON.stringify({
|
|
24
|
+
name,
|
|
25
|
+
version: '0.1.0',
|
|
26
|
+
private: true,
|
|
27
|
+
type: 'module',
|
|
28
|
+
scripts: { start: 'node server.js' },
|
|
29
|
+
}, null, 2) + '\n');
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The whole app: one file, two routes.
|
|
33
|
+
*
|
|
34
|
+
* It reads its configuration from the environment rather than a config module,
|
|
35
|
+
* because the two values it needs are the two the platform gave the developer
|
|
36
|
+
* and neither is a decision.
|
|
37
|
+
*/
|
|
38
|
+
function server() {
|
|
39
|
+
return `import { createServer } from 'node:http';
|
|
40
|
+
|
|
41
|
+
// ── Configuration ─────────────────────────────────────────────────────────
|
|
42
|
+
//
|
|
43
|
+
// Both come from the platform when you create the app. CLIENT_SECRET is shown
|
|
44
|
+
// ONCE, at creation; if you lose it, rotate it rather than hunting for it.
|
|
45
|
+
const PORT = Number(process.env.PORT ?? 3000);
|
|
46
|
+
const API = process.env.WB_API ?? 'http://localhost:8080';
|
|
47
|
+
const CLIENT_ID = process.env.WB_CLIENT_ID ?? '';
|
|
48
|
+
const CLIENT_SECRET = process.env.WB_CLIENT_SECRET ?? '';
|
|
49
|
+
|
|
50
|
+
// This must match the redirect URI registered on your VERSION exactly — the
|
|
51
|
+
// platform compares them character for character, and a mismatch is refused
|
|
52
|
+
// rather than guessed at.
|
|
53
|
+
const REDIRECT_URI = process.env.WB_REDIRECT_URI ?? \`http://localhost:\${PORT}/oauth/callback\`;
|
|
54
|
+
|
|
55
|
+
// Tokens live in memory, which is correct for a scaffold and wrong for
|
|
56
|
+
// production: a restart loses them and the merchant has to install again.
|
|
57
|
+
// Where you put them is your first real decision, and it is deliberately not
|
|
58
|
+
// made for you here.
|
|
59
|
+
const installs = new Map();
|
|
60
|
+
|
|
61
|
+
const server = createServer(async (req, res) => {
|
|
62
|
+
const url = new URL(req.url, \`http://\${req.headers.host}\`);
|
|
63
|
+
|
|
64
|
+
// ── The embedded screen ─────────────────────────────────────────────────
|
|
65
|
+
//
|
|
66
|
+
// This is what a merchant sees inside their admin. The platform frames it in
|
|
67
|
+
// a SANDBOXED iframe and appends three query parameters.
|
|
68
|
+
if (url.pathname === '/embed') {
|
|
69
|
+
const frameToken = url.searchParams.get('wb_frame_token') ?? '';
|
|
70
|
+
const siteId = url.searchParams.get('wb_site_id') ?? '';
|
|
71
|
+
|
|
72
|
+
// NEVER TRUST THE FRAME TOKEN AS IT ARRIVES. It is proof of nothing until
|
|
73
|
+
// your own server resolves it with your client credentials — see
|
|
74
|
+
// /oauth/frame in the guide. This scaffold shows it rather than resolving
|
|
75
|
+
// it, because resolving it is your app's first real piece of logic.
|
|
76
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
77
|
+
res.end(\`<!doctype html>
|
|
78
|
+
<meta charset="utf-8">
|
|
79
|
+
<title>My app</title>
|
|
80
|
+
<body style="font: 15px/1.6 system-ui; margin: 2rem; color: #171717">
|
|
81
|
+
<h1 style="font-size: 20px">It works.</h1>
|
|
82
|
+
<p>This page is running on your machine and framed inside the merchant's admin.</p>
|
|
83
|
+
<p>Store: <code>\${siteId || '(none)'}</code></p>
|
|
84
|
+
<p>Frame token: <code>\${frameToken ? frameToken.slice(0, 12) + '…' : '(none)'}</code></p>
|
|
85
|
+
<p style="color:#5c5c5c">Resolve that token from your own server before you trust it.</p>
|
|
86
|
+
</body>\`);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ── The OAuth callback ──────────────────────────────────────────────────
|
|
91
|
+
//
|
|
92
|
+
// The merchant approved your app; the platform sent their browser here with a
|
|
93
|
+
// single-use code that lives 60 seconds.
|
|
94
|
+
if (url.pathname === '/oauth/callback') {
|
|
95
|
+
const code = url.searchParams.get('code');
|
|
96
|
+
if (!code) {
|
|
97
|
+
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
98
|
+
res.end('no code');
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
// SERVER TO SERVER, with your client credentials. Never from the browser:
|
|
103
|
+
// the secret would be in the page.
|
|
104
|
+
const r = await fetch(\`\${API}/oauth/token\`, {
|
|
105
|
+
method: 'POST',
|
|
106
|
+
headers: { 'Content-Type': 'application/json' },
|
|
107
|
+
body: JSON.stringify({
|
|
108
|
+
grantType: 'authorization_code',
|
|
109
|
+
clientId: CLIENT_ID,
|
|
110
|
+
clientSecret: CLIENT_SECRET,
|
|
111
|
+
code,
|
|
112
|
+
// Matched as part of redeeming the code. A mismatch does NOT consume
|
|
113
|
+
// the code, so a typo here is recoverable.
|
|
114
|
+
redirectUri: REDIRECT_URI,
|
|
115
|
+
}),
|
|
116
|
+
});
|
|
117
|
+
const body = await r.json();
|
|
118
|
+
if (!r.ok) {
|
|
119
|
+
res.writeHead(r.status, { 'Content-Type': 'application/json' });
|
|
120
|
+
res.end(JSON.stringify(body));
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
// The access token names the install. Refresh tokens ROTATE: the one you
|
|
124
|
+
// send is burned and a new one comes back, so store what you receive.
|
|
125
|
+
installs.set(body.accessToken, body);
|
|
126
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
127
|
+
res.end(\`<!doctype html><meta charset="utf-8">
|
|
128
|
+
<body style="font: 15px/1.6 system-ui; margin: 2rem; color: #171717">
|
|
129
|
+
<h1 style="font-size: 20px">Installed.</h1>
|
|
130
|
+
<p>You now hold an access token for this store. Call /api/v1 with it.</p>
|
|
131
|
+
</body>\`);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
134
|
+
res.end(\`could not reach \${API}: \${err.message}\`);
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
140
|
+
res.end('not found');
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
server.listen(PORT, () => {
|
|
144
|
+
console.log(\`app listening on http://localhost:\${PORT}\`);
|
|
145
|
+
console.log(\` embedded screen http://localhost:\${PORT}/embed\`);
|
|
146
|
+
console.log(\` oauth callback \${REDIRECT_URI}\`);
|
|
147
|
+
if (!CLIENT_ID || !CLIENT_SECRET) {
|
|
148
|
+
console.log('');
|
|
149
|
+
console.log('WB_CLIENT_ID / WB_CLIENT_SECRET are not set — the install will fail at the token exchange.');
|
|
150
|
+
console.log('Copy .env.example, fill it in, and restart.');
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
`;
|
|
154
|
+
}
|
|
155
|
+
/** The two values the platform gives you, and nothing else. */
|
|
156
|
+
function envExample(port) {
|
|
157
|
+
return `# Both are shown when you create the app. The SECRET is shown once.
|
|
158
|
+
WB_CLIENT_ID=
|
|
159
|
+
WB_CLIENT_SECRET=
|
|
160
|
+
|
|
161
|
+
# Where the platform's API lives.
|
|
162
|
+
WB_API=http://localhost:8080
|
|
163
|
+
|
|
164
|
+
# Must match the redirect URI on your version EXACTLY.
|
|
165
|
+
WB_REDIRECT_URI=http://localhost:${port}/oauth/callback
|
|
166
|
+
|
|
167
|
+
PORT=${port}
|
|
168
|
+
`;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* The README is the four steps in order, and it says what is deliberately
|
|
172
|
+
* missing — a scaffold that pretends to be complete teaches the wrong lesson
|
|
173
|
+
* about what the developer still has to decide.
|
|
174
|
+
*/
|
|
175
|
+
function readme(name, port) {
|
|
176
|
+
return `# ${name}
|
|
177
|
+
|
|
178
|
+
An app for the Store Builder platform. It starts, serves an embedded screen, and
|
|
179
|
+
completes the OAuth exchange. That is all it does on purpose.
|
|
180
|
+
|
|
181
|
+
## Run it
|
|
182
|
+
|
|
183
|
+
cp .env.example .env # fill in WB_CLIENT_ID and WB_CLIENT_SECRET
|
|
184
|
+
npm start
|
|
185
|
+
|
|
186
|
+
Your app is on http://localhost:${port}. Nothing else is needed to develop it —
|
|
187
|
+
**no tunnel.** A draft version may point at \`http://localhost\`, and a sandbox
|
|
188
|
+
install may frame it, so the whole loop runs on your machine.
|
|
189
|
+
|
|
190
|
+
## Install it on your own store
|
|
191
|
+
|
|
192
|
+
1. Create the app, and a DRAFT version pointing at your local URLs:
|
|
193
|
+
- embed URL: \`http://localhost:${port}/embed\`
|
|
194
|
+
- redirect URI: \`http://localhost:${port}/oauth/callback\`
|
|
195
|
+
2. Send your browser to \`/oauth/authorize\` with your \`clientId\`, \`versionId\`,
|
|
196
|
+
\`redirectUri\` and \`site_id\`.
|
|
197
|
+
3. Approve. The platform sends the browser back here and this app exchanges the
|
|
198
|
+
code for a token.
|
|
199
|
+
4. Open the app from the merchant's Apps screen — the embedded page above is
|
|
200
|
+
what appears.
|
|
201
|
+
|
|
202
|
+
Full detail, including every error code: **/app-docs**.
|
|
203
|
+
|
|
204
|
+
## What is deliberately not here
|
|
205
|
+
|
|
206
|
+
- **Token storage.** They are in memory, so a restart loses them. Where they
|
|
207
|
+
belong is your first real decision.
|
|
208
|
+
- **Frame-token verification.** \`/embed\` displays the token rather than
|
|
209
|
+
resolving it. Resolve it from your own server (\`/oauth/frame\`) before you
|
|
210
|
+
trust anything it says.
|
|
211
|
+
- **Blocks, islands and app data.** All documented at **/block-docs**, none of
|
|
212
|
+
them needed to see this work.
|
|
213
|
+
|
|
214
|
+
## Before you submit for review
|
|
215
|
+
|
|
216
|
+
Your version must point at **public https URLs**. The loopback allowance covers
|
|
217
|
+
development only — submitting is refused while either URL is \`localhost\`, and
|
|
218
|
+
that refusal is the platform's, not this app's.
|
|
219
|
+
`;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* files returns the whole scaffold as a path→contents map.
|
|
223
|
+
*
|
|
224
|
+
* A map rather than a series of writes, so the caller decides what to do with it
|
|
225
|
+
* — which is what lets the test assert the CONTENT without touching a disk, and
|
|
226
|
+
* what makes "would this overwrite something" answerable before anything is
|
|
227
|
+
* written.
|
|
228
|
+
*/
|
|
229
|
+
export function files(name, port = 3000) {
|
|
230
|
+
return {
|
|
231
|
+
'package.json': pkg(name),
|
|
232
|
+
'server.js': server(),
|
|
233
|
+
'.env.example': envExample(port),
|
|
234
|
+
'README.md': readme(name, port),
|
|
235
|
+
'.gitignore': 'node_modules\n.env\n',
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
//# sourceMappingURL=scaffold.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scaffold.js","sourceRoot":"","sources":["../../src/scaffold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,yCAAyC;AACzC,SAAS,GAAG,CAAC,IAAY;IACvB,OAAO,CACL,IAAI,CAAC,SAAS,CACZ;QACE,IAAI;QACJ,OAAO,EAAE,OAAO;QAChB,OAAO,EAAE,IAAI;QACb,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE,EAAE,KAAK,EAAE,gBAAgB,EAAE;KACrC,EACD,IAAI,EACJ,CAAC,CACF,GAAG,IAAI,CACT,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,MAAM;IACb,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkHR,CAAC;AACF,CAAC;AAED,+DAA+D;AAC/D,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO;;;;;;;;mCAQ0B,IAAI;;OAEhC,IAAI;CACV,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,SAAS,MAAM,CAAC,IAAY,EAAE,IAAY;IACxC,OAAO,KAAK,IAAI;;;;;;;;;;kCAUgB,IAAI;;;;;;;uCAOC,IAAI;wCACH,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;CAyB3C,CAAC;AACF,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,KAAK,CAAC,IAAY,EAAE,IAAI,GAAG,IAAI;IAC7C,OAAO;QACL,cAAc,EAAE,GAAG,CAAC,IAAI,CAAC;QACzB,WAAW,EAAE,MAAM,EAAE;QACrB,cAAc,EAAE,UAAU,CAAC,IAAI,CAAC;QAChC,WAAW,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC;QAC/B,YAAY,EAAE,sBAAsB;KACrC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shapes this CLI reads and sends.
|
|
3
|
+
*
|
|
4
|
+
* They live in one file because three of them cross a module boundary — the
|
|
5
|
+
* config `dev` reads is the config `deploy` plans from, and the server error
|
|
6
|
+
* `dev` translates is the one `deploy` re-throws. Declaring each separately
|
|
7
|
+
* where it is used is how two descriptions of one payload start disagreeing.
|
|
8
|
+
*
|
|
9
|
+
* NOTHING HERE IS VALIDATION. `wb.json` is parsed with `JSON.parse` and these
|
|
10
|
+
* types say what the program EXPECTS, not what it verified — which is why
|
|
11
|
+
* `readConfig` still checks the five required keys at runtime. A type is a
|
|
12
|
+
* claim about our own code; a file on a developer's disk is input.
|
|
13
|
+
*/
|
|
14
|
+
export {};
|
|
15
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG"}
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sbuilder/cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Scaffold, run and deploy an app for the Store Builder platform.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"wb": "dist/bin/wb.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=20"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc -p tsconfig.build.json",
|
|
17
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
18
|
+
"test": "npm run build && vitest run"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^26.0.1",
|
|
22
|
+
"typescript": "^5.6.0",
|
|
23
|
+
"vitest": "^2.1.9"
|
|
24
|
+
}
|
|
25
|
+
}
|