create-ilorb 0.2.0 → 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 +92 -73
- package/assets/dev-local.mjs +2 -2
- package/dist/args.js +1 -1
- package/dist/generate.js +1 -1
- package/dist/i18n/en.js +72 -30
- package/dist/i18n/es.js +72 -30
- package/dist/i18n/pt.js +72 -30
- package/dist/main.js +61 -13
- package/dist/products.js +35 -35
- package/dist/readme.js +42 -42
- package/dist/steps.js +11 -5
- package/dist/theme/preview.js +28 -0
- package/dist/theme/vendor/color.js +1 -1
- package/dist/theme/vendor/tokens.js +1 -1
- package/dist/theme/vendor/validate.js +219 -0
- package/dist/update.js +348 -0
- package/package.json +1 -2
- package/LICENSE-API.md +0 -108
package/dist/theme/preview.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// Theme samples in the terminal, with the SAME engine as the app (buildTheme, faithful copy of
|
|
2
2
|
// overture-core/app/react-native/packages/theme/src — the theme-sync test checks it has not diverged).
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
3
5
|
import { contrast } from "./vendor/color.js";
|
|
6
|
+
import { checkThemeShape, normalizeHex as fullHex } from "./vendor/validate.js";
|
|
4
7
|
import { buildTheme, PRESETS, resolveConfig } from "./vendor/tokens.js";
|
|
5
8
|
import { t } from "../i18n/index.js";
|
|
6
9
|
export const PRESET_IDS = Object.keys(PRESETS);
|
|
@@ -31,6 +34,31 @@ export function resolveTheme(preset, primary) {
|
|
|
31
34
|
const r = resolveConfig({ preset, ...(primary ? { primary: normalizeHex(primary) } : {}) });
|
|
32
35
|
return { preset: r.preset, mode: r.mode, primary: r.primary, accent: r.accent, radius: r.radius, font: r.font, density: r.density };
|
|
33
36
|
}
|
|
37
|
+
export const THEME_FILE = 'overture.theme.json';
|
|
38
|
+
/**
|
|
39
|
+
* The look the buyer chose on Ilorb Code: `<template folder>/overture.theme.json` (appended to the zip by the download,
|
|
40
|
+
* next to ilorb.env; same shape this installer writes). Validated with the engine's checkThemeShape (format: known keys,
|
|
41
|
+
* hex colors, enums). null = no file; `{ error }` = a file that is not usable (the caller warns and asks as usual).
|
|
42
|
+
* Its radius and font are KEPT (resolveConfig), not re-derived from the style.
|
|
43
|
+
*/
|
|
44
|
+
export function readThemeFile(dir) {
|
|
45
|
+
const file = join(dir, THEME_FILE);
|
|
46
|
+
if (!existsSync(file))
|
|
47
|
+
return null;
|
|
48
|
+
let input;
|
|
49
|
+
try {
|
|
50
|
+
input = JSON.parse(readFileSync(file, 'utf8'));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return { error: 'not JSON' };
|
|
54
|
+
}
|
|
55
|
+
const issues = checkThemeShape(input).filter((i) => i.severity === 'error');
|
|
56
|
+
if (issues.length)
|
|
57
|
+
return { error: [...new Set(issues.map((i) => i.field || 'theme'))].join(', ') };
|
|
58
|
+
const r = resolveConfig(input);
|
|
59
|
+
// #abc → #AABBCC: the answers (and --primary) use 6 hex digits
|
|
60
|
+
return { theme: { preset: r.preset, mode: r.mode, primary: fullHex(r.primary), accent: fullHex(r.accent), radius: r.radius, font: r.font, density: r.density } };
|
|
61
|
+
}
|
|
34
62
|
/** What the engine did with the chosen color (to tell the buyer, with no surprise). */
|
|
35
63
|
export function primaryReport(cfg) {
|
|
36
64
|
const l = buildTheme(cfg, 'light').colors;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Ilorb color: sRGB ↔ OKLCH conversion, WCAG 2.x contrast and adjustment until the minimum is met.
|
|
2
2
|
// No dependencies. OKLCH is used because changing its lightness (L) does not change the perceived
|
|
3
3
|
// "tone" — which is what lets us generate a whole scale from ONE color the buyer chose.
|
|
4
4
|
const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Ilorb tokens — the ONLY source of visual values for all products.
|
|
2
2
|
// No screen writes a loose color, size, radius or shadow: everything comes out of buildTheme().
|
|
3
3
|
import { buildScale, contrast, ensureContrast, hexToOklch, mix, oklchToHex, onColor } from "./color.js";
|
|
4
4
|
/** body size in px: the rest of the scale follows in the same proportion */
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Buyer theme validation — the SAME on the server (rejects with 422 invalid_theme) and in the panel (contrast table,
|
|
2
|
+
// "Fix" button). Two families of problems:
|
|
3
|
+
// 1. format: unknown key, color that is not hex, size outside 14–18, bad URL… → error
|
|
4
|
+
// 2. legibility of what the BUYER chose: text/background below 4.5, background outside the mode's range → error
|
|
5
|
+
// (DERIVED colors are not checked here: the engine always fixes them — see buildTheme)
|
|
6
|
+
// + warnings (non-blocking): the engine will show the color with a different lightness, a button that vanishes into the background.
|
|
7
|
+
// Every problem carries the pair, the measured ratio, the minimum and a SUGGESTION (the field value that fixes it).
|
|
8
|
+
import { contrast, ensureContrast } from "./color.js";
|
|
9
|
+
import { BACKGROUND_RANGE, DENSITY_IDS, FONT_IDS, FONT_SIZE, HEADING_WEIGHT_IDS, MODE_IDS, PRESETS, RADIUS_IDS, TEXT_MIN, chosenSurface, clampBackground, defaultBackground, defaultText, isHex, resolveConfig, solidWithOn, } from "./tokens.js";
|
|
10
|
+
/** all the keys the theme accepts (v1 format) */
|
|
11
|
+
export const THEME_FIELDS = [
|
|
12
|
+
'preset', 'mode', 'primary', 'secondary', 'accent', 'background', 'text', 'backgroundDark', 'textDark', 'success', 'danger',
|
|
13
|
+
'radius', 'font', 'fontSize', 'headingWeight', 'density', 'logo', 'logoDark', 'favicon',
|
|
14
|
+
];
|
|
15
|
+
export const COLOR_FIELDS = ['primary', 'secondary', 'accent', 'background', 'text', 'backgroundDark', 'textDark', 'success', 'danger'];
|
|
16
|
+
export const URL_FIELDS = ['logo', 'logoDark', 'favicon'];
|
|
17
|
+
const round2 = (n) => Math.round(n * 100) / 100;
|
|
18
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
19
|
+
/** URL accepted for logo/favicon: https (or http on localhost/127.0.0.1, for local mode), up to 500 characters */
|
|
20
|
+
export function isAssetUrl(v) {
|
|
21
|
+
if (typeof v !== 'string' || v.length > 500 || /\s/.test(v))
|
|
22
|
+
return false;
|
|
23
|
+
try {
|
|
24
|
+
const u = new URL(v);
|
|
25
|
+
if (u.protocol === 'https:')
|
|
26
|
+
return true;
|
|
27
|
+
return u.protocol === 'http:' && (u.hostname === 'localhost' || u.hostname === '127.0.0.1');
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** format only (serves the general theme and a product's "only what changes"). `null` in a field = remove it. */
|
|
34
|
+
export function checkThemeShape(input, opts = {}) {
|
|
35
|
+
const issues = [];
|
|
36
|
+
if (!isObj(input))
|
|
37
|
+
return [{ code: 'invalid_value', severity: 'error', field: '', message: 'o tema precisa ser um objeto' }];
|
|
38
|
+
const bad = (field, message, suggestion) => issues.push({ code: 'invalid_value', severity: 'error', field, message, ...(suggestion !== undefined ? { suggestion } : {}) });
|
|
39
|
+
for (const [k, v] of Object.entries(input)) {
|
|
40
|
+
if (!THEME_FIELDS.includes(k)) {
|
|
41
|
+
issues.push({ code: 'unknown_field', severity: 'error', field: k, suggestion: null, message: `campo desconhecido: ${k}` });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (v === null || v === undefined) {
|
|
45
|
+
if (k === 'preset' && !opts.partial)
|
|
46
|
+
bad(k, 'preset é obrigatório', 'clean');
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
switch (k) {
|
|
50
|
+
case 'preset':
|
|
51
|
+
if (typeof v !== 'string' || !(v in PRESETS))
|
|
52
|
+
bad(k, 'preset: clean|bold|soft|night', 'clean');
|
|
53
|
+
break;
|
|
54
|
+
case 'mode':
|
|
55
|
+
if (!MODE_IDS.includes(v))
|
|
56
|
+
bad(k, 'mode: system|light|dark', 'system');
|
|
57
|
+
break;
|
|
58
|
+
case 'radius':
|
|
59
|
+
if (!RADIUS_IDS.includes(v))
|
|
60
|
+
bad(k, 'radius: sharp|soft|round', 'soft');
|
|
61
|
+
break;
|
|
62
|
+
case 'font':
|
|
63
|
+
if (!FONT_IDS.includes(v))
|
|
64
|
+
bad(k, 'font: system|inter|jakarta|nunito', 'inter');
|
|
65
|
+
break;
|
|
66
|
+
case 'density':
|
|
67
|
+
if (!DENSITY_IDS.includes(v))
|
|
68
|
+
bad(k, 'density: compact|regular|comfortable', 'regular');
|
|
69
|
+
break;
|
|
70
|
+
case 'headingWeight':
|
|
71
|
+
if (!HEADING_WEIGHT_IDS.includes(v))
|
|
72
|
+
bad(k, 'headingWeight: semibold|bold|extrabold', 'bold');
|
|
73
|
+
break;
|
|
74
|
+
case 'fontSize':
|
|
75
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v < FONT_SIZE.min || v > FONT_SIZE.max) {
|
|
76
|
+
const n = typeof v === 'number' && Number.isFinite(v) ? Math.min(FONT_SIZE.max, Math.max(FONT_SIZE.min, Math.round(v))) : FONT_SIZE.default;
|
|
77
|
+
bad(k, `fontSize: inteiro de ${FONT_SIZE.min} a ${FONT_SIZE.max}`, n);
|
|
78
|
+
}
|
|
79
|
+
break;
|
|
80
|
+
case 'logo':
|
|
81
|
+
case 'logoDark':
|
|
82
|
+
case 'favicon':
|
|
83
|
+
if (!isAssetUrl(v))
|
|
84
|
+
bad(k, `${k}: URL https (até 500 caracteres)`, null);
|
|
85
|
+
break;
|
|
86
|
+
default:
|
|
87
|
+
if (!isHex(v))
|
|
88
|
+
bad(k, `${k}: cor em hex (#RRGGBB)`, null);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!opts.partial && !('preset' in input))
|
|
92
|
+
bad('preset', 'preset é obrigatório', 'clean');
|
|
93
|
+
return issues;
|
|
94
|
+
}
|
|
95
|
+
/** Merges the general theme with the product's "only what changes" (field by field; `null` in the product = inherit). */
|
|
96
|
+
export function mergeTheme(general, override) {
|
|
97
|
+
const out = { ...general };
|
|
98
|
+
if (override)
|
|
99
|
+
for (const [k, v] of Object.entries(override))
|
|
100
|
+
if (v !== null && v !== undefined)
|
|
101
|
+
out[k] = v;
|
|
102
|
+
// `secondary` is the new name of `accent`: whoever changes one in the product changes the color of both
|
|
103
|
+
if (override && (override.secondary || override.accent)) {
|
|
104
|
+
out.secondary = override.secondary ?? override.accent;
|
|
105
|
+
delete out.accent;
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** the keys the product inherits from the general theme (the ones it does not change) */
|
|
110
|
+
export function inheritedFields(override) {
|
|
111
|
+
const own = new Set(Object.entries(override ?? {}).filter(([, v]) => v !== null && v !== undefined).map(([k]) => k));
|
|
112
|
+
if (own.has('accent'))
|
|
113
|
+
own.add('secondary');
|
|
114
|
+
if (own.has('secondary'))
|
|
115
|
+
own.add('accent');
|
|
116
|
+
return THEME_FIELDS.filter((f) => !own.has(f));
|
|
117
|
+
}
|
|
118
|
+
/** Legibility of what the buyer chose (the config already has a valid format). */
|
|
119
|
+
function checkLegibility(cfg) {
|
|
120
|
+
const issues = [];
|
|
121
|
+
for (const scheme of ['light', 'dark']) {
|
|
122
|
+
const chosen = chosenSurface(cfg, scheme);
|
|
123
|
+
const bgField = scheme === 'light' ? 'background' : 'backgroundDark';
|
|
124
|
+
const textField = scheme === 'light' ? 'text' : 'textDark';
|
|
125
|
+
let bg = chosen.bg ?? defaultBackground(cfg, scheme);
|
|
126
|
+
// 1. background within the mode's range (only what the buyer GAVE: the derived one is born inside it)
|
|
127
|
+
if (chosen.bgFrom === bgField) {
|
|
128
|
+
const r = BACKGROUND_RANGE[scheme];
|
|
129
|
+
const ratio = contrast(bg, r.against);
|
|
130
|
+
if (ratio < r.min) {
|
|
131
|
+
const fixed = clampBackground(bg, scheme);
|
|
132
|
+
issues.push({
|
|
133
|
+
code: 'background_range', severity: 'error', field: bgField, scheme, pair: [bgField, scheme === 'light' ? '#000000' : '#FFFFFF'],
|
|
134
|
+
colors: [bg, r.against], ratio: round2(ratio), min: r.min, suggestion: ensureContrast(bg, r.against, r.min + 0.2),
|
|
135
|
+
message: scheme === 'light'
|
|
136
|
+
? `fundo do modo claro escuro demais (${round2(ratio)}:1 com o preto; mínimo ${r.min}:1)`
|
|
137
|
+
: `fundo do modo escuro claro demais (${round2(ratio)}:1 com o branco; mínimo ${r.min}:1)`,
|
|
138
|
+
});
|
|
139
|
+
bg = fixed;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// 2. text over the background (when either of the two is the buyer's choice)
|
|
143
|
+
const givenText = chosen.textFrom === textField;
|
|
144
|
+
const givenBg = chosen.bgFrom === bgField;
|
|
145
|
+
if (givenText || givenBg) {
|
|
146
|
+
const text = chosen.text ?? defaultText(cfg, scheme);
|
|
147
|
+
const ratio = contrast(text, bg);
|
|
148
|
+
if (ratio < TEXT_MIN) {
|
|
149
|
+
// fixes the text if it was the one the buyer gave; otherwise the background (which is the one they gave)
|
|
150
|
+
const field = givenText ? textField : bgField;
|
|
151
|
+
const suggestion = givenText ? ensureContrast(text, bg, TEXT_MIN + 0.1) : clampBackground(ensureContrast(bg, text, TEXT_MIN + 0.1), scheme);
|
|
152
|
+
issues.push({
|
|
153
|
+
code: 'low_contrast', severity: 'error', field, scheme, pair: [textField, bgField], colors: [text, bg],
|
|
154
|
+
ratio: round2(ratio), min: TEXT_MIN, suggestion,
|
|
155
|
+
message: `texto sobre o fundo (${scheme === 'light' ? 'claro' : 'escuro'}) = ${round2(ratio)}:1; mínimo ${TEXT_MIN}:1`,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// warnings: the solid color the engine will show in light mode differs from the chosen one (button, success, error)
|
|
161
|
+
const lightBg = clampBackground(cfg.background ?? '#FFFFFF', 'light');
|
|
162
|
+
for (const field of ['primary', 'success', 'danger']) {
|
|
163
|
+
const chosenColor = cfg[field];
|
|
164
|
+
// the style's default color raises no warning (Bold is born with the red adjusted on purpose)
|
|
165
|
+
if (!chosenColor || (field === 'primary' && normalizeHex(chosenColor) === PRESETS[cfg.preset].primary))
|
|
166
|
+
continue;
|
|
167
|
+
const { solid, on } = solidWithOn(chosenColor);
|
|
168
|
+
if (solid.toUpperCase() !== normalizeHex(chosenColor)) {
|
|
169
|
+
issues.push({
|
|
170
|
+
code: 'adjusted', severity: 'warning', field, scheme: 'light', pair: [field, 'on'], colors: [chosenColor, on],
|
|
171
|
+
ratio: round2(contrast(chosenColor, on)), min: 4.5, suggestion: solid,
|
|
172
|
+
message: `${field}: o texto em cima não passa 4.5; o app mostra ${solid}`,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (cfg.background) {
|
|
177
|
+
const { solid } = solidWithOn(cfg.primary);
|
|
178
|
+
const ratio = contrast(solid, lightBg);
|
|
179
|
+
if (ratio < 3) {
|
|
180
|
+
issues.push({
|
|
181
|
+
code: 'low_visibility', severity: 'warning', field: 'primary', scheme: 'light', pair: ['primary', 'background'],
|
|
182
|
+
colors: [solid, lightBg], ratio: round2(ratio), min: 3, suggestion: ensureContrast(solid, lightBg, 3.1),
|
|
183
|
+
message: `botão principal quase some no fundo (${round2(ratio)}:1; recomendado 3:1)`,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return issues;
|
|
188
|
+
}
|
|
189
|
+
/** #abc / #AbCdEf → #AABBCC */
|
|
190
|
+
export function normalizeHex(hex) {
|
|
191
|
+
let h = hex.trim().replace(/^#/, '');
|
|
192
|
+
if (h.length === 3)
|
|
193
|
+
h = h.split('').map((c) => c + c).join('');
|
|
194
|
+
return `#${h.toUpperCase()}`;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The theme's problems (format + legibility). `ok` = no ERROR (warnings do not block).
|
|
198
|
+
* The server saves only if `ok`; the panel shows everything and "Fix" applies `suggestion` to `field`.
|
|
199
|
+
*/
|
|
200
|
+
export function validateTheme(input) {
|
|
201
|
+
const shape = checkThemeShape(input);
|
|
202
|
+
if (shape.length)
|
|
203
|
+
return { ok: false, issues: shape };
|
|
204
|
+
const issues = checkLegibility(resolveConfig(input));
|
|
205
|
+
return { ok: !issues.some((i) => i.severity === 'error'), issues };
|
|
206
|
+
}
|
|
207
|
+
/** Applies the suggestions (from "Fix all" or from a single problem). `null` removes the field. */
|
|
208
|
+
export function applySuggestions(config, issues) {
|
|
209
|
+
const out = { ...config };
|
|
210
|
+
for (const i of issues) {
|
|
211
|
+
if (i.suggestion === undefined || !i.field)
|
|
212
|
+
continue;
|
|
213
|
+
if (i.suggestion === null)
|
|
214
|
+
delete out[i.field];
|
|
215
|
+
else
|
|
216
|
+
out[i.field] = i.suggestion;
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-ilorb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
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
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
"files": [
|
|
12
12
|
"dist",
|
|
13
13
|
"assets",
|
|
14
|
-
"LICENSE-API.md",
|
|
15
14
|
"README.md"
|
|
16
15
|
],
|
|
17
16
|
"engines": {
|