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/update.js ADDED
@@ -0,0 +1,348 @@
1
+ // create-ilorb update — template updates (idea 14.6; refs: ThemeForest / Envato updates, Shopify theme updates).
2
+ //
3
+ // create-ilorb update [folder] [--site <url>] is there a newer version? what changed since mine? how to update
4
+ // create-ilorb update [folder] --apply <new folder> 3-way plan against the unzipped new version (dry run)
5
+ // create-ilorb update [folder] --apply <new folder> --yes apply it
6
+ //
7
+ // The project's version: ilorb-template.json (copied from the zip at install time) → the install state → the README
8
+ // footer "Package <id> <version>". The download needs a sign-in on the site, so this command NEVER downloads: the buyer
9
+ // unzips the new version next to the project and points --apply at it.
10
+ // The 3-way plan per file uses the hashes of the files we shipped (saved at install time in .overture/install.json,
11
+ // state.template.files): unchanged by the buyer → replaced; changed by the buyer and by us → theirs kept, ours written as
12
+ // <file>.ilorb-new; new upstream → added; removed upstream → listed, never deleted. ilorb.env, .env*, .dev.vars, databases,
13
+ // node_modules, .git and .overture are never touched.
14
+ import { createHash } from 'node:crypto';
15
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, statSync } from 'node:fs';
16
+ import { dirname, join, relative, resolve, sep } from 'node:path';
17
+ import { HumanError } from "./errors.js";
18
+ import { writeFileAtomic } from "./fsutil.js";
19
+ import { getLang, t } from "./i18n/index.js";
20
+ import { COPY_EXCLUDE, COPY_EXCLUDE_RE, FORBIDDEN_TEMPLATE_RE, PRODUCTS } from "./products.js";
21
+ import { loadState, saveState } from "./state.js";
22
+ export const TEMPLATE_VERSION_FILE = 'ilorb-template.json';
23
+ export const DEFAULT_SITE = 'https://code.ilorb.com';
24
+ export const NEW_SUFFIX = '.ilorb-new';
25
+ export const VERSION_RE = /^\d{4}\.\d{2}\.\d{2}-[0-9a-f]{8}$/;
26
+ const ID_RE = /^[a-z0-9-]{1,40}$/;
27
+ const README_FOOTER_RE = /^Package ([a-z0-9-]{1,40}) (\d{4}\.\d{2}\.\d{2}-[0-9a-f]{8})\b/m;
28
+ const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex');
29
+ /** a folder's own version: ilorb-template.json, else the README footer (an unzipped download or a project) */
30
+ export function readTemplateVersion(dir) {
31
+ const file = join(dir, TEMPLATE_VERSION_FILE);
32
+ if (existsSync(file)) {
33
+ try {
34
+ const j = JSON.parse(readFileSync(file, 'utf8'));
35
+ if (ID_RE.test(String(j.template)) && VERSION_RE.test(String(j.version)))
36
+ return {
37
+ template: String(j.template),
38
+ version: String(j.version),
39
+ ...(typeof j.packedAt === 'string' ? { packedAt: j.packedAt } : {}),
40
+ ...(typeof j.site === 'string' ? { site: j.site } : {}),
41
+ source: 'file',
42
+ };
43
+ }
44
+ catch { }
45
+ }
46
+ const readme = join(dir, 'README.md');
47
+ if (existsSync(readme)) {
48
+ const m = README_FOOTER_RE.exec(readFileSync(readme, 'utf8'));
49
+ if (m)
50
+ return { template: m[1], version: m[2], source: 'readme' };
51
+ }
52
+ return null;
53
+ }
54
+ /** the project's version: its ilorb-template.json → the install state → its README footer */
55
+ export function projectVersion(dir, state) {
56
+ const own = readTemplateVersion(dir);
57
+ if (own?.source === 'file')
58
+ return own;
59
+ if (state?.template?.version)
60
+ return { template: state.template.id, version: state.template.version, ...(state.template.packedAt ? { packedAt: state.template.packedAt } : {}), source: 'state' };
61
+ return own;
62
+ }
63
+ // ─── which files a template ships ───────────────────────────────────────────────────────────────────────────
64
+ /** never read from the new version nor written in the project, whatever the plan says */
65
+ const PROTECTED_DIRS = new Set(['node_modules', '.git', '.overture', '.wrangler']);
66
+ export function isProtected(rel) {
67
+ const parts = rel.split('/');
68
+ if (parts.some((p) => PROTECTED_DIRS.has(p)))
69
+ return true;
70
+ const name = parts.at(-1);
71
+ if (name === 'ilorb.env' || name === '.dev.vars' || name === TEMPLATE_VERSION_FILE)
72
+ return true;
73
+ if (/^\.env(\..+)?$/.test(name) && name !== '.env.example')
74
+ return true;
75
+ return /\.(sqlite3?|db)(-journal|-wal|-shm)?$/i.test(name);
76
+ }
77
+ /** the files of the product's template folders, with the installer's own copy rules (generate.ts copyTemplates) */
78
+ export function scanTemplate(root, product) {
79
+ const files = [];
80
+ const prot = [];
81
+ const add = (rel) => (isProtected(rel) ? prot : files).push(rel);
82
+ const walkDir = (base, abs) => {
83
+ for (const e of readdirSync(abs, { withFileTypes: true })) {
84
+ const relToBase = relative(base, join(abs, e.name)).split(sep).join('/');
85
+ const rel = `${relative(root, base).split(sep).join('/')}/${relToBase}`;
86
+ if (COPY_EXCLUDE.has(e.name) || COPY_EXCLUDE_RE.some((re) => re.test(e.name)) || FORBIDDEN_TEMPLATE_RE.test(rel))
87
+ continue;
88
+ if (e.isSymbolicLink())
89
+ continue;
90
+ if (e.isDirectory()) {
91
+ if (!PROTECTED_DIRS.has(e.name))
92
+ walkDir(base, join(abs, e.name));
93
+ }
94
+ else if (e.isFile())
95
+ add(rel);
96
+ }
97
+ };
98
+ for (const rel of product.templates) {
99
+ if (FORBIDDEN_TEMPLATE_RE.test(rel))
100
+ continue;
101
+ const src = join(root, rel);
102
+ if (!existsSync(src))
103
+ continue;
104
+ if (statSync(src).isFile())
105
+ add(rel);
106
+ else
107
+ walkDir(src, src);
108
+ }
109
+ return { files: files.sort(), protected: prot.sort() };
110
+ }
111
+ /** path → sha256 of every file the template ships (saved at install time: the base of the 3-way plan) */
112
+ export function shippedHashes(root, product) {
113
+ const out = {};
114
+ for (const f of scanTemplate(root, product).files)
115
+ out[f] = sha256(join(root, f));
116
+ return out;
117
+ }
118
+ /** the install-time record: version (when the folder has one) + the shipped file hashes */
119
+ export function templateRecord(root, product) {
120
+ const v = readTemplateVersion(root);
121
+ return {
122
+ id: product.id,
123
+ version: v && v.template === product.id ? v.version : null,
124
+ ...(v?.packedAt ? { packedAt: v.packedAt } : {}),
125
+ files: shippedHashes(root, product),
126
+ };
127
+ }
128
+ export function planUpdate(projectDir, newRoot, product, base) {
129
+ const plan = { replace: [], add: [], conflict: [], keep: [], removed: [], protected: [], unchanged: 0, noBase: !base };
130
+ const scan = scanTemplate(newRoot, product);
131
+ plan.protected.push(...scan.protected);
132
+ const inNew = new Set(scan.files);
133
+ for (const f of scan.files) {
134
+ const target = join(projectDir, f);
135
+ const theirs = existsSync(target) || isSymlink(target) ? target : null;
136
+ // a symlink (or a non-file) in the project is never followed nor replaced
137
+ if (theirs && (isSymlink(theirs) || !statSync(theirs).isFile())) {
138
+ plan.protected.push(f);
139
+ continue;
140
+ }
141
+ const ours = sha256(join(newRoot, f));
142
+ const was = base?.[f];
143
+ const now = theirs ? sha256(theirs) : null;
144
+ if (now === ours)
145
+ plan.unchanged++;
146
+ else if (!theirs) {
147
+ // missing in the project: new upstream → add; deleted by the buyer → keep deleted unless we changed it
148
+ if (!was)
149
+ plan.add.push(f);
150
+ else if (was === ours)
151
+ plan.unchanged++;
152
+ else
153
+ plan.conflict.push(f);
154
+ }
155
+ else if (was && now === was)
156
+ plan.replace.push(f);
157
+ else if (was && ours === was)
158
+ plan.keep.push(f);
159
+ else
160
+ plan.conflict.push(f);
161
+ }
162
+ for (const f of Object.keys(base ?? {}))
163
+ if (!inNew.has(f) && !scan.protected.includes(f) && existsSync(join(projectDir, f)))
164
+ plan.removed.push(f);
165
+ for (const k of ['replace', 'add', 'conflict', 'keep', 'removed', 'protected'])
166
+ plan[k].sort();
167
+ return plan;
168
+ }
169
+ const isSymlink = (p) => {
170
+ try {
171
+ return lstatSync(p).isSymbolicLink();
172
+ }
173
+ catch {
174
+ return false;
175
+ }
176
+ };
177
+ /** no folder between the project and the file may be a symlink (the update never writes outside the project) */
178
+ function safeTarget(projectDir, rel) {
179
+ const parts = rel.split('/');
180
+ let cur = projectDir;
181
+ for (const p of parts.slice(0, -1)) {
182
+ cur = join(cur, p);
183
+ if (isSymlink(cur))
184
+ throw new HumanError('update_unsafe_path', { path: rel });
185
+ }
186
+ const out = resolve(projectDir, rel);
187
+ if (!out.startsWith(resolve(projectDir) + sep) || isProtected(rel))
188
+ throw new HumanError('update_unsafe_path', { path: rel });
189
+ return out;
190
+ }
191
+ export function applyPlan(projectDir, newRoot, plan) {
192
+ const copy = (rel, to) => {
193
+ mkdirSync(dirname(to), { recursive: true });
194
+ copyFileSync(join(newRoot, rel), to);
195
+ };
196
+ for (const f of [...plan.replace, ...plan.add])
197
+ copy(f, safeTarget(projectDir, f));
198
+ for (const f of plan.conflict)
199
+ copy(f, safeTarget(projectDir, f + NEW_SUFFIX));
200
+ return { replaced: plan.replace.length, added: plan.add.length, conflicts: plan.conflict.length };
201
+ }
202
+ const SITE_LANG = { pt: 'pt-BR', es: 'es', en: 'en' };
203
+ export function siteUrl(flag, env, fromFile) {
204
+ const raw = (flag ?? env.ILORB_CODE_URL ?? fromFile ?? DEFAULT_SITE).replace(/\/+$/, '');
205
+ if (!/^https:\/\/[a-z0-9.-]+(:\d+)?$/i.test(raw) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(raw))
206
+ throw new HumanError('update_bad_site', { url: raw });
207
+ return raw;
208
+ }
209
+ async function getJson(f, url) {
210
+ let res;
211
+ try {
212
+ res = await f(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(15_000) });
213
+ }
214
+ catch (e) {
215
+ throw new HumanError('update_unreachable', { url }, e?.message);
216
+ }
217
+ let body = {};
218
+ try {
219
+ body = (await res.json());
220
+ }
221
+ catch {
222
+ throw new HumanError('update_unreachable', { url }, `HTTP ${res.status}, not JSON`);
223
+ }
224
+ return { status: res.status, body };
225
+ }
226
+ const asRelease = (r) => ({
227
+ version: String(r.version ?? ''),
228
+ date: String(r.date ?? ''),
229
+ notes: Array.isArray(r.notes) ? r.notes.map((n) => String(n)) : [],
230
+ });
231
+ export async function checkUpdate(f, site, template, current) {
232
+ const lang = SITE_LANG[getLang()];
233
+ const latestUrl = `${site}/api/templates/${encodeURIComponent(template)}/latest?lang=${lang}`;
234
+ const l = await getJson(f, latestUrl);
235
+ if (l.status === 404)
236
+ throw new HumanError('update_unknown_template', { template, site });
237
+ if (l.status !== 200 || !VERSION_RE.test(String(l.body.version)))
238
+ throw new HumanError('update_unreachable', { url: latestUrl }, `HTTP ${l.status}`);
239
+ const latest = asRelease(l.body);
240
+ const url = String(l.body.url ?? `${site}/templates`);
241
+ if (latest.version === current)
242
+ return { current, latest, url, since: [] };
243
+ const c = await getJson(f, `${site}/api/templates/${encodeURIComponent(template)}/changes?from=${encodeURIComponent(current)}&lang=${lang}`);
244
+ const since = c.status === 200 && Array.isArray(c.body.releases) ? c.body.releases.map(asRelease) : null;
245
+ return { current, latest, url, since };
246
+ }
247
+ const npmCmd = (args) => `npm create ilorb@latest update${args ? ` -- ${args}` : ''}`;
248
+ export async function runUpdate(i) {
249
+ const { dir, out, flags } = i;
250
+ const state = loadState(dir);
251
+ const mine = projectVersion(dir, state);
252
+ const apply = typeof flags.apply === 'string' ? resolve(i.cwd, flags.apply) : null;
253
+ if (flags.apply === true)
254
+ throw new HumanError('update_apply_folder');
255
+ if (apply)
256
+ return runApply(i, apply, state, mine);
257
+ if (!mine?.version)
258
+ throw new HumanError('update_no_version', { dir });
259
+ const site = siteUrl(typeof flags.site === 'string' ? flags.site : undefined, i.env, mine.site);
260
+ out.line();
261
+ out.line(`${out.bold(out.magenta('◆'))} ${out.bold(t('update.title', { template: mine.template }))}`);
262
+ const r = await checkUpdate(i.fetch, site, mine.template, mine.version);
263
+ if (!r.since?.length && r.since !== null) {
264
+ out.ok(t('update.upToDate', { version: r.current }));
265
+ out.line();
266
+ return 0;
267
+ }
268
+ out.line(` ${t('update.available', { current: out.bold(r.current), latest: out.bold(out.green(r.latest.version)), date: r.latest.date })}`);
269
+ out.line();
270
+ const list = r.since ?? [r.latest];
271
+ out.line(` ${out.bold(r.since ? t('update.notesSince') : t('update.unknownVersion', { version: r.current }))}`);
272
+ for (const rel of list) {
273
+ out.line(` ${out.cyan(rel.version)} ${out.dim(rel.date)}`);
274
+ for (const n of rel.notes)
275
+ out.line(` • ${n}`);
276
+ }
277
+ out.line();
278
+ out.line(` ${out.bold(t('update.steps'))}`);
279
+ const folder = `../ilorb-code-${mine.template}`;
280
+ out.line(` 1. ${t('update.step1', { url: out.cyan(r.url) })}`);
281
+ out.line(` 2. ${t('update.step2', { folder })}`);
282
+ out.line(` 3. ${t('update.step3', { cmd: out.cyan(npmCmd(`--apply ${folder}`)) })}`);
283
+ out.line(` 4. ${t('update.step4', { cmd: out.cyan(npmCmd(`--apply ${folder} --yes`)), suffix: NEW_SUFFIX })}`);
284
+ out.line(` 5. ${t('update.step5', { suffix: NEW_SUFFIX })}`);
285
+ out.line();
286
+ return 0;
287
+ }
288
+ async function runApply(i, newRoot, state, mine) {
289
+ const { dir, out } = i;
290
+ if (resolve(newRoot) === resolve(dir))
291
+ throw new HumanError('update_same_folder', { dir });
292
+ if (!existsSync(newRoot) || !statSync(newRoot).isDirectory())
293
+ throw new HumanError('update_no_folder', { dir: newRoot });
294
+ const next = readTemplateVersion(newRoot);
295
+ const productId = state?.product ?? mine?.template ?? next?.template;
296
+ const product = productId ? PRODUCTS[productId] : undefined;
297
+ if (!product)
298
+ throw new HumanError('update_no_version', { dir });
299
+ if (next && next.template !== product.id)
300
+ throw new HumanError('update_wrong_template', { theirs: product.id, ours: next.template });
301
+ const missing = product.templates.filter((rel) => !FORBIDDEN_TEMPLATE_RE.test(rel) && !existsSync(join(newRoot, rel)));
302
+ if (missing.length)
303
+ throw new HumanError('templates_missing', { path: missing.join(', ') });
304
+ const from = mine?.version ?? '?';
305
+ const to = next?.version ?? '?';
306
+ if (mine?.version && next?.version && next.version.slice(0, 10) < mine.version.slice(0, 10))
307
+ throw new HumanError('update_downgrade', { from, to });
308
+ const base = state?.template?.files && Object.keys(state.template.files).length ? state.template.files : null;
309
+ const plan = planUpdate(dir, newRoot, product, base);
310
+ out.line();
311
+ out.line(`${out.bold(out.magenta('◆'))} ${out.bold(t('update.plan.title', { template: product.id, from, to }))}`);
312
+ if (plan.noBase)
313
+ out.line(` ${out.yellow('!')} ${t('update.plan.noBase', { suffix: NEW_SUFFIX })}`);
314
+ const section = (key, files, mark, fmt = (f) => f) => {
315
+ if (!files.length)
316
+ return;
317
+ out.line(` ${out.bold(t(key, { n: files.length, suffix: NEW_SUFFIX }))}`);
318
+ for (const f of files.slice(0, 200))
319
+ out.line(` ${mark} ${fmt(f)}`);
320
+ if (files.length > 200)
321
+ out.line(` … +${files.length - 200}`);
322
+ };
323
+ section('update.plan.replace', plan.replace, out.green('~'));
324
+ section('update.plan.add', plan.add, out.green('+'));
325
+ section('update.plan.conflict', plan.conflict, out.yellow('!'), (f) => `${f} → ${f}${NEW_SUFFIX}`);
326
+ section('update.plan.keep', plan.keep, out.dim('='));
327
+ section('update.plan.removed', plan.removed, out.red('-'));
328
+ section('update.plan.protected', plan.protected, out.dim('#'));
329
+ out.line(` ${out.dim(t('update.plan.unchanged', { n: plan.unchanged }))}`);
330
+ out.line();
331
+ if (i.flags.yes !== true) {
332
+ out.line(t('update.dryRun', { cmd: out.cyan(npmCmd(`--apply ${relative(i.cwd, newRoot) || '.'} --yes`)) }));
333
+ out.line();
334
+ return 0;
335
+ }
336
+ const done = applyPlan(dir, newRoot, plan);
337
+ // the new base: what this version ships (a kept or conflicting file of the buyer stays "changed by the buyer")
338
+ if (state) {
339
+ state.template = { id: product.id, version: next?.version ?? null, ...(next?.packedAt ? { packedAt: next.packedAt } : {}), files: shippedHashes(newRoot, product) };
340
+ saveState(dir, state);
341
+ }
342
+ if (next?.source === 'file')
343
+ writeFileAtomic(join(dir, TEMPLATE_VERSION_FILE), readFileSync(join(newRoot, TEMPLATE_VERSION_FILE), 'utf8'));
344
+ out.ok(t('update.applied', { replaced: done.replaced, added: done.added, conflicts: done.conflicts, version: to, suffix: NEW_SUFFIX }));
345
+ out.line(` ${t('update.step5', { suffix: NEW_SUFFIX })}`);
346
+ out.line();
347
+ return 0;
348
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "create-ilorb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Ilorb Code installer: a free template (with its Ilorb key from ilorb.env) → your project, database and Ilorb Core, locally or on your own Cloudflare account. npm create ilorb",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "create-ilorb": "dist/cli.js",
9
+ "create-overture": "dist/cli.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "assets",
14
+ "README.md"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "packageManager": "pnpm@11.25.0",
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.build.json && node tools/postbuild.mjs",
22
+ "typecheck": "tsc --noEmit -p .",
23
+ "test": "vitest run",
24
+ "e2e": "node e2e/local.mjs",
25
+ "e2e:widgets": "node e2e/widgets-local.mjs",
26
+ "e2e:consultas": "node e2e/consultas-local.mjs",
27
+ "e2e:status": "node e2e/status-local.mjs",
28
+ "e2e:agenda": "node e2e/agenda-local.mjs",
29
+ "e2e:sites": "node e2e/sites-local.mjs",
30
+ "e2e:starter": "node e2e/starter-local.mjs",
31
+ "e2e:link": "node e2e/link-local.mjs",
32
+ "e2e:imoveis": "node e2e/imoveis-local.mjs",
33
+ "e2e:quiz": "node e2e/quiz-local.mjs",
34
+ "e2e:helpcenter": "node e2e/helpcenter-local.mjs",
35
+ "e2e:classificados": "node e2e/classificados-local.mjs",
36
+ "e2e:delivery": "node e2e/delivery-local.mjs",
37
+ "e2e:cardapio": "node e2e/cardapio-local.mjs",
38
+ "e2e:shop": "node e2e/shop-local.mjs",
39
+ "e2e:faturas": "node e2e/faturas-local.mjs",
40
+ "e2e:cursos": "node e2e/cursos-local.mjs",
41
+ "license-server": "node tools/fake-license-server.mjs"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "22.20.5",
45
+ "typescript": "5.9.3",
46
+ "vitest": "4.1.11"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }