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