diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1ba1928..1473f25 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,20 @@ versions at once, go through every "Requires project changes" section in order, version you have. A new release = a new section at the top; we remove the oldest ones only once there are more than 20. +## Unreleased + +### Fixed +- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish + text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`, + the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's + TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or + `blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`, + `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several + lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`. + +### What projects must update +- `pnpm exec ipal-skills` after upgrading: `pnpm audit:code` runs the project's copy of the script. Nothing else. + ## 1.15.2 ### Fixed diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index ff7cb30..587bb7f 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -748,7 +748,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo (`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters. - Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project): `label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`, - `admin.group`. Type: `AdminText` from `@intecion/ipal-kit`. + `admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from + `@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error. - `admin.description` only when the label is not enough — one sentence ≤ 120 characters: what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`), never how the code works (no component, function, env-var or package names). diff --git a/docs/agent/skills/ipal-audit/SKILL.md b/docs/agent/skills/ipal-audit/SKILL.md index 0d4f4fc..044a8a5 100644 --- a/docs/agent/skills/ipal-audit/SKILL.md +++ b/docs/agent/skills/ipal-audit/SKILL.md @@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on a client decision recorded in `AGENTS.md` as `ipal-audit-skip: — ` (keys in AGENT.md §0b). Never add that line yourself just to make the audit pass. +## Polish text and panel labels (AGENT.md §2, §6.5a) +`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`, +`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`, +`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a +`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`. + ## Design tokens (AGENT.md §6.11) The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated), diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/ipal-audit/scripts/audit.sh index 4446dc0..f134ae6 100644 --- a/docs/agent/skills/ipal-audit/scripts/audit.sh +++ b/docs/agent/skills/ipal-audit/scripts/audit.sh @@ -238,8 +238,10 @@ fi if [ -n "$FRONT" ]; then report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \ "$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')" - report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \ - "$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')" + # The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep. + POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \ + POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]') + report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH" fi GLOBALS=$(dirs src/globals) if [ -n "$GLOBALS" ]; then diff --git a/docs/agent/skills/ipal-audit/scripts/polish-literals.mjs b/docs/agent/skills/ipal-audit/scripts/polish-literals.mjs new file mode 100644 index 0000000..1aeb061 --- /dev/null +++ b/docs/agent/skills/ipal-audit/scripts/polish-literals.mjs @@ -0,0 +1,98 @@ +#!/usr/bin/env node +// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0. +// node polish-literals.mjs [ …] +// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work. +// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under +// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file: +// - adminText('Title', 'Tytuł') from @intecion/ipal-kit +// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group +// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit +// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' } +// Anything under defaultValue is public content, so it is reported. So is a Polish-only label. +// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep). +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join } from 'node:path' + +const load = (from) => { + try { + return createRequire(from)('typescript') + } catch { + return null + } +} +const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url) +if (!ts) process.exit(3) + +const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/ +const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group']) +const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\// +const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/ +const IPAL = /^@intecion\/ipal-kit(?:\/|$)/ + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null) + +for (const file of files) { + const text = readFileSync(file, 'utf8') + if (!POLISH.test(text)) continue + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS) + const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text)) + + // Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count. + const helpers = new Map() + for (const st of source.statements) { + if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue + const named = st.importClause?.namedBindings + if (!named || !ts.isNamedImports(named)) continue + for (const el of named.elements) { + const name = (el.propertyName ?? el.name).text + if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name) + } + } + + const isBilingual = (node) => + ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k)) + + // Is this literal one of the panel's own labels? Walks up from the literal. + const isAdminLabel = (literal) => { + let inside = false + for (let node = literal; node.parent; node = node.parent) { + const parent = node.parent + if (keyName(parent) === 'defaultValue') return false + if (inside) continue + if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) { + const helper = helpers.get(parent.expression.text) + if (helper === 'adminText') inside = true + // rowLabel(fields, fallback): the fallback only, as { en, pl } + if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true + } + if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true + if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true + } + return inside + } + + const seen = new Set() + const visit = (node) => { + if (ts.isImportDeclaration(node)) return + const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) + if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) { + const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + if (!seen.has(line)) { + seen.add(line) + console.log(`${file}:${line + 1}:${text.split('\n')[line]}`) + } + } + ts.forEachChild(node, visit) + } + visit(source) +} diff --git a/docs/doctor.md b/docs/doctor.md index 3edffaf..0be6ea3 100644 --- a/docs/doctor.md +++ b/docs/doctor.md @@ -110,7 +110,7 @@ Turn off: `ipalKit({ doctor: false })`. Adapt: `ipalKit({ doctor: { tokenVar: 'M | | `blocks-duplicate` | warning | a project block whose `slug` (or `interfaceName`) matches a library block — also a slug renamed through the block's `slug` option — unless it is an override in `createBlockRegistry({ components })` | | | `blocks-helper-copy` | warning | no local copy of a plugin field builder (`blockLibraryManifest.fieldBuilders`), `ctaHref`, `buildActionButtonsField` | | | `blocks-tokens` | error / warning | from `ipal-audit`: hex colours, the token standard not wired, `ipal-tokens --check` | -| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code | +| audit | `i18n-literals` | error / warning | from `ipal-audit`: hardcoded text in blocks (error) and components (warning), Polish literals in code (not the panel's `adminText()` / `{ en, pl }` labels in a schema file — the `ipal-audit` skill) | | | `audit:` | as reported | every other `ipal-audit --quick` finding, one per file | | live | `live-reachable`, `live-health`, `live-noindex`, `live-seo` | error / warning | the URL answers; `/api/health` 200; production not noindex (staging must be); every `ipal-seo-check` error and warning | | deep | `deep-status` | error | the deep check could not finish | diff --git a/reference/.agents/skills/ipal-audit/SKILL.md b/reference/.agents/skills/ipal-audit/SKILL.md index 0d4f4fc..044a8a5 100644 --- a/reference/.agents/skills/ipal-audit/SKILL.md +++ b/reference/.agents/skills/ipal-audit/SKILL.md @@ -30,6 +30,12 @@ following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The on a client decision recorded in `AGENTS.md` as `ipal-audit-skip: <keys> — <reason>` (keys in AGENT.md §0b). Never add that line yourself just to make the audit pass. +## Polish text and panel labels (AGENT.md §2, §6.5a) +`hardcoded Polish text in code` covers public text. In a schema file (a `.ts` file under `collections/`, `globals/`, +`fields/` or `blocks/`, or one importing Payload's schema types) the panel's own labels are fine: `adminText('Title', 'Tytuł')`, +`{ en, pl }` as `label`, `singular`, `plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback, a +`const x: AdminText`. Still an error: any `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`. + ## Design tokens (AGENT.md §6.11) The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated), diff --git a/reference/.agents/skills/ipal-audit/scripts/audit.sh b/reference/.agents/skills/ipal-audit/scripts/audit.sh index 4446dc0..f134ae6 100644 --- a/reference/.agents/skills/ipal-audit/scripts/audit.sh +++ b/reference/.agents/skills/ipal-audit/scripts/audit.sh @@ -238,8 +238,10 @@ fi if [ -n "$FRONT" ]; then report ERROR "logic keyed on content text" "§2 the editor can rename it any time — a style/flag is a panel field (e.g. buildLinkField({ appearances: [...] }))" \ "$(g "\.(label|title|heading|name|text)\??\.(toLowerCase|toUpperCase|trim)\(\) *[!=]==? *['\"]|\.(label|title|heading)\?? *[!=]==? *['\"][^'\"]+['\"]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '==')" - report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields" \ - "$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]')" + # The panel's own { en, pl } / adminText() labels in schema files are not public text (polish-literals.mjs); without TypeScript, a plain grep. + POLISH=$(node "$(dirname "$0")/polish-literals.mjs" $FRONT 2>/dev/null) || \ + POLISH=$(g "['\"\`][^'\"\`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'\"\`]*['\"\`]" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]') + report ERROR "hardcoded Polish text in code" "§2 every visible text comes from the panel — legal links: getSystemLinks(locale) (page titles), labels: localized fields; panel labels: adminText() or { en, pl } in a schema file" "$POLISH" fi GLOBALS=$(dirs src/globals) if [ -n "$GLOBALS" ]; then diff --git a/reference/.agents/skills/ipal-audit/scripts/polish-literals.mjs b/reference/.agents/skills/ipal-audit/scripts/polish-literals.mjs new file mode 100644 index 0000000..1aeb061 --- /dev/null +++ b/reference/.agents/skills/ipal-audit/scripts/polish-literals.mjs @@ -0,0 +1,98 @@ +#!/usr/bin/env node +// Polish text hardcoded in code (AGENT.md §2) — prints "file:line: source line" per finding, exit 0. +// node polish-literals.mjs <dir> [<dir> …] +// Reads the syntax tree (the project's TypeScript), so comments never count and multi-line forms work. +// Not reported: the panel's own labels (AGENT.md §6.5a), only in a schema file — a .ts file under +// collections/, globals/, fields/ or blocks/, or one importing Payload's schema types; never a .tsx file: +// - adminText('Title', 'Tytuł') from @intecion/ipal-kit +// - { en: 'Title', pl: 'Tytuł' } as the value of label, singular, plural, description, placeholder or group +// - rowLabel('title', { en: 'Item', pl: 'Pozycja' }) from @intecion/ipal-kit +// - const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' } +// Anything under defaultValue is public content, so it is reported. So is a Polish-only label. +// Exit 3 = TypeScript not found (audit.sh falls back to a plain grep). +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join } from 'node:path' + +const load = (from) => { + try { + return createRequire(from)('typescript') + } catch { + return null + } +} +const ts = load(join(process.cwd(), 'package.json')) ?? load(import.meta.url) +if (!ts) process.exit(3) + +const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/ +const SCHEMA_KEYS = new Set(['label', 'singular', 'plural', 'description', 'placeholder', 'group']) +const SCHEMA_DIR = /(?:^|\/)(?:collections|globals|fields|blocks)\// +const SCHEMA_TYPES = /import\s+type\s*\{[^}]*\b(?:Block|CollectionConfig|Field|GlobalConfig|Tab)\b[^}]*\}\s*from\s*['"]payload['"]/ +const IPAL = /^@intecion\/ipal-kit(?:\/|$)/ + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (/\.tsx?$/.test(p) && !/\.d\.ts$|\/\(payload\)\//.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +const keyName = (node) => (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)) ? node.name.text : null) + +for (const file of files) { + const text = readFileSync(file, 'utf8') + if (!POLISH.test(text)) continue + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS) + const schemaFile = !file.endsWith('x') && !/^['"]use client['"]/m.test(text) && (SCHEMA_DIR.test(file) || SCHEMA_TYPES.test(text)) + + // Local names of the plugin's helpers (`import { adminText as t } …`); a lookalike of your own does not count. + const helpers = new Map() + for (const st of source.statements) { + if (!ts.isImportDeclaration(st) || !IPAL.test(st.moduleSpecifier.text)) continue + const named = st.importClause?.namedBindings + if (!named || !ts.isNamedImports(named)) continue + for (const el of named.elements) { + const name = (el.propertyName ?? el.name).text + if (name === 'adminText' || name === 'rowLabel') helpers.set(el.name.text, name) + } + } + + const isBilingual = (node) => + ts.isObjectLiteralExpression(node) && ['en', 'pl'].every((k) => node.properties.some((p) => keyName(p) === k)) + + // Is this literal one of the panel's own labels? Walks up from the literal. + const isAdminLabel = (literal) => { + let inside = false + for (let node = literal; node.parent; node = node.parent) { + const parent = node.parent + if (keyName(parent) === 'defaultValue') return false + if (inside) continue + if (ts.isCallExpression(parent) && parent.arguments.includes(node) && ts.isIdentifier(parent.expression)) { + const helper = helpers.get(parent.expression.text) + if (helper === 'adminText') inside = true + // rowLabel(fields, fallback): the fallback only, as { en, pl } + if (helper === 'rowLabel' && node === parent.arguments[1] && isBilingual(node)) inside = true + } + if (ts.isPropertyAssignment(parent) && parent.initializer === node && SCHEMA_KEYS.has(keyName(parent)) && isBilingual(node)) inside = true + if (ts.isVariableDeclaration(parent) && parent.initializer === node && parent.type?.getText(source) === 'AdminText' && isBilingual(node)) inside = true + } + return inside + } + + const seen = new Set() + const visit = (node) => { + if (ts.isImportDeclaration(node)) return + const literal = ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node) + if (literal && POLISH.test(node.text) && !(schemaFile && isAdminLabel(node))) { + const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + if (!seen.has(line)) { + seen.add(line) + console.log(`${file}:${line + 1}:${text.split('\n')[line]}`) + } + } + ts.forEachChild(node, visit) + } + visit(source) +} diff --git a/test/auditPolishLiterals.test.ts b/test/auditPolishLiterals.test.ts new file mode 100644 index 0000000..b3b4588 --- /dev/null +++ b/test/auditPolishLiterals.test.ts @@ -0,0 +1,180 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterEach, describe, expect, test } from 'vitest' + +import { parseToolOutput } from '../src/modules/doctor/rules/tooling.js' +import { runDoctor } from '../src/modules/doctor/run.js' + +const packageRoot = path.resolve(import.meta.dirname, '..') +const scripts = path.join(packageRoot, 'docs/agent/skills/ipal-audit/scripts') +let dirs: string[] = [] + +function project(files: Record<string, string>): string { + const root = mkdtempSync(path.join(tmpdir(), 'ipal-polish-')) + dirs.push(root) + for (const [rel, content] of Object.entries(files)) { + const file = path.join(root, rel) + mkdirSync(path.dirname(file), { recursive: true }) + writeFileSync(file, content) + } + return root +} + +/** `file:line` of every finding of the check. */ +function polish(files: Record<string, string>): string[] { + const root = project(files) + const out = execFileSync(process.execPath, [path.join(scripts, 'polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8' }) + return out.split('\n').filter(Boolean).map((l) => l.match(/^(.+?:\d+):/)?.[1] ?? l) +} + +const HELPER = "import { adminText, rowLabel } from '@intecion/ipal-kit/blocks'\n" + +afterEach(() => { + for (const d of dirs) {rmSync(d, { force: true, recursive: true })} + dirs = [] +}) + +describe('hardcoded Polish text: the panel labels are not public text', () => { + test('adminText() in a schema file, on one line and over several', () => { + expect(polish({ + 'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [ + { name: 'title', type: 'text', label: adminText('Title', 'Tytuł') }, + { name: 'heading', type: 'text', label: adminText( + 'Heading', + 'Nagłówek', + ) }, +] }\n`, + 'src/globals/Header.ts': `${HELPER}export const Header = { slug: 'header', label: adminText('Header', 'Nagłówek') }\n`, + })).toEqual([]) + }) + + test('{ en, pl } as label, singular, plural, description, placeholder, group, option label — one line and several', () => { + expect(polish({ + 'src/globals/Company.ts': `export const Company = { slug: 'company', admin: { group: { en: 'Company', pl: 'Dane firmy żółć' } }, fields: [ + { name: 'areas', type: 'array', labels: { singular: { en: 'Area', pl: 'Obszar działania' }, plural: { + en: 'Areas', + pl: 'Obszary działania', + } }, fields: [] }, + { name: 'kind', type: 'select', label: { + en: 'Social profiles', + pl: 'Profile społecznościowe', + }, admin: { description: { en: 'Where it shows', pl: 'Gdzie się wyświetla' }, placeholder: { en: 'Pick', pl: 'Wybierz coś ładnego ł' } }, options: [{ label: { en: 'Title', pl: 'Tytuł' }, value: 't' }] }, +] }\n`, + })).toEqual([]) + }) + + test('an aliased import, rowLabel fallback, a typed AdminText constant, a file importing Payload types', () => { + expect(polish({ + 'src/fields/title.ts': `import { adminText as t, rowLabel } from '@intecion/ipal-kit/blocks' +export const a = { label: t('Title', 'Tytuł'), admin: { components: rowLabel('x', { en: 'Item', pl: 'Pozycja ż' }) } }\n`, + 'src/lib/schema.ts': `import type { AdminText } from '@intecion/ipal-kit' +import type { Field } from 'payload' +const TITLE: AdminText = { en: 'Title', pl: 'Tytuł' } +export const f: Field = { name: 'title', type: 'text', label: { en: 'Title', pl: 'Tytuł' } } +export const g = TITLE\n`, + })).toEqual([]) + }) + + test('comments never count', () => { + expect(polish({ 'src/components/A.tsx': "// 'Nagłówek'\n/* \"Tytuł\" */\nexport const A = () => null\n" })).toEqual([]) + }) +}) + +describe('hardcoded Polish text: public strings are still reported', () => { + test('a public component with the same words, whichever form it uses', () => { + expect(polish({ + 'src/components/Hero.tsx': `${HELPER}export const Hero = () => ( + <section aria-label="Nagłówek"> + <Title text={'Tytuł'} label={adminText('Title', 'Tytuł')} other={{ label: { en: 'Heading', pl: 'Nagłówek' } }} /> + <Multi + caption={{ + en: 'Social profiles', + pl: 'Profile społecznościowe', + }} + /> + </section> +)\n`, + })).toEqual(['src/components/Hero.tsx:3', 'src/components/Hero.tsx:4', 'src/components/Hero.tsx:8']) + }) + + test('a block component next to its schema; a helper in lib without schema types', () => { + expect(polish({ + 'src/blocks/Hero/Component.tsx': "export const Hero = () => <h1 title=\"Nagłówek\" />\n", + 'src/blocks/Hero/config.ts': `${HELPER}export const Hero = { slug: 'hero', label: adminText('Heading', 'Nagłówek') }\n`, + 'src/lib/texts.ts': "export const labels = { label: { en: 'Title', pl: 'Tytuł' } }\n", + })).toEqual(['src/blocks/Hero/Component.tsx:1', 'src/lib/texts.ts:1']) + }) + + test('in a schema file: Polish only, another key, defaultValue, a lookalike helper, a client file', () => { + expect(polish({ + 'src/collections/Bad.ts': `${HELPER}export const Bad = { slug: 'bad', fields: [ + { name: 'a', label: 'Tytuł' }, + { name: 'b', label: { pl: 'Tytuł' } }, + { name: 'c', heading: { en: 'Title', pl: 'Tytuł' } }, + { name: 'd', defaultValue: 'Nagłówek' }, + { name: 'e', defaultValue: adminText('Heading', 'Nagłówek') }, + { name: 'f', defaultValue: { + en: 'Heading', + pl: 'Nagłówek', + } }, +] }\n`, + 'src/globals/Client.ts': `'use client'\n${HELPER}export const x = { label: adminText('Title', 'Tytuł') }\n`, + 'src/globals/Lookalike.ts': "const adminText = (a: string, b: string) => b\nexport const x = { label: adminText('Title', 'Tytuł') }\n", + })).toEqual([ + 'src/collections/Bad.ts:3', 'src/collections/Bad.ts:4', 'src/collections/Bad.ts:5', 'src/collections/Bad.ts:6', 'src/collections/Bad.ts:7', 'src/collections/Bad.ts:10', + 'src/globals/Client.ts:3', + 'src/globals/Lookalike.ts:2', + ]) + }) + + test('adminText outside a schema file is reported; rowLabel only spares its { en, pl } fallback', () => { + expect(polish({ + 'src/fields/row.ts': `${HELPER}export const a = rowLabel('x', 'Pozycja ż')\nexport const b = rowLabel('Żółć', { en: 'Item', pl: 'Pozycja ż' })\n`, + 'src/lib/text.ts': `${HELPER}export const t = adminText('Title', 'Tytuł')\n`, + })).toEqual(['src/fields/row.ts:2', 'src/fields/row.ts:3', 'src/lib/text.ts:2']) + }) +}) + +describe('ipal-audit and ipal-doctor agree', () => { + const files = { + 'package.json': JSON.stringify({ name: 'examplepl-web' }), + 'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [ + { name: 'title', label: adminText('Title', 'Tytuł') }, + { name: 'heading', label: { + en: 'Heading', + pl: 'Nagłówek', + } }, +] }\n`, + 'src/components/Public.tsx': `${HELPER}export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>\n`, + } + test('audit.sh and the i18n-literals rule report the public component only', async () => { + const root = project(files) + const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: root, encoding: 'utf8' }) + const line = parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code') + expect(line?.level).toBe('error') + expect(line?.items).toEqual([`src/components/Public.tsx:2:export const Public = () => <p title="Nagłówek">{adminText('Title', 'Tytuł')}</p>`]) + + const report = await runDoctor({ offline: true, only: ['audit'], packageRoot, root, writeSeen: false }) + const polishFindings = report.findings.filter((f) => f.rule === 'i18n-literals' && f.message.startsWith('hardcoded Polish')) + expect(polishFindings.map((f) => f.file)).toEqual(['src/components/Public.tsx']) + }) + + test('without TypeScript in reach the check still runs, as a plain grep', () => { + const copy = project({ 'x.txt': '' }) + cpSync(scripts, path.join(copy, 'scripts'), { recursive: true }) + const root = project(files) + const env = { ...process.env, NODE_PATH: '' } // pnpm's bin shims put its store on NODE_PATH + const alone = spawnSync(process.execPath, [path.join(copy, 'scripts/polish-literals.mjs'), 'src'], { cwd: root, encoding: 'utf8', env }) + expect(alone.status).toBe(3) + const audit = spawnSync('bash', [path.join(copy, 'scripts/audit.sh'), '--quick'], { cwd: root, encoding: 'utf8', env }) + expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')?.items.join('\n')).toContain('src/components/Public.tsx') + }) + + test('audit.sh passes when only schema labels hold Polish', () => { + const { 'src/components/Public.tsx': _, ...schemaOnly } = files + const audit = spawnSync('bash', [path.join(scripts, 'audit.sh'), '--quick'], { cwd: project(schemaOnly), encoding: 'utf8' }) + expect(parseToolOutput(audit.stdout).find((l) => l.title === 'hardcoded Polish text in code')).toBeUndefined() + }) +})