mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
Merge dev into feat/native-apps
Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:
- server: /api/auth/native moves onto injected services. The session is
minted by the auth domain's new LoginSessionService (login bookkeeping and
SessionsService.issue in one transaction), the one-time codes live behind a
NativeHandoffStore port with a capped in-memory implementation that drops
expired codes on write instead of running a timer, both routes declare
response contracts, and the exchange answers { success: true }. Unit and
e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
(useAccountSettings, useTripExport), the native server card is a
desktop/phone pair on useNativeServer, the hand-off call moves out of the
page hook into native/, best-effort native failures go through
reportError instead of the console, and the address screen is known to
knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:dup: keeps copied code from coming back.
|
||||
*
|
||||
* Most features have a desktop view and a phone view, and each used to carry
|
||||
* its own copy of the feature's logic, so a fix reached one of them and the
|
||||
* other kept the bug. The logic now lives in one shared hook or module per
|
||||
* feature, and this check holds the copies that remain to what they are. It
|
||||
* counts, per file under src/, the lines inside a block of code that repeats
|
||||
* elsewhere (or in the same file), at the thresholds SonarCloud uses on a
|
||||
* pull request. The files that still hold such lines are listed in
|
||||
* scripts/dup-baseline.json with their count, and a file may hold no more
|
||||
* than its entry (a file without an entry holds none). An entry above what
|
||||
* its file holds now, or for a file that is gone, fails as well until
|
||||
* --update lowers it.
|
||||
*
|
||||
* npm run lint:dup check against the baseline (CI)
|
||||
* npm run lint:dup -- --list print every copied block with its other side
|
||||
* npm run lint:dup -- --update lower the baseline to what the files hold now;
|
||||
* it never raises an entry
|
||||
*
|
||||
* The measuring lives in scripts/lib/dup.mjs.
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/dup.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:dup', (args) => check({ root, update: args.includes('--update'), list: args.includes('--list') }));
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-non-null-assertion": 382,
|
||||
"@typescript-eslint/no-misused-promises": 849,
|
||||
"no-console": 88,
|
||||
"complexity": 221,
|
||||
"@typescript-eslint/no-explicit-any": 146,
|
||||
"trek/no-swallowed-catch": 130,
|
||||
"max-params": 32,
|
||||
"trek/store-without-selector": 67,
|
||||
"react-hooks/refs": 555,
|
||||
"react-hooks/set-state-in-effect": 194,
|
||||
"@typescript-eslint/no-floating-promises": 164,
|
||||
"react-hooks/exhaustive-deps": 116,
|
||||
"@typescript-eslint/no-unused-vars": 124,
|
||||
"react-hooks/immutability": 28,
|
||||
"max-lines-per-function": 130,
|
||||
"react-hooks/static-components": 78,
|
||||
"react-hooks/preserve-manual-memoization": 12,
|
||||
"no-useless-assignment": 7,
|
||||
"no-empty": 19,
|
||||
"trek/no-window-globals": 41,
|
||||
"react-refresh/only-export-components": 44,
|
||||
"unused-disable-directive": 6,
|
||||
"max-depth": 21,
|
||||
"react-hooks/void-use-memo": 1,
|
||||
"@typescript-eslint/no-unused-expressions": 2,
|
||||
"react-hooks/purity": 2,
|
||||
"preserve-caught-error": 53,
|
||||
"no-useless-escape": 1
|
||||
},
|
||||
"suppressed": {
|
||||
"@typescript-eslint/no-explicit-any": 40,
|
||||
"react-hooks/exhaustive-deps": 46
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 490,
|
||||
"@typescript-eslint/no-non-null-assertion": 1927,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 51,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
"trek/no-window-globals": 331,
|
||||
"trek/no-swallowed-catch": 14,
|
||||
"react-hooks/globals": 5,
|
||||
"react-hooks/refs": 22,
|
||||
"@typescript-eslint/no-this-alias": 1,
|
||||
"trek/store-without-selector": 3,
|
||||
"@typescript-eslint/no-unsafe-function-type": 2,
|
||||
"no-console": 2,
|
||||
"react-refresh/only-export-components": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:warnings: ESLint warnings may only go down.
|
||||
*
|
||||
* Most rules in eslint.config.mjs are warnings, set that way to keep CI green
|
||||
* on code that was never linted, and a warning never fails a build. So they
|
||||
* piled up: unused variables hiding dead props, missing effect dependencies
|
||||
* of the kind that has already shown stale money. This runs ESLint over the
|
||||
* client and counts the warnings per rule, separately for app code and
|
||||
* tests, and the messages an eslint-disable comment silenced as a third
|
||||
* group. Each count may not pass its entry in scripts/eslint-baseline.json,
|
||||
* and an entry above its count fails as well until --update lowers it, so a
|
||||
* fixed warning cannot come back unseen.
|
||||
* Any error fails as well, so the check can stand in for `npm run lint:check`,
|
||||
* and so does a block comment that configures a rule inline (such as one that
|
||||
* turns no-explicit-any off): it leaves no message to count, so it would
|
||||
* otherwise be the free way past the ratchet.
|
||||
*
|
||||
* npm run lint:warnings check against the baseline (CI)
|
||||
* npm run lint:warnings -- --update lower the baseline to today's counts;
|
||||
* it never raises an entry
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/eslint-warnings.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:warnings', (args) => check({ root, update: args.includes('--update') }));
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:format: new code is formatted with Prettier.
|
||||
*
|
||||
* Client code was never Prettier-checked, and almost every file differs from
|
||||
* what .prettierrc asks for. Formatting all of it at once would bury the
|
||||
* history under one commit, so the files that were unformatted when this
|
||||
* check came in are listed in scripts/format-baseline.json and the list only
|
||||
* shrinks: every file outside it, a new one in particular, must be formatted,
|
||||
* and a listed file leaves the list once it has been formatted. The check
|
||||
* covers .ts, .tsx, .mjs and .css under src/, tests/, e2e/ and scripts/.
|
||||
*
|
||||
* npm run lint:format check against the baseline (CI)
|
||||
* npm run lint:format -- --list print every unformatted file
|
||||
* npm run lint:format -- --update take formatted and deleted files off the list;
|
||||
* it never adds one
|
||||
*
|
||||
* To format a file: npx prettier --write <file>. The comparison lives in
|
||||
* scripts/lib/format.mjs.
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/format.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:format', (args) =>
|
||||
check({ root, update: args.includes('--update'), list: args.includes('--list') })
|
||||
);
|
||||
@@ -0,0 +1,616 @@
|
||||
/*
|
||||
* lint:i18n-keys: every translation key the client names exists in en.
|
||||
*
|
||||
* `t()` takes any string and returns the key itself when en has no such
|
||||
* entry, so a typo or a key deleted from the locales renders as raw
|
||||
* "budget.addCategory" text and nothing fails. Locale parity cannot see it:
|
||||
* it compares the locales with en, not en with the code. This check reads
|
||||
* src/ (tests aside) and resolves what it finds against shared/src/i18n/en:
|
||||
*
|
||||
* t('x.y'), tHtml('x.y'), tr('x.y') every string literal in the first
|
||||
* argument, so both sides of a
|
||||
* `cond ? 'a.b' : 'c.d'` are checked
|
||||
* <TransHtml html="x.y" /> the markup variant
|
||||
* translateApiError(t, err, 'x.y') the fallback key
|
||||
* labelKey: 'x.y', titleKey="x.y" any property or prop named *Key that
|
||||
* holds a dotted key, the tables
|
||||
* components feed to t() later
|
||||
* const guideKey = (id) => `help.${id}` a key builder (help/registry.ts):
|
||||
* a template returned by a const
|
||||
* named *Key, read as a template key
|
||||
*
|
||||
* A key exists when en declares it, or declares `key.other` (a plural group
|
||||
* whose general form is spelled out). A template whose interpolations can
|
||||
* only produce string literals (t(`roadtrip.window.${a ? 'onRoute' : 'atStop'}`))
|
||||
* is expanded into those keys and each is checked like a literal one; a
|
||||
* literal fallback beside data (`${role ?? 'editor'}`) is checked as a key
|
||||
* too. Any other template literal key such as
|
||||
* t(`budget.category.${id}`), or a prefix with the rest appended
|
||||
* (t('costs.filter.' + f)), cannot be resolved. It is read as a pattern in
|
||||
* which each interpolation stands for one key segment (no dot), and it passes
|
||||
* on its own only when that pattern is narrow: it matches at least one en key
|
||||
* and at most MAX_IMPLICIT_MATCHES of them, the size of an enum such as the
|
||||
* docsync error codes. A pattern that matches nothing fails. A wider one
|
||||
* (`settings.${mode}` reaches every settings key, so a wrong suffix would
|
||||
* pass unseen) and one without a fixed dotted prefix need an entry in
|
||||
* DYNAMIC_ALLOWED, keyed by file and template, saying what bounds the value.
|
||||
* Listing every narrow template instead would be well over a hundred entries
|
||||
* restating their own prefix, and nothing in an entry would be checked that
|
||||
* the bound does not already check. What the bound cannot see is a runtime
|
||||
* value with no key under a narrow prefix: that needs the value's type, which
|
||||
* this text scan does not have, and is the price of not listing them.
|
||||
* A key held in a variable (`t(opt.label)`) is out of reach unless the table
|
||||
* names it in a *Key property.
|
||||
*
|
||||
* The en keys nothing reaches are a ratchet. Besides src/, the search for
|
||||
* references reads server/src (system notice and notification channel keys
|
||||
* the server sends, *Key properties in its registries), plugin-sdk/src,
|
||||
* shared/src/book (the Studio's layout template names) and the native apps'
|
||||
* address screen in native-shell/, so
|
||||
* a key the server uses does not read as dead; those references only count as
|
||||
* reached, they are not held to the rules above. The unused keys per en
|
||||
* domain file may not rise above scripts/i18n-unused-baseline.json, and an
|
||||
* entry above its count fails until --update lowers it. A key reached only
|
||||
* through a variable the scan cannot follow is reached by naming it: in a
|
||||
* *Key property of the table, or as a literal t() where the table is read.
|
||||
*
|
||||
* npm run lint:i18n-keys check (CI)
|
||||
* npm run lint:i18n-keys -- --unused also list en keys no literal or pattern reaches
|
||||
* npm run lint:i18n-keys -- --update lower the unused-key baseline; it never raises an entry
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, relative } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
// Plain paths rather than `new URL(..., import.meta.url)`: under the test runner's DOM environment URL is
|
||||
// jsdom's, which fileURLToPath refuses.
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const SRC = join(HERE, '..', 'src');
|
||||
const SHARED_SCRIPTS = join(HERE, '..', '..', 'shared', 'scripts');
|
||||
const UNUSED_BASELINE = join(HERE, 'i18n-unused-baseline.json');
|
||||
|
||||
/**
|
||||
* Where else a translation key can be named: the server sends keys for the
|
||||
* client to translate (system notices, notification channels), the plugin
|
||||
* SDK names the ones plugin surfaces use, and the shared book engine names
|
||||
* its layout templates. Read only to find which en keys are reached.
|
||||
*/
|
||||
export const REFERENCE_ROOTS = [
|
||||
// The address screen the native apps ship (vite.native.config.js): its own
|
||||
// small build outside src/, reading only the native.* strings.
|
||||
join(HERE, '..', 'native-shell'),
|
||||
join(HERE, '..', '..', 'server', 'src'),
|
||||
join(HERE, '..', '..', 'plugin-sdk', 'src'),
|
||||
join(HERE, '..', '..', 'shared', 'src', 'book'),
|
||||
];
|
||||
|
||||
/** How many en keys a template may reach and still pass without an entry below. */
|
||||
export const MAX_IMPLICIT_MATCHES = 30;
|
||||
|
||||
/**
|
||||
* Template keys the check cannot bound by itself: wider than
|
||||
* MAX_IMPLICIT_MATCHES, or without a fixed dotted prefix. Each names the file
|
||||
* it sits in and why the interpolated value can only be a real key; one with
|
||||
* no fixed prefix also lists the keys it resolves to, which must exist. An
|
||||
* entry nothing uses any more fails, so the list cannot rot.
|
||||
*/
|
||||
export const DYNAMIC_ALLOWED = [
|
||||
{
|
||||
file: 'components/Trips/TripShareDialog.tsx',
|
||||
template: '${opt.label}Hint',
|
||||
because:
|
||||
'TripShareDialog appends Hint to each SHARE_OPTIONS label (useTripShare.ts); share.optTravelOnlyHint ' +
|
||||
'and share.optHideImagesHint exist, and the template has no fixed part to match them by',
|
||||
resolves: ['share.optTravelOnlyHint', 'share.optHideImagesHint'],
|
||||
},
|
||||
...[
|
||||
'help.ctx.${id}.${part}',
|
||||
'help.ctx.${id}.bullet.${n}',
|
||||
'help.guide.${id}.${part}',
|
||||
'help.guide.${id}.step.${n}',
|
||||
'help.guide.${id}.tip.${n}',
|
||||
].map((template) => ({
|
||||
file: 'help/registry.ts',
|
||||
template,
|
||||
because:
|
||||
'a key builder over the registered help contexts and guides; src/help/registry.test.ts resolves every ' +
|
||||
'key of every registered entry against en',
|
||||
})),
|
||||
{
|
||||
file: 'mobile/screens/dashboard/MUserMenu.tsx',
|
||||
template: 'settings.${mode}',
|
||||
because: "mode is a ThemeMode from resolveMode(), 'light' | 'dark' | 'auto', and settings.light/dark/auto exist",
|
||||
},
|
||||
{
|
||||
file: 'mobile/screens/trip/sheets/MBookingFields.tsx',
|
||||
template: 'reservations.${s}',
|
||||
because: "s iterates the literal ['pending', 'confirmed'] as const; reservations.pending/confirmed exist",
|
||||
},
|
||||
...['components/Admin/AdminPluginsPanel.tsx', 'mobile/screens/admin/MAdminPluginsPanel.tsx'].map((file) => ({
|
||||
file,
|
||||
template: 'admin.plugins.perm.${perm}',
|
||||
because:
|
||||
'PermLabel translates a permission only when PERM_KEYS (generated PLUGIN_PERMISSIONS) holds it and shows ' +
|
||||
'the raw code otherwise; the plugin-facts gate keeps the permission keys in step with en',
|
||||
})),
|
||||
...['components/Settings/PhotoProvidersSection.tsx', 'mobile/screens/settings/MPhotoProvidersSection.tsx'].flatMap(
|
||||
(file) =>
|
||||
['memories.${field.label}', 'memories.${field.hint}'].map((template) => ({
|
||||
file,
|
||||
template,
|
||||
because:
|
||||
'field label and hint names come from the provider field rows PhotoProviderSeeder writes, each a ' +
|
||||
'memories.* key in en',
|
||||
}))
|
||||
),
|
||||
{
|
||||
file: 'components/Studio/stickerLibrary.ts',
|
||||
template: 'journey.studio.sticker.${id}',
|
||||
because:
|
||||
'id is a sticker id of the library in @trek/shared/stickers; stickerLibrary.test.ts resolves the key of every ' +
|
||||
'sticker the library holds against en',
|
||||
},
|
||||
{
|
||||
file: 'components/Studio/shapes.ts',
|
||||
template: 'journey.studio.shapeName.${shape}',
|
||||
because:
|
||||
'shapeName takes a BookShapeId; shared/src/book/book-shape-catalogue.spec.ts holds an en name for every ' +
|
||||
'shape of BOOK_SHAPE_GROUPS',
|
||||
},
|
||||
];
|
||||
|
||||
const KEY_RE = /^[a-z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_:-]+)+$/;
|
||||
const PREFIX_RE = /^[a-z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_:-]+)*\.$/;
|
||||
const CALL_RE = /(?<![\w$.])(?:t|tHtml|tr)\(|(?<=[\w$]\.)(?:t|tHtml)\(/g;
|
||||
const HTML_PROP_RE = /<TransHtml\b[^>]*?\bhtml=(["'])([^"'\n]+)\1/g;
|
||||
const API_ERROR_RE = /\btranslateApiError\(\s*t\s*,[^,()]*(?:\([^()]*\))?[^,()]*,\s*(['"])([^'"\n]+)\1/g;
|
||||
const KEY_BUILDER_RE = /\bconst\s+[a-zA-Z]*Key\s*=\s*\([^)]*\)\s*(?::\s*[^=]+?)?=>\s*`((?:\\.|\$\{[^}]*\}|[^`\\])*)`/g;
|
||||
const KEY_PROP_RE = /\b[a-zA-Z]*Key\s*(?::|=\{?)\s*(['"])([a-z][a-zA-Z0-9_]*\.[^'"\s]+)\1/g;
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path, files);
|
||||
else if (/\.tsx?$/.test(name) && !/\.(?:test|spec)\./.test(name) && !name.endsWith('.d.ts')) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const lineAt = (text, index) => text.slice(0, index).split('\n').length;
|
||||
|
||||
/**
|
||||
* The source of the first argument of the call whose `(` sits at `open`:
|
||||
* everything up to the top-level comma or the closing parenthesis, with
|
||||
* strings, template literals and nested brackets skipped as units.
|
||||
*/
|
||||
export function firstArgument(text, open) {
|
||||
let depth = 0;
|
||||
for (let i = open + 1; i < text.length; i++) {
|
||||
const c = text[i];
|
||||
if (c === "'" || c === '"' || c === '`') {
|
||||
for (i++; i < text.length && text[i] !== c; i++) {
|
||||
if (text[i] === '\\') i++;
|
||||
else if (c === '`' && text[i] === '$' && text[i + 1] === '{') {
|
||||
// Skip the interpolation, counting its braces.
|
||||
let braces = 0;
|
||||
for (; i < text.length; i++) {
|
||||
if (text[i] === '{') braces++;
|
||||
else if (text[i] === '}' && --braces === 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c === '(' || c === '[' || c === '{') depth++;
|
||||
else if (c === ')' || c === ']' || c === '}') {
|
||||
if (depth === 0) return text.slice(open + 1, i);
|
||||
depth--;
|
||||
} else if (c === ',' && depth === 0) return text.slice(open + 1, i);
|
||||
}
|
||||
return text.slice(open + 1);
|
||||
}
|
||||
|
||||
/** The quoted literals and template literals of an argument's source. */
|
||||
export function literalsIn(arg) {
|
||||
const quoted = [];
|
||||
const templates = [];
|
||||
for (const m of arg.matchAll(/(['"])((?:\\.|(?!\1)[^\\\n])*)\1|`((?:\\.|\$\{[^}]*\}|[^`\\])*)`/g)) {
|
||||
if (m[3] !== undefined) templates.push(m[3]);
|
||||
else quoted.push(m[2]);
|
||||
}
|
||||
return { quoted, templates };
|
||||
}
|
||||
|
||||
/**
|
||||
* A template literal's key pattern: its fixed parts, one key segment (no dot)
|
||||
* for each interpolation. Null when it has no fixed dotted prefix.
|
||||
*/
|
||||
export function templatePattern(template) {
|
||||
const parts = template.split(/\$\{[^}]*\}/);
|
||||
if (!/^[a-z][a-zA-Z0-9_]*\./.test(parts[0] ?? '')) return null;
|
||||
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
return new RegExp(`^${parts.map(escape).join('[^.]+')}$`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The top-level operator positions of an expression: ternary `?` and `:`,
|
||||
* and the `??` and `||` fallbacks. Strings and brackets are skipped as units,
|
||||
* `?.` is optional chaining.
|
||||
*/
|
||||
function topLevelOperators(expr) {
|
||||
const ops = [];
|
||||
let depth = 0;
|
||||
for (let i = 0; i < expr.length; i++) {
|
||||
const c = expr[i];
|
||||
if (c === "'" || c === '"' || c === '`') {
|
||||
for (i++; i < expr.length && expr[i] !== c; i++) if (expr[i] === '\\') i++;
|
||||
} else if (c === '(' || c === '[' || c === '{') depth++;
|
||||
else if (c === ')' || c === ']' || c === '}') depth--;
|
||||
else if (depth > 0) continue;
|
||||
else if ((c === '?' && expr[i + 1] === '?') || (c === '|' && expr[i + 1] === '|')) ops.push({ op: c + c, at: i++ });
|
||||
else if (c === '?' && expr[i + 1] !== '.') ops.push({ op: '?', at: i });
|
||||
else if (c === ':') ops.push({ op: ':', at: i });
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
const QUOTED_RE = /^(['"])((?:\\.|(?!\1)[^\\\n])*)\1$/;
|
||||
|
||||
/** Whether `e` is one parenthesized expression, its first `(` closing at its last character. */
|
||||
function wrapsWhole(e) {
|
||||
if (!e.startsWith('(') || !e.endsWith(')')) return false;
|
||||
let depth = 0;
|
||||
for (let i = 0; i < e.length; i++) {
|
||||
const c = e[i];
|
||||
if (c === "'" || c === '"' || c === '`') {
|
||||
for (i++; i < e.length && e[i] !== c; i++) if (e[i] === '\\') i++;
|
||||
} else if (c === '(') depth++;
|
||||
else if (c === ')' && --depth === 0) return i === e.length - 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The string literals an interpolated expression can produce, and whether
|
||||
* those are all it can produce. `x ? 'a' : y ? 'b' : 'c'` gives a, b and c,
|
||||
* complete; `role ?? 'editor'` gives editor, incomplete (role is data);
|
||||
* `phase` gives nothing. A literal in a condition (`phase === 'start'`) is
|
||||
* never a result.
|
||||
*/
|
||||
export function interpolationResults(expr) {
|
||||
let e = expr.trim();
|
||||
while (wrapsWhole(e)) e = e.slice(1, -1).trim();
|
||||
const ops = topLevelOperators(e);
|
||||
const q = ops.findIndex((o) => o.op === '?');
|
||||
if (q >= 0) {
|
||||
// The matching `:` of the first `?`: nested ternaries in the consequent raise the count.
|
||||
let open = 0;
|
||||
for (const o of ops.slice(q + 1)) {
|
||||
if (o.op === '?') open++;
|
||||
else if (o.op === ':' && open-- === 0) {
|
||||
const a = interpolationResults(e.slice(ops[q].at + 1, o.at));
|
||||
const b = interpolationResults(e.slice(o.at + 1));
|
||||
return { literals: [...a.literals, ...b.literals], complete: a.complete && b.complete };
|
||||
}
|
||||
}
|
||||
return { literals: [], complete: false };
|
||||
}
|
||||
const fallback = ops.filter((o) => o.op === '??' || o.op === '||');
|
||||
if (fallback.length) {
|
||||
const operands = [];
|
||||
let from = 0;
|
||||
for (const o of fallback) {
|
||||
operands.push(e.slice(from, o.at));
|
||||
from = o.at + 2;
|
||||
}
|
||||
operands.push(e.slice(from));
|
||||
// The left operands are tested values; only the literal ones among them could be produced.
|
||||
const literals = operands.flatMap((x) => interpolationResults(x).literals);
|
||||
return { literals, complete: false };
|
||||
}
|
||||
const m = QUOTED_RE.exec(e);
|
||||
return m ? { literals: [m[2]], complete: true } : { literals: [], complete: false };
|
||||
}
|
||||
|
||||
/** How many keys a template with only literal choices may expand to before it is read as a pattern instead. */
|
||||
const MAX_EXPANSION = 64;
|
||||
|
||||
/**
|
||||
* The references one template literal makes. Interpolations that can only
|
||||
* produce string literals (`${open ? 'a' : 'b'}`) are expanded, so each
|
||||
* branch is checked as a literal key and a typo in one fails. When some
|
||||
* interpolation is data, the template stays a pattern, and each literal an
|
||||
* interpolation can still produce (`${role ?? 'editor'}`) is checked with
|
||||
* that interpolation fixed, under the original template's allow-list site.
|
||||
*/
|
||||
function templateRefs(file, line, template) {
|
||||
const parts = template.split(/\$\{([^}]*)\}/);
|
||||
const fixed = parts.filter((_, i) => i % 2 === 0);
|
||||
const results = parts.filter((_, i) => i % 2 === 1).map(interpolationResults);
|
||||
const literal = [];
|
||||
const dynamic = [];
|
||||
const build = (choices) => fixed.map((f, i) => f + (i < choices.length ? choices[i] : '')).join('');
|
||||
const size = results.reduce((n, r) => n * Math.max(r.literals.length, 1), 1);
|
||||
if (results.every((r) => r.complete) && size <= MAX_EXPANSION) {
|
||||
let keys = [''];
|
||||
results.forEach((r, i) => {
|
||||
keys = keys.flatMap((k) => r.literals.map((lit) => k + fixed[i] + lit));
|
||||
});
|
||||
for (const k of keys) literal.push({ file, line, key: k + fixed[fixed.length - 1] });
|
||||
return { literal, dynamic };
|
||||
}
|
||||
dynamic.push({ file, line, template, pattern: templatePattern(template) });
|
||||
const raw = parts.filter((_, i) => i % 2 === 1).map((x) => `\${${x}}`);
|
||||
results.forEach((r, i) => {
|
||||
for (const lit of r.literals) {
|
||||
const choices = raw.map((x, j) => (j === i ? lit : x));
|
||||
const derived = build(choices);
|
||||
if (!derived.includes('${')) literal.push({ file, line, key: derived });
|
||||
else dynamic.push({ file, line, template: derived, pattern: templatePattern(derived), site: template });
|
||||
}
|
||||
});
|
||||
return { literal, dynamic };
|
||||
}
|
||||
|
||||
/** Every key reference in one file's source. */
|
||||
export function scanSource(text, file = '<source>') {
|
||||
const literal = [];
|
||||
const dynamic = [];
|
||||
for (const m of text.matchAll(CALL_RE)) {
|
||||
const open = m.index + m[0].length - 1;
|
||||
const { quoted, templates } = literalsIn(firstArgument(text, open));
|
||||
const line = lineAt(text, m.index);
|
||||
for (const key of quoted) {
|
||||
if (KEY_RE.test(key)) literal.push({ file, line, key });
|
||||
// t('costs.filter.' + f): a prefix with the rest appended, read like a template.
|
||||
else if (PREFIX_RE.test(key))
|
||||
dynamic.push({ file, line, template: `${key}\${…}`, pattern: templatePattern(`${key}\${…}`) });
|
||||
}
|
||||
for (const template of templates) {
|
||||
if (!template.includes('${')) {
|
||||
if (KEY_RE.test(template)) literal.push({ file, line, key: template });
|
||||
continue;
|
||||
}
|
||||
const refs = templateRefs(file, line, template);
|
||||
literal.push(...refs.literal);
|
||||
dynamic.push(...refs.dynamic);
|
||||
}
|
||||
}
|
||||
for (const m of text.matchAll(KEY_BUILDER_RE)) {
|
||||
// Builders of other strings (cache keys) have no fixed dotted prefix and are not translation keys.
|
||||
const pattern = templatePattern(m[1]);
|
||||
if (pattern) dynamic.push({ file, line: lineAt(text, m.index), template: m[1], pattern });
|
||||
}
|
||||
for (const re of [HTML_PROP_RE, API_ERROR_RE, KEY_PROP_RE]) {
|
||||
for (const m of text.matchAll(re)) {
|
||||
if (KEY_RE.test(m[2])) literal.push({ file, line: lineAt(text, m.index), key: m[2] });
|
||||
}
|
||||
}
|
||||
return { literal, dynamic };
|
||||
}
|
||||
|
||||
/** en's keys with the domain file each sits in, read with the shared parity tooling's reader. */
|
||||
export async function readEnKeyFiles() {
|
||||
const { listDomainFiles, readCatalog } = await import(pathToFileURL(join(SHARED_SCRIPTS, 'i18n-catalog.mjs')).href);
|
||||
const files = new Map();
|
||||
for (const file of listDomainFiles('en')) for (const { key } of readCatalog('en', file)) files.set(key, file);
|
||||
if (files.size === 0) throw new Error('shared/src/i18n/en holds no keys: the reader or the path is broken');
|
||||
return files;
|
||||
}
|
||||
|
||||
/** en's keys, read from the locale sources with the shared parity tooling's reader. */
|
||||
export async function readEnKeys() {
|
||||
return new Set((await readEnKeyFiles()).keys());
|
||||
}
|
||||
|
||||
export const hasKey = (enKeys, key) => enKeys.has(key) || enKeys.has(`${key}.other`);
|
||||
|
||||
const base = (k) => k.replace(/\.(?:zero|one|two|few|many|other)$/, '');
|
||||
|
||||
/** How many en keys a pattern reaches, a plural group counted once. */
|
||||
export function countMatches(pattern, enKeys) {
|
||||
const reached = new Set();
|
||||
for (const k of enKeys) {
|
||||
if (pattern.test(k)) reached.add(k);
|
||||
else if (pattern.test(base(k))) reached.add(base(k));
|
||||
}
|
||||
return reached.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* The verdict over a scan: literal keys en lacks, template keys no en key
|
||||
* matches, templates too wide to pass without an allow-list entry,
|
||||
* allow-list entries that no file uses any more or that the check no longer
|
||||
* needs, and the en keys nothing reaches. elsewhere holds the references
|
||||
* outside src/ (scanElsewhere), which only count as reaching keys.
|
||||
*
|
||||
* @param {ReturnType<typeof scanElsewhere>} [elsewhere]
|
||||
*/
|
||||
export function evaluate(scan, enKeys, allowed = DYNAMIC_ALLOWED, elsewhere = { literal: [], dynamic: [] }) {
|
||||
const missing = scan.literal.filter(({ key }) => !hasKey(enKeys, key));
|
||||
const site = (file, template) => `${file}\n${template}`;
|
||||
const allowedSites = new Set(allowed.map((a) => site(a.file, a.template)));
|
||||
const counts = new Map();
|
||||
const reach = (template, pattern) => {
|
||||
if (!counts.has(template)) counts.set(template, pattern ? countMatches(pattern, enKeys) : null);
|
||||
return counts.get(template);
|
||||
};
|
||||
const unmatched = [];
|
||||
const broad = [];
|
||||
for (const d of scan.dynamic) {
|
||||
const n = reach(d.template, d.pattern);
|
||||
const isAllowed = allowedSites.has(site(d.file, d.site ?? d.template));
|
||||
if (n === 0 || (n === null && !isAllowed)) unmatched.push(d);
|
||||
else if (n > MAX_IMPLICIT_MATCHES && !isAllowed) broad.push({ ...d, matches: n });
|
||||
}
|
||||
const usedSites = new Set(scan.dynamic.map((d) => site(d.file, d.site ?? d.template)));
|
||||
const stale = allowed.filter((a) => {
|
||||
if (!usedSites.has(site(a.file, a.template))) return true;
|
||||
if ((a.resolves ?? []).some((k) => !hasKey(enKeys, k))) return true;
|
||||
// An entry for a template narrow enough to pass by itself only lengthens the list.
|
||||
const n = reach(a.template, templatePattern(a.template));
|
||||
return n !== null && n <= MAX_IMPLICIT_MATCHES;
|
||||
});
|
||||
// References outside src/ (see REFERENCE_ROOTS) only mark keys as reached.
|
||||
const reached = new Set([
|
||||
...scan.literal.map((l) => l.key),
|
||||
...elsewhere.literal.map((l) => l.key),
|
||||
...allowed.flatMap((a) => a.resolves ?? []),
|
||||
]);
|
||||
const patterns = [...scan.dynamic, ...elsewhere.dynamic].map((d) => d.pattern).filter(Boolean);
|
||||
const unused = [...enKeys].filter(
|
||||
(k) => !reached.has(k) && !reached.has(base(k)) && !patterns.some((p) => p.test(k) || p.test(base(k)))
|
||||
);
|
||||
return { missing, unmatched, broad, stale, unused };
|
||||
}
|
||||
|
||||
export function scanTree(root = SRC) {
|
||||
if (!existsSync(root)) throw new Error(`${root} does not exist`);
|
||||
const scan = { literal: [], dynamic: [] };
|
||||
for (const path of walk(root)) {
|
||||
const found = scanSource(readFileSync(path, 'utf8'), relative(root, path).split('\\').join('/'));
|
||||
scan.literal.push(...found.literal);
|
||||
scan.dynamic.push(...found.dynamic);
|
||||
}
|
||||
if (scan.literal.length === 0) throw new Error(`no translation key found under ${root}: the scanner is broken`);
|
||||
return scan;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every key reference under the reference roots, for the unused count. A root
|
||||
* that is missing or names no key at all is fine here: these are extra places
|
||||
* to look, not the code the check is about.
|
||||
*
|
||||
* @param {string[]} [roots]
|
||||
* @returns {{ literal: { file: string, line: number, key: string }[], dynamic: { file: string, line: number, template: string, pattern: RegExp | null, site?: string }[] }}
|
||||
*/
|
||||
export function scanElsewhere(roots = REFERENCE_ROOTS) {
|
||||
const scan = { literal: [], dynamic: [] };
|
||||
for (const root of roots) {
|
||||
if (!existsSync(root)) continue;
|
||||
for (const path of walk(root)) {
|
||||
const found = scanSource(readFileSync(path, 'utf8'), relative(root, path).split('\\').join('/'));
|
||||
scan.literal.push(...found.literal);
|
||||
scan.dynamic.push(...found.dynamic);
|
||||
}
|
||||
}
|
||||
return scan;
|
||||
}
|
||||
|
||||
/** The unused keys per en domain file. */
|
||||
export function unusedPerFile(unused, keyFiles) {
|
||||
const counts = {};
|
||||
for (const key of unused) {
|
||||
const file = keyFiles.get(key);
|
||||
if (file) counts[file] = (counts[file] ?? 0) + 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* The unused counts held against the baseline: the files that gained unused
|
||||
* keys, the entries above their count (or for a file that is gone), and the
|
||||
* baseline lowered to today, which --update writes. An entry never rises and
|
||||
* a file without one holds no unused key.
|
||||
*/
|
||||
export function compareUnused(baseline, counts) {
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline[file] ?? 0));
|
||||
const lowered = {};
|
||||
for (const [file, allowed] of Object.entries(baseline)) {
|
||||
const now = counts[file] ?? 0;
|
||||
if (now > 0) lowered[file] = Math.min(allowed, now);
|
||||
}
|
||||
const stale = Object.entries(baseline)
|
||||
.filter(([file, allowed]) => lowered[file] !== allowed)
|
||||
.map(([file, allowed]) => ({ file, allowed, now: counts[file] ?? 0 }));
|
||||
return { grown, stale, lowered };
|
||||
}
|
||||
|
||||
/** The committed baseline, which fails closed: a missing or malformed file is an error, never empty. */
|
||||
export function readUnusedBaseline(path = UNUSED_BASELINE) {
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(readFileSync(path, 'utf8'));
|
||||
} catch (err) {
|
||||
throw new Error(`scripts/i18n-unused-baseline.json cannot be read (${err.message}); restore it from git`);
|
||||
}
|
||||
const ok =
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
!Array.isArray(value) &&
|
||||
Object.values(value).every((n) => Number.isInteger(n) && n > 0);
|
||||
if (!ok)
|
||||
throw new Error('scripts/i18n-unused-baseline.json is not an object of file → positive count; restore it from git');
|
||||
return value;
|
||||
}
|
||||
|
||||
// Compared by real path, so the check still runs when the script is started through a symlink.
|
||||
const isCli =
|
||||
Boolean(process.argv[1]) &&
|
||||
existsSync(process.argv[1]) &&
|
||||
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isCli) {
|
||||
try {
|
||||
const scan = scanTree();
|
||||
const keyFiles = await readEnKeyFiles();
|
||||
const enKeys = new Set(keyFiles.keys());
|
||||
const { missing, unmatched, broad, stale, unused } = evaluate(scan, enKeys, DYNAMIC_ALLOWED, scanElsewhere());
|
||||
const unusedCounts = unusedPerFile(unused, keyFiles);
|
||||
let unusedBaseline = readUnusedBaseline();
|
||||
if (process.argv.includes('--update')) {
|
||||
unusedBaseline = compareUnused(unusedBaseline, unusedCounts).lowered;
|
||||
const sorted = Object.fromEntries(Object.entries(unusedBaseline).sort(([a], [b]) => (a < b ? -1 : 1)));
|
||||
writeFileSync(UNUSED_BASELINE, JSON.stringify(sorted, null, 2) + '\n');
|
||||
}
|
||||
const unusedVerdict = compareUnused(unusedBaseline, unusedCounts);
|
||||
for (const { file, line, key } of missing) {
|
||||
console.error(`FAIL ${file}:${line}: '${key}' is not a key in shared/src/i18n/en`);
|
||||
}
|
||||
for (const { file, line, template } of unmatched) {
|
||||
console.error(`FAIL ${file}:${line}: \`${template}\` matches no key in shared/src/i18n/en`);
|
||||
}
|
||||
for (const { file, line, template, matches } of broad) {
|
||||
console.error(
|
||||
`FAIL ${file}:${line}: \`${template}\` reaches ${matches} en keys, more than ${MAX_IMPLICIT_MATCHES}: ` +
|
||||
'narrow the prefix, or add a DYNAMIC_ALLOWED entry saying what bounds the value'
|
||||
);
|
||||
}
|
||||
for (const { file, template } of stale) {
|
||||
console.error(
|
||||
`FAIL DYNAMIC_ALLOWED lists \`${template}\` in ${file}, which that file no longer uses, whose keys en ` +
|
||||
'lacks, or which is narrow enough to pass without it: remove or fix the entry'
|
||||
);
|
||||
}
|
||||
for (const [file, n] of unusedVerdict.grown) {
|
||||
const keys = unused.filter((k) => keyFiles.get(k) === file).slice(0, 5);
|
||||
console.error(
|
||||
`FAIL en/${file}: ${n} key(s) nothing in client, server or plugin-sdk reaches, baseline ` +
|
||||
`${unusedBaseline[file] ?? 0} (${keys.join(', ')}). Use the key, or delete it from every locale.`
|
||||
);
|
||||
}
|
||||
for (const { file, allowed, now } of unusedVerdict.stale) {
|
||||
console.error(
|
||||
`FAIL en/${file} is held at ${allowed} in scripts/i18n-unused-baseline.json, but ${now} key(s) are unused ` +
|
||||
'now. Run npm run lint:i18n-keys -- --update to lower it.'
|
||||
);
|
||||
}
|
||||
if (process.argv.includes('--unused')) for (const key of unused.sort()) console.log(`unused ${key}`);
|
||||
console.log(
|
||||
`i18n keys: ${new Set(scan.literal.map((l) => l.key)).size} literal and ${scan.dynamic.length} template ` +
|
||||
`reference(s) checked against ${enKeys.size} en keys; ${unused.length} en key(s) reached by neither, ` +
|
||||
`baseline allows ${Object.values(unusedBaseline).reduce((a, b) => a + b, 0)} (--unused lists them)`
|
||||
);
|
||||
if (
|
||||
missing.length ||
|
||||
unmatched.length ||
|
||||
broad.length ||
|
||||
stale.length ||
|
||||
unusedVerdict.grown.length ||
|
||||
unusedVerdict.stale.length
|
||||
)
|
||||
process.exit(1);
|
||||
} catch (err) {
|
||||
console.error(`FAIL ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"admin.ts": 126,
|
||||
"atlas.ts": 9,
|
||||
"backup.ts": 10,
|
||||
"budget.ts": 36,
|
||||
"categories.ts": 1,
|
||||
"collab.ts": 9,
|
||||
"collection.ts": 35,
|
||||
"common.ts": 7,
|
||||
"dashboard.ts": 65,
|
||||
"dawarich.ts": 15,
|
||||
"dayplan.ts": 17,
|
||||
"docsync.ts": 25,
|
||||
"files.ts": 4,
|
||||
"help.ts": 3,
|
||||
"inspector.ts": 4,
|
||||
"journey.ts": 65,
|
||||
"login.ts": 1,
|
||||
"map.ts": 5,
|
||||
"memories.ts": 8,
|
||||
"mobileNav.ts": 2,
|
||||
"mobileVacay.ts": 4,
|
||||
"nav.ts": 1,
|
||||
"notif.ts": 7,
|
||||
"notifications.ts": 17,
|
||||
"packing.ts": 6,
|
||||
"pdf.ts": 1,
|
||||
"perm.ts": 4,
|
||||
"places.ts": 9,
|
||||
"planner.ts": 53,
|
||||
"reservations.ts": 21,
|
||||
"roadtrip.ts": 36,
|
||||
"settings.ts": 37,
|
||||
"share.ts": 7,
|
||||
"shared.ts": 2,
|
||||
"storage.ts": 16,
|
||||
"system_notice.ts": 32,
|
||||
"todo.ts": 3,
|
||||
"tours.ts": 12,
|
||||
"trip.ts": 10,
|
||||
"undo.ts": 1,
|
||||
"vacay.ts": 17
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:layers: imports follow the layering, downwards only.
|
||||
*
|
||||
* Components reached up into pages/ for models and helpers, and sideways into
|
||||
* mobile/ for phone hooks and sheets, so nothing could be moved or split
|
||||
* without touching three trees. scripts/lib/layers.mjs holds the rules: a
|
||||
* component imports neither pages/ nor mobile/, a shared hook no view, and
|
||||
* nothing under the views (stores, repos, sync, api, db, helpers) a view at
|
||||
* all. The imports that already broke a rule are counted per file in
|
||||
* scripts/layers-baseline.json, and a file may hold no more of them than its
|
||||
* entry (a file without an entry holds none). Type-only imports count: a type
|
||||
* the lower layer needs belongs below it. An entry above what its file holds
|
||||
* now, or for a file that is gone, fails as well until --update lowers it.
|
||||
*
|
||||
* npm run lint:layers check against the baseline (CI)
|
||||
* npm run lint:layers -- --list print every import against the layering
|
||||
* npm run lint:layers -- --update lower the baseline to what the files hold now;
|
||||
* it never raises an entry
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/layers.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:layers', (args) =>
|
||||
check({ root, update: args.includes('--update'), list: args.includes('--list') })
|
||||
);
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"src/api/client.ts": 1,
|
||||
"src/components/Atlas/AtlasCountryPlaces.tsx": 1,
|
||||
"src/components/Budget/ReceiptScanModal.tsx": 1,
|
||||
"src/components/Collab/CollabLinks.tsx": 1,
|
||||
"src/components/Collab/CollabNotes.tsx": 1,
|
||||
"src/components/Collections/AddPlaceToCollectionModal.tsx": 1,
|
||||
"src/components/Collections/CollectionFilterBar.tsx": 2,
|
||||
"src/components/Collections/CollectionLabelFilter.tsx": 1,
|
||||
"src/components/Collections/CollectionMap.tsx": 1,
|
||||
"src/components/Collections/CollectionPicker.tsx": 1,
|
||||
"src/components/Collections/CollectionPlaceDetail.tsx": 1,
|
||||
"src/components/Collections/ListEditorModal.tsx": 1,
|
||||
"src/components/Collections/MSaveToCollectionSheet.tsx": 3,
|
||||
"src/components/Dawarich/DawarichAcceptDialog.tsx": 3,
|
||||
"src/components/Dawarich/DawarichAtlasDialog.tsx": 3,
|
||||
"src/components/Dawarich/DawarichSuggestionsPanel.tsx": 1,
|
||||
"src/components/Journey/ContributorInviteDialog.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageAddTripDialog.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageChips.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageEntryCard.tsx": 2,
|
||||
"src/components/Journey/JourneyDetailPageEntryEditor.tsx": 2,
|
||||
"src/components/Journey/JourneyDetailPageGalleryView.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageMapView.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPagePhotoGrid.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageProviderPicker.tsx": 2,
|
||||
"src/components/Journey/JourneyDetailPageSettingsDialog.tsx": 1,
|
||||
"src/components/Journey/JourneyEntryCover.tsx": 2,
|
||||
"src/components/Journey/MobileEntryView.tsx": 1,
|
||||
"src/components/Map/MapView.tsx": 1,
|
||||
"src/components/Map/MapViewGL.tsx": 1,
|
||||
"src/components/Planner/IcsSubscribeModal.tsx": 1,
|
||||
"src/components/Planner/TransitJourneyModal.tsx": 1,
|
||||
"src/components/Planner/TransitSearchPanel.tsx": 1,
|
||||
"src/components/Planner/TripWarningsBanner.tsx": 1,
|
||||
"src/components/Planner/transitDisplay.tsx": 1,
|
||||
"src/components/Plugins/PluginFrame.tsx": 1,
|
||||
"src/components/Roadtrip/RoadtripSidebarDriveBands.tsx": 1,
|
||||
"src/components/Roadtrip/RoadtripSidebarRefuelBand.tsx": 1,
|
||||
"src/components/Studio/StudioShell.tsx": 1,
|
||||
"src/components/Studio/sidebar/StudioEntryCard.tsx": 1,
|
||||
"src/components/Studio/travel/BadgeIcon.tsx": 1,
|
||||
"src/components/Todo/useTodoList.ts": 1,
|
||||
"src/components/shared/ConfirmDialog.tsx": 1,
|
||||
"src/components/shared/CountryFlag.tsx": 1,
|
||||
"src/components/shared/EmptyState.tsx": 1,
|
||||
"src/components/shared/TripLoadingSplash.tsx": 1,
|
||||
"src/components/shared/dialogFocus.ts": 1,
|
||||
"src/hooks/useDawarichConnection.ts": 1,
|
||||
"src/hooks/useDawarichJournalTrail.ts": 1,
|
||||
"src/hooks/useDawarichSuggestions.ts": 1,
|
||||
"src/hooks/useDayNotes.ts": 1,
|
||||
"src/hooks/useRouteCalculation.ts": 4,
|
||||
"src/hooks/useTransportRoutes.ts": 1,
|
||||
"src/hooks/useWebPush.ts": 1,
|
||||
"src/repo/pluginPoiRepo.ts": 1,
|
||||
"src/store/slices/budgetSlice.ts": 1,
|
||||
"src/store/studioStore.ts": 1,
|
||||
"src/store/vacayStore.ts": 1
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* The measuring and the comparison behind lint:dup (scripts/dup-lint.mjs).
|
||||
*
|
||||
* Copies are found by jscpd's detector at the thresholds SonarCloud applies to
|
||||
* TypeScript: a block counts once MIN_TOKENS tokens repeat over at least
|
||||
* MIN_LINES lines. Both .ts and .tsx are read as TypeScript, because Sonar
|
||||
* treats them as one language and a hook in a .ts file that repeats a view's
|
||||
* .tsx code is a copy all the same. A file's count is the number of its lines
|
||||
* inside a copied block, the duplicated lines Sonar reports. Which of three
|
||||
* copies a block is matched against depends on the order the files are read
|
||||
* in, so they are read sorted by path, and with readText, so every machine
|
||||
* counts the same.
|
||||
*/
|
||||
import { Detector, getModeHandler, MemoryStore } from '@jscpd/core';
|
||||
import { Tokenizer } from '@jscpd/tokenizer';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
countMap,
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
export const MIN_TOKENS = 100;
|
||||
export const MIN_LINES = 10;
|
||||
|
||||
export const DIRS = ['src'];
|
||||
|
||||
/** The files SonarCloud analyses as source: tests and declaration files are left out. */
|
||||
export function accepts(key) {
|
||||
return /\.tsx?$/.test(key) && !key.endsWith('.d.ts') && !TEST_FILE.test(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every copied block under root as a pair of line ranges, one per side. Both
|
||||
* sides can be the same file.
|
||||
*
|
||||
* @returns {Promise<{ key: string, start: number, end: number }[][]>}
|
||||
*/
|
||||
export async function findCopies(root) {
|
||||
const keys = listFiles(root, DIRS, accepts)
|
||||
.map((path) => toKey(root, path))
|
||||
.sort();
|
||||
const detector = new Detector(new Tokenizer(), new MemoryStore(), [], {
|
||||
minTokens: MIN_TOKENS,
|
||||
minLines: MIN_LINES,
|
||||
mode: getModeHandler('mild'),
|
||||
});
|
||||
const side = ({ sourceId, start, end }) => ({ key: sourceId, start: start.line, end: end.line });
|
||||
const copies = [];
|
||||
for (const key of keys) {
|
||||
const clones = await detector.detect(key, readText(join(root, key)), 'typescript');
|
||||
for (const clone of clones) copies.push([side(clone.duplicationA), side(clone.duplicationB)]);
|
||||
}
|
||||
return copies;
|
||||
}
|
||||
|
||||
/** Per file in path order, how many of its lines sit inside a copied block. */
|
||||
export function countLines(copies) {
|
||||
const lines = {};
|
||||
for (const pair of copies) {
|
||||
for (const { key, start, end } of pair) {
|
||||
const set = (lines[key] ??= new Set());
|
||||
for (let line = start; line <= end; line++) set.add(line);
|
||||
}
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(lines)
|
||||
.filter(([, set]) => set.size > 0)
|
||||
.sort(([a], [b]) => (a < b ? -1 : 1))
|
||||
.map(([key, set]) => [key, set.size])
|
||||
);
|
||||
}
|
||||
|
||||
/** Per file, its copied blocks as "start-end = other:start-end", in line order. */
|
||||
export function describeCopies(copies) {
|
||||
const found = {};
|
||||
const range = ({ start, end }) => `${start}-${end}`;
|
||||
for (const [a, b] of copies) {
|
||||
(found[a.key] ??= []).push({ at: a.start, text: `${range(a)} = ${b.key}:${range(b)}` });
|
||||
(found[b.key] ??= []).push({ at: b.start, text: `${range(b)} = ${a.key}:${range(a)}` });
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(found).map(([key, list]) => [key, list.sort((x, y) => x.at - y.at).map(({ text }) => text)])
|
||||
);
|
||||
}
|
||||
|
||||
/** Runs the check against the baseline at baselinePath and returns the exit code. */
|
||||
export async function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/dup-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const copies = await findCopies(root);
|
||||
const counts = countLines(copies);
|
||||
const blocks = describeCopies(copies);
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
|
||||
if (list) {
|
||||
for (const [key, n] of Object.entries(counts)) {
|
||||
log(`${key} (${n}, baseline ${baseline[key] ?? 0})`);
|
||||
for (const line of blocks[key]) log(` ${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([key, n]) => n > (baseline[key] ?? 0));
|
||||
const stale = staleCounts(baseline, counts);
|
||||
|
||||
for (const [key, n] of grown) {
|
||||
error(`FAIL ${key}: ${n} line(s) in copied blocks, baseline ${baseline[key] ?? 0}:`);
|
||||
for (const line of blocks[key]) error(` ${line}`);
|
||||
}
|
||||
if (grown.length) {
|
||||
error(
|
||||
'Put the code both places need in one shared hook or module and import it from both instead of copying it ' +
|
||||
'(useInstanceSettings and useRangeBypass under src/components/Admin/ are the pattern).'
|
||||
);
|
||||
}
|
||||
reportStale(stale, { file: 'dup-baseline.json', command: 'lint:dup', root, error });
|
||||
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
|
||||
log(
|
||||
`dup: ${sum(counts)} line(s) in copied blocks in ${Object.keys(counts).length} file(s), baseline allows ${sum(baseline)}`
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* The client's own ESLint rules, as the local plugin `trek` in eslint.config.mjs.
|
||||
*
|
||||
* Each one finds a smell client/CLAUDE.md forbids and that no stock rule sees
|
||||
* on its own. They run as warnings, so lint:warnings
|
||||
* (scripts/eslint-ratchet.mjs) holds what exists today in
|
||||
* scripts/eslint-baseline.json and fails on each new one.
|
||||
*/
|
||||
|
||||
/** The expression under any `as`, `!`, `satisfies` or type assertion, which do not change the value. */
|
||||
function unwrap(node) {
|
||||
let current = node;
|
||||
while (
|
||||
current &&
|
||||
(current.type === 'TSAsExpression' ||
|
||||
current.type === 'TSNonNullExpression' ||
|
||||
current.type === 'TSSatisfiesExpression' ||
|
||||
current.type === 'TSTypeAssertion')
|
||||
)
|
||||
current = current.expression;
|
||||
return current;
|
||||
}
|
||||
|
||||
const isWindow = (node) => {
|
||||
const target = unwrap(node);
|
||||
return (
|
||||
(target?.type === 'Identifier' && (target.name === 'window' || target.name === 'globalThis')) ||
|
||||
(target?.type === 'MemberExpression' &&
|
||||
!target.computed &&
|
||||
target.property.name === 'window' &&
|
||||
unwrap(target.object)?.type === 'Identifier' &&
|
||||
unwrap(target.object).name === 'globalThis')
|
||||
);
|
||||
};
|
||||
|
||||
const propertyName = (member) =>
|
||||
!member.computed && member.property.type === 'Identifier'
|
||||
? member.property.name
|
||||
: member.property.type === 'Literal' && typeof member.property.value === 'string'
|
||||
? member.property.value
|
||||
: null;
|
||||
|
||||
/**
|
||||
* `.catch(() => {})`, `.catch(() => undefined)`, `.catch(() => null)`: the
|
||||
* failure disappears without a trace. A write that fails needs a rollback and
|
||||
* a toast; a read that may fail says why it may, in code that handles it.
|
||||
*/
|
||||
/** @type {import('eslint').Rule.RuleModule} */
|
||||
const noSwallowedCatch = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
schema: [],
|
||||
messages: {
|
||||
swallowed:
|
||||
'This .catch() swallows the error. Roll back and tell the user (toast), or handle the failure on purpose ' +
|
||||
'and say why in the handler; never .catch(() => {}).',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const empty = (fn) => {
|
||||
if (fn?.type !== 'ArrowFunctionExpression' && fn?.type !== 'FunctionExpression') return false;
|
||||
const body = fn.body;
|
||||
if (body.type === 'BlockStatement') return body.body.length === 0;
|
||||
return (
|
||||
(body.type === 'Identifier' && body.name === 'undefined') ||
|
||||
(body.type === 'Literal' && body.value === null) ||
|
||||
(body.type === 'UnaryExpression' && body.operator === 'void')
|
||||
);
|
||||
};
|
||||
return {
|
||||
CallExpression(node) {
|
||||
const callee = node.callee;
|
||||
if (callee.type !== 'MemberExpression' || propertyName(callee) !== 'catch') return;
|
||||
if (node.arguments.length === 1 && empty(node.arguments[0])) context.report({ node, messageId: 'swallowed' });
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* `useTripStore()` with no selector subscribes the component to the whole
|
||||
* store, so it re-renders on every change anywhere in it. And on Zustand 5 the
|
||||
* obvious repair, a selector that builds an object, loops forever without
|
||||
* useShallow, because each call returns a new object.
|
||||
*/
|
||||
/** @type {import('eslint').Rule.RuleModule} */
|
||||
const storeWithoutSelector = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
schema: [],
|
||||
messages: {
|
||||
whole:
|
||||
'{{name}}() without a selector subscribes to the whole store and re-renders on every change in it. ' +
|
||||
'Select what you read: {{name}}(s => s.field), or for several fields {{name}}(useShallow(s => ({ a: s.a, b: s.b }))). ' +
|
||||
'On Zustand 5 an object selector without useShallow loops forever. In an effect or handler use {{name}}.getState().',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === 'Identifier' &&
|
||||
/^use[A-Z]\w*Store$/.test(node.callee.name) &&
|
||||
node.arguments.length === 0
|
||||
)
|
||||
context.report({ node, messageId: 'whole', data: { name: node.callee.name } });
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Events the browser itself fires on window; dispatching one of these is simulating the platform, not a bus. */
|
||||
const PLATFORM_EVENTS = new Set([
|
||||
'resize',
|
||||
'scroll',
|
||||
'storage',
|
||||
'online',
|
||||
'offline',
|
||||
'focus',
|
||||
'blur',
|
||||
'popstate',
|
||||
'hashchange',
|
||||
'visibilitychange',
|
||||
'load',
|
||||
'beforeunload',
|
||||
'pagehide',
|
||||
'pageshow',
|
||||
'message',
|
||||
'keydown',
|
||||
'keyup',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Global mutable state and event buses on window: `window.__dragData`,
|
||||
* `window.__addToast` and any other `window.__*`, and window.dispatchEvent
|
||||
* with an event of the app's own. Nothing types them, nothing finds their
|
||||
* listeners, and a test has to fake the global to reach them.
|
||||
*/
|
||||
/** @type {import('eslint').Rule.RuleModule} */
|
||||
const noWindowGlobals = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
schema: [],
|
||||
messages: {
|
||||
global:
|
||||
'window.{{name}} is global mutable state. Keep it in a module (a store, a small session module) and import it.',
|
||||
bus:
|
||||
'window.dispatchEvent with an event of our own is an untyped global bus. Call a store action, or bump a ' +
|
||||
'version counter in a slice that the listener selects.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const ownEvent = (arg) => {
|
||||
const event = unwrap(arg);
|
||||
if (event?.type !== 'NewExpression' || event.callee.type !== 'Identifier') return false;
|
||||
if (event.callee.name === 'CustomEvent') return true;
|
||||
if (event.callee.name !== 'Event') return false;
|
||||
const name = event.arguments[0];
|
||||
return !(name?.type === 'Literal' && typeof name.value === 'string' && PLATFORM_EVENTS.has(name.value));
|
||||
};
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
const name = propertyName(node);
|
||||
if (name?.startsWith('__') && isWindow(node.object))
|
||||
context.report({ node, messageId: 'global', data: { name } });
|
||||
},
|
||||
CallExpression(node) {
|
||||
const callee = unwrap(node.callee);
|
||||
if (callee?.type !== 'MemberExpression' || propertyName(callee) !== 'dispatchEvent') return;
|
||||
if (isWindow(callee.object) && ownEvent(node.arguments[0])) context.report({ node, messageId: 'bus' });
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
meta: { name: 'trek' },
|
||||
rules: {
|
||||
'no-swallowed-catch': noSwallowedCatch,
|
||||
'store-without-selector': storeWithoutSelector,
|
||||
'no-window-globals': noWindowGlobals,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,282 @@
|
||||
/*
|
||||
* The tally and the comparison behind lint:warnings (scripts/eslint-ratchet.mjs).
|
||||
*/
|
||||
import { ESLint } from 'eslint';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
countMap,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
/**
|
||||
* Where a warning is counted: in the app code, in the tests, or, for a
|
||||
* message an eslint-disable comment silenced, among the suppressed ones. An
|
||||
* inline disable must not be the cheap way under the ratchet, and an inline
|
||||
* rule config, which silences without a trace, fails outright (see tally).
|
||||
*/
|
||||
export const AREAS = ['src', 'tests', 'suppressed'];
|
||||
|
||||
const areaOf = (key) => (key.startsWith('tests/') || TEST_FILE.test(key) ? 'tests' : 'src');
|
||||
|
||||
const ruleOf = (message) =>
|
||||
message.ruleId ?? (/eslint-disable/.test(message.message) ? 'unused-disable-directive' : '(no rule)');
|
||||
|
||||
/** A baseline: each area an object of rule → positive count. */
|
||||
export function areaCounts(value) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not an object of area → rule counts';
|
||||
for (const area of Object.keys(value))
|
||||
if (!AREAS.includes(area)) return `"${area}" is not one of ${AREAS.join(', ')}`;
|
||||
for (const area of AREAS) {
|
||||
if (!(area in value)) return `the "${area}" area is missing`;
|
||||
const problem = countMap(value[area]);
|
||||
if (problem) return `in "${area}", ${problem}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const scriptKind = (file) =>
|
||||
file.endsWith('.tsx')
|
||||
? ts.ScriptKind.TSX
|
||||
: /\.[cm]?ts$/.test(file)
|
||||
? ts.ScriptKind.TS
|
||||
: file.endsWith('.jsx')
|
||||
? ts.ScriptKind.JSX
|
||||
: ts.ScriptKind.JS;
|
||||
|
||||
/** ESLint's label for a block comment that configures rules, as opposed to eslint-disable and the like. */
|
||||
const INLINE_CONFIG = /^\s*eslint(?:\s|$)/;
|
||||
|
||||
/**
|
||||
* The block comments in a file that configure ESLint rules, such as
|
||||
* `/* eslint no-empty: off *\/`, as `line:column comment`. Such a comment
|
||||
* switches a rule off for the whole file without a single message reaching
|
||||
* either the warnings or the suppressed ones, so it would walk past the
|
||||
* ratchet unseen. The comments come from the TypeScript parser, so the same
|
||||
* text inside a string or a template does not count.
|
||||
*/
|
||||
export function inlineConfigsOf(source, file) {
|
||||
const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, scriptKind(file));
|
||||
const seen = new Set();
|
||||
const found = [];
|
||||
const collect = (ranges) => {
|
||||
for (const range of ranges ?? []) {
|
||||
if (seen.has(range.pos)) continue;
|
||||
seen.add(range.pos);
|
||||
if (range.kind !== ts.SyntaxKind.MultiLineCommentTrivia) continue;
|
||||
const text = source.slice(range.pos, range.end);
|
||||
if (!INLINE_CONFIG.test(text.slice(2, -2))) continue;
|
||||
const { line, character } = sf.getLineAndCharacterOfPosition(range.pos);
|
||||
found.push(`${line + 1}:${character + 1} ${text.replace(/\s+/g, ' ').slice(0, 80)}`);
|
||||
}
|
||||
};
|
||||
const visit = (node) => {
|
||||
collect(ts.getLeadingCommentRanges(source, node.pos));
|
||||
collect(ts.getTrailingCommentRanges(source, node.pos));
|
||||
for (const child of node.getChildren(sf)) visit(child);
|
||||
};
|
||||
visit(sf);
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The warnings per area and rule in ESLint's results, the files behind each
|
||||
* count, and every error (an error, a parse failure included, always fails).
|
||||
* An inline rule config comment (see inlineConfigsOf) is an error too: the
|
||||
* place to change a rule is eslint.config.mjs.
|
||||
*/
|
||||
export function tally(results, root) {
|
||||
const counts = Object.fromEntries(AREAS.map((area) => [area, {}]));
|
||||
const files = Object.fromEntries(AREAS.map((area) => [area, {}]));
|
||||
const errors = [];
|
||||
const add = (area, rule, key) => {
|
||||
counts[area][rule] = (counts[area][rule] ?? 0) + 1;
|
||||
const where = (files[area][rule] ??= {});
|
||||
where[key] = (where[key] ?? 0) + 1;
|
||||
};
|
||||
for (const result of results) {
|
||||
const key = toKey(root, result.filePath);
|
||||
for (const comment of result.inlineConfigs ?? [])
|
||||
errors.push(`${key}:${comment} configures a rule inline; set it in eslint.config.mjs (inline-config)`);
|
||||
for (const message of result.messages) {
|
||||
if (message.fatal || message.severity === 2)
|
||||
errors.push(`${key}:${message.line ?? 0}:${message.column ?? 0} ${message.message} (${ruleOf(message)})`);
|
||||
else add(areaOf(key), ruleOf(message), key);
|
||||
}
|
||||
for (const message of result.suppressedMessages ?? []) add('suppressed', ruleOf(message), key);
|
||||
}
|
||||
return { counts, files, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of an ESLint result the tally reads.
|
||||
*
|
||||
* @typedef {{ ruleId: string | null, severity: number, message: string, fatal?: boolean, line?: number, column?: number }} LintMessage
|
||||
* @typedef {{ filePath: string, messages: LintMessage[], suppressedMessages?: LintMessage[], inlineConfigs?: string[] }} LintResult
|
||||
*/
|
||||
|
||||
/**
|
||||
* ESLint over the whole client, with its own config, as `npm run lint:check`
|
||||
* runs it, each result with the inline rule configs of its file.
|
||||
*
|
||||
* @param {string} root
|
||||
* @returns {Promise<LintResult[]>}
|
||||
*/
|
||||
export async function lintClient(root) {
|
||||
const results = await new ESLint({ cwd: root }).lintFiles(['.']);
|
||||
return results.map((result) => ({
|
||||
...result,
|
||||
inlineConfigs: inlineConfigsOf(readText(result.filePath), result.filePath),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The ref new warnings are measured against: TREK_LINT_BASE (the CI sets it), else origin/dev. */
|
||||
const baseRef = () => process.env.TREK_LINT_BASE || 'origin/dev';
|
||||
|
||||
/** Git in the workspace: its output, or null when it fails (no repository, no such ref). */
|
||||
function gitIn(root, args) {
|
||||
try {
|
||||
return execFileSync('git', args, {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
maxBuffer: 1 << 28,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The messages of one rule in one area of a single file's lint result. */
|
||||
function ofRule(results, rule, area) {
|
||||
const result = results[0];
|
||||
if (!result) return [];
|
||||
const pool =
|
||||
area === 'suppressed' ? (result.suppressedMessages ?? []) : result.messages.filter((m) => m.severity === 1);
|
||||
return pool.filter((m) => ruleOf(m) === rule);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a grown rule's new warnings sit: every file among `keys` (the files
|
||||
* holding the rule now) that differs from `ref` and holds more of the rule
|
||||
* than it did there, each of its warnings of the rule as `file:line message`.
|
||||
* The count alone names no file, and the files holding the most are old ones;
|
||||
* this names the file that tipped it. Null when `ref` is not at hand (a clone
|
||||
* without it), and the report then keeps to the files holding the most.
|
||||
*/
|
||||
export async function newWarningsOf({ root, rule, area, keys, lintText, ref = baseRef(), git = gitIn }) {
|
||||
const changed = git(root, ['diff', '--name-only', '--relative', ref, '--', '.']);
|
||||
if (changed === null) return null;
|
||||
const differs = new Set(changed.split('\n').filter(Boolean));
|
||||
const found = await Promise.all(
|
||||
keys
|
||||
.filter((key) => differs.has(key))
|
||||
.map(async (key) => {
|
||||
const path = join(root, key);
|
||||
// A typed rule can trip over a text that is not the file on disk (the
|
||||
// base version); then the file's own warnings are told, marked so.
|
||||
const lint = async (text) => {
|
||||
try {
|
||||
return { messages: ofRule(await lintText(text, path), rule, area) };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const now = await lint(readText(path));
|
||||
if (!now) return [];
|
||||
const before = git(root, ['show', `${ref}:./${key}`]);
|
||||
const was = before === null ? { messages: [] } : await lint(before);
|
||||
if (was && now.messages.length <= was.messages.length) return [];
|
||||
const note = was ? '' : ' (the base version could not be linted)';
|
||||
return now.messages.map((m) => `${key}:${m.line ?? 0} ${m.message}${note}`);
|
||||
})
|
||||
);
|
||||
return found.flat();
|
||||
}
|
||||
|
||||
/** Prints, under the grown counts, the files and lines behind each one (see newWarningsOf). */
|
||||
async function reportNew(grown, { root, files, lintText, error }) {
|
||||
if (!grown.length || !lintText) return;
|
||||
const found = await Promise.all(
|
||||
grown.map(({ area, rule }) => newWarningsOf({ root, rule, area, keys: Object.keys(files[area][rule]), lintText }))
|
||||
);
|
||||
grown.forEach(({ area, rule }, i) => {
|
||||
const lines = found[i];
|
||||
if (!lines?.length) return;
|
||||
error(`New ${rule} warning(s) in ${area}, against ${baseRef()}:`);
|
||||
for (const line of lines) error(` ${line}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** Lints one file's text with the client's own config, for newWarningsOf. */
|
||||
function lintTextClient(root) {
|
||||
const eslint = new ESLint({ cwd: root });
|
||||
return (text, filePath) => eslint.lintText(text, { filePath });
|
||||
}
|
||||
|
||||
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
|
||||
|
||||
/**
|
||||
* Runs ESLint (or lint, in a test) and compares the warnings with the
|
||||
* baseline at baselinePath. Returns the exit code.
|
||||
*/
|
||||
export async function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/eslint-baseline.json'),
|
||||
update = false,
|
||||
lint = lintClient,
|
||||
lintText = lint === lintClient ? lintTextClient : null,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
let baseline = readBaseline(baselinePath, areaCounts);
|
||||
const { counts, files, errors } = tally(await lint(root), root);
|
||||
|
||||
if (update) {
|
||||
baseline = Object.fromEntries(AREAS.map((area) => [area, lowerCounts(baseline[area], counts[area])]));
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
for (const line of errors) error(`FAIL ${line}`);
|
||||
const grown = [];
|
||||
let stale = 0;
|
||||
for (const area of AREAS) {
|
||||
for (const [rule, n] of Object.entries(counts[area])) {
|
||||
const allowed = baseline[area][rule] ?? 0;
|
||||
if (n <= allowed) continue;
|
||||
grown.push({ area, rule });
|
||||
const top = Object.entries(files[area][rule])
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.slice(0, 5)
|
||||
.map(([key, k]) => `${key} (${k})`);
|
||||
error(`FAIL ${area}: ${n} ${rule} warning(s), baseline ${allowed}. Most in: ${top.join(', ')}`);
|
||||
}
|
||||
const fallen = staleCounts(baseline[area], counts[area]);
|
||||
reportStale(fallen, {
|
||||
file: 'eslint-baseline.json',
|
||||
command: 'lint:warnings',
|
||||
label: (rule) => `${area}: ${rule}`,
|
||||
error,
|
||||
});
|
||||
stale += fallen.length;
|
||||
}
|
||||
await reportNew(grown, { root, files, lintText: lintText && lintText(root), error });
|
||||
if (grown.length) {
|
||||
error(
|
||||
'Fix the new warning rather than silencing it: an eslint-disable comment is counted under "suppressed". ' +
|
||||
'Run npx eslint <file> to see each one.'
|
||||
);
|
||||
}
|
||||
log(
|
||||
`eslint: ${errors.length} error(s); warnings ${AREAS.map((area) => `${area} ${sum(counts[area])}/${sum(baseline[area])}`).join(', ')} (now/baseline)`
|
||||
);
|
||||
return errors.length || grown.length || stale ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* The comparison behind lint:format (scripts/format-lint.mjs): which files
|
||||
* Prettier would rewrite, against the list of files that were unformatted
|
||||
* when the check came in.
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import * as prettier from 'prettier';
|
||||
import {
|
||||
fileList,
|
||||
listFiles,
|
||||
lowerList,
|
||||
RatchetError,
|
||||
readBaseline,
|
||||
readText,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
/** The app, its tests, the Playwright specs and the client's own tooling. */
|
||||
export const DIRS = ['src', 'tests', 'e2e', 'scripts'];
|
||||
|
||||
export const accepts = (key) => /\.(?:tsx?|mjs|css)$/.test(key);
|
||||
|
||||
/**
|
||||
* Whether Prettier leaves the file as it is, with the config that applies to
|
||||
* it. The text is read with LF line ends, so a Windows checkout agrees with CI
|
||||
* about endOfLine. A file Prettier cannot parse is not formatted.
|
||||
*/
|
||||
export async function isFormatted(path) {
|
||||
const options = await prettier.resolveConfig(path);
|
||||
if (!options) throw new RatchetError(`no Prettier config applies to ${path}`);
|
||||
try {
|
||||
return await prettier.check(readText(path), { ...options, filepath: path });
|
||||
} catch (err) {
|
||||
stopped.set(path, String(err instanceof Error ? err.message : err).split('\n')[0]);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Why Prettier gave up on a file, by its path, so the failure line can say it was not about style. */
|
||||
const stopped = new Map();
|
||||
|
||||
/** The files under root that Prettier would rewrite, keyed by their path from root. */
|
||||
export async function unformatted(root) {
|
||||
const found = [];
|
||||
for (const path of listFiles(root, DIRS, accepts)) if (!(await isFormatted(path))) found.push(toKey(root, path));
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the check against the list at baselinePath. A file outside the list
|
||||
* must be formatted. A listed file that is formatted now, or gone, fails the
|
||||
* check as well until --update takes it out: the list only shrinks, and a
|
||||
* stale entry would let the next file at that path in unformatted. Returns
|
||||
* the exit code.
|
||||
*/
|
||||
export async function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/format-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const found = await unformatted(root);
|
||||
let baseline = readBaseline(baselinePath, fileList);
|
||||
|
||||
if (update) {
|
||||
baseline = lowerList(baseline, found);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const allowed = new Set(baseline);
|
||||
const fresh = found.filter((key) => !allowed.has(key));
|
||||
const now = new Set(found);
|
||||
const stale = baseline.filter((key) => !now.has(key));
|
||||
|
||||
if (list) for (const key of found) log(`${allowed.has(key) ? 'listed' : 'new '} ${key}`);
|
||||
for (const key of fresh) {
|
||||
error(`FAIL ${key} is not formatted. Run: npx prettier --write ${key}`);
|
||||
const why = stopped.get(join(root, key));
|
||||
if (why) error(` Prettier could not format it: ${why}`);
|
||||
}
|
||||
for (const key of stale) {
|
||||
error(`FAIL ${key} is listed in scripts/format-baseline.json but is formatted now or gone.`);
|
||||
}
|
||||
if (stale.length) error('Run npm run lint:format -- --update to take the formatted files off the list.');
|
||||
log(`format: ${found.length} unformatted file(s), ${baseline.length} listed in the baseline`);
|
||||
return fresh.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* The imports of a source file, read from its syntax tree rather than with a
|
||||
* regular expression, so an import split over lines, a dynamic import() and a
|
||||
* re-export count, and an import inside a comment or a string does not.
|
||||
*/
|
||||
import { dirname, join, relative, resolve } from 'node:path';
|
||||
import ts from 'typescript';
|
||||
import { listFiles, readText, TEST_FILE, toKey } from './ratchet.mjs';
|
||||
|
||||
const bindingsAreTypes = (elements) => elements.length > 0 && elements.every((el) => el.isTypeOnly);
|
||||
|
||||
/**
|
||||
* Every module the file names, with the line it is named on and whether the
|
||||
* import only brings in types (erased from the bundle, so no runtime path).
|
||||
*/
|
||||
export function importsOf(source, file) {
|
||||
const kind = file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
||||
const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, kind);
|
||||
const found = [];
|
||||
const add = (node, literal, typeOnly) => {
|
||||
if (!literal || !ts.isStringLiteralLike(literal)) return;
|
||||
found.push({
|
||||
specifier: literal.text,
|
||||
line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
|
||||
typeOnly,
|
||||
});
|
||||
};
|
||||
const visit = (node) => {
|
||||
if (ts.isImportDeclaration(node)) {
|
||||
const clause = node.importClause;
|
||||
const named =
|
||||
clause?.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : null;
|
||||
const typeOnly = Boolean(clause && (clause.isTypeOnly || (!clause.name && named && bindingsAreTypes(named))));
|
||||
add(node, node.moduleSpecifier, typeOnly);
|
||||
} else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
|
||||
const named = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : null;
|
||||
add(node, node.moduleSpecifier, node.isTypeOnly || Boolean(named && bindingsAreTypes(named)));
|
||||
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
||||
add(node, node.moduleReference.expression, node.isTypeOnly);
|
||||
} else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
|
||||
add(node, node.argument.literal, true);
|
||||
} else if (
|
||||
ts.isCallExpression(node) &&
|
||||
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
||||
(ts.isIdentifier(node.expression) && node.expression.text === 'require'))
|
||||
) {
|
||||
add(node, node.arguments[0], false);
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sf);
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer of a path from src/: its top directory ("components", "api"), or,
|
||||
* for a file directly in src/, its name without the extension. src/types.ts
|
||||
* is then the layer "types" both when it imports and when it is imported as
|
||||
* '../types', and its rules are those of the src/types/ directory.
|
||||
*/
|
||||
export function layerOfPath(fromSrc) {
|
||||
const [top, ...rest] = fromSrc.split('/');
|
||||
return rest.length ? top : top.replace(/(\.d)?\.[cm]?[jt]sx?$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer a relative import lands in (see layerOfPath), or null for a
|
||||
* package or a path outside src/.
|
||||
*/
|
||||
export function layerOf(srcRoot, fromFile, specifier) {
|
||||
if (!specifier.startsWith('.')) return null;
|
||||
const target = relative(srcRoot, resolve(dirname(fromFile), specifier))
|
||||
.split('\\')
|
||||
.join('/');
|
||||
if (!target || target.startsWith('..')) return null;
|
||||
return layerOfPath(target);
|
||||
}
|
||||
|
||||
/** Every source file under root/src outside the tests, with its key, its layer and its imports resolved to layers. */
|
||||
export function sourceGraph(root) {
|
||||
const src = join(root, 'src');
|
||||
return listFiles(root, ['src'], (key) => /\.tsx?$/.test(key) && !TEST_FILE.test(key)).map((path) => ({
|
||||
key: toKey(root, path),
|
||||
layer: layerOfPath(toKey(src, path)),
|
||||
imports: importsOf(readText(path), path).map((imp) => ({ ...imp, layer: layerOf(src, path, imp.specifier) })),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* The rules and the comparison behind lint:layers (scripts/layer-lint.mjs).
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import { sourceGraph } from './imports.mjs';
|
||||
import { countMap, lowerCounts, readBaseline, reportStale, staleCounts, writeBaseline } from './ratchet.mjs';
|
||||
|
||||
const VIEW = ['components', 'mobile', 'pages', 'hooks'];
|
||||
|
||||
/**
|
||||
* For each directory under src/, the directories its files may not import
|
||||
* from. The view layers sit on top: a page composes components, a component
|
||||
* may use a shared hook, and the phone screens reuse both. Nothing below the
|
||||
* views (stores, repos, sync, api, the Dexie schema and the helpers) knows a
|
||||
* view exists, a repo sits under the stores, and the Dexie schema under all
|
||||
* of them. help/ (the help center's screen registry, plain data) and vacay/
|
||||
* (date helpers) are helpers like utils/. Directories without an entry are
|
||||
* free on purpose: mobile and pages sit at the top, the app root wires
|
||||
* everything, and managed/ is the slot an operator fills with whole screens
|
||||
* at build time. A file directly in src/ is the layer of its name, so
|
||||
* src/types.ts falls under types like the src/types/ directory.
|
||||
*/
|
||||
export const RULES = {
|
||||
components: ['pages', 'mobile'],
|
||||
hooks: ['pages', 'mobile', 'components'],
|
||||
store: VIEW,
|
||||
sync: VIEW,
|
||||
api: VIEW,
|
||||
utils: VIEW,
|
||||
i18n: VIEW,
|
||||
theme: VIEW,
|
||||
constants: VIEW,
|
||||
services: VIEW,
|
||||
push: VIEW,
|
||||
types: VIEW,
|
||||
help: VIEW,
|
||||
vacay: VIEW,
|
||||
repo: [...VIEW, 'store'],
|
||||
db: [...VIEW, 'store', 'repo', 'sync', 'api'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Every import that crosses a boundary the wrong way, per file. A type-only
|
||||
* import counts too: a type the lower layer needs belongs below it.
|
||||
*/
|
||||
export function violations(root, rules = RULES) {
|
||||
const found = {};
|
||||
for (const file of sourceGraph(root)) {
|
||||
const banned = rules[file.layer];
|
||||
if (!banned) continue;
|
||||
const wrong = file.imports.filter((imp) => imp.layer && banned.includes(imp.layer));
|
||||
if (wrong.length)
|
||||
found[file.key] = wrong.map((imp) => `${imp.line}: '${imp.specifier}' (${file.layer} into ${imp.layer})`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Runs the check against the baseline at baselinePath and returns the exit code. */
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/layers-baseline.json'),
|
||||
rules = RULES,
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const found = violations(root, rules);
|
||||
const counts = Object.fromEntries(Object.entries(found).map(([key, list]) => [key, list.length]));
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
|
||||
if (list) {
|
||||
for (const [key, wrong] of Object.entries(found)) {
|
||||
log(`${key} (${wrong.length}, baseline ${baseline[key] ?? 0})`);
|
||||
for (const line of wrong) log(` ${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([key, n]) => n > (baseline[key] ?? 0));
|
||||
const stale = staleCounts(baseline, counts);
|
||||
|
||||
for (const [key, n] of grown) {
|
||||
error(`FAIL ${key}: ${n} import(s) against the layering, baseline ${baseline[key] ?? 0}:`);
|
||||
for (const line of found[key]) error(` ${line}`);
|
||||
}
|
||||
if (grown.length) {
|
||||
error(
|
||||
'Move what both sides need down into a layer they may share (a model or helper under utils/, ' +
|
||||
'a hook under hooks/, a type under types/) instead of importing upwards.'
|
||||
);
|
||||
}
|
||||
reportStale(stale, { file: 'layers-baseline.json', command: 'lint:layers', root, error });
|
||||
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
|
||||
log(
|
||||
`layers: ${sum(counts)} import(s) against the layering in ${Object.keys(counts).length} file(s), baseline allows ${sum(baseline)}`
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* The comparison behind lint:offline (scripts/offline-lint.mjs).
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import { sourceGraph } from './imports.mjs';
|
||||
import { fileList, lowerList, readBaseline, writeBaseline } from './ratchet.mjs';
|
||||
|
||||
/** The layers that render or drive a view, and so must not hold a network call. */
|
||||
export const VIEW_LAYERS = ['components', 'mobile', 'pages', 'hooks'];
|
||||
|
||||
/**
|
||||
* The view files that import from src/api/ for anything but types, each with
|
||||
* the imports that do it. A type-only import is erased from the bundle and
|
||||
* carries no request, so it does not count.
|
||||
*/
|
||||
export function bypasses(root) {
|
||||
const found = {};
|
||||
for (const file of sourceGraph(root)) {
|
||||
if (!VIEW_LAYERS.includes(file.layer)) continue;
|
||||
const direct = file.imports.filter((imp) => imp.layer === 'api' && !imp.typeOnly);
|
||||
if (direct.length) found[file.key] = direct.map((imp) => `${imp.line}: '${imp.specifier}'`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the check against the list at baselinePath. A view file outside the
|
||||
* list may not import src/api/. A listed file that no longer does fails the
|
||||
* check as well until --update takes it out, so the list only shrinks and
|
||||
* the next file at that path does not inherit the exemption. Returns the exit
|
||||
* code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/offline-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const found = bypasses(root);
|
||||
const offenders = Object.keys(found);
|
||||
let baseline = readBaseline(baselinePath, fileList);
|
||||
|
||||
if (update) {
|
||||
baseline = lowerList(baseline, offenders);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const allowed = new Set(baseline);
|
||||
const fresh = offenders.filter((key) => !allowed.has(key));
|
||||
const stale = baseline.filter((key) => !found[key]);
|
||||
|
||||
if (list) {
|
||||
for (const [key, direct] of Object.entries(found)) {
|
||||
log(`${allowed.has(key) ? 'listed' : 'new '} ${key}`);
|
||||
for (const line of direct) log(` ${line}`);
|
||||
}
|
||||
}
|
||||
for (const key of fresh) {
|
||||
error(`FAIL ${key} imports src/api/ directly:`);
|
||||
for (const line of found[key]) error(` ${line}`);
|
||||
}
|
||||
if (fresh.length) {
|
||||
error(
|
||||
'A view reads through a repo (src/repo/) or a store and writes through the mutation queue, ' +
|
||||
'so it keeps working offline. A domain that is online-only on purpose still gets its calls ' +
|
||||
'in a store or a repo, not in the view. See client/CLAUDE.md, "Data flow".'
|
||||
);
|
||||
}
|
||||
for (const key of stale) {
|
||||
error(`FAIL ${key} is listed in scripts/offline-baseline.json but no longer imports src/api/ (or is gone).`);
|
||||
}
|
||||
if (stale.length) error('Run npm run lint:offline -- --update to take it off the list.');
|
||||
log(`offline: ${offenders.length} view file(s) import src/api/ directly, ${baseline.length} listed in the baseline`);
|
||||
return fresh.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* The manifest and the checks behind lint:pairs (scripts/pairs-lint.mjs).
|
||||
*/
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { importsOf } from './imports.mjs';
|
||||
import { listFiles, readBaseline, readText, TEST_FILE, toKey } from './ratchet.mjs';
|
||||
|
||||
/** The phone screens every entry of the manifest is weighed against. */
|
||||
export const SCREENS = 'src/mobile/screens';
|
||||
|
||||
/**
|
||||
* Where a shared hook may live: below the views that both import it, or next
|
||||
* to a page in its folder under pages/ (use<Page> and its models), which the
|
||||
* phone shell of that page imports as well. Never in a view itself.
|
||||
*/
|
||||
const SHARED = /^src\/(?:components|hooks|utils)\/|^src\/pages\/[^/]+\//;
|
||||
|
||||
const SOURCE = /\.tsx?$/;
|
||||
const isPath = (value) => typeof value === 'string' && SOURCE.test(value) && !value.includes('\\');
|
||||
const isPathList = (value) => Array.isArray(value) && value.length > 0 && value.every(isPath);
|
||||
|
||||
/**
|
||||
* scripts/feature-pairs.json: pairs is a list of features, each with the
|
||||
* shared hooks or models that hold its logic and the desktop and phone files
|
||||
* that run on them; mobileOnly maps each phone screen file that has no
|
||||
* desktop twin, or no logic a twin could share, to the reason.
|
||||
*/
|
||||
export function manifestShape(value) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not an object';
|
||||
const keys = Object.keys(value).sort().join(',');
|
||||
if (keys !== 'mobileOnly,pairs') return 'it needs exactly the keys "pairs" and "mobileOnly"';
|
||||
if (!Array.isArray(value.pairs)) return '"pairs" is not a list';
|
||||
const names = new Set();
|
||||
for (const pair of value.pairs) {
|
||||
if (!pair || typeof pair !== 'object' || typeof pair.feature !== 'string' || !pair.feature.trim())
|
||||
return `a pair without a feature name: ${JSON.stringify(pair)}`;
|
||||
if (names.has(pair.feature)) return `the feature "${pair.feature}" is listed twice`;
|
||||
names.add(pair.feature);
|
||||
for (const field of ['hooks', 'desktop', 'mobile'])
|
||||
if (!isPathList(pair[field]))
|
||||
return `"${pair.feature}" needs "${field}" as a list of source files from the client root`;
|
||||
}
|
||||
const only = value.mobileOnly;
|
||||
if (!only || typeof only !== 'object' || Array.isArray(only)) return '"mobileOnly" is not an object of file → reason';
|
||||
for (const [key, reason] of Object.entries(only)) {
|
||||
if (!isPath(key)) return `"${key}" in "mobileOnly" is not a source file from the client root`;
|
||||
if (typeof reason !== 'string' || !reason.trim()) return `"${key}" in "mobileOnly" has no reason`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The path a relative import lands on from the client root, without its extension. */
|
||||
function targetOf(root, fromFile, specifier) {
|
||||
if (!specifier.startsWith('.')) return null;
|
||||
return toKey(root, resolve(dirname(fromFile), specifier)).replace(/(?:\/index)?(?:\.[cm]?[jt]sx?)?$/, '');
|
||||
}
|
||||
|
||||
const stem = (key) => key.replace(/\.[cm]?[jt]sx?$/, '');
|
||||
|
||||
/** The modules a file imports for more than types, as paths from the root without extensions. */
|
||||
function runtimeImports(root, key) {
|
||||
const path = join(root, key);
|
||||
return new Set(
|
||||
importsOf(readText(path), path)
|
||||
.filter((imp) => !imp.typeOnly)
|
||||
.map((imp) => targetOf(root, path, imp.specifier))
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything wrong with the manifest against the tree, as lines to print:
|
||||
* a listed file that is gone, a hook outside the shared layers, a view of a
|
||||
* pair that does not import every hook of the pair, a phone screen listed
|
||||
* both as a pair and as phone only, and a phone screen that is in neither.
|
||||
*/
|
||||
export function problems(root, manifest) {
|
||||
const found = [];
|
||||
const listed = new Set();
|
||||
const present = (key, where) => {
|
||||
if (existsSync(join(root, key))) return true;
|
||||
found.push(`${key} is listed under ${where} but does not exist`);
|
||||
return false;
|
||||
};
|
||||
|
||||
for (const pair of manifest.pairs) {
|
||||
const where = `"${pair.feature}"`;
|
||||
const hooks = pair.hooks.filter((key) => present(key, where));
|
||||
for (const key of hooks)
|
||||
if (!SHARED.test(key))
|
||||
found.push(`${key}, the hook of ${where}, is not under src/components, src/hooks, src/utils or a page folder`);
|
||||
for (const key of [...pair.desktop, ...pair.mobile]) {
|
||||
if (pair.mobile.includes(key)) listed.add(key);
|
||||
if (!present(key, where)) continue;
|
||||
const imported = runtimeImports(root, key);
|
||||
const missing = hooks.filter((hook) => !imported.has(stem(hook)));
|
||||
for (const hook of missing) found.push(`${key} is a view of ${where} but does not import ${hook}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of Object.keys(manifest.mobileOnly)) {
|
||||
if (!present(key, 'mobileOnly')) continue;
|
||||
if (listed.has(key)) found.push(`${key} is listed in a pair and under mobileOnly; it is one or the other`);
|
||||
listed.add(key);
|
||||
}
|
||||
|
||||
const screens = listFiles(
|
||||
root,
|
||||
[SCREENS],
|
||||
(key) => SOURCE.test(key) && !TEST_FILE.test(key) && !key.endsWith('.d.ts')
|
||||
);
|
||||
for (const path of screens) {
|
||||
const key = toKey(root, path);
|
||||
if (!listed.has(key)) found.push(`${key} is a phone screen file that scripts/feature-pairs.json does not list`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Runs the check against the manifest at manifestPath and returns the exit code. */
|
||||
export function check({
|
||||
root,
|
||||
manifestPath = join(root, 'scripts/feature-pairs.json'),
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const manifest = readBaseline(manifestPath, manifestShape);
|
||||
const found = problems(root, manifest);
|
||||
|
||||
if (list) {
|
||||
for (const pair of manifest.pairs) log(`${pair.feature}: ${pair.hooks.join(', ')}`);
|
||||
}
|
||||
for (const line of found) error(`FAIL ${line}`);
|
||||
if (found.length) {
|
||||
error(
|
||||
'A feature that has a desktop view and a phone view keeps its logic in one shared hook both import. ' +
|
||||
'Add a new phone screen to scripts/feature-pairs.json: as a view of the pair whose hook it runs on, ' +
|
||||
'or under mobileOnly with the reason it has no twin. See client/CLAUDE.md, "Desktop and phone views".'
|
||||
);
|
||||
}
|
||||
const only = Object.keys(manifest.mobileOnly).length;
|
||||
log(
|
||||
`pairs: ${manifest.pairs.length} shared feature(s), ${only} phone-only screen file(s), ${found.length} problem(s)`
|
||||
);
|
||||
return found.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
/*
|
||||
* The parts every ratchet in scripts/ shares: walking the tree, reading a file
|
||||
* the same way on Windows and Linux, and reading, lowering and writing a
|
||||
* baseline.
|
||||
*
|
||||
* A ratchet fails closed. A baseline that is missing, cannot be parsed or has
|
||||
* the wrong shape stops the run with its reason instead of reading as empty
|
||||
* (as empty, the check would fail with no hint at the cause, and --update
|
||||
* would write an empty file over the real one). A directory that should be
|
||||
* scanned and is not there, or a scan that finds no file at all, stops it too:
|
||||
* a check that looked at nothing must not report green.
|
||||
*/
|
||||
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { basename, join, relative } from 'node:path';
|
||||
|
||||
/** A problem with the check itself rather than a violation it found. */
|
||||
export class RatchetError extends Error {}
|
||||
|
||||
export const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
|
||||
|
||||
/** Every file under root/<dir> for each dir whose path passes accept, as absolute paths. */
|
||||
export function listFiles(root, dirs, accept) {
|
||||
const files = [];
|
||||
const walk = (dir) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === 'node_modules') continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path);
|
||||
else if (accept(toKey(root, path))) files.push(path);
|
||||
}
|
||||
};
|
||||
for (const dir of dirs) {
|
||||
const path = join(root, dir);
|
||||
if (!existsSync(path) || !statSync(path).isDirectory()) {
|
||||
throw new RatchetError(`${dir}/ does not exist under ${root}, so there is nothing to check`);
|
||||
}
|
||||
walk(path);
|
||||
}
|
||||
if (!files.length) throw new RatchetError(`no file to check under ${dirs.map((d) => `${d}/`).join(', ')}`);
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
/** A path relative to root with forward slashes, the form every baseline uses. */
|
||||
export function toKey(root, path) {
|
||||
return relative(root, path).split('\\').join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* A text file as the repository holds it: without a byte order mark and with
|
||||
* LF line ends, so a Windows checkout with CRLF counts the same as CI.
|
||||
*/
|
||||
export function readText(path) {
|
||||
const text = readFileSync(path, 'utf8');
|
||||
return (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).replace(/\r\n?/g, '\n');
|
||||
}
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n > 0;
|
||||
|
||||
/** A JSON object of file → positive count. */
|
||||
export function countMap(value) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not an object of file → count';
|
||||
for (const [key, n] of Object.entries(value))
|
||||
if (!isCount(n)) return `"${key}" holds ${JSON.stringify(n)}, not a positive whole number`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A JSON array of distinct file paths. */
|
||||
export function fileList(value) {
|
||||
if (!Array.isArray(value)) return 'it is not an array of file paths';
|
||||
const seen = new Set();
|
||||
for (const entry of value) {
|
||||
if (typeof entry !== 'string' || !entry) return `${JSON.stringify(entry)} is not a file path`;
|
||||
if (seen.has(entry)) return `"${entry}" is listed twice`;
|
||||
seen.add(entry);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The baseline as committed, checked against shape (one of the validators
|
||||
* above, which returns null when the value fits and the reason otherwise).
|
||||
*/
|
||||
export function readBaseline(path, shape) {
|
||||
const name = basename(path);
|
||||
let text;
|
||||
try {
|
||||
text = readFileSync(path, 'utf8');
|
||||
} catch (err) {
|
||||
throw new RatchetError(`scripts/${name} cannot be read (${err.code ?? err.message}); restore it from git`);
|
||||
}
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
} catch (err) {
|
||||
throw new RatchetError(`scripts/${name} is not valid JSON (${err.message}); restore it from git`);
|
||||
}
|
||||
const problem = shape(value);
|
||||
if (problem) throw new RatchetError(`scripts/${name} has the wrong shape: ${problem}; restore it from git`);
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Writes value as sorted, two-space JSON with a final newline. */
|
||||
export function writeBaseline(path, value) {
|
||||
const sorted = Array.isArray(value)
|
||||
? [...value].sort()
|
||||
: Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
||||
writeFileSync(path, JSON.stringify(sorted, null, 2) + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* The baseline lowered to the counts measured now. An entry never rises, a
|
||||
* file that is not in the baseline never enters it, and an entry whose count
|
||||
* fell to floor or below leaves. floor is a number, or a function of the key
|
||||
* when the limit differs between files.
|
||||
*
|
||||
* @param {Record<string, number>} baseline
|
||||
* @param {Record<string, number>} counts
|
||||
* @param {number | ((key: string) => number)} [floor]
|
||||
*/
|
||||
export function lowerCounts(baseline, counts, floor = 0) {
|
||||
const lowered = {};
|
||||
for (const [key, allowed] of Object.entries(baseline)) {
|
||||
const now = counts[key] ?? 0;
|
||||
if (now > (typeof floor === 'function' ? floor(key) : floor)) lowered[key] = Math.min(allowed, now);
|
||||
}
|
||||
return lowered;
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries of a count baseline that allow more than is measured now: a
|
||||
* count that fell below its entry, one back at floor or under it, or a file
|
||||
* that is gone. Exactly the entries lowerCounts would lower or drop. Each one
|
||||
* fails its check until --update lowers it, or the count could grow back to
|
||||
* the old entry unseen, and a deleted file would hand its allowance to the
|
||||
* next file at its path.
|
||||
*
|
||||
* @param {Record<string, number>} baseline
|
||||
* @param {Record<string, number>} counts
|
||||
* @param {number | ((key: string) => number)} [floor]
|
||||
* @returns {{ key: string, entry: number, now: number }[]}
|
||||
*/
|
||||
export function staleCounts(baseline, counts, floor = 0) {
|
||||
const lowered = lowerCounts(baseline, counts, floor);
|
||||
return Object.entries(baseline)
|
||||
.filter(([key, entry]) => lowered[key] !== entry)
|
||||
.map(([key, entry]) => ({ key, entry, now: counts[key] ?? 0 }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a FAIL line for each stale entry (see staleCounts) of the baseline
|
||||
* scripts/<file>, then how to lower them. With root, an entry whose file is
|
||||
* not there is called gone; label names an entry that is not a file path.
|
||||
*
|
||||
* @param {{ key: string, entry: number, now: number }[]} stale
|
||||
* @param {{ file: string, command: string, root?: string, label?: (key: string) => string, error: (line: string) => void }} options
|
||||
*/
|
||||
export function reportStale(stale, { file, command, root, label = (key) => key, error }) {
|
||||
for (const { key, entry, now } of stale) {
|
||||
const gone = root !== undefined && !existsSync(join(root, key));
|
||||
error(
|
||||
`FAIL ${label(key)} is held at ${entry} in scripts/${file}, ` +
|
||||
(gone ? 'but the file is gone.' : `but there are ${now} now.`)
|
||||
);
|
||||
}
|
||||
if (stale.length) {
|
||||
error(
|
||||
`Run npm run ${command} -- --update to lower the baseline with the change that made it smaller: ` +
|
||||
'an entry above the count lets it grow back unseen.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The baseline entries that are still offenders: a list only ever loses files. */
|
||||
export function lowerList(baseline, offenders) {
|
||||
const now = new Set(offenders);
|
||||
return baseline.filter((file) => now.has(file));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one ratchet as a command. main returns the exit code; a RatchetError is
|
||||
* printed as a failure of the check itself. There is no "am I the entry
|
||||
* point" guard to get wrong: the command files only ever run, and the logic
|
||||
* they call lives in scripts/lib/ where tests import it.
|
||||
*/
|
||||
export async function runCli(name, main) {
|
||||
try {
|
||||
process.exitCode = await main(process.argv.slice(2));
|
||||
} catch (err) {
|
||||
if (!(err instanceof RatchetError)) throw err;
|
||||
console.error(`FAIL ${name}: ${err.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* The matching and the comparison behind lint:rtl (scripts/rtl-lint.mjs).
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
countMap,
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
import { markedInComment, withoutComments } from './source.mjs';
|
||||
|
||||
// Tailwind utilities that name a physical side, with any variant prefix
|
||||
// (sm:, hover:, group-hover:) and the negative form (-ml-2).
|
||||
const CLASS = new RegExp(
|
||||
String.raw`(?<![\w-])(?:[\w-]+:)*-?(?:` +
|
||||
[
|
||||
String.raw`(?:ml|mr|pl|pr|left|right|scroll-m[lr]|scroll-p[lr])-(?:\[[^\]\s]+\]|[\w./]+)`,
|
||||
String.raw`text-(?:left|right)(?![\w-])`,
|
||||
String.raw`border-[lr](?:-[\w[\]#./()-]+)?(?![\w-])`,
|
||||
String.raw`rounded-(?:l|r|tl|tr|bl|br)(?:-[\w[\]./]+)?(?![\w-])`,
|
||||
String.raw`(?:float|clear)-(?:left|right)(?![\w-])`,
|
||||
String.raw`space-x-[\w.]+`,
|
||||
].join('|') +
|
||||
')',
|
||||
'g'
|
||||
);
|
||||
// The same sides as React style keys, and as properties in a stylesheet.
|
||||
const STYLE =
|
||||
/\b(?:marginLeft|marginRight|paddingLeft|paddingRight|borderLeft\w*|borderRight\w*|border(?:Top|Bottom)(?:Left|Right)Radius|left|right)\s*:|\b(?:textAlign|float)\s*:\s*['"](?:left|right)['"]/g;
|
||||
const CSS =
|
||||
/(?<![\w-])(?:margin-left|margin-right|padding-left|padding-right|border-left[\w-]*|border-right[\w-]*|border-(?:top|bottom)-(?:left|right)-radius|left|right)\s*:|(?<![\w-])(?:text-align|float)\s*:\s*(?:left|right)\b/g;
|
||||
|
||||
export const DISABLE = 'rtl-lint-disable';
|
||||
|
||||
/**
|
||||
* One file read once: every physical use as `line: match`, skipping the lines
|
||||
* marked as physical on purpose, and how many lines carry that mark.
|
||||
*/
|
||||
export function inspect(source, file) {
|
||||
const isCss = file.endsWith('.css');
|
||||
const uses = [];
|
||||
let markers = 0;
|
||||
const lines = source.split('\n');
|
||||
withoutComments(source, file)
|
||||
.split('\n')
|
||||
.forEach((code, i) => {
|
||||
if (markedInComment(lines[i], code, DISABLE)) {
|
||||
markers++;
|
||||
return;
|
||||
}
|
||||
const patterns = isCss ? [CSS] : [CLASS, STYLE];
|
||||
for (const re of patterns) for (const m of code.match(re) ?? []) uses.push(`${i + 1}: ${m.trim()}`);
|
||||
});
|
||||
return { uses, markers };
|
||||
}
|
||||
|
||||
/** Every physical use in one file, as `line: match`. */
|
||||
export function physicalUses(source, file) {
|
||||
return inspect(source, file).uses;
|
||||
}
|
||||
|
||||
/** The physical uses and the disable markers per file under root/src, keyed by the path from src/. */
|
||||
export function scan(root) {
|
||||
const counts = {};
|
||||
const listed = {};
|
||||
const markers = {};
|
||||
const accept = (key) => /\.(?:tsx?|css)$/.test(key) && !TEST_FILE.test(key);
|
||||
for (const path of listFiles(root, ['src'], accept)) {
|
||||
const found = inspect(readText(path), path);
|
||||
const key = toKey(join(root, 'src'), path);
|
||||
if (found.uses.length) {
|
||||
counts[key] = found.uses.length;
|
||||
listed[key] = found.uses;
|
||||
}
|
||||
if (found.markers) markers[key] = found.markers;
|
||||
}
|
||||
return { counts, listed, markers };
|
||||
}
|
||||
|
||||
const sum = (counts) => Object.values(counts).reduce((a, b) => a + b, 0);
|
||||
|
||||
/**
|
||||
* Runs the check against both baselines: rtl-baseline.json for the physical
|
||||
* sides, rtl-disable-baseline.json for the lines that opt out of the check. A
|
||||
* marker hides a side from the count, so the markers are a ratchet as well:
|
||||
* a file holds no more of them than its entry. Returns the exit code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/rtl-baseline.json'),
|
||||
disableBaselinePath = join(root, 'scripts/rtl-disable-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const { counts, listed, markers } = scan(root);
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
let allowedMarkers = readBaseline(disableBaselinePath, countMap);
|
||||
|
||||
if (list) {
|
||||
for (const [file, uses] of Object.entries(listed).sort()) {
|
||||
log(`${file} (${uses.length}, baseline ${baseline[file] ?? 0})`);
|
||||
for (const use of uses) log(` ${use}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
allowedMarkers = lowerCounts(allowedMarkers, markers);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
writeBaseline(disableBaselinePath, allowedMarkers);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline[file] ?? 0));
|
||||
const marked = Object.entries(markers).filter(([file, n]) => n > (allowedMarkers[file] ?? 0));
|
||||
const stale = staleCounts(baseline, counts);
|
||||
const staleMarkers = staleCounts(allowedMarkers, markers);
|
||||
|
||||
for (const [file, n] of grown) {
|
||||
error(
|
||||
`FAIL ${file}: ${n} physical side(s), baseline ${baseline[file] ?? 0}. ` +
|
||||
'Use ms-/me-/ps-/pe-/start-/end-/text-start/text-end/border-s/border-e/rounded-s/rounded-e ' +
|
||||
'or marginInlineStart/paddingInlineEnd/insetInlineStart/textAlign: start. ' +
|
||||
`If the side is geometry, mark the line with ${DISABLE} in a comment.`
|
||||
);
|
||||
}
|
||||
for (const [file, n] of marked) {
|
||||
error(
|
||||
`FAIL ${file}: ${n} line(s) marked ${DISABLE}, scripts/rtl-disable-baseline.json allows ${allowedMarkers[file] ?? 0}. ` +
|
||||
'Use the logical form where the side follows the text. A side that is geometry on purpose ' +
|
||||
'(a map, a measured position, a time axis) needs a reviewer to raise the entry by hand.'
|
||||
);
|
||||
}
|
||||
reportStale(stale, { file: 'rtl-baseline.json', command: 'lint:rtl', root: join(root, 'src'), error });
|
||||
reportStale(staleMarkers, { file: 'rtl-disable-baseline.json', command: 'lint:rtl', root: join(root, 'src'), error });
|
||||
log(
|
||||
`rtl: ${sum(counts)} physical side(s) in ${Object.keys(counts).length} file(s), baseline allows ${sum(baseline)}; ` +
|
||||
`${sum(markers)} line(s) marked ${DISABLE}, baseline allows ${sum(allowedMarkers)}`
|
||||
);
|
||||
return grown.length || marked.length || stale.length || staleMarkers.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* The measuring and the comparison behind lint:size (scripts/size-lint.mjs).
|
||||
*
|
||||
* A file's size is its lines as an editor wraps them at WIDTH columns: a line
|
||||
* up to WIDTH characters counts once, a longer one once per WIDTH characters
|
||||
* it spans. Counting newlines alone let a file stay under its entry by joining
|
||||
* lines, and the trip planner page already held a 3760 character one; WIDTH is
|
||||
* the printWidth in .prettierrc, so formatted code counts what it shows.
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
countMap,
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
export const WIDTH = 120;
|
||||
|
||||
/**
|
||||
* The kinds of file the check covers, each with the size a file without a
|
||||
* baseline entry may reach. Tests get more room: a spec mirrors the component
|
||||
* it covers and holds fixtures, but past LIMIT it is a god file too. The
|
||||
* Playwright specs and their fixtures under e2e/ count as tests.
|
||||
*/
|
||||
export const GROUPS = [
|
||||
{
|
||||
name: 'test',
|
||||
limit: 2000,
|
||||
accepts: (key) =>
|
||||
/\.tsx?$/.test(key) && (key.startsWith('tests/') || key.startsWith('e2e/') || TEST_FILE.test(key)),
|
||||
},
|
||||
{
|
||||
name: 'source',
|
||||
limit: 1000,
|
||||
accepts: (key) => key.startsWith('src/') && /\.tsx?$/.test(key) && !TEST_FILE.test(key),
|
||||
},
|
||||
{ name: 'stylesheet', limit: 1000, accepts: (key) => key.startsWith('src/') && key.endsWith('.css') },
|
||||
];
|
||||
|
||||
export const DIRS = ['src', 'tests', 'e2e'];
|
||||
|
||||
export function groupOf(key) {
|
||||
return GROUPS.find((group) => group.accepts(key)) ?? null;
|
||||
}
|
||||
|
||||
/** The size of a text as wrapped at WIDTH; a final newline does not start another line. */
|
||||
export function sizeOf(text) {
|
||||
if (text === '') return 0;
|
||||
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
||||
if (text.endsWith('\n')) lines.pop();
|
||||
return lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(line.length / WIDTH)), 0);
|
||||
}
|
||||
|
||||
/** Every covered file under root with its size, keyed by its path from root. */
|
||||
export function measure(root) {
|
||||
const sizes = {};
|
||||
for (const path of listFiles(root, DIRS, (key) => groupOf(key) !== null))
|
||||
sizes[toKey(root, path)] = sizeOf(readText(path));
|
||||
return sizes;
|
||||
}
|
||||
|
||||
const limitOf = (key) => groupOf(key)?.limit ?? 0;
|
||||
|
||||
/**
|
||||
* Runs the check against the baseline at baselinePath. With update, the
|
||||
* baseline is lowered first. An entry above the file's size now, or for a
|
||||
* file that is gone, fails as well until --update lowers it. Returns the
|
||||
* exit code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/size-baseline.json'),
|
||||
update = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const sizes = measure(root);
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, sizes, limitOf);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
const grown = Object.entries(sizes).filter(([key, n]) => n > Math.max(baseline[key] ?? 0, limitOf(key)));
|
||||
const stale = staleCounts(baseline, sizes, limitOf);
|
||||
|
||||
for (const [key, n] of grown) {
|
||||
const entry = baseline[key];
|
||||
error(
|
||||
`FAIL ${key}: ${n} lines (wrapped at ${WIDTH} columns), ` +
|
||||
(entry ? `its baseline is ${entry}. ` : `the limit for a ${groupOf(key).name} file is ${limitOf(key)}. `) +
|
||||
'Move a concern into a module of its own instead of growing the file or packing its lines.'
|
||||
);
|
||||
}
|
||||
reportStale(stale, { file: 'size-baseline.json', command: 'lint:size', root, error });
|
||||
log(
|
||||
`size: ${Object.keys(sizes).length} file(s), ${Object.keys(baseline).length} past their limit held at their baseline`
|
||||
);
|
||||
return grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* The matching and the comparison behind lint:skips (scripts/skip-lint.mjs).
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import ts from 'typescript';
|
||||
import {
|
||||
countMap,
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
/** The test functions of vitest and Playwright a modifier can hang off. */
|
||||
const RUNNERS = new Set(['it', 'test', 'describe', 'suite', 'bench']);
|
||||
/** The jasmine-style shorthands vitest also knows. */
|
||||
const SHORTHAND = new Set(['xit', 'xtest', 'xdescribe']);
|
||||
|
||||
export const DIRS = ['src', 'tests', 'e2e'];
|
||||
|
||||
const accepts = (key) => /\.tsx?$/.test(key) && (key.startsWith('src/') ? TEST_FILE.test(key) : true);
|
||||
|
||||
/** The identifier a chain like test.describe.skip.each starts from. */
|
||||
function rootOf(node) {
|
||||
while (ts.isPropertyAccessExpression(node) || ts.isCallExpression(node)) node = node.expression;
|
||||
return ts.isIdentifier(node) ? node.text : null;
|
||||
}
|
||||
|
||||
/** Playwright specs live under e2e/; everything else runs under vitest. */
|
||||
const isPlaywright = (file) => file.startsWith('e2e/');
|
||||
|
||||
const isTitle = (node) => Boolean(node) && (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node));
|
||||
const isFunction = (node) => Boolean(node) && (ts.isArrowFunction(node) || ts.isFunctionExpression(node));
|
||||
|
||||
/**
|
||||
* Whether a skip or fixme call switches tests off for good. Under vitest it
|
||||
* always does: the first argument is the title, a literal or not. Playwright
|
||||
* also knows a run-time form, test.skip(condition, 'why'), which only skips
|
||||
* when the condition holds. A call counts there unless it is that form: it
|
||||
* declares a test (a title first or a test body second), it has no argument
|
||||
* (called bare, it skips the test or group it sits in), or its condition is
|
||||
* the literal true.
|
||||
*/
|
||||
function switchesOff(call, file) {
|
||||
const [first, second] = call.arguments;
|
||||
if (!isPlaywright(file) || !first || isTitle(first) || isFunction(second)) return true;
|
||||
return first.kind === ts.SyntaxKind.TrueKeyword;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tests a file switches off or narrows down, as `line: code`.
|
||||
*
|
||||
* skipped: it.skip / describe.skip / test.todo / test.fixme and the
|
||||
* x-shorthands, each switching off a test that never runs. Playwright's
|
||||
* test.skip(!seed.id, 'why') decides at run time and does not count (see
|
||||
* switchesOff); neither do skipIf and runIf, unless their condition is the
|
||||
* literal that always skips: skipIf(true), runIf(false).
|
||||
*
|
||||
* only: .only anywhere, which silently drops every other test in the file.
|
||||
*
|
||||
* file is the path from the client root: it decides vitest or Playwright.
|
||||
*/
|
||||
export function modifiers(source, file) {
|
||||
const kind = file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
||||
const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, kind);
|
||||
const skipped = [];
|
||||
const only = [];
|
||||
const at = (node) =>
|
||||
`${sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1}: ${node.getText(sf).slice(0, 60)}`;
|
||||
const visit = (node) => {
|
||||
if (ts.isPropertyAccessExpression(node) && RUNNERS.has(rootOf(node.expression) ?? '')) {
|
||||
const name = node.name.text;
|
||||
if (name === 'only') only.push(at(node));
|
||||
else if (name === 'todo') skipped.push(at(node));
|
||||
else if (name === 'skip' || name === 'fixme') {
|
||||
const call = ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null;
|
||||
// test.skip.each(table)(...) declares skipped tests without being called directly.
|
||||
if (!call || switchesOff(call, file)) skipped.push(at(node));
|
||||
} else if (name === 'skipIf' || name === 'runIf') {
|
||||
// skipIf(true) and runIf(false) are a skip in disguise: the condition can never change.
|
||||
const call = ts.isCallExpression(node.parent) && node.parent.expression === node ? node.parent : null;
|
||||
const never = name === 'skipIf' ? ts.SyntaxKind.TrueKeyword : ts.SyntaxKind.FalseKeyword;
|
||||
if (call?.arguments[0]?.kind === never) skipped.push(at(node));
|
||||
}
|
||||
} else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && SHORTHAND.has(node.expression.text)) {
|
||||
skipped.push(at(node.expression));
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sf);
|
||||
return { skipped, only };
|
||||
}
|
||||
|
||||
/** The skipped and focused tests per file under src/, tests/ and e2e/, keyed by the path from root. */
|
||||
export function scan(root) {
|
||||
const skipped = {};
|
||||
const only = {};
|
||||
for (const path of listFiles(root, DIRS, accepts)) {
|
||||
const key = toKey(root, path);
|
||||
const found = modifiers(readText(path), key);
|
||||
if (found.skipped.length) skipped[key] = found.skipped;
|
||||
if (found.only.length) only[key] = found.only;
|
||||
}
|
||||
return { skipped, only };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the check: no .only anywhere, and no file with more skipped tests than
|
||||
* its entry in the baseline at baselinePath. Returns the exit code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/skip-baseline.json'),
|
||||
update = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const { skipped, only } = scan(root);
|
||||
const counts = Object.fromEntries(Object.entries(skipped).map(([key, list]) => [key, list.length]));
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
for (const [key, list] of Object.entries(only)) {
|
||||
error(`FAIL ${key}: .only runs this test alone and drops every other one in the file:`);
|
||||
for (const line of list) error(` ${line}`);
|
||||
}
|
||||
const grown = Object.entries(counts).filter(([key, n]) => n > (baseline[key] ?? 0));
|
||||
for (const [key, n] of grown) {
|
||||
error(`FAIL ${key}: ${n} skipped or todo test(s), baseline ${baseline[key] ?? 0}:`);
|
||||
for (const line of skipped[key]) error(` ${line}`);
|
||||
}
|
||||
if (grown.length) {
|
||||
error('Fix the test, delete it if its feature is gone, or use skipIf/runIf when it depends on the environment.');
|
||||
}
|
||||
const stale = staleCounts(baseline, counts);
|
||||
reportStale(stale, { file: 'skip-baseline.json', command: 'lint:skips', root, error });
|
||||
const sum = (map) => Object.values(map).reduce((a, b) => a + b, 0);
|
||||
log(
|
||||
`skips: ${sum(counts)} skipped or todo test(s), baseline allows ${sum(baseline)}; ${Object.keys(only).length} file(s) with .only`
|
||||
);
|
||||
return grown.length || stale.length || Object.keys(only).length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Reading source the way the line ratchets need it: with the comments blanked
|
||||
* out, and telling a disable marker in a comment from the same text in code.
|
||||
* Shared by lint:rtl (scripts/lib/rtl.mjs) and theme:lint (scripts/lib/theme.mjs).
|
||||
*/
|
||||
import ts from 'typescript';
|
||||
|
||||
/**
|
||||
* The source with its comments blanked out, so prose like "top right" or
|
||||
* "left out" is no side. TypeScript finds the comments in a .ts/.tsx file,
|
||||
* which keeps `/*` and `//` inside strings and JSX text where they belong
|
||||
* (accept="image/*", a URL); a stylesheet only has block comments.
|
||||
*/
|
||||
export function withoutComments(source, file) {
|
||||
const chars = source.split('');
|
||||
const blank = (pos, end) => {
|
||||
for (let i = pos; i < end; i++) if (chars[i] !== '\n') chars[i] = ' ';
|
||||
};
|
||||
if (file.endsWith('.css')) {
|
||||
for (const m of source.matchAll(/\/\*[\s\S]*?\*\//g)) blank(m.index, m.index + m[0].length);
|
||||
return chars.join('');
|
||||
}
|
||||
const kind = file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
|
||||
const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, kind);
|
||||
const seen = new Set();
|
||||
const take = (ranges) => {
|
||||
for (const r of ranges ?? []) {
|
||||
if (seen.has(r.pos)) continue;
|
||||
seen.add(r.pos);
|
||||
blank(r.pos, r.end);
|
||||
}
|
||||
};
|
||||
const visit = (node) => {
|
||||
take(ts.getLeadingCommentRanges(source, node.pos));
|
||||
take(ts.getTrailingCommentRanges(source, node.end));
|
||||
// JSX text holds no comments, and asking for them there would read `//` in a URL as one.
|
||||
if (!ts.isJsxText(node)) for (const child of node.getChildren(sf)) visit(child);
|
||||
};
|
||||
visit(sf);
|
||||
take(ts.getLeadingCommentRanges(source, sf.endOfFileToken.pos));
|
||||
return chars.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether line carries marker inside a comment; in a string or in code it is no
|
||||
* marker. code is the same line from withoutComments.
|
||||
*/
|
||||
export function markedInComment(line, code, marker) {
|
||||
for (let at = line.indexOf(marker); at !== -1; at = line.indexOf(marker, at + 1)) {
|
||||
if (!code.slice(at, at + marker.length).trim()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* The tally and the comparison behind lint:strict (scripts/strict-lint.mjs).
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
countMap,
|
||||
lowerCounts,
|
||||
RatchetError,
|
||||
readBaseline,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
|
||||
// `src/a.ts(12,5): error TS2531: Object is possibly 'null'.` as tsc prints it with --pretty false.
|
||||
const FILE_ERROR = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
|
||||
// An error tied to no file, such as a broken tsconfig, starts the same way without the position.
|
||||
const OTHER_ERROR = /^(?:.+?: )?error (TS\d+): (.*)$/;
|
||||
|
||||
/**
|
||||
* The strict errors per file in tsc's output, with each error's line, and the
|
||||
* errors tied to no file (a broken config), which always fail. A file key is
|
||||
* the path tsc printed, relative to the client root, with forward slashes; the
|
||||
* indented lines that continue a message belong to the error above them.
|
||||
|
||||
*
|
||||
* @param {string} output
|
||||
* @returns {{ counts: Record<string, number>, listed: Record<string, string[]>, general: string[] }}
|
||||
*/
|
||||
export function parseTscOutput(output) {
|
||||
const counts = {};
|
||||
const listed = {};
|
||||
const general = [];
|
||||
for (const line of output.replace(/\r\n?/g, '\n').split('\n')) {
|
||||
const hit = FILE_ERROR.exec(line);
|
||||
if (hit) {
|
||||
const key = hit[1].split('\\').join('/');
|
||||
counts[key] = (counts[key] ?? 0) + 1;
|
||||
(listed[key] ??= []).push(`${hit[2]}:${hit[3]} ${hit[4]} ${hit[5]}`);
|
||||
continue;
|
||||
}
|
||||
if (!/^\s/.test(line) && OTHER_ERROR.test(line)) general.push(line.trim());
|
||||
}
|
||||
return { counts, listed, general };
|
||||
}
|
||||
|
||||
/** tsc over tsconfig.strict.json, as its plain-text output. */
|
||||
export function runTsc(root) {
|
||||
const tsc = createRequire(join(root, 'package.json')).resolve('typescript/bin/tsc');
|
||||
const result = spawnSync(process.execPath, [tsc, '-p', 'tsconfig.strict.json', '--noEmit', '--pretty', 'false'], {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 256 * 1024 * 1024,
|
||||
});
|
||||
if (result.error) throw new RatchetError(`tsc did not run: ${result.error.message}`);
|
||||
// tsc exits 0 when clean and 1 or 2 when it reports errors; anything else is a crash.
|
||||
if (![0, 1, 2].includes(result.status ?? -1))
|
||||
throw new RatchetError(
|
||||
`tsc stopped with exit code ${result.status}: ${(result.stderr || result.stdout).slice(0, 500)}`
|
||||
);
|
||||
return `${result.stdout}\n${result.stderr}`;
|
||||
}
|
||||
|
||||
const sum = (counts) => Object.values(counts).reduce((a, b) => a + b, 0);
|
||||
|
||||
/**
|
||||
* Runs tsc (or tsc, in a test) and compares the strict errors per file with
|
||||
* the baseline at baselinePath. Returns the exit code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/strict-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
tsc = runTsc,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
const { counts, listed, general } = parseTscOutput(tsc(root));
|
||||
|
||||
if (list) {
|
||||
for (const [file, errors] of Object.entries(listed).sort()) {
|
||||
log(`${file} (${errors.length}, baseline ${baseline[file] ?? 0})`);
|
||||
for (const line of errors) log(` ${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
}
|
||||
|
||||
for (const line of general) error(`FAIL ${line}`);
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline[file] ?? 0));
|
||||
for (const [file, n] of grown) {
|
||||
const first = listed[file].slice(0, 3).join('; ');
|
||||
error(
|
||||
`FAIL ${file}: ${n} error(s) under strictNullChecks and noImplicitAny, baseline ${baseline[file] ?? 0}. ` +
|
||||
`First: ${first}`
|
||||
);
|
||||
}
|
||||
if (grown.length) {
|
||||
error(
|
||||
'Handle the null or type the value rather than asserting it away with `!` or `any`: both are counted by ' +
|
||||
'lint:warnings. Run npm run lint:strict -- --list for every error.'
|
||||
);
|
||||
}
|
||||
const stale = staleCounts(baseline, counts);
|
||||
reportStale(stale, { file: 'strict-baseline.json', command: 'lint:strict', root, error });
|
||||
log(
|
||||
`strict: ${sum(counts)} error(s) in ${Object.keys(counts).length} file(s) under strictNullChecks and ` +
|
||||
`noImplicitAny, baseline allows ${sum(baseline)}`
|
||||
);
|
||||
return general.length || grown.length || stale.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* The matching and the comparison behind theme:lint (scripts/theme-lint.mjs).
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
countMap,
|
||||
listFiles,
|
||||
lowerCounts,
|
||||
readBaseline,
|
||||
readText,
|
||||
reportStale,
|
||||
staleCounts,
|
||||
TEST_FILE,
|
||||
toKey,
|
||||
writeBaseline,
|
||||
} from './ratchet.mjs';
|
||||
import { markedInComment, withoutComments } from './source.mjs';
|
||||
|
||||
export const DISABLE = 'theme-lint-disable';
|
||||
|
||||
// A Tailwind variant prefix (dark:, hover:, md:, group-hover:) and the important mark.
|
||||
const VARIANT = String.raw`(?<![\w-])(?:[\w-]+:)*!?`;
|
||||
const PALETTE =
|
||||
'slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose';
|
||||
const COLOR_UTILITY = String.raw`bg|text|border(?:-[trblxyse])?|ring(?:-offset)?|fill|stroke|from|via|to|divide|outline|decoration|placeholder|caret|accent|shadow`;
|
||||
|
||||
/**
|
||||
* The z-index steps in src/index.css start at 60 (--z-bar). A literal above
|
||||
* Tailwind's own z-50 is a fixed surface placing itself by a number of its own
|
||||
* instead of docking onto a step; z-0 to z-50 stay free for stacking inside a
|
||||
* component.
|
||||
*/
|
||||
export const Z_LITERAL_ABOVE = 50;
|
||||
|
||||
/**
|
||||
* Each rule of the contract in src/theme/README.md the check can see in source,
|
||||
* with the fix its failure message names. A rule returns the offending matches
|
||||
* in one line of code (comments already blanked out).
|
||||
*/
|
||||
export const RULES = [
|
||||
{
|
||||
name: 'arbitrary-color',
|
||||
fix: 'a token utility (bg-surface*, text-content*, border-edge*, bg-accent) or bg-[var(--token)]',
|
||||
re: new RegExp(
|
||||
String.raw`\b(?:bg|text|border|ring|fill|stroke|from|via|to|shadow|outline|decoration|divide|caret)-\[\s*(?:#|rgba?\(|hsla?\(|oklch\()[^\]]*\]`,
|
||||
'g'
|
||||
),
|
||||
},
|
||||
{
|
||||
name: 'inline-color',
|
||||
fix: 'var(--token) in the style, or the token utility as a class',
|
||||
re: /(?:color|background|backgroundColor|borderColor|border|borderTop|borderBottom|borderLeft|borderRight|boxShadow|fill|stroke|outline|textDecorationColor)\s*:\s*['"`]?\s*(?:#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(|oklch\()/g,
|
||||
},
|
||||
{
|
||||
name: 'inline-font-size',
|
||||
fix: 'a type tier (text-title, text-subtitle, text-body, text-caption)',
|
||||
re: /fontSize\s*:\s*['"`]?\d/g,
|
||||
},
|
||||
{
|
||||
name: 'palette-class',
|
||||
fix: 'a token utility: bg-surface*, text-content*, border-edge*, bg-accent with text-accent-text, or a status color',
|
||||
re: new RegExp(
|
||||
`${VARIANT}(?:${COLOR_UTILITY})-(?:(?:${PALETTE})-\\d{2,3}|white|black)(?:\\/\\d{1,3})?(?![\\w-])`,
|
||||
'g'
|
||||
),
|
||||
},
|
||||
{
|
||||
name: 'raw-text-size',
|
||||
fix: 'a type tier (text-title, text-subtitle, text-body, text-caption), which follows the text size setting',
|
||||
// The named sizes and the arbitrary ones (text-[13px], text-[0.8rem]) alike.
|
||||
re: new RegExp(`${VARIANT}text-(?:xs|sm|base|lg|xl|[2-9]xl|\\[\\d*\\.?\\d+(?:px|rem|em)\\])(?![\\w-])`, 'g'),
|
||||
},
|
||||
{
|
||||
name: 'z-index-literal',
|
||||
fix: 'a step of the layering scale: z-[var(--z-modal)] as a class, zIndex: "var(--z-modal)" inline',
|
||||
match: (code) => {
|
||||
const found = [];
|
||||
const add = (m, n) => {
|
||||
if (Math.abs(Number(n)) > Z_LITERAL_ABOVE) found.push(m.trim());
|
||||
};
|
||||
for (const m of code.matchAll(new RegExp(`${VARIANT}-?z-(?:\\[(-?\\d+)\\]|(\\d+))(?![\\w-])`, 'g')))
|
||||
add(m[0], m[1] ?? m[2]);
|
||||
for (const m of code.matchAll(/\b(?:zIndex\s*:|z-index\s*:)\s*['"`]?\s*(-?\d+)/g)) add(m[0], m[1]);
|
||||
return found;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'dark-mode-read',
|
||||
fix: 'the .dark class (useIsDark, dark: variants); only applyAppearance reads the setting',
|
||||
re: /\??\.dark_mode\b/g,
|
||||
},
|
||||
];
|
||||
|
||||
const matchesOf = (rule, code) => (rule.match ? rule.match(code) : [...code.matchAll(rule.re)].map((m) => m[0].trim()));
|
||||
|
||||
/**
|
||||
* One file read once: every hit as `line: rule: match`, skipping the lines
|
||||
* that carry the marker in a comment, and how many lines carry it.
|
||||
*/
|
||||
export function inspect(source, file) {
|
||||
const hits = [];
|
||||
let markers = 0;
|
||||
const lines = source.split('\n');
|
||||
withoutComments(source, file)
|
||||
.split('\n')
|
||||
.forEach((code, i) => {
|
||||
if (markedInComment(lines[i], code, DISABLE)) {
|
||||
markers++;
|
||||
return;
|
||||
}
|
||||
for (const rule of RULES) for (const m of matchesOf(rule, code)) hits.push(`${i + 1}: ${rule.name}: ${m}`);
|
||||
});
|
||||
return { hits, markers };
|
||||
}
|
||||
|
||||
/** The hits and markers per file under root/src (tests excluded), keyed by the path from src/. */
|
||||
export function scan(root) {
|
||||
const counts = {};
|
||||
const listed = {};
|
||||
const markers = {};
|
||||
const accept = (key) => /\.tsx?$/.test(key) && !TEST_FILE.test(key);
|
||||
for (const path of listFiles(root, ['src'], accept)) {
|
||||
const found = inspect(readText(path), path);
|
||||
const key = toKey(join(root, 'src'), path);
|
||||
if (found.hits.length) {
|
||||
counts[key] = found.hits.length;
|
||||
listed[key] = found.hits;
|
||||
}
|
||||
if (found.markers) markers[key] = found.markers;
|
||||
}
|
||||
return { counts, listed, markers };
|
||||
}
|
||||
|
||||
const sum = (counts) => Object.values(counts).reduce((a, b) => a + b, 0);
|
||||
|
||||
/**
|
||||
* Runs the check against theme-baseline.json (hits per file) and
|
||||
* theme-disable-baseline.json (marked lines per file). Returns the exit code.
|
||||
*/
|
||||
export function check({
|
||||
root,
|
||||
baselinePath = join(root, 'scripts/theme-baseline.json'),
|
||||
disableBaselinePath = join(root, 'scripts/theme-disable-baseline.json'),
|
||||
update = false,
|
||||
list = false,
|
||||
log = console.log,
|
||||
error = console.error,
|
||||
}) {
|
||||
const { counts, listed, markers } = scan(root);
|
||||
let baseline = readBaseline(baselinePath, countMap);
|
||||
let allowedMarkers = readBaseline(disableBaselinePath, countMap);
|
||||
|
||||
if (list) {
|
||||
for (const [file, hits] of Object.entries(listed).sort()) {
|
||||
log(`${file} (${hits.length}, baseline ${baseline[file] ?? 0})`);
|
||||
for (const hit of hits) log(` ${hit}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (update) {
|
||||
baseline = lowerCounts(baseline, counts);
|
||||
allowedMarkers = lowerCounts(allowedMarkers, markers);
|
||||
writeBaseline(baselinePath, baseline);
|
||||
writeBaseline(disableBaselinePath, allowedMarkers);
|
||||
}
|
||||
|
||||
const grown = Object.entries(counts).filter(([file, n]) => n > (baseline[file] ?? 0));
|
||||
const marked = Object.entries(markers).filter(([file, n]) => n > (allowedMarkers[file] ?? 0));
|
||||
const stale = staleCounts(baseline, counts);
|
||||
const staleMarkers = staleCounts(allowedMarkers, markers);
|
||||
|
||||
for (const [file, n] of grown) {
|
||||
const rules = [...new Set(listed[file].map((hit) => hit.split(': ')[1]))];
|
||||
error(`FAIL ${file}: ${n} styling bypass(es) of the theme tokens, baseline ${baseline[file] ?? 0}.`);
|
||||
for (const name of rules) error(` ${name}: use ${RULES.find((rule) => rule.name === name).fix}.`);
|
||||
}
|
||||
if (grown.length) {
|
||||
error(
|
||||
`Run npm run theme:lint -- --list to see each hit. A colour CSS variables cannot reach (map paint, PDF, ` +
|
||||
`brand) is marked with ${DISABLE} in a comment on its line. See src/theme/README.md.`
|
||||
);
|
||||
}
|
||||
for (const [file, n] of marked) {
|
||||
error(
|
||||
`FAIL ${file}: ${n} line(s) marked ${DISABLE}, scripts/theme-disable-baseline.json allows ` +
|
||||
`${allowedMarkers[file] ?? 0}. Use a token where one reaches; a surface it cannot reach (map paint, PDF, ` +
|
||||
'brand colours) needs a reviewer to raise the entry by hand.'
|
||||
);
|
||||
}
|
||||
reportStale(stale, { file: 'theme-baseline.json', command: 'theme:lint', root: join(root, 'src'), error });
|
||||
reportStale(staleMarkers, {
|
||||
file: 'theme-disable-baseline.json',
|
||||
command: 'theme:lint',
|
||||
root: join(root, 'src'),
|
||||
error,
|
||||
});
|
||||
log(
|
||||
`theme: ${sum(counts)} styling bypass(es) in ${Object.keys(counts).length} file(s), baseline allows ${sum(baseline)}; ` +
|
||||
`${sum(markers)} line(s) marked ${DISABLE}, baseline allows ${sum(allowedMarkers)}`
|
||||
);
|
||||
return grown.length || marked.length || stale.length || staleMarkers.length ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
[
|
||||
"src/components/Admin/addons/useAddonManager.ts",
|
||||
"src/components/Admin/addons/useLlmParsingConfig.ts",
|
||||
"src/components/Admin/plugins/usePluginDetail.ts",
|
||||
"src/components/Admin/plugins/usePluginsAdmin.ts",
|
||||
"src/components/Admin/storage/useStorageAdmin.ts",
|
||||
"src/components/Admin/useAdminNotificationMatrix.ts",
|
||||
"src/components/Admin/useAdminNotificationSettings.ts",
|
||||
"src/components/Admin/useAdminSettingsActions.ts",
|
||||
"src/components/Admin/useAdminUserActions.ts",
|
||||
"src/components/Admin/useAuditLog.ts",
|
||||
"src/components/Admin/useBackupAdmin.ts",
|
||||
"src/components/Admin/useCategoryAdmin.ts",
|
||||
"src/components/Admin/useDefaultUserSettings.ts",
|
||||
"src/components/Admin/useDevNotifications.ts",
|
||||
"src/components/Admin/useGithubReleases.ts",
|
||||
"src/components/Admin/useGoogleQuota.ts",
|
||||
"src/components/Admin/useInstanceSettings.ts",
|
||||
"src/components/Admin/useMcpTokensAdmin.ts",
|
||||
"src/components/Admin/useNotificationChannels.ts",
|
||||
"src/components/Admin/usePackingTemplateAdmin.ts",
|
||||
"src/components/Admin/usePermissionsAdmin.ts",
|
||||
"src/components/BackgroundTasks/BackgroundTasksWidget.tsx",
|
||||
"src/components/Budget/ReceiptPreviewModal.tsx",
|
||||
"src/components/Budget/receiptUploads.ts",
|
||||
"src/components/Collab/CollabChatLinkPreview.tsx",
|
||||
"src/components/Collab/CollabLinks.tsx",
|
||||
"src/components/Collab/CollabNotes.tsx",
|
||||
"src/components/Collab/CollabNotesAuthedImg.tsx",
|
||||
"src/components/Collab/CollabNotesFilePreviewPortal.tsx",
|
||||
"src/components/Collab/CollabNotesWebsiteThumbnail.tsx",
|
||||
"src/components/Collab/useCollabChatData.ts",
|
||||
"src/components/Collab/useCollabNotesData.ts",
|
||||
"src/components/Collab/useCollabPolls.ts",
|
||||
"src/components/Collections/CollectionPicker.tsx",
|
||||
"src/components/Collections/ImportFromTripModal.tsx",
|
||||
"src/components/Collections/useAddPlaceToCollection.ts",
|
||||
"src/components/Collections/useCollectionPlaceForm.ts",
|
||||
"src/components/Collections/useCollectionSharing.ts",
|
||||
"src/components/Collections/useListEditor.ts",
|
||||
"src/components/Collections/useSaveToCollection.ts",
|
||||
"src/components/Collections/useSaveTripPlacesToList.ts",
|
||||
"src/components/Collections/useTripCopyPicker.ts",
|
||||
"src/components/Dashboard/useCollectionLists.ts",
|
||||
"src/components/Dawarich/DawarichAtlasDialog.tsx",
|
||||
"src/components/Files/FileManagerAuthedImg.tsx",
|
||||
"src/components/Files/FileManagerImageLightbox.tsx",
|
||||
"src/components/Files/docsync/useConflicts.ts",
|
||||
"src/components/Files/docsync/useDocSync.ts",
|
||||
"src/components/Files/useFileManager.ts",
|
||||
"src/components/Files/useMediaLightbox.ts",
|
||||
"src/components/Journey/ContributorInviteDialog.tsx",
|
||||
"src/components/Journey/JourneyDetailPageEntryCard.tsx",
|
||||
"src/components/Journey/JourneyDetailPageEntryEditor.tsx",
|
||||
"src/components/Journey/JourneyDetailPageProviderPicker.tsx",
|
||||
"src/components/Journey/useConnectedPhotoProviders.ts",
|
||||
"src/components/Journey/useEntryPhotoOrder.ts",
|
||||
"src/components/Journey/useJourneyEntryForm.ts",
|
||||
"src/components/Journey/useJourneySettings.ts",
|
||||
"src/components/Journey/useJourneyShareLink.ts",
|
||||
"src/components/Journey/useJourneyTripSuggestion.ts",
|
||||
"src/components/Map/MapPluginLayers.tsx",
|
||||
"src/components/Map/MapPluginMarkers.tsx",
|
||||
"src/components/Map/MapView.tsx",
|
||||
"src/components/Map/MapViewGL.tsx",
|
||||
"src/components/Map/RouteCalculator.ts",
|
||||
"src/components/Map/routeUsageCounter.ts",
|
||||
"src/components/Map/usePoiExplore.ts",
|
||||
"src/components/OAuth/useScopeSelection.ts",
|
||||
"src/components/PDF/TripPDF.tsx",
|
||||
"src/components/Packing/ApplyTemplateButton.tsx",
|
||||
"src/components/Packing/usePackingBags.ts",
|
||||
"src/components/Packing/usePackingCategoryAssignees.ts",
|
||||
"src/components/Packing/usePackingExport.ts",
|
||||
"src/components/Packing/usePackingImport.ts",
|
||||
"src/components/Packing/usePackingListPanel.ts",
|
||||
"src/components/Packing/usePackingTemplates.ts",
|
||||
"src/components/Planner/AddressInput.tsx",
|
||||
"src/components/Planner/AirTrailImportModal.tsx",
|
||||
"src/components/Planner/AirportSelect.tsx",
|
||||
"src/components/Planner/BookingImportModal.tsx",
|
||||
"src/components/Planner/LocationSelect.tsx",
|
||||
"src/components/Planner/PlaceDetailsColumn.tsx",
|
||||
"src/components/Planner/PlaceInspector.tsx",
|
||||
"src/components/Planner/TransitSearchPanel.tsx",
|
||||
"src/components/Planner/TripWarningsBanner.tsx",
|
||||
"src/components/Planner/useDayDetail.ts",
|
||||
"src/components/Planner/useListImport.ts",
|
||||
"src/components/Planner/usePlaceSearch.ts",
|
||||
"src/components/Planner/usePlacesFileImport.ts",
|
||||
"src/components/Planner/usePlacesPool.ts",
|
||||
"src/components/Plugins/PluginContributions.tsx",
|
||||
"src/components/Plugins/PluginDaySchedule.tsx",
|
||||
"src/components/Plugins/PluginFrame.tsx",
|
||||
"src/components/Plugins/TripCardBadges.tsx",
|
||||
"src/components/Plugins/usePluginUserSettings.ts",
|
||||
"src/components/Roadtrip/useDayBoundaries.ts",
|
||||
"src/components/Roadtrip/useRefuelSearch.ts",
|
||||
"src/components/Roadtrip/useRoadtripVias.ts",
|
||||
"src/components/Settings/ApiKeysSection.tsx",
|
||||
"src/components/Settings/useAccountSettings.ts",
|
||||
"src/components/Settings/useAirTrailSettings.ts",
|
||||
"src/components/Settings/useMcpIntegration.ts",
|
||||
"src/components/Settings/useNotificationSettings.ts",
|
||||
"src/components/Settings/useOfflineSettings.ts",
|
||||
"src/components/Settings/usePasskeys.ts",
|
||||
"src/components/Settings/usePhotoProviderConnections.ts",
|
||||
"src/components/Settings/usePluginActivity.ts",
|
||||
"src/components/Studio/useBookPresence.ts",
|
||||
"src/components/Studio/useBookStore.ts",
|
||||
"src/components/Todo/useTodoList.ts",
|
||||
"src/components/Trips/TripFormModal.tsx",
|
||||
"src/components/Trips/useTripCoverPicker.ts",
|
||||
"src/components/Trips/useTripShare.ts",
|
||||
"src/components/Vacay/holidayRegions.ts",
|
||||
"src/components/Vacay/useVacayCalendarLogic.ts",
|
||||
"src/components/Vacay/useVacaySettings.ts",
|
||||
"src/components/Vacay/useVacayUserPicker.ts",
|
||||
"src/hooks/useAirtrailConnection.ts",
|
||||
"src/hooks/useDawarichConnection.ts",
|
||||
"src/hooks/useDawarichSuggestions.ts",
|
||||
"src/hooks/useInAppNotificationListener.ts",
|
||||
"src/hooks/usePlaceSuggestions.ts",
|
||||
"src/hooks/useRoadtripPreferencesSync.ts",
|
||||
"src/hooks/useTripWebSocket.ts",
|
||||
"src/hooks/useWebPush.ts",
|
||||
"src/mobile/screens/journey/MJourneyDetail.tsx",
|
||||
"src/mobile/screens/trip/plan/useMPlanTimeline.ts",
|
||||
"src/mobile/screens/trip/tabs/MCollabNotes.tsx",
|
||||
"src/pages/JourneyDetailPage.tsx",
|
||||
"src/pages/OAuthAuthorizePage.tsx",
|
||||
"src/pages/admin/AdminSettingsTab.tsx",
|
||||
"src/pages/admin/useAdmin.ts",
|
||||
"src/pages/admin/useNotificationDefaults.ts",
|
||||
"src/pages/atlas/useAtlas.ts",
|
||||
"src/pages/atlas/useAtlasCountryActions.ts",
|
||||
"src/pages/collections/useCollections.ts",
|
||||
"src/pages/dashboard/useDashboard.ts",
|
||||
"src/pages/dashboard/useTripSearch.ts",
|
||||
"src/pages/forgotPassword/useForgotPassword.ts",
|
||||
"src/pages/help/useHelp.ts",
|
||||
"src/pages/join/useJoinTrip.ts",
|
||||
"src/pages/journey/useJourney.ts",
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts",
|
||||
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
|
||||
"src/pages/journeyPublic/useJourneyPublic.ts",
|
||||
"src/pages/journeyStudio/useJourneyStudio.ts",
|
||||
"src/pages/login/useLogin.ts",
|
||||
"src/pages/oauthAuthorize/useOAuthAuthorize.ts",
|
||||
"src/pages/resetPassword/useResetPassword.ts",
|
||||
"src/pages/settings/useSettings.ts",
|
||||
"src/pages/sharedTrip/useSharedTrip.ts",
|
||||
"src/pages/tripPlanner/useBookingEdits.ts",
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.ts",
|
||||
"src/pages/tripPlanner/usePlannerDialogs.ts",
|
||||
"src/pages/tripPlanner/useTripPlanner.ts",
|
||||
"src/pages/vacay/useVacay.ts"
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:offline: views go through the offline core, not around it.
|
||||
*
|
||||
* The data path is component, feature hook, store, repo, then api or Dexie,
|
||||
* and writes go through the mutation queue. A view that imports src/api/
|
||||
* skips the cache, the optimistic write and the idempotent replay, so the
|
||||
* feature breaks offline. Such files kept growing, by about fifteen a month.
|
||||
* The view files (components/, mobile/, pages/, hooks/) that already import
|
||||
* src/api/ for more than types are listed in scripts/offline-baseline.json;
|
||||
* no other view file may, and the list only shrinks.
|
||||
*
|
||||
* npm run lint:offline check against the baseline (CI)
|
||||
* npm run lint:offline -- --list print every view file that imports src/api/
|
||||
* npm run lint:offline -- --update take the files that stopped off the list;
|
||||
* it never adds one
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/offline.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:offline', (args) =>
|
||||
check({ root, update: args.includes('--update'), list: args.includes('--list') })
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:pairs: a desktop view and its phone twin run on the same logic.
|
||||
*
|
||||
* Most features have a desktop view under components/ or pages/ and a phone
|
||||
* view under mobile/, and each used to carry its own copy of the feature's
|
||||
* state, loading and handlers, so a fix on one side drifted away from the
|
||||
* other. The logic now lives in one shared hook per feature, and
|
||||
* scripts/feature-pairs.json names, for every feature, the hooks and the
|
||||
* desktop and phone files that run on them. The check fails when a listed
|
||||
* view stops importing one of its pair's hooks, when a listed file is gone,
|
||||
* when a hook sits in a view layer, and when a file under src/mobile/screens
|
||||
* is in no pair and not under mobileOnly with the reason it has no twin. A
|
||||
* new phone screen is so either wired to the desktop feature's hook or marked
|
||||
* as phone only on purpose, never a quiet second copy. lint:dup catches the
|
||||
* copies that look alike; this catches the ones written anew.
|
||||
*
|
||||
* npm run lint:pairs check the manifest against the tree (CI)
|
||||
* npm run lint:pairs -- --list print every pair with its hooks
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { check } from './lib/pairs.mjs';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:pairs', (args) => check({ root, list: args.includes('--list') }));
|
||||
@@ -1,34 +0,0 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const packagePath = require.resolve('maplibre-gl/package.json')
|
||||
const { version } = JSON.parse(readFileSync(packagePath, 'utf8'))
|
||||
|
||||
if (version !== '5.24.0') throw new Error('Recheck the MapLibre sanitizer backport before changing its version')
|
||||
|
||||
// Backport maplibre-gl-js#8189 without removing WebGL1 support in version 6.
|
||||
const loops = [
|
||||
['of elem.attributes)', 'of Array.from(elem.attributes))'],
|
||||
['of e.attributes)', 'of Array.from(e.attributes))'],
|
||||
]
|
||||
|
||||
for (const filename of [
|
||||
'src/util/dom.ts',
|
||||
'dist/maplibre-gl.js',
|
||||
'dist/maplibre-gl-dev.js',
|
||||
'dist/maplibre-gl-csp.js',
|
||||
'dist/maplibre-gl-csp-dev.js',
|
||||
]) {
|
||||
const target = join(dirname(packagePath), filename)
|
||||
const code = readFileSync(target, 'utf8')
|
||||
const loop = loops.find(([before, after]) => code.includes(before) || code.includes(after))
|
||||
if (!loop) throw new Error(`MapLibre sanitizer loop not found in ${filename}`)
|
||||
const [before, after] = loop
|
||||
if (code.split(before).length === 1 && code.split(after).length === 2) continue
|
||||
if (code.split(before).length !== 2 || code.includes(after)) {
|
||||
throw new Error(`Unexpected MapLibre sanitizer in ${filename}`)
|
||||
}
|
||||
writeFileSync(target, code.replace(before, after))
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"components/Admin/AdminPluginsPanel.tsx": 2,
|
||||
"components/Budget/BudgetPanelMemberChips.tsx": 6,
|
||||
"components/Budget/CostsPanel.tsx": 3,
|
||||
"components/Budget/ReceiptPreviewModal.tsx": 2,
|
||||
"components/Collab/CollabChatEmojiPicker.tsx": 3,
|
||||
"components/Collab/CollabChatReactionBadge.tsx": 3,
|
||||
"components/Collab/CollabChatReactionMenu.tsx": 1,
|
||||
"components/Collections/CollectionPlaceDetail.tsx": 2,
|
||||
"components/Files/FileManagerAvatarChip.tsx": 3,
|
||||
"components/Journey/JourneyDayJump.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageDatePicker.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageEntryEditor.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageGalleryView.tsx": 1,
|
||||
"components/Journey/JourneyDetailPagePhotoGrid.tsx": 1,
|
||||
"components/Journey/JourneyDetailPageProviderPicker.tsx": 1,
|
||||
"components/Journey/JourneyEntryCover.tsx": 1,
|
||||
"components/Journey/JourneyMap.tsx": 1,
|
||||
"components/Journey/JourneyMapGL.tsx": 2,
|
||||
"components/Journey/MobileEntryView.tsx": 1,
|
||||
"components/Journey/journeyPhotoLayer.ts": 1,
|
||||
"components/Layout/Navbar.tsx": 1,
|
||||
"components/Layout/OfflineBanner.tsx": 1,
|
||||
"components/Map/DawarichTrailPill.tsx": 1,
|
||||
"components/Map/LocationButton.tsx": 1,
|
||||
"components/Map/MapTogglePill.tsx": 1,
|
||||
"components/Map/MapView.tsx": 6,
|
||||
"components/Map/MapViewGL.tsx": 8,
|
||||
"components/Map/NightPauseTooltip.tsx": 1,
|
||||
"components/Map/PlaceHoverCard.tsx": 1,
|
||||
"components/Map/PoiCategoryPill.tsx": 1,
|
||||
"components/Map/hazardPopup.css": 2,
|
||||
"components/Map/hazardPopup.ts": 1,
|
||||
"components/Map/locationMarkerMapbox.ts": 2,
|
||||
"components/Map/nightPauseMarker.ts": 4,
|
||||
"components/Map/ratingBadge.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 8,
|
||||
"components/PDF/tripMapImage.ts": 1,
|
||||
"components/Packing/PackingListPanelBagCard.tsx": 1,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 3,
|
||||
"components/Packing/PackingListPanelItemRow.tsx": 2,
|
||||
"components/Packing/PackingShareControl.tsx": 3,
|
||||
"components/Planner/DayDetailPanel.tsx": 1,
|
||||
"components/Planner/PlaceInspector.tsx": 1,
|
||||
"components/Planner/TransitSearchPanel.tsx": 3,
|
||||
"components/Planner/bookings/BookingsTimeline.tsx": 24,
|
||||
"components/Roadtrip/AnchoredPopover.tsx": 2,
|
||||
"components/Settings/IntegrationsTab.tsx": 2,
|
||||
"components/Settings/PluginSettingsTab.tsx": 2,
|
||||
"components/Settings/ToggleSwitch.tsx": 1,
|
||||
"components/Studio/BookSheetsView.tsx": 3,
|
||||
"components/Studio/PageNumbers.tsx": 1,
|
||||
"components/Studio/PeerCursors.tsx": 1,
|
||||
"components/Studio/PhotoView.tsx": 4,
|
||||
"components/Studio/SpreadView.tsx": 4,
|
||||
"components/Studio/StudioCanvas.tsx": 12,
|
||||
"components/Studio/StudioElementsPanel.tsx": 1,
|
||||
"components/Studio/StudioExport.tsx": 1,
|
||||
"components/Studio/StudioSavedLayouts.tsx": 1,
|
||||
"components/Studio/TravelElements.tsx": 4,
|
||||
"components/Studio/TravelPreview.tsx": 1,
|
||||
"components/Vacay/VacayCalendar.tsx": 3,
|
||||
"components/Vacay/VacayMonthCard.tsx": 7,
|
||||
"components/Vacay/VacaySettings.tsx": 1,
|
||||
"components/shared/ContextMenu.tsx": 3,
|
||||
"components/shared/CustomDateTimePicker.tsx": 2,
|
||||
"components/shared/CustomSelect.tsx": 4,
|
||||
"components/shared/CustomTimePicker.tsx": 3,
|
||||
"components/shared/DetailShell.tsx": 1,
|
||||
"components/shared/ElevationProfile.tsx": 2,
|
||||
"components/shared/NavigationMenu.tsx": 2,
|
||||
"components/shared/PublicLanguagePicker.tsx": 1,
|
||||
"components/shared/SlidingTabs.tsx": 3,
|
||||
"components/shared/StarRating.tsx": 3,
|
||||
"components/shared/Toast.tsx": 1,
|
||||
"components/shared/Tooltip.tsx": 2,
|
||||
"components/shared/dialogParts.tsx": 1,
|
||||
"help/contexts/tripMap.ts": 1,
|
||||
"hooks/useAnchoredPosition.ts": 3,
|
||||
"hooks/useElementRect.ts": 3,
|
||||
"mobile/components/MSegmented.tsx": 3,
|
||||
"mobile/components/MSheet.tsx": 1,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 1,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 3,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 1,
|
||||
"mobile/screens/trip/MTripShell.tsx": 3,
|
||||
"mobile/screens/trip/map/MMapArea.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MCollabPolls.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
|
||||
"mobile/screens/vacay/MVacay.tsx": 1,
|
||||
"mobile/screens/vacay/MVacayMonth.tsx": 1,
|
||||
"pages/AtlasPage.tsx": 2,
|
||||
"pages/JourneyDetailPage.tsx": 1,
|
||||
"pages/JourneyPublicPage.tsx": 3,
|
||||
"pages/LoginPage.tsx": 23,
|
||||
"pages/TripPlannerPage.tsx": 11,
|
||||
"pages/VacayPage.tsx": 1,
|
||||
"pages/admin/AdminNotificationsTab.tsx": 1,
|
||||
"pages/admin/AdminSettingsTab.tsx": 1,
|
||||
"pages/atlas/AtlasLayerToggle.tsx": 1,
|
||||
"pages/sharedTrip/SharedMap.tsx": 4,
|
||||
"styles/collections.css": 1,
|
||||
"styles/studio.css": 7,
|
||||
"utils/formatters.ts": 1,
|
||||
"utils/mapViewport.ts": 4,
|
||||
"utils/touchDragBridge.ts": 1
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"components/Collections/CollectionMap.tsx": 1,
|
||||
"components/Studio/LineHandles.tsx": 1,
|
||||
"components/Studio/StudioSelectionChrome.tsx": 2,
|
||||
"components/Studio/inspector/FocalPad.tsx": 1,
|
||||
"mobile/components/trek3d/MascotClip.tsx": 1,
|
||||
"pages/tripPlanner/PlanMapStage.tsx": 4
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:rtl: keeps the layout following the reading direction.
|
||||
*
|
||||
* Arabic runs the app with dir="rtl". A physical class or style (ml-2,
|
||||
* text-left, paddingLeft, left: 0) stays on the same side in either direction,
|
||||
* so a gap, an indent or an alignment that follows the text in English lands
|
||||
* on the wrong side in Arabic. The logical forms (ms-2, text-start,
|
||||
* paddingInlineStart, insetInlineStart) follow the direction, and in a
|
||||
* left-to-right language they are exactly the physical ones.
|
||||
*
|
||||
* Some things are physical on purpose: a map, a chart axis, a drag handle, a
|
||||
* popover placed at measured coordinates. Those stay. Every file's physical
|
||||
* uses are counted against scripts/rtl-baseline.json, and the check fails when
|
||||
* a file holds more than its entry (a file without an entry holds none), so
|
||||
* new code reaches for the logical forms. A line that is physical on purpose
|
||||
* carries `rtl-lint-disable` in a comment (in a string it is no marker). The
|
||||
* marked lines are counted too, against scripts/rtl-disable-baseline.json, so
|
||||
* the marker cannot quietly take the place of the logical forms: a new one
|
||||
* raises its file's entry by hand, where review sees it. An entry of either
|
||||
* baseline above what its file holds now, or for a file that is gone, fails
|
||||
* as well until --update lowers it.
|
||||
*
|
||||
* npm run lint:rtl check against the baselines (CI)
|
||||
* npm run lint:rtl -- --list print every counted use, file by file
|
||||
* npm run lint:rtl -- --update lower both baselines to what the files hold now;
|
||||
* it never raises an entry
|
||||
*
|
||||
* The matching lives in scripts/lib/rtl.mjs.
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
import { check } from './lib/rtl.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:rtl', (args) => check({ root, update: args.includes('--update'), list: args.includes('--list') }));
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"e2e/help/fixtures.ts": 2291,
|
||||
"src/api/client.ts": 1873,
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1667,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 2736,
|
||||
"src/components/Budget/CostsPanel.tsx": 1798,
|
||||
"src/components/Map/MapView.tsx": 1385,
|
||||
"src/components/Map/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2290,
|
||||
"src/components/Map/RouteCalculator.ts": 1076,
|
||||
"src/components/PDF/TripPDF.tsx": 1082,
|
||||
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
|
||||
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 2936,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
|
||||
"src/components/Planner/PlaceFormModal.tsx": 1157,
|
||||
"src/components/Planner/PlaceInspector.tsx": 1290,
|
||||
"src/components/Studio/TravelElements.tsx": 1559,
|
||||
"src/components/Studio/countryShapes.ts": 2595,
|
||||
"src/index.css": 1636,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1507,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 4030,
|
||||
"src/pages/LoginPage.tsx": 1347,
|
||||
"src/pages/TripPlannerPage.tsx": 1128,
|
||||
"src/pages/atlas/useAtlas.ts": 1211,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3270,
|
||||
"src/styles/studio.css": 1918
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:size: keeps files from growing into the next god file.
|
||||
*
|
||||
* A file past a thousand lines holds several concerns that no longer fit in
|
||||
* one reading, and every change to one of them risks the others. Each source
|
||||
* file and stylesheet under src/ may hold 1000 lines, each test (under tests/,
|
||||
* a Playwright spec or fixture under e2e/, or a co-located *.test.*) 2000. Lines are counted as an editor wraps them
|
||||
* at 120 columns, so joining lines does not make a file smaller. The files
|
||||
* that were already larger are listed in scripts/size-baseline.json with the
|
||||
* size they had, and the check fails when one of them grows past its entry. A
|
||||
* file that needs to grow is split by concern instead (the trip planner hook,
|
||||
* page and road trip sidebar are the precedent). An entry above the file's
|
||||
* size now, or for a file that is gone, fails as well until --update lowers
|
||||
* it: otherwise the file could grow back unseen, and a new file at a deleted
|
||||
* path would inherit its allowance.
|
||||
*
|
||||
* npm run lint:size check against the baseline (CI)
|
||||
* npm run lint:size -- --update lower the baseline to what the files hold now;
|
||||
* it never raises an entry, and drops a file
|
||||
* that is back under its limit
|
||||
*
|
||||
* The measuring lives in scripts/lib/size.mjs.
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
import { check } from './lib/size.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:size', (args) => check({ root, update: args.includes('--update') }));
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"src/pages/JourneyDetailPage.test.tsx": 35
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:skips: no test is focused, and skipped tests may only go away.
|
||||
*
|
||||
* A stray .only passes CI while the rest of its file never runs, so it fails
|
||||
* this check wherever it appears. A skipped or todo test is coverage that was
|
||||
* switched off and then forgotten (JourneyDetailPage.test.tsx has carried 35
|
||||
* skipped blocks since April); the files that hold some are listed in
|
||||
* scripts/skip-baseline.json with their count, and a file may hold no more.
|
||||
* An entry above what its file holds now, or for a file that is gone, fails
|
||||
* as well until --update lowers it.
|
||||
* Playwright's test.fixme counts as a skip. Only a skip that decides at run
|
||||
* time is left out: skipIf and runIf, and in a Playwright spec
|
||||
* test.skip(condition, 'why'), unless the condition is a literal that always
|
||||
* skips (skipIf(true), runIf(false), test.skip(true, 'why')).
|
||||
* Covers the vitest tests under src/ and tests/ and the Playwright specs
|
||||
* under e2e/.
|
||||
*
|
||||
* npm run lint:skips check against the baseline (CI)
|
||||
* npm run lint:skips -- --update lower the baseline to what the files hold now;
|
||||
* it never raises an entry
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
import { check } from './lib/skips.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:skips', (args) => check({ root, update: args.includes('--update') }));
|
||||
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"src/components/Admin/AddonManager.tsx": 2,
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 3,
|
||||
"src/components/Admin/storage/useStorageAdmin.test.tsx": 1,
|
||||
"src/components/Admin/useBackupAdmin.ts": 1,
|
||||
"src/components/Budget/BudgetPanelMemberChips.tsx": 1,
|
||||
"src/components/Budget/CostsPanel.test.tsx": 1,
|
||||
"src/components/Collab/CollabChat.helpers.ts": 1,
|
||||
"src/components/Collab/CollabChat.tsx": 3,
|
||||
"src/components/Collab/CollabChatEmojiPicker.tsx": 5,
|
||||
"src/components/Collab/CollabChatMessages.tsx": 4,
|
||||
"src/components/Collab/CollabChatReactionBadge.tsx": 1,
|
||||
"src/components/Collab/CollabChatReactionMenu.tsx": 2,
|
||||
"src/components/Collab/CollabChatTwemojiImg.tsx": 1,
|
||||
"src/components/Collab/CollabNotes.helpers.ts": 3,
|
||||
"src/components/Collab/CollabNotes.test.tsx": 2,
|
||||
"src/components/Collab/CollabNotes.tsx": 22,
|
||||
"src/components/Collab/CollabNotesCard.tsx": 1,
|
||||
"src/components/Collab/CollabNotesCategorySettingsModal.tsx": 6,
|
||||
"src/components/Collab/CollabNotesEditableCatName.tsx": 2,
|
||||
"src/components/Collab/CollabNotesFormModal.tsx": 7,
|
||||
"src/components/Collab/CollabPanel.tsx": 6,
|
||||
"src/components/Collab/CollabPolls.test.tsx": 1,
|
||||
"src/components/Collab/CollabPolls.tsx": 4,
|
||||
"src/components/Collab/WhatsNextWidget.test.tsx": 1,
|
||||
"src/components/Collab/WhatsNextWidget.tsx": 5,
|
||||
"src/components/Collab/useCollabChat.ts": 6,
|
||||
"src/components/Files/FileManager.tsx": 2,
|
||||
"src/components/Files/FileManagerAssignModal.tsx": 2,
|
||||
"src/components/Files/FileManagerMarkdownPreviewModal.tsx": 4,
|
||||
"src/components/Files/FileManagerPdfPreviewModal.tsx": 5,
|
||||
"src/components/Files/FileManagerPreviewModals.test.tsx": 3,
|
||||
"src/components/Files/useFileManager.ts": 5,
|
||||
"src/components/Journey/JourneyDayDawarich.test.tsx": 1,
|
||||
"src/components/Journey/JourneyDetailPageSettingsDialog.tsx": 1,
|
||||
"src/components/Journey/JourneyMap.test.tsx": 6,
|
||||
"src/components/Journey/journeyGeo.ts": 4,
|
||||
"src/components/Layout/Navbar.test.tsx": 1,
|
||||
"src/components/Map/MapView.test.tsx": 2,
|
||||
"src/components/Map/MapView.tsx": 8,
|
||||
"src/components/Map/MapViewGL.tsx": 1,
|
||||
"src/components/Map/ReservationOverlay.test.tsx": 1,
|
||||
"src/components/Map/transitGeometry.ts": 1,
|
||||
"src/components/Map/useDawarichTrailGL.test.ts": 4,
|
||||
"src/components/Map/useMarkerThumbs.ts": 1,
|
||||
"src/components/PDF/TripPDF.tsx": 40,
|
||||
"src/components/Packing/PackingListPanelItemRow.test.tsx": 2,
|
||||
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 61,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 3,
|
||||
"src/components/Planner/PlaceFormModal.tsx": 1,
|
||||
"src/components/Planner/PlaceInspector.tsx": 16,
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
|
||||
"src/components/Planner/PlacesSidebar.tsx": 1,
|
||||
"src/components/Planner/PlacesSidebarMobileDayPicker.tsx": 8,
|
||||
"src/components/Planner/ReservationModal.tsx": 4,
|
||||
"src/components/Planner/TransitSearchPanel.tsx": 2,
|
||||
"src/components/Planner/assignmentOptions.ts": 1,
|
||||
"src/components/Planner/bookings/bookingFacts.ts": 1,
|
||||
"src/components/Planner/bookings/bookingsModel.ts": 2,
|
||||
"src/components/Planner/bookings/timelineModel.ts": 4,
|
||||
"src/components/Planner/reservationFormModel.test.ts": 1,
|
||||
"src/components/Planner/transportEndpoints.ts": 2,
|
||||
"src/components/Planner/useDayDetail.ts": 2,
|
||||
"src/components/Planner/usePlacesSidebar.ts": 1,
|
||||
"src/components/Planner/useTripExport.ts": 1,
|
||||
"src/components/Plugins/PluginFrame.tsx": 2,
|
||||
"src/components/Roadtrip/RoadtripAlternativesBar.tsx": 1,
|
||||
"src/components/Roadtrip/RoadtripCorridorPanel.tsx": 4,
|
||||
"src/components/Roadtrip/RoadtripSidebarBadges.tsx": 4,
|
||||
"src/components/Roadtrip/RoadtripSidebarDriveBands.tsx": 2,
|
||||
"src/components/Roadtrip/RoadtripSidebarHeaders.tsx": 1,
|
||||
"src/components/Roadtrip/RoadtripSidebarRefuelBand.tsx": 5,
|
||||
"src/components/Roadtrip/RoadtripTrackModal.tsx": 4,
|
||||
"src/components/Roadtrip/ServiceStopSection.tsx": 2,
|
||||
"src/components/Roadtrip/useRoadtripRoutes.test.ts": 2,
|
||||
"src/components/Roadtrip/useRoadtripRoutes.ts": 4,
|
||||
"src/components/Settings/DisplaySettingsTab.tsx": 2,
|
||||
"src/components/Settings/MapboxPreview.tsx": 1,
|
||||
"src/components/Settings/NotificationsTab.test.tsx": 1,
|
||||
"src/components/Settings/PasskeysSection.tsx": 1,
|
||||
"src/components/Settings/PhotoProvidersSection.test.tsx": 2,
|
||||
"src/components/Todo/todoListModel.ts": 1,
|
||||
"src/components/Tours/planner/TourPlannerPanels.tsx": 2,
|
||||
"src/components/Tours/planner/useTourPlanner.ts": 2,
|
||||
"src/components/Trips/TripFormModal.tsx": 3,
|
||||
"src/components/Vacay/VacayCalendar.tsx": 1,
|
||||
"src/components/Vacay/VacayPersons.tsx": 4,
|
||||
"src/components/Vacay/VacaySettings.tsx": 2,
|
||||
"src/components/Vacay/VacaySharedCalendars.tsx": 1,
|
||||
"src/components/Vacay/holidayRegions.test.ts": 2,
|
||||
"src/components/Vacay/holidayRegions.ts": 4,
|
||||
"src/components/Weather/WeatherWidget.tsx": 14,
|
||||
"src/components/shared/CustomSelect.test.tsx": 1,
|
||||
"src/components/shared/PlaceAvatar.test.tsx": 2,
|
||||
"src/components/shared/PlaceAvatar.tsx": 1,
|
||||
"src/hooks/useDawarichSuggestions.test.ts": 1,
|
||||
"src/mobile/screens/admin/MAdminAddonManager.tsx": 2,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 6,
|
||||
"src/mobile/screens/journey/MJourneySettingsSheet.tsx": 1,
|
||||
"src/mobile/screens/settings/MSettingsAccount.tsx": 1,
|
||||
"src/mobile/screens/trip/MTripShell.tsx": 1,
|
||||
"src/mobile/screens/trip/map/MMapArea.tsx": 1,
|
||||
"src/mobile/screens/trip/places/MPlacesBrowser.tsx": 2,
|
||||
"src/mobile/screens/trip/plan/planTimelineModel.ts": 1,
|
||||
"src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 2,
|
||||
"src/mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 1,
|
||||
"src/mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 1,
|
||||
"src/mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 2,
|
||||
"src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
|
||||
"src/mobile/screens/trip/tabs/transportsModel.ts": 1,
|
||||
"src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1,
|
||||
"src/pages/AtlasPage.tsx": 6,
|
||||
"src/pages/FilesPage.tsx": 1,
|
||||
"src/pages/JourneyDetailPage.tsx": 1,
|
||||
"src/pages/JourneyPublicPage.test.tsx": 1,
|
||||
"src/pages/LoginPage.tsx": 1,
|
||||
"src/pages/VacayPage.tsx": 1,
|
||||
"src/pages/admin/useAdmin.ts": 4,
|
||||
"src/pages/atlas/atlasModel.ts": 2,
|
||||
"src/pages/atlas/useAtlas.ts": 9,
|
||||
"src/pages/collections/collectionsModel.ts": 1,
|
||||
"src/pages/journeyDetail/useJourneyDetail.ts": 3,
|
||||
"src/pages/sharedTrip/SharedPlanView.tsx": 1,
|
||||
"src/pages/tripPlanner/PlanMapStage.tsx": 1,
|
||||
"src/pages/tripPlanner/b4a-wiring.test.ts": 1,
|
||||
"src/pages/tripPlanner/useBookingEdits.ts": 1,
|
||||
"src/pages/tripPlanner/useDayPlanEdits.ts": 2,
|
||||
"src/pages/tripPlanner/useMapPlaces.ts": 3,
|
||||
"src/pages/tripPlanner/usePlaceEdits.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.test.ts": 2,
|
||||
"src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
|
||||
"src/pages/tripPlanner/useTripPlanner.ts": 2,
|
||||
"src/repo/tripRepo.ts": 2,
|
||||
"src/store/slices/budgetSlice.test.ts": 1,
|
||||
"src/utils/formatters.test.ts": 1,
|
||||
"src/utils/touchDragPolyfill.ts": 1,
|
||||
"tests/integration/api/client.test.ts": 1,
|
||||
"tests/integration/hooks/useRouteCalculation.test.ts": 1,
|
||||
"tests/unit/i18n/i18nKeysScript.test.ts": 3,
|
||||
"tests/unit/mobile/admin/MAdminGitHubPanel.test.tsx": 1,
|
||||
"tests/unit/mobile/admin/MAdminNotifyMatrix.test.tsx": 1,
|
||||
"tests/unit/mobile/admin/MAdminStoragePanel.test.tsx": 1,
|
||||
"tests/unit/mobile/dashboard/MDashWidgets.test.tsx": 1,
|
||||
"tests/unit/mobile/settings/MSettingsNotifications.test.tsx": 3,
|
||||
"tests/unit/mobile/settings/MSettingsPlugins.test.tsx": 2,
|
||||
"tests/unit/mobile/trip/MCostsTab.test.tsx": 1,
|
||||
"tests/unit/mobile/trip/filesModel.test.ts": 3,
|
||||
"tests/unit/remoteEventHandler/budget.test.ts": 1,
|
||||
"tests/unit/remoteEventHandler/trip.test.ts": 1,
|
||||
"tests/unit/scripts/eslint-ratchet.test.ts": 1,
|
||||
"tests/unit/slices/budgetSlice.test.ts": 1,
|
||||
"tests/unit/studio/autoLayout.travel.test.ts": 3,
|
||||
"tests/unit/studio/mapFraming.test.tsx": 1
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:strict: the errors strict null checks would raise may only go down.
|
||||
*
|
||||
* The client compiles with strict: false, so a `.nullable()` field from
|
||||
* @trek/shared arrives as if it were always there and an untyped parameter is
|
||||
* an `any` nobody sees. Turning strict on at once would mean fixing hundreds
|
||||
* of files in one go. Instead tsconfig.strict.json is the same program with
|
||||
* strictNullChecks and noImplicitAny on, and this counts its errors per file
|
||||
* against scripts/strict-baseline.json: a file may not gain one, and a file
|
||||
* without an entry, which every new file is, has to be clean. An entry above
|
||||
* its count, or for a file that is gone, fails until --update lowers it, so a
|
||||
* file brought down stays down. When a whole directory reaches zero, it can
|
||||
* move into the main tsconfig's strict settings for good.
|
||||
*
|
||||
* npm run lint:strict check against the baseline (CI)
|
||||
* npm run lint:strict -- --list print every error, file by file
|
||||
* npm run lint:strict -- --update lower the baseline to today's counts;
|
||||
* it never raises an entry
|
||||
*
|
||||
* The parsing and the comparison live in scripts/lib/strict.mjs.
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
import { check } from './lib/strict.mjs';
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('lint:strict', (args) =>
|
||||
check({ root, update: args.includes('--update'), list: args.includes('--list') })
|
||||
);
|
||||
@@ -0,0 +1,312 @@
|
||||
{
|
||||
"App.tsx": 11,
|
||||
"components/Admin/AdminPluginsPanel.tsx": 2,
|
||||
"components/Admin/DefaultUserSettingsTab.tsx": 1,
|
||||
"components/Atlas/AtlasCountryPlaces.tsx": 6,
|
||||
"components/BackgroundTasks/BackgroundTasksWidget.tsx": 4,
|
||||
"components/Budget/BudgetPanel.helpers.ts": 2,
|
||||
"components/Budget/BudgetPanelMemberChips.tsx": 4,
|
||||
"components/Budget/CostsPanel.tsx": 37,
|
||||
"components/Budget/ReceiptPreviewModal.tsx": 6,
|
||||
"components/Budget/ReceiptScanModal.tsx": 2,
|
||||
"components/Budget/costsCategories.tsx": 14,
|
||||
"components/Collab/CollabChat.tsx": 1,
|
||||
"components/Collab/CollabChatAttachment.tsx": 4,
|
||||
"components/Collab/CollabChatEmojiPicker.tsx": 1,
|
||||
"components/Collab/CollabChatReactionBadge.tsx": 1,
|
||||
"components/Collab/CollabChatReactionMenu.tsx": 1,
|
||||
"components/Collab/CollabLinks.tsx": 1,
|
||||
"components/Collab/CollabNotesFilePreviewPortal.tsx": 2,
|
||||
"components/Collab/CollabPolls.tsx": 3,
|
||||
"components/Collections/CollectionHero.tsx": 1,
|
||||
"components/Collections/MSaveToCollectionSheet.tsx": 12,
|
||||
"components/Collections/StatusBadge.tsx": 4,
|
||||
"components/Dawarich/DawarichAtlasDialog.tsx": 3,
|
||||
"components/Files/FileManagerAvatarChip.tsx": 1,
|
||||
"components/Files/FileManagerImageLightbox.tsx": 8,
|
||||
"components/Journey/ContributorInviteDialog.tsx": 76,
|
||||
"components/Journey/JournalBody.tsx": 1,
|
||||
"components/Journey/JourneyDayDawarich.tsx": 2,
|
||||
"components/Journey/JourneyDayJump.tsx": 6,
|
||||
"components/Journey/JourneyDayScrubber.tsx": 3,
|
||||
"components/Journey/JourneyDetailPageChips.tsx": 2,
|
||||
"components/Journey/JourneyDetailPageDatePicker.tsx": 43,
|
||||
"components/Journey/JourneyDetailPageEntryCard.tsx": 73,
|
||||
"components/Journey/JourneyDetailPageEntryEditor.tsx": 2,
|
||||
"components/Journey/JourneyDetailPageExpandableStory.tsx": 17,
|
||||
"components/Journey/JourneyDetailPageGalleryView.tsx": 15,
|
||||
"components/Journey/JourneyDetailPageMapView.tsx": 50,
|
||||
"components/Journey/JourneyDetailPagePhotoGrid.tsx": 6,
|
||||
"components/Journey/JourneyDetailPageProviderPicker.tsx": 163,
|
||||
"components/Journey/JourneyDetailPageScrollTrigger.tsx": 4,
|
||||
"components/Journey/JourneyDetailPageVerdictSection.tsx": 51,
|
||||
"components/Journey/JourneyEntryCover.tsx": 15,
|
||||
"components/Journey/JourneyMap.tsx": 3,
|
||||
"components/Journey/JourneyMapGL.tsx": 5,
|
||||
"components/Journey/MobileEntryView.tsx": 94,
|
||||
"components/Journey/MobileMapTimeline.tsx": 8,
|
||||
"components/Journey/PhotoLightbox.tsx": 13,
|
||||
"components/Journey/VideoPlayer.tsx": 2,
|
||||
"components/Journey/VideoPlayerLazy.tsx": 1,
|
||||
"components/Journey/journeyMapPopup.ts": 17,
|
||||
"components/Journey/moodConfig.ts": 5,
|
||||
"components/Layout/BottomNav.tsx": 3,
|
||||
"components/Layout/InAppNotificationBell.tsx": 3,
|
||||
"components/Layout/MobileTopBar.tsx": 51,
|
||||
"components/Layout/Navbar.tsx": 21,
|
||||
"components/Layout/NewVersionNotice.tsx": 3,
|
||||
"components/Layout/OfflineBanner.tsx": 2,
|
||||
"components/Layout/PageSidebar.tsx": 3,
|
||||
"components/Map/LocationButton.tsx": 1,
|
||||
"components/Map/MapPluginMarkers.tsx": 2,
|
||||
"components/Map/MapTogglePill.tsx": 1,
|
||||
"components/Map/MapView.tsx": 8,
|
||||
"components/Map/MapViewGL.tsx": 11,
|
||||
"components/Map/NightPauseTooltip.tsx": 1,
|
||||
"components/Map/PlaceHoverCard.tsx": 1,
|
||||
"components/Map/ReservationOverlay.tsx": 5,
|
||||
"components/Map/RoadtripViaMarkers.tsx": 1,
|
||||
"components/Map/locationMarkerMapbox.ts": 2,
|
||||
"components/Map/placePopup.ts": 6,
|
||||
"components/Map/poiCategories.ts": 7,
|
||||
"components/Map/ratingBadge.ts": 2,
|
||||
"components/Map/reservationsMapbox.ts": 1,
|
||||
"components/PDF/TripPDF.tsx": 53,
|
||||
"components/Packing/PackingListPanelBagModal.tsx": 2,
|
||||
"components/Packing/PackingListPanelCategoryGroup.tsx": 5,
|
||||
"components/Packing/PackingListPanelHeader.tsx": 5,
|
||||
"components/Packing/PackingListPanelItemRow.tsx": 2,
|
||||
"components/Packing/PackingShareControl.tsx": 3,
|
||||
"components/Packing/packingPrintDocument.ts": 24,
|
||||
"components/Planner/AirTrailImportModal.tsx": 4,
|
||||
"components/Planner/BookingCostsSection.tsx": 1,
|
||||
"components/Planner/BookingImportModal.tsx": 4,
|
||||
"components/Planner/DayDetailPanel.tsx": 1,
|
||||
"components/Planner/IcsSubscribeModal.tsx": 10,
|
||||
"components/Planner/PlaceInspector.tsx": 1,
|
||||
"components/Planner/PlacesSidebarMobileDayPicker.tsx": 3,
|
||||
"components/Planner/SubscribeLinks.tsx": 5,
|
||||
"components/Planner/SuggestionDropdown.tsx": 1,
|
||||
"components/Planner/TransitJourneyModal.tsx": 4,
|
||||
"components/Planner/TransitSearchPanel.tsx": 2,
|
||||
"components/Planner/TravelerPicker.tsx": 3,
|
||||
"components/Planner/bookings/BookingsTimeline.tsx": 1,
|
||||
"components/Plugins/PluginContributions.tsx": 5,
|
||||
"components/Plugins/PluginWidgets.tsx": 1,
|
||||
"components/Roadtrip/AnchoredPopover.tsx": 1,
|
||||
"components/Roadtrip/ServiceStopSection.tsx": 1,
|
||||
"components/Roadtrip/serviceMarker.ts": 1,
|
||||
"components/Settings/useAppearanceEditor.ts": 5,
|
||||
"components/Studio/BookSheetsView.tsx": 2,
|
||||
"components/Studio/PhotoView.tsx": 2,
|
||||
"components/Studio/SpreadView.tsx": 1,
|
||||
"components/Studio/StudioElementsPanel.tsx": 8,
|
||||
"components/Studio/StudioShell.tsx": 2,
|
||||
"components/Studio/TravelElements.tsx": 5,
|
||||
"components/Studio/printSheets.ts": 5,
|
||||
"components/Studio/sidebar/contentDrops.ts": 2,
|
||||
"components/SystemNotices/SystemNoticeBanner.tsx": 28,
|
||||
"components/SystemNotices/SystemNoticeModal.tsx": 107,
|
||||
"components/Todo/TodoListPanel.tsx": 6,
|
||||
"components/Todo/todoListModel.ts": 3,
|
||||
"components/Trips/TripFormModal.tsx": 9,
|
||||
"components/Vacay/VacayBadge.tsx": 3,
|
||||
"components/Vacay/VacayCalendar.tsx": 20,
|
||||
"components/Vacay/VacayMonthCard.tsx": 5,
|
||||
"components/Vacay/VacayPersons.tsx": 4,
|
||||
"components/Vacay/VacaySettings.tsx": 27,
|
||||
"components/Vacay/VacaySharedCalendars.tsx": 6,
|
||||
"components/Vacay/VacayStats.tsx": 14,
|
||||
"components/Weather/WeatherWidget.tsx": 4,
|
||||
"components/shared/ConfirmDialog.tsx": 8,
|
||||
"components/shared/ContextMenu.tsx": 1,
|
||||
"components/shared/CopyTripDialog.tsx": 12,
|
||||
"components/shared/CustomDateTimePicker.tsx": 1,
|
||||
"components/shared/CustomSelect.tsx": 1,
|
||||
"components/shared/CustomTimePicker.tsx": 1,
|
||||
"components/shared/EmptyState.tsx": 1,
|
||||
"components/shared/ErrorBoundary.tsx": 2,
|
||||
"components/shared/Modal.tsx": 3,
|
||||
"components/shared/NavigationMenu.tsx": 1,
|
||||
"components/shared/NoteColorPicker.tsx": 2,
|
||||
"components/shared/PublicLanguagePicker.tsx": 3,
|
||||
"components/shared/Skeleton.tsx": 2,
|
||||
"components/shared/Spinner.tsx": 2,
|
||||
"components/shared/StarRating.tsx": 1,
|
||||
"components/shared/Toast.tsx": 8,
|
||||
"components/shared/Tooltip.tsx": 1,
|
||||
"components/shared/TrackColorPicker.tsx": 2,
|
||||
"components/shared/TripLoadingSplash.tsx": 10,
|
||||
"mobile/components/MBadge.tsx": 2,
|
||||
"mobile/components/MBottomNav.tsx": 2,
|
||||
"mobile/components/MChip.tsx": 2,
|
||||
"mobile/components/MDayImpactList.tsx": 4,
|
||||
"mobile/components/MListRow.tsx": 1,
|
||||
"mobile/components/MSegmented.tsx": 2,
|
||||
"mobile/components/MSheet.tsx": 1,
|
||||
"mobile/components/MStorageTestResult.tsx": 3,
|
||||
"mobile/components/MToastHost.tsx": 2,
|
||||
"mobile/components/MUserPickerList.tsx": 1,
|
||||
"mobile/screens/admin/MAdmin.tsx": 9,
|
||||
"mobile/screens/admin/MAdminAddonManager.tsx": 9,
|
||||
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
|
||||
"mobile/screens/admin/MAdminBackupPanel.tsx": 8,
|
||||
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
|
||||
"mobile/screens/admin/MAdminDefaultUserSettings.tsx": 5,
|
||||
"mobile/screens/admin/MAdminDevNotificationsPanel.tsx": 6,
|
||||
"mobile/screens/admin/MAdminGitHubPanel.tsx": 30,
|
||||
"mobile/screens/admin/MAdminMcpTokensPanel.tsx": 14,
|
||||
"mobile/screens/admin/MAdminNotifyMatrix.tsx": 5,
|
||||
"mobile/screens/admin/MAdminPackingTemplateManager.tsx": 8,
|
||||
"mobile/screens/admin/MAdminPermissionsPanel.tsx": 5,
|
||||
"mobile/screens/admin/MAdminPluginsPanel.tsx": 129,
|
||||
"mobile/screens/admin/MAdminSettingsSection.tsx": 10,
|
||||
"mobile/screens/admin/MAdminSheets.tsx": 11,
|
||||
"mobile/screens/admin/MAdminStoragePanel.tsx": 42,
|
||||
"mobile/screens/admin/MAdminUi.tsx": 10,
|
||||
"mobile/screens/admin/MAdminUsersSection.tsx": 14,
|
||||
"mobile/screens/admin/MApiProviderBlocks.tsx": 10,
|
||||
"mobile/screens/atlas/MAtlas.tsx": 7,
|
||||
"mobile/screens/atlas/MAtlasBucketSheet.tsx": 16,
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 11,
|
||||
"mobile/screens/atlas/MAtlasSearch.tsx": 5,
|
||||
"mobile/screens/atlas/MAtlasStatsCard.tsx": 3,
|
||||
"mobile/screens/collections/MCollAddSheet.tsx": 7,
|
||||
"mobile/screens/collections/MCollCategoryPicker.tsx": 2,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 5,
|
||||
"mobile/screens/collections/MCollLabelsSheet.tsx": 6,
|
||||
"mobile/screens/collections/MCollLinksEditor.tsx": 2,
|
||||
"mobile/screens/collections/MCollListPickerSheet.tsx": 3,
|
||||
"mobile/screens/collections/MCollPlaceRow.tsx": 3,
|
||||
"mobile/screens/collections/MCollPlaceSheet.tsx": 11,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 14,
|
||||
"mobile/screens/collections/MCollSheetKit.tsx": 6,
|
||||
"mobile/screens/collections/MCollTripPickerSheet.tsx": 4,
|
||||
"mobile/screens/collections/MCollections.tsx": 21,
|
||||
"mobile/screens/dashboard/MDashWidgets.tsx": 22,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 36,
|
||||
"mobile/screens/dashboard/MNewTripSheet.tsx": 20,
|
||||
"mobile/screens/dashboard/MUserMenu.tsx": 7,
|
||||
"mobile/screens/journey/MJourney.tsx": 10,
|
||||
"mobile/screens/journey/MJourneyCreateSheet.tsx": 10,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 6,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 52,
|
||||
"mobile/screens/journey/MJourneySettingsSheet.tsx": 32,
|
||||
"mobile/screens/journey/mobileJourneyMeta.ts": 4,
|
||||
"mobile/screens/notifications/MNotificationRow.tsx": 4,
|
||||
"mobile/screens/notifications/MNotifications.tsx": 3,
|
||||
"mobile/screens/settings/MAirTrailConnectionSection.tsx": 2,
|
||||
"mobile/screens/settings/MConfirmSheet.tsx": 2,
|
||||
"mobile/screens/settings/MDawarichConnectionSection.tsx": 5,
|
||||
"mobile/screens/settings/MMobileDashOrder.tsx": 2,
|
||||
"mobile/screens/settings/MMobileNavCustomizer.tsx": 8,
|
||||
"mobile/screens/settings/MPhotoProvidersSection.tsx": 2,
|
||||
"mobile/screens/settings/MScopeGroupPicker.tsx": 5,
|
||||
"mobile/screens/settings/MSetPickerSheet.tsx": 2,
|
||||
"mobile/screens/settings/MSettings.tsx": 2,
|
||||
"mobile/screens/settings/MSettingsAbout.tsx": 5,
|
||||
"mobile/screens/settings/MSettingsAccount.tsx": 20,
|
||||
"mobile/screens/settings/MSettingsAppearance.tsx": 12,
|
||||
"mobile/screens/settings/MSettingsMap.tsx": 5,
|
||||
"mobile/screens/settings/MSettingsMcp.tsx": 30,
|
||||
"mobile/screens/settings/MSettingsNotifications.tsx": 5,
|
||||
"mobile/screens/settings/MSettingsOffline.tsx": 18,
|
||||
"mobile/screens/settings/MSettingsPlugins.tsx": 14,
|
||||
"mobile/screens/settings/MSettingsUi.tsx": 11,
|
||||
"mobile/screens/settings/MWebPushCard.tsx": 1,
|
||||
"mobile/screens/trip/MTripLoadingSplash.tsx": 2,
|
||||
"mobile/screens/trip/MTripShell.tsx": 9,
|
||||
"mobile/screens/trip/places/MPlacesBrowser.tsx": 10,
|
||||
"mobile/screens/trip/places/MPlacesBulkCategorySheet.tsx": 4,
|
||||
"mobile/screens/trip/places/MPlacesFilterControls.tsx": 1,
|
||||
"mobile/screens/trip/places/MPlacesFilterSheet.tsx": 3,
|
||||
"mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx": 7,
|
||||
"mobile/screens/trip/places/MPlacesToursModeSwitch.tsx": 1,
|
||||
"mobile/screens/trip/plan/MPlanTimeline.tsx": 14,
|
||||
"mobile/screens/trip/plan/MPlanTimelineRows.tsx": 26,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 31,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripTab.tsx": 16,
|
||||
"mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 8,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorBar.tsx": 2,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 7,
|
||||
"mobile/screens/trip/roadtrip/MRtDraftSheet.tsx": 5,
|
||||
"mobile/screens/trip/roadtrip/MRtInfoSheet.tsx": 9,
|
||||
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 3,
|
||||
"mobile/screens/trip/roadtrip/MRtStaySheet.tsx": 17,
|
||||
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 12,
|
||||
"mobile/screens/trip/sheets/ImpFileStep.tsx": 12,
|
||||
"mobile/screens/trip/sheets/ImpListStep.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MAccommodationSheet.tsx": 10,
|
||||
"mobile/screens/trip/sheets/MBookingFields.tsx": 6,
|
||||
"mobile/screens/trip/sheets/MBrowseActionsSheet.tsx": 5,
|
||||
"mobile/screens/trip/sheets/MCostSheet.tsx": 33,
|
||||
"mobile/screens/trip/sheets/MDaySheet.tsx": 22,
|
||||
"mobile/screens/trip/sheets/MDaysSheet.tsx": 4,
|
||||
"mobile/screens/trip/sheets/MExportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MImportSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MMehrSheet.tsx": 3,
|
||||
"mobile/screens/trip/sheets/MNoteSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MPlaceSheet.tsx": 23,
|
||||
"mobile/screens/trip/sheets/MReservationSheet.tsx": 2,
|
||||
"mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9,
|
||||
"mobile/screens/trip/sheets/MTransportSheet.tsx": 12,
|
||||
"mobile/screens/trip/sheets/MTripSheetUi.tsx": 5,
|
||||
"mobile/screens/trip/sheets/MTripSheets.tsx": 2,
|
||||
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 2,
|
||||
"mobile/screens/trip/sheets/PlFileAttach.tsx": 7,
|
||||
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6,
|
||||
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 7,
|
||||
"mobile/screens/trip/sheets/PlTimeFields.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MBagsSheet.tsx": 13,
|
||||
"mobile/screens/trip/tabs/MBookingsTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MCollabChat.tsx": 22,
|
||||
"mobile/screens/trip/tabs/MCollabNotes.tsx": 19,
|
||||
"mobile/screens/trip/tabs/MCollabPolls.tsx": 18,
|
||||
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MCostsTab.tsx": 71,
|
||||
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
|
||||
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
|
||||
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
|
||||
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
|
||||
"mobile/screens/trip/tabs/MFilesTab.tsx": 12,
|
||||
"mobile/screens/trip/tabs/MPackItemSheet.tsx": 7,
|
||||
"mobile/screens/trip/tabs/MPackingImportSheet.tsx": 3,
|
||||
"mobile/screens/trip/tabs/MPackingListTab.tsx": 32,
|
||||
"mobile/screens/trip/tabs/MReservationCardParts.tsx": 6,
|
||||
"mobile/screens/trip/tabs/MTaskSheet.tsx": 6,
|
||||
"mobile/screens/trip/tabs/MTodoListTab.tsx": 15,
|
||||
"mobile/screens/trip/tabs/MTransportsTab.tsx": 2,
|
||||
"mobile/screens/trip/tabs/filesModel.ts": 5,
|
||||
"mobile/screens/trip/tabs/tabChrome.tsx": 12,
|
||||
"mobile/screens/vacay/MVacay.tsx": 23,
|
||||
"mobile/screens/vacay/MVacayInviteSheet.tsx": 9,
|
||||
"mobile/screens/vacay/MVacayMonth.tsx": 3,
|
||||
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 36,
|
||||
"mobile/screens/vacay/MVacayShareSheet.tsx": 11,
|
||||
"mobile/screens/vacay/vacayDayModel.ts": 1,
|
||||
"pages/AtlasPage.tsx": 32,
|
||||
"pages/DashboardPage.tsx": 1,
|
||||
"pages/FilesPage.tsx": 11,
|
||||
"pages/ForgotPasswordPage.tsx": 18,
|
||||
"pages/HelpPage.tsx": 21,
|
||||
"pages/JoinTripPage.tsx": 4,
|
||||
"pages/JourneyDetailPage.tsx": 53,
|
||||
"pages/JourneyPage.tsx": 64,
|
||||
"pages/JourneyPublicPage.tsx": 113,
|
||||
"pages/LoginPage.tsx": 58,
|
||||
"pages/OAuthAuthorizePage.tsx": 33,
|
||||
"pages/PluginPage.tsx": 1,
|
||||
"pages/ResetPasswordPage.tsx": 23,
|
||||
"pages/TripPlannerPage.tsx": 7,
|
||||
"pages/VacayPage.tsx": 13,
|
||||
"pages/atlas/useAtlas.ts": 2,
|
||||
"pages/collections/useCollections.ts": 1,
|
||||
"pages/sharedTrip/SharedChrome.tsx": 2,
|
||||
"pages/sharedTrip/SharedMap.tsx": 1,
|
||||
"pages/tripPlanner/ListsContainer.tsx": 1,
|
||||
"pages/tripPlanner/PlanMapStage.tsx": 1,
|
||||
"utils/touchDragBridge.ts": 1
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"components/Admin/GitHubPanel.tsx": 3,
|
||||
"components/Admin/PluginPoiCategoryList.tsx": 1,
|
||||
"components/Admin/useCategoryAdmin.ts": 1,
|
||||
"components/Budget/CostsPanel.tsx": 1,
|
||||
"components/Budget/CostsToolbar.tsx": 1,
|
||||
"components/Collab/CollabNotesFilePreviewPortal.tsx": 3,
|
||||
"components/Collections/AddPlaceToCollectionModal.tsx": 1,
|
||||
"components/Collections/BulkAssignLabelModal.tsx": 1,
|
||||
"components/Collections/CollectionPicker.tsx": 1,
|
||||
"components/Collections/ImportCollectionModal.tsx": 1,
|
||||
"components/Collections/MoveToListModal.tsx": 1,
|
||||
"components/Collections/SaveTripPlacesToListModal.tsx": 1,
|
||||
"components/Dawarich/DawarichAtlasSidePanel.tsx": 1,
|
||||
"components/Files/FileManagerImageLightbox.tsx": 1,
|
||||
"components/Files/FileManagerRow.tsx": 3,
|
||||
"components/Files/FileManagerToolbar.tsx": 1,
|
||||
"components/Help/HelpNav.tsx": 1,
|
||||
"components/Journey/journeyPhotoLayer.ts": 2,
|
||||
"components/Map/DawarichTrailLayer.tsx": 1,
|
||||
"components/Map/dawarichTrail.ts": 10,
|
||||
"components/Map/useDawarichTrailGL.ts": 1,
|
||||
"components/Packing/PackingListPanelItemRow.tsx": 1,
|
||||
"components/Planner/DayReorderPopup.tsx": 1,
|
||||
"components/Planner/bookings/bookingsModel.ts": 1,
|
||||
"components/Planner/bookings/transitParts.tsx": 1,
|
||||
"components/Planner/usePlaceForm.ts": 1,
|
||||
"components/Roadtrip/RangeStrip.tsx": 1,
|
||||
"components/Roadtrip/RoadtripAlternativesBar.tsx": 1,
|
||||
"components/Roadtrip/RoadtripCategoryPicker.tsx": 2,
|
||||
"components/Roadtrip/RoadtripCorridorPanel.tsx": 3,
|
||||
"components/Roadtrip/RoadtripSidebarStopRows.tsx": 4,
|
||||
"components/Roadtrip/RoadtripTrackModal.tsx": 1,
|
||||
"components/Roadtrip/StopKindPicker.tsx": 2,
|
||||
"components/Roadtrip/dayColors.ts": 8,
|
||||
"components/Roadtrip/nightBookend.ts": 1,
|
||||
"components/Roadtrip/stopKinds.ts": 1,
|
||||
"components/Settings/AboutTab.tsx": 3,
|
||||
"components/Settings/AccountTab.tsx": 2,
|
||||
"components/Settings/AppearanceSettingsTab.tsx": 1,
|
||||
"components/Settings/PasskeysSection.tsx": 1,
|
||||
"components/Studio/BookSheetsView.tsx": 1,
|
||||
"components/Studio/PhotoView.tsx": 1,
|
||||
"components/Studio/SpreadView.tsx": 1,
|
||||
"components/Studio/StudioElementsPanel.tsx": 2,
|
||||
"components/Studio/StudioSwatches.tsx": 1,
|
||||
"components/Studio/TravelElements.tsx": 3,
|
||||
"components/Studio/peerColour.ts": 1,
|
||||
"components/Studio/printSheets.ts": 4,
|
||||
"components/Studio/travel/badgeLook.ts": 2,
|
||||
"components/Trips/TripMemberAvatar.tsx": 2,
|
||||
"components/Vacay/VacayPersons.tsx": 1,
|
||||
"components/shared/DialogShell.tsx": 2,
|
||||
"components/shared/PasswordChecklist.tsx": 2,
|
||||
"mobile/components/MSheet.tsx": 1,
|
||||
"mobile/screens/atlas/MAtlas.tsx": 1,
|
||||
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2,
|
||||
"mobile/screens/atlas/MAtlasSearch.tsx": 1,
|
||||
"mobile/screens/collections/MCollEditSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollPlaceSheet.tsx": 2,
|
||||
"mobile/screens/collections/MCollShareSheet.tsx": 1,
|
||||
"mobile/screens/collections/collectionsMobileModel.ts": 15,
|
||||
"mobile/screens/dashboard/MDashboard.tsx": 3,
|
||||
"mobile/screens/journey/MJourney.tsx": 2,
|
||||
"mobile/screens/trip/roadtrip/MRoadtripRows.tsx": 2,
|
||||
"mobile/screens/trip/roadtrip/MRtAlternativesBar.tsx": 1,
|
||||
"mobile/screens/trip/roadtrip/MRtCorridorSheet.tsx": 1,
|
||||
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 1,
|
||||
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 1,
|
||||
"mobile/screens/trip/sheets/MCostSheet.tsx": 1,
|
||||
"pages/AtlasPage.tsx": 1,
|
||||
"pages/admin/AdminUserModals.tsx": 1,
|
||||
"pages/sharedTrip/SharedChrome.tsx": 4,
|
||||
"pages/sharedTrip/SharedMap.tsx": 2
|
||||
}
|
||||
@@ -1,73 +1,42 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* theme:lint — guards the appearance token system.
|
||||
* theme:lint: styling that bypasses the appearance tokens may only go down.
|
||||
*
|
||||
* Flags styling that bypasses the design tokens and therefore won't follow a
|
||||
* user's chosen scheme / transparency / text-size:
|
||||
* - inline color literals (color: '#111', background: 'rgba(...)', boxShadow: '...rgba...')
|
||||
* - inline numeric fontSize (fontSize: 13)
|
||||
* - arbitrary-value Tailwind color classes (bg-[#..], text-[rgba(..)])
|
||||
* A user picks a colour scheme, an accent, transparency and a text size, and
|
||||
* applyAppearance() turns that into CSS variables. A colour literal, a palette
|
||||
* class, a raw text size or a z-index of its own never hears about any of it,
|
||||
* so the surface stays light in a dark scheme, keeps indigo under a red
|
||||
* accent, or ignores the text size setting. The contract is in
|
||||
* src/theme/README.md; this counts what of it source shows, per file under
|
||||
* src/ (tests excluded):
|
||||
*
|
||||
* ALLOWED (never flagged): var(--token) inline styles, bg-[var(--..)] classes,
|
||||
* and genuinely dynamic values (data-driven colors, computed sizes/positions).
|
||||
* arbitrary-color bg-[#..], text-[rgba(..)] and the like
|
||||
* inline-color color: '#111', background: 'rgba(...)' in a style
|
||||
* inline-font-size fontSize: 13
|
||||
* palette-class bg-gray-100, text-indigo-600, bg-white, text-black
|
||||
* raw-text-size text-xs, text-sm ... text-9xl instead of the type tiers
|
||||
* z-index-literal z-[9999], zIndex: 10000 above Tailwind's z-50, instead of
|
||||
* a step of the layering scale (--z-bar ... --z-toast)
|
||||
* dark-mode-read reading settings.dark_mode instead of the .dark class
|
||||
*
|
||||
* Mirrors the i18n:parity gate. Default mode reports a baseline and exits 0;
|
||||
* `--strict` exits non-zero when any violations remain (for once the backlog is
|
||||
* burned down, or wired to changed files only). Add `theme-lint-disable` in a
|
||||
* line comment to suppress an intentional exception (map/PDF/brand colors).
|
||||
* Each file may hold no more hits than its entry in scripts/theme-baseline.json
|
||||
* (a file without an entry holds none). A line that is literal on purpose (map
|
||||
* paint, PDF, brand colours) carries `theme-lint-disable` in a comment; those
|
||||
* lines are counted against scripts/theme-disable-baseline.json, so the marker
|
||||
* cannot quietly take the place of the tokens. An entry of either baseline
|
||||
* above what its file holds now, or for a file that is gone, fails as well
|
||||
* until --update lowers it.
|
||||
*
|
||||
* npm run theme:lint check against the baselines (CI)
|
||||
* npm run theme:lint -- --list print every hit, file by file
|
||||
* npm run theme:lint -- --update lower both baselines to what the files hold now;
|
||||
* it never raises an entry
|
||||
*
|
||||
* The matching lives in scripts/lib/theme.mjs.
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { runCli } from './lib/ratchet.mjs';
|
||||
import { check } from './lib/theme.mjs';
|
||||
|
||||
let SRC = new URL('../src', import.meta.url).pathname;
|
||||
if (process.platform === 'win32' && SRC.startsWith('/')) SRC = SRC.slice(1);
|
||||
|
||||
// Surfaces where CSS variables genuinely cannot reach (injected map HTML, WebGL
|
||||
// paint, standalone PDF documents) — colors there must stay literal.
|
||||
const EXEMPT = [
|
||||
/Mapbox/i, /placePopup/i, /marker/i, /popup/i, /TripPDF/, /JourneyBookPDF/,
|
||||
/MapViewGL/, /MapView\./, /JourneyMapGL/, /reservationsMapbox/, /useAtlas/,
|
||||
/ReservationOverlay/, /\.test\./, /\.spec\./,
|
||||
];
|
||||
|
||||
const ARB_CLASS = /\b(?:bg|text|border|ring|fill|stroke|from|via|to|shadow|outline|decoration|divide|caret)-\[\s*(?:#|rgba?\(|hsla?\(|oklch\()/;
|
||||
const INLINE_COLOR = /(?:color|background|backgroundColor|borderColor|border|borderTop|borderBottom|borderLeft|borderRight|boxShadow|fill|stroke|outline|textDecorationColor)\s*:\s*['"`]?\s*(?:#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(|oklch\()/;
|
||||
const INLINE_FONTSIZE = /fontSize\s*:\s*['"`]?\d/;
|
||||
|
||||
function walk(dir, files = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, files);
|
||||
else if (/\.(ts|tsx)$/.test(name)) files.push(p);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const strict = process.argv.includes('--strict');
|
||||
const offenders = [];
|
||||
let total = 0;
|
||||
|
||||
for (const f of walk(SRC)) {
|
||||
if (EXEMPT.some((re) => re.test(f))) continue;
|
||||
let count = 0;
|
||||
for (const line of readFileSync(f, 'utf8').split('\n')) {
|
||||
if (line.includes('theme-lint-disable')) continue;
|
||||
if (ARB_CLASS.test(line) || INLINE_COLOR.test(line) || INLINE_FONTSIZE.test(line)) count++;
|
||||
}
|
||||
if (count) {
|
||||
offenders.push([relative(SRC, f).replace(/\\/g, '/'), count]);
|
||||
total += count;
|
||||
}
|
||||
}
|
||||
|
||||
offenders.sort((a, b) => b[1] - a[1]);
|
||||
console.log(`theme:lint — ${total} hardcoded-style hits across ${offenders.length} files (map/PDF excluded).`);
|
||||
for (const [f, c] of offenders.slice(0, 20)) console.log(` ${String(c).padStart(4)} ${f}`);
|
||||
if (offenders.length > 20) console.log(` … and ${offenders.length - 20} more files.`);
|
||||
console.log('\nNew/changed code must use tokens (bg-surface / text-content / bg-accent / var(--..)) and the');
|
||||
console.log('text-title/subtitle/body/caption tiers — never inline #hex, never bg-[#..]. See src/theme/README.md.');
|
||||
|
||||
if (strict && total > 0) {
|
||||
console.error(`\n✖ theme:lint:strict — ${total} violations remain.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const root = fileURLToPath(new URL('..', import.meta.url));
|
||||
await runCli('theme:lint', (args) => check({ root, update: args.includes('--update'), list: args.includes('--list') }));
|
||||
|
||||
Reference in New Issue
Block a user