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/dist/exec.js ADDED
@@ -0,0 +1,49 @@
1
+ // Running external commands (pnpm, wrangler, expo, tar). Everything goes through here so tests can swap in a fake
2
+ // and so --dry-run shows exactly what would run.
3
+ import { spawn } from 'node:child_process';
4
+ export const realExec = (cmd, args, opts = {}) => new Promise((resolve) => {
5
+ const p = spawn(cmd, args, {
6
+ cwd: opts.cwd,
7
+ env: { ...process.env, CI: '1', WRANGLER_SEND_METRICS: 'false', ...opts.env },
8
+ stdio: ['pipe', 'pipe', 'pipe'],
9
+ shell: process.platform === 'win32',
10
+ });
11
+ let stdout = '';
12
+ let stderr = '';
13
+ let timer;
14
+ if (opts.timeoutMs)
15
+ timer = setTimeout(() => p.kill('SIGTERM'), opts.timeoutMs);
16
+ p.stdout.on('data', (d) => {
17
+ stdout += d;
18
+ if (opts.live)
19
+ process.stdout.write(d);
20
+ });
21
+ p.stderr.on('data', (d) => {
22
+ stderr += d;
23
+ if (opts.live)
24
+ process.stderr.write(d);
25
+ });
26
+ p.on('error', (e) => {
27
+ if (timer)
28
+ clearTimeout(timer);
29
+ resolve({ code: 127, stdout, stderr: stderr + String(e.message) });
30
+ });
31
+ p.on('close', (code) => {
32
+ if (timer)
33
+ clearTimeout(timer);
34
+ resolve({ code: code ?? 1, stdout, stderr });
35
+ });
36
+ if (opts.input !== undefined)
37
+ p.stdin.end(opts.input);
38
+ else
39
+ p.stdin.end();
40
+ });
41
+ /** Readable command line for the plan and the error message (with quotes when needed). */
42
+ export function shellLine(cmd, args) {
43
+ const q = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
44
+ return [cmd, ...args].map(q).join(' ');
45
+ }
46
+ /** Last lines of an output (to show in the error without dumping everything). */
47
+ export function tail(text, lines = 12) {
48
+ return text.trim().split('\n').slice(-lines).join('\n');
49
+ }
package/dist/fsutil.js ADDED
@@ -0,0 +1,130 @@
1
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, relative, sep } from 'node:path';
3
+ /** Strips // and /* *\/ comments and trailing commas from a JSONC, respecting strings ("https://…" stays). */
4
+ export function stripJsonc(src) {
5
+ let out = '';
6
+ let i = 0;
7
+ let inStr = false;
8
+ while (i < src.length) {
9
+ const c = src[i];
10
+ const n = src[i + 1];
11
+ if (inStr) {
12
+ out += c;
13
+ if (c === '\\') {
14
+ out += n ?? '';
15
+ i += 2;
16
+ continue;
17
+ }
18
+ if (c === '"')
19
+ inStr = false;
20
+ i++;
21
+ continue;
22
+ }
23
+ if (c === '"') {
24
+ inStr = true;
25
+ out += c;
26
+ i++;
27
+ continue;
28
+ }
29
+ if (c === '/' && n === '/') {
30
+ while (i < src.length && src[i] !== '\n')
31
+ i++;
32
+ continue;
33
+ }
34
+ if (c === '/' && n === '*') {
35
+ i += 2;
36
+ while (i < src.length && !(src[i] === '*' && src[i + 1] === '/'))
37
+ i++;
38
+ i += 2;
39
+ continue;
40
+ }
41
+ out += c;
42
+ i++;
43
+ }
44
+ return out.replace(/,(\s*[}\]])/g, '$1');
45
+ }
46
+ export const readJsonc = (file) => JSON.parse(stripJsonc(readFileSync(file, 'utf8')));
47
+ export const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
48
+ /** Writes atomically (temporary file + rename): a Ctrl+C in the middle does not leave the state half-written. */
49
+ export function writeFileAtomic(file, data, mode) {
50
+ mkdirSync(dirname(file), { recursive: true });
51
+ const tmp = `${file}.tmp-${process.pid}`;
52
+ writeFileSync(tmp, data, mode !== undefined ? { mode } : undefined);
53
+ if (mode !== undefined)
54
+ chmodSync(tmp, mode);
55
+ renameSync(tmp, file);
56
+ }
57
+ export const writeJson = (file, v, mode) => writeFileAtomic(file, JSON.stringify(v, null, 2) + '\n', mode);
58
+ /** Copies a tree skipping whatever `skip(name, relativePath)` says. Returns how many files. */
59
+ export function copyTree(src, dest, skip, base = src) {
60
+ const st = statSync(src);
61
+ if (st.isFile()) {
62
+ mkdirSync(dirname(dest), { recursive: true });
63
+ copyFileSync(src, dest);
64
+ return 1;
65
+ }
66
+ let n = 0;
67
+ mkdirSync(dest, { recursive: true });
68
+ for (const e of readdirSync(src, { withFileTypes: true })) {
69
+ const rel = relative(base, join(src, e.name)).split(sep).join('/');
70
+ if (skip(e.name, rel))
71
+ continue;
72
+ if (e.isSymbolicLink())
73
+ continue;
74
+ if (e.isDirectory())
75
+ n += copyTree(join(src, e.name), join(dest, e.name), skip, base);
76
+ else if (e.isFile()) {
77
+ copyFileSync(join(src, e.name), join(dest, e.name));
78
+ n++;
79
+ }
80
+ }
81
+ return n;
82
+ }
83
+ /** Lists files (relative, with "/") skipping folders by name. */
84
+ export function walk(root, skipDir = () => false, rel = '') {
85
+ const out = [];
86
+ const dir = join(root, rel);
87
+ if (!existsSync(dir))
88
+ return out;
89
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
90
+ const r = rel ? `${rel}/${e.name}` : e.name;
91
+ if (e.isDirectory()) {
92
+ if (!skipDir(e.name))
93
+ out.push(...walk(root, skipDir, r));
94
+ }
95
+ else if (e.isFile())
96
+ out.push(r);
97
+ }
98
+ return out;
99
+ }
100
+ /**
101
+ * What git would IGNORE in the generated project: the root .gitignore + the .gitignore of each folder (simple patterns,
102
+ * which are the only ones the templates use: "name", "name/", "*.ext", ".env.*"). Used by the secrets scan.
103
+ */
104
+ export function isIgnored(root, relFile) {
105
+ const parts = relFile.split('/');
106
+ for (let depth = 0; depth < parts.length; depth++) {
107
+ const dir = parts.slice(0, depth).join('/');
108
+ const gi = join(root, dir, '.gitignore');
109
+ if (!existsSync(gi))
110
+ continue;
111
+ const rest = parts.slice(depth);
112
+ const pats = readFileSync(gi, 'utf8').split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#') && !l.startsWith('!'));
113
+ for (const raw of pats) {
114
+ const anchored = raw.startsWith('/');
115
+ const p = raw.replace(/^\//, '').replace(/\/$/, '');
116
+ const re = new RegExp('^' + p.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*') + '$');
117
+ if (p.includes('/')) {
118
+ // pattern with a slash: matches the path from this folder
119
+ for (let k = 1; k <= rest.length; k++)
120
+ if (re.test(rest.slice(0, k).join('/')))
121
+ return true;
122
+ continue;
123
+ }
124
+ const candidates = anchored ? [rest[0]] : rest;
125
+ if (candidates.some((seg) => re.test(seg)))
126
+ return true;
127
+ }
128
+ }
129
+ return false;
130
+ }
@@ -0,0 +1,260 @@
1
+ // Generates the buyer's project: copies the templates (Core + product) and applies name, ids, URLs and theme.
2
+ // The templates do NOT move (they find each other through ../../../overture-core and ../../../vendor/…).
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { copyTree, isIgnored, readJson, readJsonc, walk, writeFileAtomic, writeJson } from "./fsutil.js";
7
+ import { COPY_EXCLUDE, COPY_EXCLUDE_RE, CORE_R2, FORBIDDEN_TEMPLATE_RE } from "./products.js";
8
+ import { formatEnv } from "./state.js";
9
+ export function copyTemplates(templatesRoot, dir, product) {
10
+ let n = 0;
11
+ for (const rel of product.templates) {
12
+ // the Opera chat server (vendor/…/apps) NEVER goes to the buyer — not even if someone puts it in the list
13
+ if (FORBIDDEN_TEMPLATE_RE.test(rel))
14
+ throw new Error(`template proibido: ${rel}`);
15
+ const src = join(templatesRoot, rel);
16
+ if (!existsSync(src))
17
+ throw Object.assign(new Error(rel), { missing: rel });
18
+ n += copyTree(src, join(dir, rel), (name, r) => {
19
+ if (COPY_EXCLUDE.has(name) || COPY_EXCLUDE_RE.some((re) => re.test(name)))
20
+ return true;
21
+ return FORBIDDEN_TEMPLATE_RE.test(`${rel}/${r}`);
22
+ });
23
+ }
24
+ return n;
25
+ }
26
+ export function missingTemplates(templatesRoot, product) {
27
+ return product.templates.filter((rel) => !existsSync(join(templatesRoot, rel)));
28
+ }
29
+ const ZERO_ID = '00000000-0000-0000-0000-000000000000';
30
+ const header = (from) => `// Gerado pelo create-overture a partir do template ${from} (o original, com comentários, está no pacote de templates).\n` +
31
+ `// Segredos NÃO ficam aqui: na nuvem vão no deploy (wrangler deploy --secrets-file); local, no .dev.vars (fora do git).\n`;
32
+ function writeWrangler(file, from, mut) {
33
+ const w = readJsonc(file);
34
+ mut(w);
35
+ writeFileAtomic(file, header(from) + JSON.stringify(w, null, 2) + '\n');
36
+ }
37
+ /** writes `<slug>-<suffix>` into each R2 with a binding (replaces the template's, keeps the others) */
38
+ function setR2(w, slug, r2) {
39
+ for (const r of r2) {
40
+ if (!r.binding)
41
+ continue;
42
+ const list = (w.r2_buckets ?? []).filter((b) => b.binding !== r.binding);
43
+ w.r2_buckets = [...list, { binding: r.binding, bucket_name: `${slug}-${r.suffix}` }];
44
+ }
45
+ }
46
+ export function applyConfig({ dir, product, answers, state, urls, cliVersion }) {
47
+ const a = answers;
48
+ const local = a.target === 'local';
49
+ const written = [];
50
+ const d1 = (key) => state.resources.d1[key]?.id ?? ZERO_ID;
51
+ const W = (rel, from, mut) => {
52
+ writeWrangler(join(dir, rel, 'wrangler.jsonc'), from, mut);
53
+ written.push(`${rel}/wrangler.jsonc`);
54
+ };
55
+ // Core Auth
56
+ W('overture-core/api/workers', 'overture-core/api/workers', (w) => {
57
+ w.name = `${a.slug}-auth`;
58
+ const db = w.d1_databases[0];
59
+ db.database_name = `${a.slug}-identity`;
60
+ db.database_id = d1('identity');
61
+ w.vars = {
62
+ ...w.vars,
63
+ PUBLIC_URL: urls.auth,
64
+ // local: the code comes back in the response (devCode). Cloud: ALWAYS real sending — "log" would let anyone
65
+ // sign in with any email (including the owner's).
66
+ DELIVERY_MODE: local ? 'log' : 'send',
67
+ ENVIRONMENT: local ? 'dev' : 'production',
68
+ OWNER_EMAIL: a.ownerEmail,
69
+ };
70
+ setR2(w, a.slug, CORE_R2);
71
+ });
72
+ // product server (name, D1, vars and the service binding to the Core come from the ProductSpec)
73
+ const api = product.api;
74
+ W(api.dir, api.dir, (w) => {
75
+ w.name = `${a.slug}-${api.suffix}`;
76
+ const db = w.d1_databases[0];
77
+ db.database_name = `${a.slug}-${product.d1.find((d) => d.key === api.d1Key).suffix}`;
78
+ db.database_id = d1(api.d1Key);
79
+ if (!local)
80
+ w.services = [{ binding: 'CORE', service: `${a.slug}-auth` }];
81
+ else
82
+ delete w.services;
83
+ w.vars = { ...w.vars, ...product.workerVars(a, urls, local) };
84
+ // product cron (Consultas: reminders, expired locks; Status: the checks) — in the cloud Cloudflare calls it; locally, dev-local does
85
+ if (product.cron)
86
+ w.triggers = { crons: [product.cron] };
87
+ // own domain (Status): wrangler deploy attaches the Custom Domain (the zone must be in the same Cloudflare account)
88
+ // R2 with a binding in the product Worker (Sites: FILES → <slug>-sites-files); locally, wrangler dev simulates the bucket
89
+ setR2(w, a.slug, product.r2);
90
+ // paid-plan-only queue (Link: clicks). Without it, the product writes straight to D1
91
+ if (product.paidQueue) {
92
+ const q = product.paidQueue;
93
+ if (!local && a.workersPaid) {
94
+ const name = `${a.slug}-${q.suffix}`;
95
+ w.queues = { producers: [{ binding: q.binding, queue: name }], consumers: [{ queue: name, max_batch_size: q.maxBatchSize, max_batch_timeout: q.maxBatchTimeout }] };
96
+ }
97
+ else
98
+ delete w.queues;
99
+ }
100
+ if (product.customDomain && !local && a.domain)
101
+ w.routes = [{ pattern: a.domain, custom_domain: true }];
102
+ else if (product.customDomain)
103
+ delete w.routes;
104
+ });
105
+ // panel (Pages)
106
+ W('overture-core/web/react', 'overture-core/web/react', (w) => {
107
+ w.name = `${a.slug}-admin`;
108
+ });
109
+ writeFileSync(join(dir, 'overture-core/web/react/.env.production.local'), `# Gerado pelo create-overture (URL pública, não é segredo)\nVITE_AUTH_URL=${urls.auth}\n`);
110
+ written.push('overture-core/web/react/.env.production.local');
111
+ // product web page (Agenda: bookings): the API URL in index.html's <meta> (its README asks the installer to write it)
112
+ if (product.webBuild?.metaApi) {
113
+ const f = join(dir, product.webBuild.dir, 'index.html');
114
+ const html = readFileSync(f, 'utf8');
115
+ const re = new RegExp(`(<meta name="${product.webBuild.metaApi}" content=")[^"]*(")`);
116
+ if (re.test(html)) {
117
+ writeFileSync(f, html.replace(re, `$1${urls.api}$2`));
118
+ written.push(`${product.webBuild.dir}/index.html`);
119
+ }
120
+ }
121
+ // app (Expo) — only products with an app
122
+ if (product.app)
123
+ written.push(...applyAppConfig(dir, product.app.dir, product, a, urls, local));
124
+ // project root
125
+ const lj = {
126
+ product: product.id,
127
+ appName: a.appName,
128
+ slug: a.slug,
129
+ ownerEmail: a.ownerEmail,
130
+ languages: a.languages,
131
+ bundleId: product.app ? a.bundleId : null,
132
+ theme: 'overture.theme.json',
133
+ target: a.target,
134
+ cloudflare: { accountId: a.cloudflare.accountId },
135
+ opera: { appId: a.opera.appId },
136
+ email: { from: a.email.from },
137
+ ...(product.customDomain ? { domain: a.domain ?? null } : {}),
138
+ ...(product.paidQueue ? { workersPaid: !!a.workersPaid } : {}),
139
+ urls: state.resources.urls,
140
+ ...(state.local ? { local: state.local } : {}),
141
+ generatedBy: `create-overture ${cliVersion}`,
142
+ };
143
+ writeJson(join(dir, 'overture.json'), lj);
144
+ writeJson(join(dir, 'overture.theme.json'), a.theme);
145
+ written.push('overture.json', 'overture.theme.json');
146
+ return written;
147
+ }
148
+ function applyAppConfig(dir, rel, product, a, urls, local) {
149
+ const written = [];
150
+ const appDir = join(dir, rel);
151
+ const appJsonFile = join(appDir, 'app.json');
152
+ const appJson = readJson(appJsonFile);
153
+ const e = appJson.expo;
154
+ e.name = a.appName;
155
+ e.slug = a.slug;
156
+ e.scheme = a.slug;
157
+ e.ios = { ...e.ios, bundleIdentifier: a.bundleId };
158
+ e.android = { ...e.android, package: a.bundleId };
159
+ e.web = { ...e.web, name: a.appName };
160
+ e.extra = { ...e.extra, overture: { product: product.id, languages: a.languages } };
161
+ writeJson(appJsonFile, appJson);
162
+ written.push(`${rel}/app.json`);
163
+ // the app URLs: .env to run locally and eas.json (versioned) for the Expo cloud build
164
+ const apiEnv = product.app.apiEnv;
165
+ const webEnv = product.app.webEnv;
166
+ const env = { EXPO_PUBLIC_AUTH_URL: urls.auth, [apiEnv]: urls.api, ...(webEnv && urls.app ? { [webEnv]: urls.app } : {}) };
167
+ writeFileSync(join(appDir, '.env'), `# Gerado pelo create-overture (URLs públicas)\n${Object.entries(env).map(([k, v]) => `${k}=${v}`).join('\n')}\n`);
168
+ written.push(`${rel}/.env`);
169
+ if (!local) {
170
+ writeJson(join(appDir, 'eas.json'), {
171
+ cli: { version: '>= 16.0.0', appVersionSource: 'remote' },
172
+ build: {
173
+ development: { developmentClient: true, distribution: 'internal', env },
174
+ preview: { distribution: 'internal', env },
175
+ production: { autoIncrement: true, env },
176
+ },
177
+ submit: { production: {} },
178
+ });
179
+ written.push(`${rel}/eas.json`);
180
+ }
181
+ return written;
182
+ }
183
+ /** Root files that are written only once (the buyer may edit them afterwards). */
184
+ export function writeRootFiles(dir, a, product, readme) {
185
+ const gi = join(dir, '.gitignore');
186
+ if (!existsSync(gi)) {
187
+ writeFileSync(gi, [
188
+ '# create-overture: estado da instalação e SEGREDOS (nunca no git)',
189
+ '.overture/',
190
+ '.dev.vars',
191
+ '.env',
192
+ '.env.*',
193
+ '!.env.example',
194
+ 'node_modules/',
195
+ '.wrangler/',
196
+ 'dist/',
197
+ '.expo/',
198
+ 'web-build/',
199
+ '*.log',
200
+ '.DS_Store',
201
+ '',
202
+ ].join('\n'));
203
+ }
204
+ const pkg = join(dir, 'package.json');
205
+ if (!existsSync(pkg)) {
206
+ writeJson(pkg, {
207
+ name: a.slug,
208
+ private: true,
209
+ description: `${a.appName} — ${product.name} (Ilorb Code)`,
210
+ scripts: {
211
+ dev: 'node scripts/dev-local.mjs',
212
+ 'install:all': product.installDirs.map((d) => `pnpm -C ${d} install`).join(' && '),
213
+ },
214
+ });
215
+ }
216
+ const readmeFile = join(dir, 'README.md');
217
+ if (!existsSync(readmeFile))
218
+ writeFileSync(readmeFile, readme);
219
+ mkdirSync(join(dir, 'scripts'), { recursive: true });
220
+ const devLocal = fileURLToPath(new URL('../assets/dev-local.mjs', import.meta.url));
221
+ writeFileSync(join(dir, 'scripts/dev-local.mjs'), readFileSync(devLocal));
222
+ }
223
+ /** .dev.vars of each Worker (local) — outside git through each template's .gitignore and the root one. */
224
+ export function writeDevVars(dir, rel, vars) {
225
+ writeFileAtomic(join(dir, rel, '.dev.vars'), formatEnv(vars, '# Gerado pelo create-overture para rodar LOCAL. Fora do git.'), 0o600);
226
+ }
227
+ // ─── scan: no secret in a versioned file ───────────────────────────────────────────
228
+ const SECRET_PATTERNS = [
229
+ // a real key = header + base64 body (the header alone shows up in comments and placeholders)
230
+ ['private key', /-----BEGIN [A-Z ]*PRIVATE KEY-----(\\n|\s)+[A-Za-z0-9+/=]{40,}/],
231
+ ['opera app secret', /\bsk_(live|test|local)_[A-Za-z0-9_-]{8,}/],
232
+ ['webhook secret', /\bwhsec_[A-Za-z0-9_-]{8,}/],
233
+ ['resend key', /\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9]{8,}/],
234
+ ['license key', /\bosc1\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/],
235
+ ];
236
+ /**
237
+ * Looks, in the files git WOULD version (outside .gitignore), for each secret value of this installation and the
238
+ * known key formats. Skips node_modules and the template files that carry FAKE example values.
239
+ */
240
+ export function scanForSecrets(dir, secretValues) {
241
+ const hits = [];
242
+ const values = secretValues.filter((v) => v && v.length >= 12);
243
+ const files = walk(dir, (n) => n === 'node_modules' || n === '.git' || n === '.overture' || n === '.wrangler' || n === 'dist');
244
+ for (const f of files) {
245
+ if (isIgnored(dir, f))
246
+ continue;
247
+ if (/\.(png|jpg|jpeg|gif|ttf|otf|woff2?|ico|zip|gz)$/i.test(f))
248
+ continue;
249
+ const text = readFileSync(join(dir, f), 'utf8');
250
+ for (const v of values)
251
+ if (text.includes(v))
252
+ hits.push({ file: f, what: 'valor de segredo desta instalação' });
253
+ if (/\.dev\.vars\.example$|\.env\.example$|\/test\/|\.test\.tsx?$|vitest\.config\.|fakeServer|\/e2e\//.test(f))
254
+ continue;
255
+ for (const [what, re] of SECRET_PATTERNS)
256
+ if (re.test(text))
257
+ hits.push({ file: f, what });
258
+ }
259
+ return hits;
260
+ }