create-ilorb 0.0.0-stage → 0.3.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 +304 -2
- package/assets/dev-local.mjs +205 -0
- package/dist/args.js +39 -0
- package/dist/cli.js +7 -0
- package/dist/cloudflare/provider.js +48 -0
- package/dist/cloudflare/real.js +211 -0
- package/dist/cloudflare/simulated.js +213 -0
- package/dist/core-admin.js +85 -0
- package/dist/engine.js +52 -0
- package/dist/errors.js +23 -0
- package/dist/exec.js +49 -0
- package/dist/fsutil.js +130 -0
- package/dist/generate.js +260 -0
- package/dist/i18n/en.js +422 -0
- package/dist/i18n/es.js +414 -0
- package/dist/i18n/index.js +23 -0
- package/dist/i18n/pt.js +414 -0
- package/dist/license/activate.js +71 -0
- package/dist/license/keys.js +14 -0
- package/dist/license/verify.js +56 -0
- package/dist/local/ports.js +33 -0
- package/dist/main.js +642 -0
- package/dist/products.js +1528 -0
- package/dist/readme.js +228 -0
- package/dist/state.js +58 -0
- package/dist/steps.js +875 -0
- package/dist/templates.js +31 -0
- package/dist/theme/preview.js +67 -0
- package/dist/theme/vendor/color.js +133 -0
- package/dist/theme/vendor/tokens.js +314 -0
- package/dist/theme/vendor/validate.js +219 -0
- package/dist/ui/prompt.js +108 -0
- package/dist/ui/term.js +92 -0
- package/dist/update.js +348 -0
- package/package.json +49 -4
package/dist/steps.js
ADDED
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
// The installation steps, in order. Cloud and local share the first ones (license, project, secrets,
|
|
2
|
+
// dependencies) and then split. Each step is idempotent: looks up before creating, compares before writing.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
5
|
+
import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { configureCore, createBootstrapLink } from "./core-admin.js";
|
|
8
|
+
import { hashOf } from "./engine.js";
|
|
9
|
+
import { HumanError } from "./errors.js";
|
|
10
|
+
import { shellLine, tail } from "./exec.js";
|
|
11
|
+
import { writeFileAtomic, writeJson } from "./fsutil.js";
|
|
12
|
+
import { applyConfig, copyTemplates, missingTemplates, scanForSecrets, writeDevVars, writeRootFiles } from "./generate.js";
|
|
13
|
+
import { t } from "./i18n/index.js";
|
|
14
|
+
import { activate, machineId } from "./license/activate.js";
|
|
15
|
+
import { isLocalServer } from "./license/keys.js";
|
|
16
|
+
import { maskCredential, verifyLicenseKey } from "./license/verify.js";
|
|
17
|
+
import { CF_COMMANDS } from "./cloudflare/real.js";
|
|
18
|
+
import { isFree, pickPorts } from "./local/ports.js";
|
|
19
|
+
import { CORE_R2, OPERA_CLOUD } from "./products.js";
|
|
20
|
+
import { licensePath, saveState, STATE_DIR } from "./state.js";
|
|
21
|
+
import { saveSecrets } from "./state.js";
|
|
22
|
+
import { downloadTemplates } from "./templates.js";
|
|
23
|
+
import { buildReadme } from "./readme.js";
|
|
24
|
+
import { readTemplateVersion, TEMPLATE_VERSION_FILE, templateRecord } from "./update.js";
|
|
25
|
+
/** for the plan (--dry-run): the names the product Worker would receive, without generating anything */
|
|
26
|
+
const fakeSecrets = (c) => ({ ...Object.fromEntries(['SERVICE_TOKEN', 'PRODUCT_SERVICE_TOKEN', ...Object.keys(c.product.generatedSecrets)].map((k) => [k, '…'])), ...c.secrets });
|
|
27
|
+
const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
|
|
28
|
+
const fileHash = (f) => (existsSync(f) ? sha(readFileSync(f, 'utf8')) : 'none');
|
|
29
|
+
const token = () => !!process.env.CLOUDFLARE_API_TOKEN;
|
|
30
|
+
async function run(ctx, cmd, args, opts = {}) {
|
|
31
|
+
ctx.out.log(`$ ${shellLine(cmd, args)}${opts.cwd ? ` (em ${opts.cwd})` : ''}`);
|
|
32
|
+
const r = await ctx.exec(cmd, args, opts);
|
|
33
|
+
ctx.out.log(tail(r.stdout + '\n' + r.stderr, 40));
|
|
34
|
+
if (r.code !== 0) {
|
|
35
|
+
if (r.code === 127 && cmd === 'pnpm')
|
|
36
|
+
throw new HumanError('pnpm_missing');
|
|
37
|
+
throw new HumanError('command_failed', { code: r.code, cmd: shellLine(cmd, args) }, tail(r.stderr || r.stdout, 15));
|
|
38
|
+
}
|
|
39
|
+
return r;
|
|
40
|
+
}
|
|
41
|
+
const names = (a, p) => ({
|
|
42
|
+
auth: `${a.slug}-auth`,
|
|
43
|
+
api: `${a.slug}-${p.api.suffix}`,
|
|
44
|
+
admin: `${a.slug}-admin`,
|
|
45
|
+
d1: (suffix) => `${a.slug}-${suffix}`,
|
|
46
|
+
r2: (suffix) => `${a.slug}-${suffix}`,
|
|
47
|
+
});
|
|
48
|
+
const wranglerBin = (ctx, rel = 'overture-core/api/workers') => join(ctx.dir, rel, 'node_modules/.bin', process.platform === 'win32' ? 'wrangler.cmd' : 'wrangler');
|
|
49
|
+
// ─── common ────────────────────────────────────────────────────────────────────────────────────
|
|
50
|
+
function licenseStep() {
|
|
51
|
+
return {
|
|
52
|
+
id: 'license',
|
|
53
|
+
title: t('step.license'),
|
|
54
|
+
hash: (c) => hashOf(c.product.id, c.credential.type, sha(c.credential.type === 'license' ? c.credential.key : c.credential.purchaseCode), c.licenseServer),
|
|
55
|
+
plan: (c) => [
|
|
56
|
+
c.credential?.type === 'license' ? 'conferir a assinatura Ed25519 da chave (offline, chave pública embutida)' : 'formato do purchase code da Envato',
|
|
57
|
+
`POST ${c.licenseServer}/v1/licenses/activate {credential, product:"${c.product.id}", installId, machine, cliVersion}`,
|
|
58
|
+
'conferir o recibo assinado pela loja (Ed25519)',
|
|
59
|
+
],
|
|
60
|
+
async run(c) {
|
|
61
|
+
if (!c.credential)
|
|
62
|
+
throw new HumanError('license_missing');
|
|
63
|
+
const allowTestKeys = isLocalServer(c.licenseServer);
|
|
64
|
+
if (c.credential.type === 'license') {
|
|
65
|
+
const p = verifyLicenseKey(c.credential.key, { product: c.product.id, allowTestKeys });
|
|
66
|
+
c.out.ok(t('license.offlineOk', { lid: p.lid, type: p.type, products: p.products.join(',') }));
|
|
67
|
+
}
|
|
68
|
+
else
|
|
69
|
+
c.out.info(t('license.envatoFormat'));
|
|
70
|
+
const res = await activate(c.licenseServer, { credential: c.credential, product: c.product.id, installId: c.state.installId, machine: machineId(), cliVersion: c.cliVersion, target: c.answers.target }, { fetch: c.fetch, allowTestKeys });
|
|
71
|
+
const a = res.activation;
|
|
72
|
+
c.out.ok(a.supportUntil
|
|
73
|
+
? t('license.activated', { id: a.id, used: a.activationsUsed, limit: a.activationsLimit, support: a.supportUntil.slice(0, 10) })
|
|
74
|
+
: t('license.activatedNoSupport', { id: a.id, used: a.activationsUsed, limit: a.activationsLimit }));
|
|
75
|
+
c.state.activation = { id: a.id, licenseId: a.licenseId, type: a.type, source: a.source, supportUntil: a.supportUntil, templatesVersion: res.templates.version };
|
|
76
|
+
// the credential and the receipt stay outside git, only for this machine (0600)
|
|
77
|
+
writeJson(licensePath(c.dir), { credential: c.credential, receipt: res.receipt, activation: a, templates: res.templates }, 0o600);
|
|
78
|
+
return { activationId: a.id, templates: res.templates };
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function generateStep() {
|
|
83
|
+
return {
|
|
84
|
+
id: 'generate',
|
|
85
|
+
title: t('step.generate'),
|
|
86
|
+
hash: (c) => hashOf(c.product.id, c.state.activation?.templatesVersion ?? 'local'),
|
|
87
|
+
plan: (c) => [
|
|
88
|
+
c.templatesDir ? `templates da pasta ${c.templatesDir}` : 'GET <templates.url da ativação> → conferir sha256 → tar -xzf em .overture/tmp/',
|
|
89
|
+
`copiar ${c.product.templates.length} pastas para ${c.dir} (sem node_modules, dist, .wrangler, .dev.vars, prints)`,
|
|
90
|
+
'gravar .gitignore, package.json, README.md, scripts/dev-local.mjs na raiz',
|
|
91
|
+
'write ilorb-template.json (template version) at the root and the sha256 of every copied file in .overture/install.json (base of create-ilorb update)',
|
|
92
|
+
],
|
|
93
|
+
async run(c) {
|
|
94
|
+
let root = c.templatesDir;
|
|
95
|
+
const tmp = join(c.dir, STATE_DIR, 'tmp/templates');
|
|
96
|
+
if (!root) {
|
|
97
|
+
if (!existsSync(licensePath(c.dir)))
|
|
98
|
+
throw new HumanError('templates_needed', { product: c.product.id });
|
|
99
|
+
const lic = JSON.parse(readFileSync(licensePath(c.dir), 'utf8'));
|
|
100
|
+
root = await downloadTemplates(lic.templates, tmp, c.fetch, c.exec);
|
|
101
|
+
c.out.ok(t('license.templates', { version: lic.templates.version }));
|
|
102
|
+
}
|
|
103
|
+
else
|
|
104
|
+
c.out.info(t('license.templatesLocal', { dir: root }));
|
|
105
|
+
const missing = missingTemplates(root, c.product);
|
|
106
|
+
if (missing.length)
|
|
107
|
+
throw new HumanError('templates_missing', { path: missing.join(', ') });
|
|
108
|
+
const n = copyTemplates(root, c.dir, c.product);
|
|
109
|
+
// the version installed + the hash of every shipped file: the base of `create-ilorb update --apply` (update.ts)
|
|
110
|
+
c.state.template = templateRecord(root, c.product);
|
|
111
|
+
if (readTemplateVersion(root)?.source === 'file')
|
|
112
|
+
writeFileAtomic(join(c.dir, TEMPLATE_VERSION_FILE), readFileSync(join(root, TEMPLATE_VERSION_FILE), 'utf8'));
|
|
113
|
+
if (!c.templatesDir)
|
|
114
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
115
|
+
writeRootFiles(c.dir, c.answers, c.product, buildReadme(c.answers, c.product));
|
|
116
|
+
c.out.ok(t('gen.copied', { n }));
|
|
117
|
+
return { files: n };
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function secretsStep() {
|
|
122
|
+
return {
|
|
123
|
+
id: 'secrets',
|
|
124
|
+
title: t('step.secrets'),
|
|
125
|
+
hash: (c) => hashOf(c.answers.target),
|
|
126
|
+
plan: (c) => [
|
|
127
|
+
`MASTER_KEY = 32 bytes (base64) · ADMIN_TOKEN = 24 bytes (base64url) · SERVICE_TOKEN = 24 bytes (rota de serviço do Core, ${c.product.name} → Core)${usesServiceToken(c) ? ` · SERVICE_TOKENS = {"${c.product.id}": 32 bytes} (o token só do ${c.product.name})` : ''}${Object.keys(c.product.generatedSecrets).map((k) => ` · ${k}`).join('')}`,
|
|
128
|
+
`o Worker do produto recebe: ${Object.keys(c.product.workerSecrets(fakeSecrets(c))).join(', ') || 'nenhum (só os opcionais que você der)'} — nunca o ADMIN_TOKEN`,
|
|
129
|
+
...(c.product.coreSecrets.length ? [`o Worker do Core também recebe: ${c.product.coreSecrets.join(', ')} (o mesmo valor dos dois lados)`] : []),
|
|
130
|
+
`gravar ${STATE_DIR}/secrets.env (0600, fora do git) — nunca troca um segredo que já existe`,
|
|
131
|
+
],
|
|
132
|
+
async run(c) {
|
|
133
|
+
const s = c.secrets;
|
|
134
|
+
s.MASTER_KEY ||= randomBytes(32).toString('base64');
|
|
135
|
+
s.ADMIN_TOKEN ||= 'adm_' + randomBytes(24).toString('base64url');
|
|
136
|
+
// Core service route (find person / people by role): the product does NOT receive the ADMIN_TOKEN
|
|
137
|
+
s.SERVICE_TOKEN ||= 'svc_' + randomBytes(24).toString('base64url');
|
|
138
|
+
// THIS product's token (the Core's SERVICE_TOKENS, AUTH-API.md): the product Worker receives this one, not the common one
|
|
139
|
+
s.PRODUCT_SERVICE_TOKEN ||= `svc_${c.product.id}_` + randomBytes(32).toString('base64url');
|
|
140
|
+
// the product's own (e.g. Chat: CHAT_SECRETS_KEY; Widgets: WIDGETS_VISITOR_KEY, WIDGETS_SECRETS_KEY)
|
|
141
|
+
for (const [k, gen] of Object.entries(c.product.generatedSecrets))
|
|
142
|
+
s[k] ||= gen();
|
|
143
|
+
saveSecrets(c.dir, s);
|
|
144
|
+
c.out.ok(t('gen.secrets', { names: ['MASTER_KEY', 'ADMIN_TOKEN', 'SERVICE_TOKEN', ...(usesServiceToken(c) ? ['SERVICE_TOKENS'] : []), ...Object.keys(c.product.generatedSecrets)].join(', ') }));
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function installStep() {
|
|
149
|
+
return {
|
|
150
|
+
id: 'install',
|
|
151
|
+
title: t('step.install'),
|
|
152
|
+
hash: (c) => hashOf(c.product.installDirs.map((d) => fileHash(join(c.dir, d, 'pnpm-lock.yaml')))),
|
|
153
|
+
plan: (c) => c.product.installDirs.map((d) => `pnpm install --frozen-lockfile --prefer-offline (em ${d})`),
|
|
154
|
+
async run(c) {
|
|
155
|
+
for (const d of c.product.installDirs) {
|
|
156
|
+
await run(c, 'pnpm', ['install', '--frozen-lockfile', '--prefer-offline', '--reporter=silent'], { cwd: join(c.dir, d) });
|
|
157
|
+
c.out.ok(t('install.dir', { dir: d }));
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function scanStep() {
|
|
163
|
+
return {
|
|
164
|
+
id: 'scan',
|
|
165
|
+
title: t('step.scan'),
|
|
166
|
+
always: true,
|
|
167
|
+
plan: () => ['procurar cada segredo desta instalação e formatos de chave (sk_, whsec_, re_, osc1., PRIVATE KEY) nos arquivos que o git versionaria'],
|
|
168
|
+
async run(c) {
|
|
169
|
+
const values = [...Object.values(c.secrets), ...(c.credential ? [c.credential.type === 'license' ? c.credential.key : c.credential.purchaseCode] : [])];
|
|
170
|
+
const hits = scanForSecrets(c.dir, values);
|
|
171
|
+
if (hits.length)
|
|
172
|
+
throw new HumanError('secret_in_repo', { files: [...new Set(hits.map((h) => h.file))].join(', ') });
|
|
173
|
+
const n = countVersioned(c.dir);
|
|
174
|
+
c.out.ok(t('gen.scanOk', { n }));
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function countVersioned(dir) {
|
|
179
|
+
// for the message only: how many files outside .gitignore were read
|
|
180
|
+
let n = 0;
|
|
181
|
+
const walkCount = (rel) => {
|
|
182
|
+
for (const e of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
183
|
+
if (['node_modules', '.git', '.overture', '.wrangler', 'dist', '.expo'].includes(e.name))
|
|
184
|
+
continue;
|
|
185
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
186
|
+
if (e.isDirectory())
|
|
187
|
+
walkCount(r);
|
|
188
|
+
else
|
|
189
|
+
n++;
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
walkCount('');
|
|
193
|
+
return n;
|
|
194
|
+
}
|
|
195
|
+
// ─── cloud ─────────────────────────────────────────────────────────────────────────────────────
|
|
196
|
+
function cloudUrls(c) {
|
|
197
|
+
const n = names(c.answers, c.product);
|
|
198
|
+
const sub = c.state.resources.subdomain ?? 'SEU-SUBDOMINIO';
|
|
199
|
+
return {
|
|
200
|
+
auth: c.state.resources.workers.auth?.url ?? `https://${n.auth}.${sub}.workers.dev`,
|
|
201
|
+
api: c.state.resources.workers.api?.url ?? `https://${n.api}.${sub}.workers.dev`,
|
|
202
|
+
admin: c.state.resources.pages.admin?.url ?? `https://${n.admin}.pages.dev`,
|
|
203
|
+
// web app on Pages (Starter): the `<app>-app` project URL; the other products do not publish the app in the cloud
|
|
204
|
+
app: c.product.pages.some((p) => p.key === 'app') ? c.state.resources.pages.app?.url ?? `https://${c.answers.slug}-app.pages.dev` : null,
|
|
205
|
+
// product web page on Pages (Agenda: bookings) — otherwise nothing (the Widgets test page is local only)
|
|
206
|
+
site: (() => {
|
|
207
|
+
const pg = c.product.pages.find((p) => p.key === 'site');
|
|
208
|
+
return pg ? c.state.resources.pages.site?.url ?? `https://${c.answers.slug}-${pg.suffix}.pages.dev` : null;
|
|
209
|
+
})(),
|
|
210
|
+
opera: (c.env.ILORB_CHAT_URL || OPERA_CLOUD.chat).replace(/\/+$/, ''),
|
|
211
|
+
rooms: (c.env.ILORB_API_URL || OPERA_CLOUD.rooms).replace(/\/+$/, ''),
|
|
212
|
+
callMedia: true,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
const P = (c) => {
|
|
216
|
+
if (!c.provider)
|
|
217
|
+
throw new Error('sem provider da Cloudflare');
|
|
218
|
+
return c.provider;
|
|
219
|
+
};
|
|
220
|
+
function cloudSteps() {
|
|
221
|
+
const steps = [];
|
|
222
|
+
steps.push({
|
|
223
|
+
id: 'cf.auth',
|
|
224
|
+
title: t('step.cfAuth'),
|
|
225
|
+
always: true,
|
|
226
|
+
plan: () => CF_COMMANDS.auth(token()),
|
|
227
|
+
async run(c) {
|
|
228
|
+
const p = P(c);
|
|
229
|
+
const auth = await p.auth();
|
|
230
|
+
let acc = c.answers.cloudflare.accountId ? auth.accounts.find((a) => a.id === c.answers.cloudflare.accountId) : auth.accounts.length === 1 ? auth.accounts[0] : undefined;
|
|
231
|
+
if (c.answers.cloudflare.accountId && !acc)
|
|
232
|
+
throw new HumanError('cf_account_not_found', { account: c.answers.cloudflare.accountId });
|
|
233
|
+
if (!acc) {
|
|
234
|
+
if (!c.prompter)
|
|
235
|
+
throw new HumanError('missing_answer', { field: t('q.account'), flag: '--account-id <id>' });
|
|
236
|
+
const id = await c.prompter.select(t('q.account'), auth.accounts.map((a) => ({ value: a.id, label: a.name, hint: a.id })));
|
|
237
|
+
acc = auth.accounts.find((a) => a.id === id);
|
|
238
|
+
}
|
|
239
|
+
p.useAccount(acc.id);
|
|
240
|
+
c.answers.cloudflare = { accountId: acc.id, accountName: acc.name };
|
|
241
|
+
c.out.ok(`${t('cf.account', { name: acc.name, id: acc.id })} · ${auth.via === 'token' ? t('cf.via.token') : t('cf.via.wrangler')}${auth.email ? ` · ${auth.email}` : ''}`);
|
|
242
|
+
return { accountId: acc.id };
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
steps.push({
|
|
246
|
+
id: 'cf.subdomain',
|
|
247
|
+
title: t('step.cfSubdomain'),
|
|
248
|
+
hash: (c) => hashOf(c.answers.cloudflare.accountId),
|
|
249
|
+
plan: () => CF_COMMANDS.subdomain(token()),
|
|
250
|
+
async run(c) {
|
|
251
|
+
const sub = await P(c).workersSubdomain();
|
|
252
|
+
if (sub) {
|
|
253
|
+
c.state.resources.subdomain = sub;
|
|
254
|
+
c.out.ok(t('cf.subdomain', { sub }));
|
|
255
|
+
}
|
|
256
|
+
else if (token())
|
|
257
|
+
throw new HumanError('cf_workers_subdomain_missing');
|
|
258
|
+
else
|
|
259
|
+
c.out.info(t('cf.subdomain', { sub: '?' }) + ' — 1º deploy');
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
return steps;
|
|
263
|
+
}
|
|
264
|
+
function d1Step(key, suffix) {
|
|
265
|
+
return {
|
|
266
|
+
id: `cf.d1.${key}`,
|
|
267
|
+
title: t('step.d1', { name: `<app>-${suffix}` }),
|
|
268
|
+
hash: (c) => hashOf(c.answers.cloudflare.accountId, names(c.answers, c.product).d1(suffix)),
|
|
269
|
+
plan: (c) => {
|
|
270
|
+
const n = names(c.answers, c.product).d1(suffix);
|
|
271
|
+
return [...CF_COMMANDS.findD1(n, token()), `se não existe: ${CF_COMMANDS.createD1(n, token()).join(' ')}`, 'se existe e NÃO foi criado por esta instalação: para com erro (nunca reaproveita)'];
|
|
272
|
+
},
|
|
273
|
+
async run(c) {
|
|
274
|
+
const p = P(c);
|
|
275
|
+
const name = names(c.answers, c.product).d1(suffix);
|
|
276
|
+
const mine = c.state.resources.d1[key];
|
|
277
|
+
const found = await p.findD1(name);
|
|
278
|
+
const pendingKey = `pending:d1:${name}`;
|
|
279
|
+
const pending = !!c.state.steps[pendingKey];
|
|
280
|
+
if (found && (mine?.id === found.id || pending)) {
|
|
281
|
+
c.state.resources.d1[key] = { name, id: found.id };
|
|
282
|
+
delete c.state.steps[pendingKey];
|
|
283
|
+
c.out.ok(t('cf.d1.reused', { id: found.id }));
|
|
284
|
+
return { id: found.id };
|
|
285
|
+
}
|
|
286
|
+
if (found)
|
|
287
|
+
throw new HumanError('cf_d1_name_taken', { name });
|
|
288
|
+
// mark the intent BEFORE creating: if the process dies between "created" and saving, the next run adopts it
|
|
289
|
+
c.state.steps[pendingKey] = { status: 'done', hash: '', at: new Date().toISOString() };
|
|
290
|
+
saveState(c.dir, c.state);
|
|
291
|
+
const created = await p.createD1(name);
|
|
292
|
+
c.state.resources.d1[key] = { name, id: created.id };
|
|
293
|
+
delete c.state.steps[pendingKey];
|
|
294
|
+
c.out.ok(t('cf.d1.created', { id: created.id }));
|
|
295
|
+
return { id: created.id };
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function r2Step(key, suffix) {
|
|
300
|
+
return {
|
|
301
|
+
id: `cf.r2.${key}`,
|
|
302
|
+
title: t('step.r2', { name: `<app>-${suffix}` }),
|
|
303
|
+
hash: (c) => hashOf(c.answers.cloudflare.accountId, names(c.answers, c.product).r2(suffix)),
|
|
304
|
+
plan: (c) => {
|
|
305
|
+
const n = names(c.answers, c.product).r2(suffix);
|
|
306
|
+
return [...CF_COMMANDS.findR2(n, token()), `se não existe: ${CF_COMMANDS.createR2(n, token()).join(' ')}`];
|
|
307
|
+
},
|
|
308
|
+
async run(c) {
|
|
309
|
+
const p = P(c);
|
|
310
|
+
const name = names(c.answers, c.product).r2(suffix);
|
|
311
|
+
if (await p.findR2(name)) {
|
|
312
|
+
c.state.resources.r2[key] = { name };
|
|
313
|
+
c.out.ok(t('cf.r2.reused'));
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
await p.createR2(name);
|
|
317
|
+
c.state.resources.r2[key] = { name };
|
|
318
|
+
c.out.ok(t('cf.r2.created'));
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function queueStep(key, suffix) {
|
|
323
|
+
return {
|
|
324
|
+
id: `cf.queue.${key}`,
|
|
325
|
+
title: t('step.queue', { name: `<app>-${suffix}` }),
|
|
326
|
+
hash: (c) => hashOf(c.answers.cloudflare.accountId, `${c.answers.slug}-${suffix}`),
|
|
327
|
+
plan: (c) => [...CF_COMMANDS.findQueue(`${c.answers.slug}-${suffix}`, token()), `se não existe: ${CF_COMMANDS.createQueue(`${c.answers.slug}-${suffix}`, token()).join(' ')}`],
|
|
328
|
+
async run(c) {
|
|
329
|
+
const name = `${c.answers.slug}-${suffix}`;
|
|
330
|
+
if (!(await P(c).findQueue(name)))
|
|
331
|
+
await P(c).createQueue(name);
|
|
332
|
+
c.state.resources.queues[key] = { name };
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/** Product Pages: the panel (`admin`, always) and, in Starter, the customer's web app (`app`, the Expo export) */
|
|
337
|
+
function pagesProjectStep(key, suffix) {
|
|
338
|
+
const nm = (c) => `${c.answers.slug}-${suffix}`;
|
|
339
|
+
return {
|
|
340
|
+
id: `cf.pages.${key}`,
|
|
341
|
+
title: t('step.pagesProject', { name: `<app>-${suffix}` }),
|
|
342
|
+
hash: (c) => hashOf(c.answers.cloudflare.accountId, nm(c)),
|
|
343
|
+
plan: (c) => [...CF_COMMANDS.findPages(nm(c), token()), `se não existe: ${CF_COMMANDS.createPages(nm(c), token()).join(' ')}`],
|
|
344
|
+
async run(c) {
|
|
345
|
+
const p = P(c);
|
|
346
|
+
const name = nm(c);
|
|
347
|
+
const found = await p.findPages(name);
|
|
348
|
+
// Pages: the name is global; finding the project IN THIS account = it is ours (from a previous run) → reuse it
|
|
349
|
+
const sub = found?.subdomain ?? (await p.createPages(name)).subdomain;
|
|
350
|
+
c.out.ok(found ? t('cf.pages.reused', { sub }) : t('cf.pages.created', { sub }));
|
|
351
|
+
c.state.resources.pages[key] = { name, url: `https://${sub}` };
|
|
352
|
+
c.state.resources.urls[key] = `https://${sub}`;
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function configStep() {
|
|
357
|
+
return {
|
|
358
|
+
id: 'config',
|
|
359
|
+
title: t('step.config'),
|
|
360
|
+
hash: (c) => hashOf(c.answers, c.answers.target === 'cloud' ? cloudUrls(c) : localUrls(c), c.state.resources.d1, c.state.local),
|
|
361
|
+
plan: (c) => c.answers.target === 'cloud'
|
|
362
|
+
? [
|
|
363
|
+
`${names(c.answers, c.product).auth}: wrangler.jsonc com o id do D1, PUBLIC_URL=${cloudUrls(c).auth}, OWNER_EMAIL, ENVIRONMENT=production, DELIVERY_MODE=send`,
|
|
364
|
+
`${names(c.answers, c.product).api}: wrangler.jsonc com o id do D1, service binding CORE → ${names(c.answers, c.product).auth}, vars ${Object.keys(c.product.workerVars(c.answers, cloudUrls(c), false)).join(', ')}`,
|
|
365
|
+
c.product.app ? 'app.json (nome, slug, bundle ids), eas.json e .env com as URLs; overture.json; overture.theme.json' : 'overture.json; overture.theme.json',
|
|
366
|
+
]
|
|
367
|
+
: [
|
|
368
|
+
c.product.opera
|
|
369
|
+
? `wrangler.jsonc dos Workers com as portas locais; .dev.vars (segredos locais e as chaves do app de TESTE do Ilorb Signal, fora do git) · chat do Ilorb Signal: ${localUrls(c).opera}`
|
|
370
|
+
: `wrangler.jsonc dos Workers com as portas locais${c.product.cron ? ` e o cron "${c.product.cron}"` : ''}; .dev.vars (segredos locais, fora do git) — sem Ilorb Signal`,
|
|
371
|
+
c.product.app ? 'app.json, .env do app, overture.json, overture.theme.json' : 'overture.json, overture.theme.json',
|
|
372
|
+
],
|
|
373
|
+
async run(c) {
|
|
374
|
+
const urls = c.answers.target === 'cloud' ? cloudUrls(c) : localUrls(c);
|
|
375
|
+
c.state.resources.urls = { ...c.state.resources.urls, auth: urls.auth, api: urls.api, ...(urls.app ? { app: urls.app } : {}), ...(urls.site ? { site: urls.site } : {}), ...(c.answers.target === 'local' ? { admin: urls.admin, ...(c.product.opera ? { opera: urls.opera } : {}) } : {}) };
|
|
376
|
+
const written = applyConfig({ dir: c.dir, product: c.product, answers: c.answers, state: c.state, urls, cliVersion: c.cliVersion });
|
|
377
|
+
if (c.answers.target === 'local')
|
|
378
|
+
written.push(...writeLocalFiles(c, urls));
|
|
379
|
+
c.out.ok(t('gen.applied', { n: written.length }));
|
|
380
|
+
return { urls };
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
function migrateStep(key, suffix, rel) {
|
|
385
|
+
return {
|
|
386
|
+
id: `cf.migrate.${key}`,
|
|
387
|
+
title: t('step.migrate', { name: `<app>-${suffix}` }),
|
|
388
|
+
hash: (c) => hashOf(c.state.resources.d1[key]?.id, listMigrations(join(c.dir, rel, 'migrations'))),
|
|
389
|
+
plan: (c) => CF_COMMANDS.migrate(names(c.answers, c.product).d1(suffix)).map((l) => `${l} (em ${rel})`),
|
|
390
|
+
async run(c) {
|
|
391
|
+
const r = await P(c).applyD1Migrations({ cwd: join(c.dir, rel), database: names(c.answers, c.product).d1(suffix) });
|
|
392
|
+
c.out.ok(t('cf.migrated', { n: r.applied }));
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
const listMigrations = (dir) => (existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.sql')).sort() : []);
|
|
397
|
+
const usesServiceToken = (c) => 'CORE_SERVICE_TOKEN' in c.product.workerSecrets(fakeSecrets(c));
|
|
398
|
+
/** The Core Worker: the usual 3 (+ SERVICE_TOKENS) + the ones the product asks for (Consultas: PAYMENTS_TOKEN, PAYMENTS_CALLBACK_SECRET) */
|
|
399
|
+
function coreSecrets(c) {
|
|
400
|
+
const s = c.secrets;
|
|
401
|
+
// SERVICE_TOKENS = {"<product>": token}, a JSON line (AUTH-API.md → "Per-product service token")
|
|
402
|
+
// — only when the product uses the service route (Status, Starter… do not receive CORE_SERVICE_TOKEN)
|
|
403
|
+
const tokens = usesServiceToken(c) ? { SERVICE_TOKENS: JSON.stringify({ [c.product.id]: s.PRODUCT_SERVICE_TOKEN ?? '…' }) } : {};
|
|
404
|
+
return { MASTER_KEY: s.MASTER_KEY, ADMIN_TOKEN: s.ADMIN_TOKEN, SERVICE_TOKEN: s.SERVICE_TOKEN, ...tokens, ...Object.fromEntries(c.product.coreSecrets.map((k) => [k, s[k] ?? '…'])) };
|
|
405
|
+
}
|
|
406
|
+
function workerSecrets(c, key) {
|
|
407
|
+
const s = c.secrets;
|
|
408
|
+
if (key === 'auth')
|
|
409
|
+
return coreSecrets(c);
|
|
410
|
+
// the product's comes from the ProductSpec — and NEVER carries the ADMIN_TOKEN (checked here too, not only in tests)
|
|
411
|
+
const out = c.product.workerSecrets(s);
|
|
412
|
+
if (s.ADMIN_TOKEN && Object.values(out).includes(s.ADMIN_TOKEN))
|
|
413
|
+
throw new Error(`o Worker do ${c.product.id} não pode receber o ADMIN_TOKEN`);
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
function deployStep(key, rel, product) {
|
|
417
|
+
// the product Worker that embeds a build (Widgets: the compiled widget) publishes again when the build changes
|
|
418
|
+
const built = key === 'api' && product.prebuild ? product.prebuild.output : null;
|
|
419
|
+
return {
|
|
420
|
+
id: `cf.deploy.${key}`,
|
|
421
|
+
title: t('step.deployWorker', { name: key === 'auth' ? '<app>-auth' : `<app>-${product.api.suffix}` }),
|
|
422
|
+
hash: (c) => hashOf(fileHash(join(c.dir, rel, 'wrangler.jsonc')), sha(JSON.stringify(workerSecrets(c, key))), ...(built ? [fileHash(join(c.dir, built))] : [])),
|
|
423
|
+
plan: (c) => CF_COMMANDS.deploy(Object.keys(workerSecrets(c, key))).map((l) => `${l} (em ${rel})`),
|
|
424
|
+
async run(c) {
|
|
425
|
+
const p = P(c);
|
|
426
|
+
const name = key === 'auth' ? names(c.answers, c.product).auth : names(c.answers, c.product).api;
|
|
427
|
+
let { url } = await p.deployWorker({ cwd: join(c.dir, rel), name, secrets: workerSecrets(c, key) });
|
|
428
|
+
url ??= cloudUrls(c)[key];
|
|
429
|
+
c.state.resources.workers[key] = { name, url };
|
|
430
|
+
c.state.resources.urls[key] = url;
|
|
431
|
+
// without a token the <sub>.workers.dev cannot be known beforehand: the 1st deploy reveals it, the config is redone and published again
|
|
432
|
+
const sub = /^https:\/\/[^.]+\.([^.]+)\.workers\.dev/.exec(url)?.[1];
|
|
433
|
+
if (sub && !c.state.resources.subdomain) {
|
|
434
|
+
c.state.resources.subdomain = sub;
|
|
435
|
+
applyConfig({ dir: c.dir, product: c.product, answers: c.answers, state: c.state, urls: cloudUrls(c), cliVersion: c.cliVersion });
|
|
436
|
+
await p.deployWorker({ cwd: join(c.dir, rel), name, secrets: {} });
|
|
437
|
+
}
|
|
438
|
+
c.out.ok(t('cf.deployed', { url }));
|
|
439
|
+
return { url };
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
/** build that the product Worker embeds (Widgets: web/js/build.mjs → api/workers/src/generated/assets.ts) */
|
|
444
|
+
function prebuildStep(pb) {
|
|
445
|
+
return {
|
|
446
|
+
id: pb.id,
|
|
447
|
+
title: t('step.prebuild', { dir: pb.dir }),
|
|
448
|
+
hash: (c) => hashOf(pb.inputs.map((rel) => treeHash(join(c.dir, rel))), existsSync(join(c.dir, pb.output))),
|
|
449
|
+
plan: () => [`node ${pb.script} (em ${pb.dir}) → ${pb.output}`],
|
|
450
|
+
async run(c) {
|
|
451
|
+
await run(c, process.execPath, [pb.script], { cwd: join(c.dir, pb.dir) });
|
|
452
|
+
c.out.ok(t('build.prebuild', { out: pb.output }));
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
/** hash of the content of a file or of a whole folder (names + content) */
|
|
457
|
+
function treeHash(path) {
|
|
458
|
+
if (!existsSync(path))
|
|
459
|
+
return 'none';
|
|
460
|
+
if (!statSync(path).isDirectory())
|
|
461
|
+
return fileHash(path);
|
|
462
|
+
return sha(readdirSync(path, { recursive: true }).map(String).sort().map((f) => `${f}:${statSync(join(path, f)).isDirectory() ? 'd' : fileHash(join(path, f))}`).join('|'));
|
|
463
|
+
}
|
|
464
|
+
/** product web page (Agenda: web/embed): `pnpm run build` with the API URL (index.html also carries the <meta>) */
|
|
465
|
+
function webBuildStep(wb) {
|
|
466
|
+
return {
|
|
467
|
+
id: 'build.site',
|
|
468
|
+
title: t('step.webBuild', { dir: wb.dir }),
|
|
469
|
+
hash: (c) => hashOf(c.state.resources.urls.api, fileHash(join(c.dir, wb.dir, 'index.html')), treeHash(join(c.dir, wb.dir, 'src'))),
|
|
470
|
+
plan: (c) => [`${wb.apiEnv}=${c.answers.target === 'cloud' ? cloudUrls(c).api : localUrls(c).api} pnpm run ${wb.script} (em ${wb.dir}) → dist/`],
|
|
471
|
+
async run(c) {
|
|
472
|
+
await run(c, 'pnpm', ['run', wb.script], { cwd: join(c.dir, wb.dir), env: { [wb.apiEnv]: c.state.resources.urls.api } });
|
|
473
|
+
c.out.ok(t('build.webBuild', { url: c.state.resources.urls.api }));
|
|
474
|
+
},
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function buildPanelStep() {
|
|
478
|
+
return {
|
|
479
|
+
id: 'build.panel',
|
|
480
|
+
title: t('step.buildPanel'),
|
|
481
|
+
hash: (c) => hashOf(c.state.resources.urls.auth),
|
|
482
|
+
plan: (c) => [`VITE_AUTH_URL=${c.answers.target === 'cloud' ? cloudUrls(c).auth : localUrls(c).auth} pnpm build (em overture-core/web/react)`],
|
|
483
|
+
async run(c) {
|
|
484
|
+
const url = c.state.resources.urls.auth;
|
|
485
|
+
await run(c, 'pnpm', ['run', 'build'], { cwd: join(c.dir, 'overture-core/web/react'), env: { VITE_AUTH_URL: url } });
|
|
486
|
+
c.out.ok(t('build.panel', { url }));
|
|
487
|
+
},
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
function deployPagesStep(key, suffix, dir) {
|
|
491
|
+
const nm = (c) => `${c.answers.slug}-${suffix}`;
|
|
492
|
+
// publishes again when the build changes (panel: build.panel; web app: build.app; product page: build.site)
|
|
493
|
+
const build = key === 'admin' ? 'build.panel' : key === 'app' ? 'build.app' : 'build.site';
|
|
494
|
+
return {
|
|
495
|
+
id: `cf.deploy.${key}`,
|
|
496
|
+
title: t('step.deployPages', { name: `<app>-${suffix}` }),
|
|
497
|
+
hash: (c) => hashOf(c.state.steps[build]?.at),
|
|
498
|
+
plan: (c) => CF_COMMANDS.deployPages(nm(c), 'dist').map((l) => `${l} (em ${dir})`),
|
|
499
|
+
async run(c) {
|
|
500
|
+
const r = await P(c).deployPages({ cwd: join(c.dir, dir), project: nm(c), dir: 'dist' });
|
|
501
|
+
c.state.resources.pages[key] = { name: nm(c), url: r.url };
|
|
502
|
+
c.state.resources.urls[key] = r.url;
|
|
503
|
+
c.out.ok(t('cf.deployed', { url: r.url }));
|
|
504
|
+
},
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function coreStep(always = false) {
|
|
508
|
+
return {
|
|
509
|
+
id: 'core.configure',
|
|
510
|
+
title: t('step.configureCore'),
|
|
511
|
+
always,
|
|
512
|
+
hash: (c) => hashOf(c.answers.appName, c.answers.theme, c.answers.languages, c.state.resources.urls, sha(c.secrets.RESEND_API_KEY ?? ''), c.answers.email.from),
|
|
513
|
+
plan: (c) => [
|
|
514
|
+
`GET ${c.state.resources.urls.auth ?? '<auth>'}/v1/admin/settings (Bearer ADMIN_TOKEN)`,
|
|
515
|
+
`PUT /v1/admin/settings {appName:"${c.answers.appName}", theme, locales:[${c.answers.languages.join(',')}], products:[{id:"${c.product.id}", name:"${c.product.core.name(c.answers)}", platforms:[${c.product.core.platforms.join(',')}], apiUrl}], corsOrigins:[painel], accountUrl:"<painel>/account"${c.product.app ? `, oauthRedirects:["${c.answers.slug}://auth"${c.state.resources.urls.app ? ', <app web>' : ''}]` : ''}} — só o que mudou`,
|
|
516
|
+
'GET /v1/admin/auth/methods → PUT [{id:"email_code", enabled:true, position:0, primary:true' + (c.secrets.RESEND_API_KEY ? ', secrets:{resendApiKey, from}' : '') + '}] se precisar',
|
|
517
|
+
],
|
|
518
|
+
async run(c) {
|
|
519
|
+
const f = c.answers.target === 'cloud' ? P(c).fetchDeployed : c.fetch;
|
|
520
|
+
const urls = c.state.resources.urls;
|
|
521
|
+
const prev = c.state.steps['core.configure']?.outputs;
|
|
522
|
+
const emailHash = sha(`${c.secrets.RESEND_API_KEY ?? ''}|${c.answers.email.from ?? ''}`);
|
|
523
|
+
const setup = {
|
|
524
|
+
authUrl: urls.auth,
|
|
525
|
+
adminToken: c.secrets.ADMIN_TOKEN,
|
|
526
|
+
appName: c.answers.appName,
|
|
527
|
+
theme: c.answers.theme,
|
|
528
|
+
product: { id: c.product.id, name: c.product.core.name(c.answers), platforms: [...c.product.core.platforms], apiUrl: urls.api ?? null },
|
|
529
|
+
locales: c.answers.languages,
|
|
530
|
+
// + the product Worker URL when its page calls the Core from the browser (Shop: the storefront checkout)
|
|
531
|
+
corsOrigins: [urls.admin, urls.app, urls.site, c.product.coreCorsApi ? urls.api : null].filter((u) => !!u && u.startsWith('https://')),
|
|
532
|
+
// redirect login (GitHub/Discord/LinkedIn…): the return to the app (app.json's scheme = the slug) and the web app
|
|
533
|
+
oauthRedirects: c.product.app ? [`${c.answers.slug}://auth`, ...(urls.app ? [urls.app.replace(/\/+$/, '')] : [])] : [],
|
|
534
|
+
// the Account screen route in the Core panel (overture-core/web/react/src/app/routes.ts: '/account')
|
|
535
|
+
accountUrl: urls.admin ? `${urls.admin.replace(/\/+$/, '')}/account` : null,
|
|
536
|
+
email: c.secrets.RESEND_API_KEY && c.answers.email.from ? { resendApiKey: c.secrets.RESEND_API_KEY, from: c.answers.email.from } : null,
|
|
537
|
+
emailAlreadySet: prev?.emailHash === emailHash,
|
|
538
|
+
};
|
|
539
|
+
// a freshly published Worker can take a few seconds to answer on workers.dev
|
|
540
|
+
let last;
|
|
541
|
+
for (let i = 0; i < 6; i++) {
|
|
542
|
+
try {
|
|
543
|
+
const r = await configureCore(setup, f);
|
|
544
|
+
c.out.ok(r.changed.length ? t('core.configured', { product: c.product.id, changes: r.changed.join(', ') }) : t('core.unchanged'));
|
|
545
|
+
return { emailHash: setup.email ? emailHash : prev?.emailHash ?? null };
|
|
546
|
+
}
|
|
547
|
+
catch (e) {
|
|
548
|
+
last = e;
|
|
549
|
+
const retry = e instanceof HumanError && (e.code === 'core_unreachable' || (e.code === 'core_admin_rejected' && (e.vars.status === 404 || Number(e.vars.status) >= 500)));
|
|
550
|
+
if (!retry)
|
|
551
|
+
throw e;
|
|
552
|
+
await new Promise((r) => setTimeout(r, c.env.OVERTURE_FAST_RETRY ? 10 : 2000 * (i + 1)));
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
throw last;
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
/** Owner's first-access link: generated on EVERY run (single use, 15 min) and shown only on screen — the owner signs in to the panel
|
|
560
|
+
* without a code and without an email provider. Failing here does not bring the installation down: the final screen explains what to do. */
|
|
561
|
+
function bootstrapStep() {
|
|
562
|
+
return {
|
|
563
|
+
id: 'core.bootstrap',
|
|
564
|
+
title: t('step.bootstrap'),
|
|
565
|
+
always: true,
|
|
566
|
+
plan: (c) => [`POST ${c.state.resources.urls.auth ?? '<auth>'}/v1/admin/bootstrap-link {email:"${c.answers.ownerEmail}", panelUrl:"${c.state.resources.urls.admin ?? '<painel>'}"} (Bearer ADMIN_TOKEN) → link de uso único, 15 min, só na tela`],
|
|
567
|
+
async run(c) {
|
|
568
|
+
const f = c.answers.target === 'cloud' ? P(c).fetchDeployed : c.fetch;
|
|
569
|
+
const urls = c.state.resources.urls;
|
|
570
|
+
try {
|
|
571
|
+
c.bootstrap = await createBootstrapLink(urls.auth, c.secrets.ADMIN_TOKEN, urls.admin ?? null, c.answers.ownerEmail, f);
|
|
572
|
+
c.bootstrapError = null;
|
|
573
|
+
c.out.ok(t('bootstrap.ok'));
|
|
574
|
+
}
|
|
575
|
+
catch (e) {
|
|
576
|
+
c.bootstrap = null;
|
|
577
|
+
c.bootstrapError = e instanceof HumanError ? e.code : 'unexpected';
|
|
578
|
+
c.out.warn(t('bootstrap.failed'));
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/** Sample data (Quiz): the CLI signs in as the owner through its OWN first-access link (ADMIN_TOKEN → /v1/auth/bootstrap →
|
|
584
|
+
* panel access token) and calls the product. Runs BEFORE the owner's link (the new link wins over this one). Failing does not bring down the
|
|
585
|
+
* installation: it warns and the buyer imports through the panel. */
|
|
586
|
+
function sampleImportStep(si) {
|
|
587
|
+
return {
|
|
588
|
+
id: 'sample.import',
|
|
589
|
+
title: t('step.sampleImport'),
|
|
590
|
+
hash: (c) => hashOf(!!c.answers.sampleData, fileHash(join(c.dir, si.file)), c.state.resources.urls.api),
|
|
591
|
+
plan: (c) => c.answers.sampleData
|
|
592
|
+
? [`POST ${c.state.resources.urls.auth ?? '<auth>'}/v1/admin/bootstrap-link (ADMIN_TOKEN) → POST /v1/auth/bootstrap → token do painel do dono`, `POST ${c.state.resources.urls.api ?? '<api>'}${si.path} {csv: ${si.file}, ${Object.keys(si.extra).join(', ')}}`]
|
|
593
|
+
: ['pular (sem --sample-data)'],
|
|
594
|
+
async run(c) {
|
|
595
|
+
if (!c.answers.sampleData) {
|
|
596
|
+
c.out.info(t('sample.skipped'));
|
|
597
|
+
return { imported: null };
|
|
598
|
+
}
|
|
599
|
+
const f = c.answers.target === 'cloud' ? P(c).fetchDeployed : c.fetch;
|
|
600
|
+
const urls = c.state.resources.urls;
|
|
601
|
+
const post = async (url, body, token) => {
|
|
602
|
+
const r = await f(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body), signal: AbortSignal.timeout(30_000) });
|
|
603
|
+
const text = await r.text();
|
|
604
|
+
if (!r.ok)
|
|
605
|
+
throw new Error(`${r.status} ${new URL(url).pathname}: ${text.slice(0, 200)}`);
|
|
606
|
+
return text ? JSON.parse(text) : {};
|
|
607
|
+
};
|
|
608
|
+
try {
|
|
609
|
+
const link = (await post(`${urls.auth}/v1/admin/bootstrap-link`, { email: c.answers.ownerEmail }, c.secrets.ADMIN_TOKEN));
|
|
610
|
+
const session = (await post(`${urls.auth}/v1/auth/bootstrap`, { token: link.token }, null));
|
|
611
|
+
const csv = readFileSync(join(c.dir, si.file), 'utf8');
|
|
612
|
+
const r = (await post(`${urls.api}${si.path}`, { csv, ...si.extra }, session.accessToken));
|
|
613
|
+
c.out.ok(t('sample.imported', { n: r.imported ?? '?' }));
|
|
614
|
+
return { imported: r.imported ?? null };
|
|
615
|
+
}
|
|
616
|
+
catch (e) {
|
|
617
|
+
c.out.log(String(e.message));
|
|
618
|
+
c.out.warn(t('sample.failed'));
|
|
619
|
+
return { imported: null, failed: true };
|
|
620
|
+
}
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
/** Product checks after configuring (ProductSpec.smoke). They do not bring the installation down: each one warns. */
|
|
625
|
+
function smokeStep(list) {
|
|
626
|
+
return {
|
|
627
|
+
id: 'verify',
|
|
628
|
+
title: t('step.verify'),
|
|
629
|
+
always: true,
|
|
630
|
+
plan: (c) => list.map((s) => `GET ${c.state.resources.urls.api ?? '<api>'}${s.path} → ${s.status}${s.check ? ' (+ o conteúdo)' : ''}`),
|
|
631
|
+
async run(c) {
|
|
632
|
+
if (c.provider?.kind === 'simulated') {
|
|
633
|
+
c.out.info(t('verify.simulated'));
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const f = c.answers.target === 'cloud' ? P(c).fetchDeployed : c.fetch;
|
|
637
|
+
let bad = 0;
|
|
638
|
+
for (const s of list) {
|
|
639
|
+
let ok = false;
|
|
640
|
+
let got = '';
|
|
641
|
+
try {
|
|
642
|
+
const r = await f(`${c.state.resources.urls.api}${s.path}`, { signal: AbortSignal.timeout(20_000) });
|
|
643
|
+
const text = await r.text();
|
|
644
|
+
got = String(r.status);
|
|
645
|
+
let body = null;
|
|
646
|
+
try {
|
|
647
|
+
body = JSON.parse(text);
|
|
648
|
+
}
|
|
649
|
+
catch { }
|
|
650
|
+
ok = r.status === s.status && (!s.check || s.check(body));
|
|
651
|
+
}
|
|
652
|
+
catch (e) {
|
|
653
|
+
got = e.message;
|
|
654
|
+
}
|
|
655
|
+
if (ok)
|
|
656
|
+
c.out.ok(s.label);
|
|
657
|
+
else {
|
|
658
|
+
bad++;
|
|
659
|
+
c.out.warn(`${s.label} — ${got}`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (bad)
|
|
663
|
+
c.out.warn(t('verify.failed', { n: bad }));
|
|
664
|
+
return { failed: bad };
|
|
665
|
+
},
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
export function buildSteps(product, target, answers, withLicense = true) {
|
|
669
|
+
// the license step only for the dormant paid path; free Ilorb Code templates start at generate
|
|
670
|
+
const common = [...(withLicense ? [licenseStep()] : []), generateStep(), secretsStep(), installStep()];
|
|
671
|
+
// build that the product Worker embeds (Widgets): before the Worker deploy/start
|
|
672
|
+
const prebuild = product.prebuild ? [prebuildStep(product.prebuild)] : [];
|
|
673
|
+
if (target === 'local') {
|
|
674
|
+
return [
|
|
675
|
+
...common,
|
|
676
|
+
// the product without Opera (Status) does not need an Opera TEST app
|
|
677
|
+
...(product.opera ? [operaTestAppStep()] : []),
|
|
678
|
+
localPortsStep(),
|
|
679
|
+
configStep(),
|
|
680
|
+
localMigrateStep(),
|
|
681
|
+
...prebuild,
|
|
682
|
+
buildPanelStep(),
|
|
683
|
+
...(product.webBuild ? [webBuildStep(product.webBuild)] : []),
|
|
684
|
+
...(product.app ? [exportAppStep()] : []),
|
|
685
|
+
scanStep(),
|
|
686
|
+
startStep(),
|
|
687
|
+
coreStep(true),
|
|
688
|
+
...(product.sampleImport ? [sampleImportStep(product.sampleImport)] : []),
|
|
689
|
+
...(product.smoke ? [smokeStep(product.smoke)] : []),
|
|
690
|
+
bootstrapStep(),
|
|
691
|
+
];
|
|
692
|
+
}
|
|
693
|
+
return [
|
|
694
|
+
...common,
|
|
695
|
+
...cloudSteps(),
|
|
696
|
+
...product.d1.map((d) => d1Step(d.key, d.suffix)),
|
|
697
|
+
// Core R2 (THEME_BUCKET: appearance logo/favicon) + the product's
|
|
698
|
+
...[...CORE_R2, ...product.r2].map((r) => r2Step(r.key, r.suffix)),
|
|
699
|
+
...product.queues.map((q) => queueStep(q.key, q.suffix)),
|
|
700
|
+
// the paid-plan queue (Link: clicks) only when the buyer said they have the paid Workers plan
|
|
701
|
+
...(product.paidQueue && answers?.workersPaid ? [queueStep(product.paidQueue.key, product.paidQueue.suffix)] : []),
|
|
702
|
+
...product.pages.map((p) => pagesProjectStep(p.key, p.suffix)),
|
|
703
|
+
configStep(),
|
|
704
|
+
...product.d1.map((d) => migrateStep(d.key, d.suffix, d.dir)),
|
|
705
|
+
...prebuild,
|
|
706
|
+
deployStep('auth', 'overture-core/api/workers', product),
|
|
707
|
+
deployStep('api', product.api.dir, product),
|
|
708
|
+
buildPanelStep(),
|
|
709
|
+
deployPagesStep('admin', 'admin', 'overture-core/web/react'),
|
|
710
|
+
// web app of the customer on Pages (Starter): expo export --clear with the cloud URLs and the dist/ deploy
|
|
711
|
+
...product.pages.filter((p) => p.key === 'app').flatMap((p) => [exportAppStep(), deployPagesStep('app', p.suffix, p.dir)]),
|
|
712
|
+
// product web page (Agenda: bookings + embed.js): vite build with the API URL and the dist/ deploy
|
|
713
|
+
...(product.webBuild ? product.pages.filter((p) => p.key === 'site').flatMap((p) => [webBuildStep(product.webBuild), deployPagesStep('site', p.suffix, p.dir)]) : []),
|
|
714
|
+
coreStep(),
|
|
715
|
+
...(product.sampleImport ? [sampleImportStep(product.sampleImport)] : []),
|
|
716
|
+
...(product.smoke ? [smokeStep(product.smoke)] : []),
|
|
717
|
+
bootstrapStep(),
|
|
718
|
+
scanStep(),
|
|
719
|
+
];
|
|
720
|
+
}
|
|
721
|
+
// ─── local ─────────────────────────────────────────────────────────────────────────────────────
|
|
722
|
+
/**
|
|
723
|
+
* INTERNAL variable (not documented to the buyer): points local mode at an Opera chat running on THIS machine (the
|
|
724
|
+
* copy in vendor/, which only exists in OUR repository) — so our e2e stay 100% local and never touch the
|
|
725
|
+
* published Opera. Without it, local uses the CLOUD Opera chat with the buyer's TEST app.
|
|
726
|
+
*/
|
|
727
|
+
export const INTERNAL_OPERA_CHAT_ENV = 'OVERTURE_INTERNAL_OPERA_CHAT_URL';
|
|
728
|
+
export const INTERNAL_OPERA_ROOMS_ENV = 'OVERTURE_INTERNAL_OPERA_ROOMS_URL';
|
|
729
|
+
function localUrls(c) {
|
|
730
|
+
const p = c.state.local?.ports;
|
|
731
|
+
const u = (k) => (p ? `http://localhost:${p[k]}` : `http://localhost:<${k}>`);
|
|
732
|
+
const internal = c.env[INTERNAL_OPERA_CHAT_ENV]?.trim();
|
|
733
|
+
// internal Opera chat without a rooms server: calls without media (port 9 = discarded)
|
|
734
|
+
const rooms = internal ? c.env[INTERNAL_OPERA_ROOMS_ENV]?.trim() || 'http://localhost:9' : c.env.ILORB_API_URL || OPERA_CLOUD.rooms;
|
|
735
|
+
const has = (k) => c.product.localPorts.includes(k);
|
|
736
|
+
return {
|
|
737
|
+
auth: u('auth'), api: u('api'), admin: u('admin'),
|
|
738
|
+
app: has('app') ? u('app') : null,
|
|
739
|
+
site: has('site') ? u('site') : null,
|
|
740
|
+
opera: (internal || c.env.ILORB_CHAT_URL || OPERA_CLOUD.chat).replace(/\/+$/, ''),
|
|
741
|
+
rooms: rooms.replace(/\/+$/, ''),
|
|
742
|
+
callMedia: !internal || !!c.env[INTERNAL_OPERA_ROOMS_ENV],
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
/** Local: the Opera chat is the CLOUD one, with the buyer's TEST app. Without the keys, stops here with the path. */
|
|
746
|
+
function operaTestAppStep() {
|
|
747
|
+
return {
|
|
748
|
+
id: 'local.opera',
|
|
749
|
+
title: t('step.operaTestApp'),
|
|
750
|
+
always: true,
|
|
751
|
+
plan: (c) => [`conferir App ID (${c.answers.opera.appId ?? 'faltando'}) e App Secret (${c.secrets.OPERA_APP_SECRET ? 'ok' : 'faltando'}) do app de TESTE do Ilorb Signal · chat ${localUrls(c).opera}`],
|
|
752
|
+
async run(c) {
|
|
753
|
+
if (!c.answers.opera.appId || !c.secrets.OPERA_APP_SECRET)
|
|
754
|
+
throw new HumanError('opera_test_app_missing', { dir: c.dir });
|
|
755
|
+
c.out.ok(t('local.opera', { appId: c.answers.opera.appId, url: localUrls(c).opera }));
|
|
756
|
+
},
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
function localPortsStep() {
|
|
760
|
+
return {
|
|
761
|
+
id: 'local.ports',
|
|
762
|
+
title: t('step.localPorts'),
|
|
763
|
+
plan: (c) => {
|
|
764
|
+
const { base, insp } = portBase(c);
|
|
765
|
+
return [`escolher ${c.product.localPorts.length} portas livres a partir de ${base} (${c.product.localPorts.join(', ')}) + 2 do inspector a partir de ${insp}; gravar em overture.json`];
|
|
766
|
+
},
|
|
767
|
+
async run(c) {
|
|
768
|
+
const { base, insp } = portBase(c);
|
|
769
|
+
const ports = await pickPorts(c.product.localPorts, base, insp);
|
|
770
|
+
c.state.local = { ports: ports };
|
|
771
|
+
c.out.ok(t(c.product.app && c.product.localPorts.includes('site') ? 'local.ports.appSite' : c.product.app ? 'local.ports' : c.product.localPorts.includes('site') ? 'local.ports.site' : 'local.ports.web', { auth: ports.auth, api: ports.api, admin: ports.admin, app: ports.app ?? '', site: ports.site ?? '' }));
|
|
772
|
+
return { ports };
|
|
773
|
+
},
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* INTERNAL variable (not documented to the buyer): the 1st port of local mode (the inspectors sit 50 above). Only so
|
|
778
|
+
* OUR e2e stay in an agreed range; the buyer uses the default (8871 and 9381).
|
|
779
|
+
*/
|
|
780
|
+
export const INTERNAL_PORT_BASE_ENV = 'OVERTURE_INTERNAL_PORT_BASE';
|
|
781
|
+
function portBase(c) {
|
|
782
|
+
const n = Number(c.env[INTERNAL_PORT_BASE_ENV]);
|
|
783
|
+
return Number.isInteger(n) && n >= 1024 && n < 65000 ? { base: n, insp: n + 50 } : { base: 8871, insp: 9381 };
|
|
784
|
+
}
|
|
785
|
+
const LOCAL = `${STATE_DIR}/local`;
|
|
786
|
+
/** folder of each D1's local state (the same one scripts/dev-local.mjs hands to wrangler dev): core | <product> */
|
|
787
|
+
const localStateKey = (d1Key) => (d1Key === 'identity' ? 'core' : d1Key);
|
|
788
|
+
function writeLocalFiles(c, urls) {
|
|
789
|
+
const s = c.secrets;
|
|
790
|
+
writeDevVars(c.dir, 'overture-core/api/workers', coreSecrets(c));
|
|
791
|
+
// the local product server talks to the cloud Opera chat using the buyer's TEST app
|
|
792
|
+
const vars = c.product.localDevVars(c.answers, s, urls);
|
|
793
|
+
if (s.ADMIN_TOKEN && Object.values(vars).includes(s.ADMIN_TOKEN))
|
|
794
|
+
throw new Error(`o Worker do ${c.product.id} não pode receber o ADMIN_TOKEN`);
|
|
795
|
+
writeDevVars(c.dir, c.product.api.dir, vars);
|
|
796
|
+
return ['overture-core/api/workers/.dev.vars', `${c.product.api.dir}/.dev.vars`];
|
|
797
|
+
}
|
|
798
|
+
function localMigrateStep() {
|
|
799
|
+
const persist = (c, k) => join(c.dir, LOCAL, 'state', k);
|
|
800
|
+
return {
|
|
801
|
+
id: 'local.migrate',
|
|
802
|
+
title: t('step.localMigrate'),
|
|
803
|
+
hash: (c) => hashOf(c.state.local, ...c.product.d1.map((d) => listMigrations(join(c.dir, d.dir, d.migrations)))),
|
|
804
|
+
plan: (c) => c.product.d1.map((d) => `wrangler d1 migrations apply ${names(c.answers, c.product).d1(d.suffix)} --local --persist-to ${LOCAL}/state/${localStateKey(d.key)} (em ${d.dir})`),
|
|
805
|
+
async run(c) {
|
|
806
|
+
let n = 0;
|
|
807
|
+
const count = (out) => (out.match(/\d{4}_[\w-]+\.sql/g) ?? []).length;
|
|
808
|
+
for (const d of c.product.d1) {
|
|
809
|
+
const r = await run(c, wranglerBin(c, d.dir), ['d1', 'migrations', 'apply', names(c.answers, c.product).d1(d.suffix), '--local', '--persist-to', persist(c, localStateKey(d.key))], { cwd: join(c.dir, d.dir) });
|
|
810
|
+
n += count(r.stdout);
|
|
811
|
+
}
|
|
812
|
+
c.out.ok(t('local.migrated', { product: c.product.id, n }));
|
|
813
|
+
},
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
/** the app's EXPO_PUBLIC_*: the Core, the product API and (Starter) the app's web address */
|
|
817
|
+
function appEnv(c, urls) {
|
|
818
|
+
const a = c.product.app;
|
|
819
|
+
return { EXPO_PUBLIC_AUTH_URL: urls.auth ?? '<auth>', [a.apiEnv]: urls.api ?? '<api>', ...(a.webEnv ? { [a.webEnv]: urls.app ?? '<app>' } : {}) };
|
|
820
|
+
}
|
|
821
|
+
function exportAppStep() {
|
|
822
|
+
return {
|
|
823
|
+
id: 'build.app',
|
|
824
|
+
title: t('step.exportApp'),
|
|
825
|
+
hash: (c) => hashOf('clear', c.state.resources.urls.auth, c.state.resources.urls.api, c.product.app?.webEnv ? c.state.resources.urls.app : null, fileHash(join(c.dir, c.product.app.dir, 'app.json'))),
|
|
826
|
+
plan: (c) => {
|
|
827
|
+
const u = c.answers.target === 'cloud' ? cloudUrls(c) : localUrls(c);
|
|
828
|
+
const env = Object.entries(appEnv(c, u)).map(([k, v]) => `${k}=${v}`).join(' ');
|
|
829
|
+
return [`${env} expo export --platform web --clear (em ${c.product.app.dir}; --clear: o cache do Metro não guarda as variáveis EXPO_PUBLIC_*)`];
|
|
830
|
+
},
|
|
831
|
+
async run(c) {
|
|
832
|
+
const bin = join(c.dir, c.product.app.dir, 'node_modules/.bin', process.platform === 'win32' ? 'expo.cmd' : 'expo');
|
|
833
|
+
// --clear: the Metro cache is shared and does NOT take EXPO_PUBLIC_* into account (without it, another build's URL comes out)
|
|
834
|
+
await run(c, bin, ['export', '--platform', 'web', '--clear'], { cwd: join(c.dir, c.product.app.dir), env: appEnv(c, c.state.resources.urls) });
|
|
835
|
+
c.out.ok(t('build.app'));
|
|
836
|
+
},
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
function startStep() {
|
|
840
|
+
return {
|
|
841
|
+
id: 'local.start',
|
|
842
|
+
title: t('step.start'),
|
|
843
|
+
always: true,
|
|
844
|
+
plan: (c) => [
|
|
845
|
+
`node scripts/dev-local.mjs → wrangler dev (Core Auth, API do ${c.product.name}) + ${c.product.webBuild ? 'painel, app e página de reservas estáticos' : c.product.app ? 'painel e app estáticos' : c.product.localPorts.includes('site') ? 'painel estático e a página de teste com o snippet' : 'painel estático'}; espera cada um responder${c.product.opera ? ' (o chat do Ilorb Signal é o da nuvem)' : ''}`,
|
|
846
|
+
...(c.product.cron ? [`cron "${c.product.cron}" (Core e API do ${c.product.name}): wrangler dev --test-scheduled + GET /__scheduled a cada minuto`] : []),
|
|
847
|
+
],
|
|
848
|
+
async run(c) {
|
|
849
|
+
const ports = c.state.local.ports;
|
|
850
|
+
for (const [k, p] of Object.entries(ports))
|
|
851
|
+
if (p && !(await isFree(p)))
|
|
852
|
+
throw new HumanError('port_busy', { port: p, service: k });
|
|
853
|
+
c.out.info(t(!c.product.opera && c.product.app ? 'local.starting.plain' : c.product.app ? 'local.starting' : c.product.localPorts.includes('site') ? 'local.starting.site' : 'local.starting.web', { product: c.product.name }));
|
|
854
|
+
const child = spawn(process.execPath, [join(c.dir, 'scripts/dev-local.mjs')], { cwd: c.dir, env: { ...process.env, OVERTURE_CHILD: '1' }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
855
|
+
c.child = child;
|
|
856
|
+
let buf = '';
|
|
857
|
+
await new Promise((resolve, reject) => {
|
|
858
|
+
const onData = (d) => {
|
|
859
|
+
buf += d;
|
|
860
|
+
c.out.log(String(d).trimEnd());
|
|
861
|
+
if (buf.includes('OVERTURE_READY'))
|
|
862
|
+
resolve();
|
|
863
|
+
const m = /OVERTURE_ERROR (\S+) (\S+)([^\n]*)\n?([\s\S]*)/.exec(buf);
|
|
864
|
+
if (m)
|
|
865
|
+
reject(m[1] === 'port_busy' ? new HumanError('port_busy', { port: m[2] }) : new HumanError('local_start_failed', { service: m[2] }, m[4]));
|
|
866
|
+
};
|
|
867
|
+
child.stdout.on('data', onData);
|
|
868
|
+
child.stderr.on('data', onData);
|
|
869
|
+
child.on('exit', (code) => reject(new HumanError('local_start_failed', { service: 'dev-local' }, `saída ${code}\n${tail(buf, 25)}`)));
|
|
870
|
+
});
|
|
871
|
+
c.out.ok(t('local.ready'));
|
|
872
|
+
},
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
export { localUrls, cloudUrls, names, maskCredential };
|