diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index e3a51a7..6f32307 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -47,12 +47,12 @@ jobs: - run: pnpm build # file:.. + injected: the site gets a copy of the built plugin with its peers from the site (README.md) - run: pnpm --dir reference install --frozen-lockfile --ignore-workspace - - run: pnpm --dir reference exec ipal-tokens --check + - run: pnpm --dir reference exec iapl-tokens --check - run: pnpm --dir reference generate:importmap && git diff --exit-code reference/src/app - run: pnpm --dir reference generate:types && git diff --exit-code reference/src/payload-types.ts - run: pnpm --dir reference typecheck - # ipal-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails - - run: node bin/ipal-doctor.mjs reference --strict --offline + # iapl-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails + - run: node bin/iapl-doctor.mjs reference --strict --offline # Full run on main (and before a release): MongoDB, seed, production build, smoke tests. reference-full: @@ -68,10 +68,10 @@ jobs: DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef NEXT_PUBLIC_SERVER_URL: http://localhost:3100 - IPAL_IP_HEADER: x-forwarded-for - # cookieScanner.crawl → ipalEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl - IPAL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl - IPAL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789 + IAPL_IP_HEADER: x-forwarded-for + # cookieScanner.crawl → iaplEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl + IAPL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl + IAPL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789 NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA ALLOW_LOCAL_MEDIA: '1' @@ -98,8 +98,8 @@ jobs: - run: pnpm --dir reference build - run: pnpm --dir reference exec playwright install --with-deps chromium - run: pnpm --dir reference test:e2e - # ipal-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site + # iapl-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site - run: | PORT=3100 pnpm --dir reference start & for i in $(seq 1 60); do curl -sf http://localhost:3100/api/health >/dev/null && break; sleep 2; done - node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100 + node bin/iapl-doctor.mjs reference --strict --offline --deep --url http://localhost:3100 diff --git a/bin/ipal-blocks.mjs b/bin/iapl-blocks.mjs similarity index 92% rename from bin/ipal-blocks.mjs rename to bin/iapl-blocks.mjs index f9ea1cc..94a4334 100755 --- a/bin/ipal-blocks.mjs +++ b/bin/iapl-blocks.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node -// ipal-blocks — the block library's command line. -// pnpm exec ipal-blocks list → the library blocks -// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx} -// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run +// iapl-blocks — the block library's command line. +// pnpm exec iapl-blocks list → the library blocks +// pnpm exec iapl-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx} +// pnpm exec iapl-blocks eject faq --dest src/blocks --dry-run // Eject copies one block's source into the project, with its imports pointing at the // package entries, so the project owns it: same slug and data shape, no migration. // Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected @@ -23,7 +23,7 @@ const libRoot = join(pkgRoot, 'src/modules/block-library') const blocksRoot = join(libRoot, 'blocks') if (!command || command === '--help' || command === '-h') { - console.log('Usage: ipal-blocks list | ipal-blocks eject [--dest src/blocks] [--dry-run]') + console.log('Usage: iapl-blocks list | iapl-blocks eject [--dest src/blocks] [--dry-run]') process.exit(0) } @@ -35,7 +35,7 @@ if (command === 'list') { } if (command !== 'eject' || !slug) { - console.error('Usage: ipal-blocks eject ') + console.error('Usage: iapl-blocks eject ') process.exit(1) } if (!slugs.includes(slug)) { diff --git a/bin/ipal-doctor.mjs b/bin/iapl-doctor.mjs similarity index 58% rename from bin/ipal-doctor.mjs rename to bin/iapl-doctor.mjs index 80a19bc..ad4cc02 100755 --- a/bin/ipal-doctor.mjs +++ b/bin/iapl-doctor.mjs @@ -1,12 +1,12 @@ #!/usr/bin/env node -// ipal-doctor — checks a site against the ipal-kit team rules and lists every gap with a fix hint +// iapl-doctor — checks a site against the IAPL team rules and lists every gap with a fix hint // (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in -// ipal-doctor.json outside CI). -// pnpm exec ipal-doctor → this project, human-readable -// pnpm exec ipal-doctor --strict --offline → CI on a new site: any finding fails -// pnpm exec ipal-doctor --deep --url http://localhost:3000 -// pnpm exec ipal-doctor --json > doctor.json -// pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor → the newest rules +// iapl-doctor.json outside CI). +// pnpm exec iapl-doctor → this project, human-readable +// pnpm exec iapl-doctor --strict --offline → CI on a new site: any finding fails +// pnpm exec iapl-doctor --deep --url http://localhost:3000 +// pnpm exec iapl-doctor --json > doctor.json +// pnpm dlx --package=@intecion/ipal-kit@latest iapl-doctor → the newest rules // Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed. import { dirname, join } from 'node:path' diff --git a/bin/ipal-skills.mjs b/bin/iapl-skills.mjs similarity index 78% rename from bin/ipal-skills.mjs rename to bin/iapl-skills.mjs index b4b89da..53a43f9 100755 --- a/bin/ipal-skills.mjs +++ b/bin/iapl-skills.mjs @@ -1,15 +1,15 @@ #!/usr/bin/env node -// ipal-skills — copies the ipal-kit agent skills into the project. -// pnpm exec ipal-skills → ./.agents/skills/ipal-* -// pnpm exec ipal-skills --dry-run → show what would change -// pnpm exec ipal-skills --dest .claude/skills -// pnpm exec ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone -// pnpm exec ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only) -// pnpm exec ipal-skills --external ext-accessibility,ext-payload → only those -// Only folders named ipal-* are touched; the project's own skills stay as they are. -// ipal-* folders that no longer exist in the package are removed (renamed/retired skills). -// ext-* folders are touched only with --external, and only those carrying ipal-kit's SOURCE.md. -// AGENTS.md (and CLAUDE.md) get a marked ipal-kit block pointing at the guide — only the +// iapl-skills — copies the IAPL agent skills into the project. +// pnpm exec iapl-skills → ./.agents/skills/iapl-* +// pnpm exec iapl-skills --dry-run → show what would change +// pnpm exec iapl-skills --dest .claude/skills +// pnpm exec iapl-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone +// pnpm exec iapl-skills --external → also the vendored third-party skills (ext-*, pinned, text only) +// pnpm exec iapl-skills --external ext-accessibility,ext-payload → only those +// Only folders named iapl-* are touched; the project's own skills stay as they are. +// iapl-* folders that no longer exist in the package are removed (renamed/retired skills). +// ext-* folders are touched only with --external, and only those carrying IAPL's SOURCE.md. +// AGENTS.md (and CLAUDE.md) get a marked IAPL block pointing at the guide — only the // text between the markers is ever rewritten; the project's own content stays as it is. import { createHash } from 'node:crypto' @@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url' const args = process.argv.slice(2) if (args.includes('--help') || args.includes('-h')) { - console.log('Usage: ipal-skills [--dest ] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills') + console.log('Usage: iapl-skills [--dest ] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills') process.exit(0) } const dryRun = args.includes('--dry-run') @@ -30,21 +30,21 @@ const externalPick = externalArg >= 0 && args[externalArg + 1] && !args[external : null const destArg = args.indexOf('--dest') const destValue = destArg >= 0 ? args[destArg + 1] : '.agents/skills' -// A missing value would resolve to cwd and remove every ipal-* folder there. +// A missing value would resolve to cwd and remove every iapl-* folder there. if (!destValue || destValue.startsWith('-')) { - console.error('ipal-skills: --dest needs a directory, e.g. --dest .claude/skills') + console.error('iapl-skills: --dest needs a directory, e.g. --dest .claude/skills') process.exit(1) } const dest = resolve(process.cwd(), destValue) if (dest === resolve(process.cwd())) { - console.error('ipal-skills: --dest must be a subdirectory, not the project root') + console.error('iapl-skills: --dest must be a subdirectory, not the project root') process.exit(1) } const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') const src = join(pkgRoot, 'docs', 'agent', 'skills') if (!existsSync(src)) { - console.error(`ipal-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`) + console.error(`iapl-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`) process.exit(1) } @@ -54,7 +54,7 @@ const manifest = externalArg >= 0 ? JSON.parse(readFileSync(join(extSrc, 'manife const known = manifest.skills.map((skill) => skill.name) const unknown = (externalPick ?? []).filter((name) => !known.includes(name)) if (unknown.length) { - console.error(`ipal-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`) + console.error(`iapl-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`) process.exit(1) } @@ -73,7 +73,7 @@ for (const name of shipped) { } } for (const name of retired) { - console.log(`remove ${name} (no longer in ipal-kit)`) + console.log(`remove ${name} (no longer in IAPL)`) if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true }) } console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`) @@ -90,12 +90,12 @@ if (externalArg >= 0) { const files = filesOf(from).sort() const tampered = files.filter((f) => skill.files[f] !== createHash('sha256').update(readFileSync(join(from, f))).digest('hex')) if (tampered.length || files.length !== Object.keys(skill.files).length) { - console.error(`ipal-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`) + console.error(`iapl-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`) process.exitCode = 1 continue } if (existsSync(join(dest, skill.name)) && !ours(skill.name)) { - console.warn(`skip ${skill.name} (a folder of that name exists and is not from ipal-kit)`) + console.warn(`skip ${skill.name} (a folder of that name exists and is not from IAPL)`) continue } console.log(`${existsSync(join(dest, skill.name)) ? 'update' : 'add '} ${skill.name} (${skill.publisher}, ${skill.license}, ${skill.commit.slice(0, 12)})`) @@ -108,7 +108,7 @@ if (externalArg >= 0) { ? readdirSync(dest).filter((n) => n.startsWith('ext-') && !known.includes(n) && ours(n)) : [] for (const name of retiredExt) { - console.log(`remove ${name} (no longer in ipal-kit)`) + console.log(`remove ${name} (no longer in IAPL)`) if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true }) } } @@ -117,24 +117,24 @@ if (externalArg >= 0) { // AGENTS.md is read by Codex/Cursor/Antigravity, CLAUDE.md by Claude Code (which also // follows `@AGENTS.md` imports, so a CLAUDE.md that imports AGENTS.md needs no copy). if (pointer) { - const START = '' - const END = '' + const START = '' + const END = '' const version = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version const skillsDir = relative(process.cwd(), dest).split('\\').join('/') const block = [ START, - `## ipal-kit ${version} — agent guide`, + `## IAPL ${version} — agent guide`, '', - '', + '', 'This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:', '', '1. Rules: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`.', - `2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`ipal-reference\` skill — \`${skillsDir}/ipal-reference/SKILL.md\`.`, - `3. New project or missing foundation: the \`ipal-setup\` skill; a whole site: \`ipal-site\`. All skills: \`${skillsDir}/\`.`, + `2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`iapl-reference\` skill — \`${skillsDir}/iapl-reference/SKILL.md\`.`, + `3. New project or missing foundation: the \`iapl-setup\` skill; a whole site: \`iapl-site\`. All skills: \`${skillsDir}/\`.`, '4. Module details: `node_modules/@intecion/ipal-kit/docs/.md`.', - '5. ipal-kit first: if the plugin has it, use it. Broken or not enough → report it with the `ipal-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.', + '5. IAPL first: if the plugin has it, use it. Broken or not enough → report it with the `iapl-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.', '6. Before you set up a site: ask the owner the architecture questions (AGENT.md "Ask before you build") and wait for the answers; record them under "Project decisions".', - '7. ipal-kit docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.', + '7. IAPL docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.', END, ].join('\n') const upsert = (file, { create }) => { diff --git a/bin/ipal-tokens.mjs b/bin/iapl-tokens.mjs similarity index 62% rename from bin/ipal-tokens.mjs rename to bin/iapl-tokens.mjs index 02b7945..e2591f7 100755 --- a/bin/ipal-tokens.mjs +++ b/bin/iapl-tokens.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -// ipal-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css, +// iapl-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css, // plus a WCAG contrast check (docs/design-tokens.md). -// pnpm exec ipal-tokens → write src/design/tokens.css, print the contrast report -// pnpm exec ipal-tokens --check → fail when the CSS is out of date (CI, ipal-doctor) -// pnpm exec ipal-tokens --in x.ts --out y.css --warn-only +// pnpm exec iapl-tokens → write src/design/tokens.css, print the contrast report +// pnpm exec iapl-tokens --check → fail when the CSS is out of date (CI, iapl-doctor) +// pnpm exec iapl-tokens --in x.ts --out y.css --warn-only import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' diff --git a/bin/ipal-kit.mjs b/bin/iapl.mjs similarity index 68% rename from bin/ipal-kit.mjs rename to bin/iapl.mjs index 0613987..aba36b5 100755 --- a/bin/ipal-kit.mjs +++ b/bin/iapl.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node -// ipal-kit — the plugin's command line. +// IAPL — the plugin's command line. // pnpm dlx @intecion/ipal-kit@ create intecion.com → a new client site (docs/project-starter.md) -// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json +// pnpm exec iapl create intecion.com --dir ../intecioncom-web --answers answers.json // `pnpm dlx ` runs the bin named after the package, so every subcommand lives here. -// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor. +// The other tools keep their own bins: iapl-skills, iapl-blocks, iapl-tokens, iapl-doctor. import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -const USAGE = `Usage: ipal-kit [options] - create a new client site from the reference site (ipal-kit create --help) +const USAGE = `Usage: IAPL [options] + create a new client site from the reference site (iapl create --help) -Other tools: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor` +Other tools: iapl-skills, iapl-blocks, iapl-tokens, iapl-doctor` const [command, ...args] = process.argv.slice(2) if (command !== 'create') { diff --git a/dev/payload-types.ts b/dev/payload-types.ts index b3396a8..e355afb 100644 --- a/dev/payload-types.ts +++ b/dev/payload-types.ts @@ -1420,7 +1420,7 @@ export interface CookieSetting { }[] | null; /** - * Cookies the site uses — shown on the cookie policy page (). Fill it from a scan: ipal-consent-check → cookie-scan. + * Cookies the site uses — shown on the cookie policy page (). Fill it from a scan: iapl-consent-check → cookie-scan. */ cookies?: | { diff --git a/dev/payload.config.ts b/dev/payload.config.ts index 3262408..95fc3a8 100644 --- a/dev/payload.config.ts +++ b/dev/payload.config.ts @@ -1,7 +1,7 @@ import { payloadTotp } from '@clocklimited/payload-2fa' import { sqliteAdapter } from '@payloadcms/db-sqlite' import { lexicalEditor } from '@payloadcms/richtext-lexical' -import { ipalKit } from '../src/index.js' +import { iapl } from '../src/index.js' import path from 'path' import { buildConfig } from 'payload' import sharp from 'sharp' @@ -64,18 +64,18 @@ export default buildConfig({ await seed(payload) }, plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, i18n: i18nConfig, consentLog: true, - // Cookie review + "Crawl site" (needs IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler). + // Cookie review + "Crawl site" (needs IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler). cookieScanner: { crawl: true }, forms: {}, seo: { collections: ['posts', 'pages'] }, stats: true, // 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator. // IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens). - twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false, + twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'IAPL dev', plugin: payloadTotp } : false, // Panel logo/icon from Site settings and the technology support credit. whiteLabel: true, }), diff --git a/dev/tsconfig.json b/dev/tsconfig.json index 0bc30d1..cf72e10 100644 --- a/dev/tsconfig.json +++ b/dev/tsconfig.json @@ -19,7 +19,7 @@ "@payload-config": [ "./payload.config.ts" ], - "ipal-kit": [ + "IAPL": [ "../src/index.ts" ], "ipal-kit/client": [ diff --git a/docs/agent/skills/ipal-audit/SKILL.md b/docs/agent/skills/iapl-audit/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-audit/SKILL.md rename to docs/agent/skills/iapl-audit/SKILL.md diff --git a/docs/agent/skills/ipal-audit/resources/smoke.spec.template.ts b/docs/agent/skills/iapl-audit/resources/smoke.spec.template.ts similarity index 100% rename from docs/agent/skills/ipal-audit/resources/smoke.spec.template.ts rename to docs/agent/skills/iapl-audit/resources/smoke.spec.template.ts diff --git a/docs/agent/skills/ipal-audit/scripts/audit.sh b/docs/agent/skills/iapl-audit/scripts/audit.sh similarity index 100% rename from docs/agent/skills/ipal-audit/scripts/audit.sh rename to docs/agent/skills/iapl-audit/scripts/audit.sh diff --git a/docs/agent/skills/ipal-audit/scripts/html-check.mjs b/docs/agent/skills/iapl-audit/scripts/html-check.mjs similarity index 100% rename from docs/agent/skills/ipal-audit/scripts/html-check.mjs rename to docs/agent/skills/iapl-audit/scripts/html-check.mjs diff --git a/docs/agent/skills/ipal-audit/scripts/jsx-text.mjs b/docs/agent/skills/iapl-audit/scripts/jsx-text.mjs similarity index 100% rename from docs/agent/skills/ipal-audit/scripts/jsx-text.mjs rename to docs/agent/skills/iapl-audit/scripts/jsx-text.mjs diff --git a/docs/agent/skills/ipal-audit/scripts/panel-check.mjs b/docs/agent/skills/iapl-audit/scripts/panel-check.mjs similarity index 100% rename from docs/agent/skills/ipal-audit/scripts/panel-check.mjs rename to docs/agent/skills/iapl-audit/scripts/panel-check.mjs diff --git a/docs/agent/skills/ipal-audit/scripts/polish-literals.mjs b/docs/agent/skills/iapl-audit/scripts/polish-literals.mjs similarity index 100% rename from docs/agent/skills/ipal-audit/scripts/polish-literals.mjs rename to docs/agent/skills/iapl-audit/scripts/polish-literals.mjs diff --git a/docs/agent/skills/ipal-block/SKILL.md b/docs/agent/skills/iapl-block/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-block/SKILL.md rename to docs/agent/skills/iapl-block/SKILL.md diff --git a/docs/agent/skills/ipal-block/resources/section-code.md b/docs/agent/skills/iapl-block/resources/section-code.md similarity index 100% rename from docs/agent/skills/ipal-block/resources/section-code.md rename to docs/agent/skills/iapl-block/resources/section-code.md diff --git a/docs/agent/skills/ipal-collection/SKILL.md b/docs/agent/skills/iapl-collection/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-collection/SKILL.md rename to docs/agent/skills/iapl-collection/SKILL.md diff --git a/docs/agent/skills/ipal-consent-check/SKILL.md b/docs/agent/skills/iapl-consent-check/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-consent-check/SKILL.md rename to docs/agent/skills/iapl-consent-check/SKILL.md diff --git a/docs/agent/skills/ipal-consent-check/scripts/consent-check.mjs b/docs/agent/skills/iapl-consent-check/scripts/consent-check.mjs similarity index 100% rename from docs/agent/skills/ipal-consent-check/scripts/consent-check.mjs rename to docs/agent/skills/iapl-consent-check/scripts/consent-check.mjs diff --git a/docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs b/docs/agent/skills/iapl-consent-check/scripts/cookie-scan.mjs similarity index 100% rename from docs/agent/skills/ipal-consent-check/scripts/cookie-scan.mjs rename to docs/agent/skills/iapl-consent-check/scripts/cookie-scan.mjs diff --git a/docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts b/docs/agent/skills/iapl-consent-check/scripts/import-cookies.ts similarity index 100% rename from docs/agent/skills/ipal-consent-check/scripts/import-cookies.ts rename to docs/agent/skills/iapl-consent-check/scripts/import-cookies.ts diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/iapl-debug/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-debug/SKILL.md rename to docs/agent/skills/iapl-debug/SKILL.md diff --git a/docs/agent/skills/ipal-doctor/SKILL.md b/docs/agent/skills/iapl-doctor/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-doctor/SKILL.md rename to docs/agent/skills/iapl-doctor/SKILL.md diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/iapl-form/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-form/SKILL.md rename to docs/agent/skills/iapl-form/SKILL.md diff --git a/docs/agent/skills/ipal-form/resources/CustomForm.example.tsx b/docs/agent/skills/iapl-form/resources/CustomForm.example.tsx similarity index 100% rename from docs/agent/skills/ipal-form/resources/CustomForm.example.tsx rename to docs/agent/skills/iapl-form/resources/CustomForm.example.tsx diff --git a/docs/agent/skills/ipal-form/resources/FormBlock.tsx b/docs/agent/skills/iapl-form/resources/FormBlock.tsx similarity index 100% rename from docs/agent/skills/ipal-form/resources/FormBlock.tsx rename to docs/agent/skills/iapl-form/resources/FormBlock.tsx diff --git a/docs/agent/skills/ipal-form/resources/actions.ts b/docs/agent/skills/iapl-form/resources/actions.ts similarity index 100% rename from docs/agent/skills/ipal-form/resources/actions.ts rename to docs/agent/skills/iapl-form/resources/actions.ts diff --git a/docs/agent/skills/ipal-form/resources/formClasses.ts b/docs/agent/skills/iapl-form/resources/formClasses.ts similarity index 100% rename from docs/agent/skills/ipal-form/resources/formClasses.ts rename to docs/agent/skills/iapl-form/resources/formClasses.ts diff --git a/docs/agent/skills/ipal-form/resources/seed-form.template.ts b/docs/agent/skills/iapl-form/resources/seed-form.template.ts similarity index 100% rename from docs/agent/skills/ipal-form/resources/seed-form.template.ts rename to docs/agent/skills/iapl-form/resources/seed-form.template.ts diff --git a/docs/agent/skills/ipal-locale-add/SKILL.md b/docs/agent/skills/iapl-locale-add/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-locale-add/SKILL.md rename to docs/agent/skills/iapl-locale-add/SKILL.md diff --git a/docs/agent/skills/ipal-locale-add/scripts/locale-coverage.ts b/docs/agent/skills/iapl-locale-add/scripts/locale-coverage.ts similarity index 100% rename from docs/agent/skills/ipal-locale-add/scripts/locale-coverage.ts rename to docs/agent/skills/iapl-locale-add/scripts/locale-coverage.ts diff --git a/docs/agent/skills/ipal-migrate-fields/SKILL.md b/docs/agent/skills/iapl-migrate-fields/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-migrate-fields/SKILL.md rename to docs/agent/skills/iapl-migrate-fields/SKILL.md diff --git a/docs/agent/skills/ipal-migrate-fields/resources/migrate-block-fields.template.ts b/docs/agent/skills/iapl-migrate-fields/resources/migrate-block-fields.template.ts similarity index 100% rename from docs/agent/skills/ipal-migrate-fields/resources/migrate-block-fields.template.ts rename to docs/agent/skills/iapl-migrate-fields/resources/migrate-block-fields.template.ts diff --git a/docs/agent/skills/ipal-nav/SKILL.md b/docs/agent/skills/iapl-nav/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-nav/SKILL.md rename to docs/agent/skills/iapl-nav/SKILL.md diff --git a/docs/agent/skills/ipal-nav/resources/nav-code.md b/docs/agent/skills/iapl-nav/resources/nav-code.md similarity index 100% rename from docs/agent/skills/ipal-nav/resources/nav-code.md rename to docs/agent/skills/iapl-nav/resources/nav-code.md diff --git a/docs/agent/skills/ipal-plugin-gap/SKILL.md b/docs/agent/skills/iapl-plugin-gap/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-plugin-gap/SKILL.md rename to docs/agent/skills/iapl-plugin-gap/SKILL.md diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/iapl-reference/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-reference/SKILL.md rename to docs/agent/skills/iapl-reference/SKILL.md diff --git a/docs/agent/skills/ipal-reference/resources/api.md b/docs/agent/skills/iapl-reference/resources/api.md similarity index 100% rename from docs/agent/skills/ipal-reference/resources/api.md rename to docs/agent/skills/iapl-reference/resources/api.md diff --git a/docs/agent/skills/ipal-seo-check/SKILL.md b/docs/agent/skills/iapl-seo-check/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-seo-check/SKILL.md rename to docs/agent/skills/iapl-seo-check/SKILL.md diff --git a/docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs b/docs/agent/skills/iapl-seo-check/scripts/seo-check.mjs similarity index 100% rename from docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs rename to docs/agent/skills/iapl-seo-check/scripts/seo-check.mjs diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/iapl-setup/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-setup/SKILL.md rename to docs/agent/skills/iapl-setup/SKILL.md diff --git a/docs/agent/skills/ipal-setup/resources/DESIGN.md b/docs/agent/skills/iapl-setup/resources/DESIGN.md similarity index 100% rename from docs/agent/skills/ipal-setup/resources/DESIGN.md rename to docs/agent/skills/iapl-setup/resources/DESIGN.md diff --git a/docs/agent/skills/ipal-setup/resources/tokens.ts b/docs/agent/skills/iapl-setup/resources/tokens.ts similarity index 100% rename from docs/agent/skills/ipal-setup/resources/tokens.ts rename to docs/agent/skills/iapl-setup/resources/tokens.ts diff --git a/docs/agent/skills/ipal-site/SKILL.md b/docs/agent/skills/iapl-site/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-site/SKILL.md rename to docs/agent/skills/iapl-site/SKILL.md diff --git a/docs/agent/skills/ipal-site/resources/seed-content.template.ts b/docs/agent/skills/iapl-site/resources/seed-content.template.ts similarity index 100% rename from docs/agent/skills/ipal-site/resources/seed-content.template.ts rename to docs/agent/skills/iapl-site/resources/seed-content.template.ts diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/iapl-upgrade/SKILL.md similarity index 100% rename from docs/agent/skills/ipal-upgrade/SKILL.md rename to docs/agent/skills/iapl-upgrade/SKILL.md diff --git a/package.json b/package.json index 62d2fad..f39d47d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@intecion/ipal-kit", "version": "1.16.8", - "description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", + "description": "Intecion Advanced Payload Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", "license": "MIT", "repository": { "type": "git", @@ -88,11 +88,16 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "bin": { - "ipal-kit": "bin/ipal-kit.mjs", - "ipal-skills": "bin/ipal-skills.mjs", - "ipal-blocks": "bin/ipal-blocks.mjs", - "ipal-tokens": "bin/ipal-tokens.mjs", - "ipal-doctor": "bin/ipal-doctor.mjs" + "iapl": "bin/iapl.mjs", + "iapl-skills": "bin/iapl-skills.mjs", + "iapl-blocks": "bin/iapl-blocks.mjs", + "iapl-tokens": "bin/iapl-tokens.mjs", + "iapl-doctor": "bin/iapl-doctor.mjs", + "ipal-kit": "bin/iapl.mjs", + "ipal-skills": "bin/iapl-skills.mjs", + "ipal-blocks": "bin/iapl-blocks.mjs", + "ipal-tokens": "bin/iapl-tokens.mjs", + "ipal-doctor": "bin/iapl-doctor.mjs" }, "files": [ "dist", diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index 384386c..808cd4f 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -18,13 +18,13 @@ const GENERATED = /^src\/app\/\(payload\)\// /** Sections in reading order: [title, AGENT.md / doc reference, path test]. */ const SECTIONS = [ ['Project files', 'AGENT.md §13, §0a', (p) => !p.includes('/') || p.startsWith('docs/')], - ['Configuration', 'AGENT.md §3, ipal-setup stage 3', (p) => /^src\/[^/]+\.ts$/.test(p)], - ['Collections and globals', 'AGENT.md §5, ipal-nav, ipal-collection', (p) => /^src\/(collections|globals)\//.test(p)], + ['Configuration', 'AGENT.md §3, iapl-setup stage 3', (p) => /^src\/[^/]+\.ts$/.test(p)], + ['Collections and globals', 'AGENT.md §5, iapl-nav, iapl-collection', (p) => /^src\/(collections|globals)\//.test(p)], ['Blocks', 'docs/block-library.md', (p) => p.startsWith('src/blocks/')], ['Design tokens', 'docs/design-tokens.md', (p) => p.startsWith('src/design/') || p.startsWith('src/components/design/') || p.includes('/design/')], ['Data layer', 'AGENT.md §3, PROGRAMISTA §2.7', (p) => p.startsWith('src/lib/')], - ['Layout and components', 'AGENT.md §6.8, ipal-nav, ipal-form', (p) => p.startsWith('src/components/') || p.startsWith('src/app/(frontend)/')], - ['SEO, GEO and ops routes', 'AGENT.md §0b, ipal-setup stages 7–8', (p) => p.startsWith('src/app/')], + ['Layout and components', 'AGENT.md §6.8, iapl-nav, iapl-form', (p) => p.startsWith('src/components/') || p.startsWith('src/app/(frontend)/')], + ['SEO, GEO and ops routes', 'AGENT.md §0b, iapl-setup stages 7–8', (p) => p.startsWith('src/app/')], ['Seeds', 'docs/seeding.md, docs/block-library.md "Page templates"', (p) => p.startsWith('src/seed/')], ['Smoke tests', 'AGENT.md §8a', (p) => p.startsWith('e2e/') || p === 'playwright.config.ts'], ] @@ -60,7 +60,7 @@ export const DESCRIPTIONS = { 'README.md': 'how to run the reference site and what is where', 'docs/DEPLOY.md': 'the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback', 'e2e/create-test-admin.ts': 'two test admins with a known TOTP secret (the specs share out the five 2FA verify attempts per account), their stored verify counts cleared, and e-mail sending pointed at the tests\' mail sink (local / CI database only)', - 'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before ipalKit (staff collections of the config: roles with one more value, the plugin\'s roles, roles of the project\'s own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)', + 'e2e/late-staff-fixture.ts': 'test fixture, on only with E2E_LATE_STAFF=1: one plugin before iapl (staff collections of the config: roles with one more value, the plugin\'s roles, roles of the project\'s own) and one after it (a staff collection without rules, one whose roles field is text, copies of staff collections under new slugs — plain, with rules of their own, one rule used for another operation, other role values, the opt-out, not staff — and a visitor collection with open sign-up)', 'e2e/late-staff.spec.ts': 'the account rules on a BUILT site (run by `pnpm e2e:built` after a webpack and a Turbopack build): a staff collection a later plugin adds, staff collections whose accounts can hold `admin`, and copies of staff collections — a visitor account gets nothing, nobody raises its own role or makes an admin, a copy is never wider than the plugin\'s rule', 'e2e/global-setup.ts': 'Playwright global setup: resets the test admins and clears their stored 2FA attempt counts before every run, so specs do not depend on run order', 'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page', @@ -68,12 +68,12 @@ export const DESCRIPTIONS = { 'e2e/smtp-sink.ts': 'a local mail sink for the smoke tests: reads what the site really sent (recipients, attachments)', 'e2e/two-factor-back.spec.ts': 'browser test of the 2FA screens\' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed', 'e2e/totp.ts': 'RFC 6238 code generator for the 2FA sign-in in the smoke test, and the address of the second test admin', - 'ipal-doctor.json': 'the production domain and launch state for ipal-doctor', + 'iapl-doctor.json': 'the production domain and launch state for iapl-doctor', 'next.config.ts': 'security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By', 'package.json': 'scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides', 'playwright.config.ts': 'smoke tests against the built, seeded site', 'postcss.config.mjs': 'Tailwind 4 through PostCSS', - 'starter.manifest.json': 'what `ipal-kit create` keeps, drops and turns into placeholders', + 'starter.manifest.json': 'what `iapl create` keeps, drops and turns into placeholders', 'src/app/(frontend)/[locale]/[[...slug]]/page.tsx': 'the catch-all page: createPageRoute, ISR, redirects, maintenance, the language switcher links', 'src/app/(frontend)/[locale]/actions.ts': 'the ONE form server action (createSubmitAction)', 'src/app/(frontend)/[locale]/design/page.tsx': 'the design-token styleguide page (noindex)', @@ -98,7 +98,7 @@ export const DESCRIPTIONS = { 'src/collections/Pages.ts': 'Pages: slug, blocks layout, AI summary, noindex, slug history, revalidation, system-page delete guard', 'src/collections/Posts.ts': 'the blog collection (archive in System pages)', 'src/collections/entryFields.ts': 'shared fields of archive collections (names the entry card reads)', - 'src/components/design/TokenPanel.tsx': 'one styleguide panel built from IPAL_TOKENS', + 'src/components/design/TokenPanel.tsx': 'one styleguide panel built from IAPL_TOKENS', 'src/components/forms/formClasses.ts': 'the ONE place forms are styled, token utilities only', 'src/components/layout/Footer.tsx': 'footer: columns, company data, legal links from System pages, NoSnippet', 'src/components/layout/Header.tsx': 'header: logo from Site settings, resolveNav menu, language and theme switch, CTA', @@ -115,7 +115,7 @@ export const DESCRIPTIONS = { 'src/instrumentation.ts': 'env validation at startup (assertEnv, database name rule)', 'src/lib/content.ts': 'createContentHelpers: the ONLY access to Payload, routes, links, JSON-LD', 'src/lib/globals.ts': 'cached getters for the project\'s own globals', - 'src/payload.config.ts': 'ipalKit with every module the site uses, R2, mail, 2FA, white-label', + 'src/payload.config.ts': 'iapl with every module the site uses, R2, mail, 2FA, white-label', 'src/proxy.ts': 'the locale proxy with Markdown negotiation (not middleware.ts)', 'src/seed/base.ts': 'BASE seed: templates, system pages, navigation, banner texts — kept by the starter', 'src/seed/demo.ts': 'DEMO seed: the made-up company in pl and en — dropped by the starter', @@ -143,12 +143,12 @@ export function buildReferenceIndex(root) { '', '', '', - `The reference site is one complete client site on ipal-kit ${version} ("Example Studio", made up) that uses`, + `The reference site is one complete client site on IAPL ${version} ("Example Studio", made up) that uses`, 'every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the', 'PATTERN of the file you need; change only the project\'s content. Files up to', `${FULL_MAX_LINES} lines are below in full; open the rest in the repo at the tag of your plugin version:`, '`https://git.intecion.net/IntecionSoftware/ipal-kit/src/tag/v/reference/`.', - 'If this index and AGENT.md disagree, report it with ipal-plugin-gap — it is a plugin bug.', + 'If this index and AGENT.md disagree, report it with iapl-plugin-gap — it is a plugin bug.', '', ] const seen = new Set() diff --git a/scripts/refresh-cookie-database.mjs b/scripts/refresh-cookie-database.mjs index 1522416..37a01ca 100644 --- a/scripts/refresh-cookie-database.mjs +++ b/scripts/refresh-cookie-database.mjs @@ -20,7 +20,7 @@ const args = process.argv.slice(2) const refArg = args.indexOf('--ref') >= 0 ? args[args.indexOf('--ref') + 1] : undefined async function get(url) { - const res = await fetch(url, { headers: { 'User-Agent': 'ipal-kit cookie-db refresh' } }) + const res = await fetch(url, { headers: { 'User-Agent': 'IAPL cookie-db refresh' } }) if (!res.ok) {throw new Error(`${url}: HTTP ${res.status}`)} return res } diff --git a/scripts/starter-gate.mjs b/scripts/starter-gate.mjs index b7c84ac..1fe7ac8 100644 --- a/scripts/starter-gate.mjs +++ b/scripts/starter-gate.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -// pnpm starter:gate — the release gate of `ipal-kit create` (prepublishOnly, after build:starter). +// pnpm starter:gate — the release gate of `iapl create` (prepublishOnly, after build:starter). // Packs the plugin, creates a site from the PACKED tarball the way a developer does (pnpm dlx), then builds and // runs it the way Coolify does: frozen install, `pnpm generate:types && pnpm build`, `pnpm start`, MongoDB in its // own container. It runs the documented targeted seed in production mode, checks that a full seed is refused -// there, and runs `ipal-doctor --strict` when the plugin ships it. Any failure exits 1 and blocks the publish. +// there, and runs `iapl-doctor --strict` when the plugin ships it. Any failure exits 1 and blocks the publish. // pnpm starter:gate → everything, then cleans up (the work folder and the MongoDB container) // pnpm starter:gate --keep → leave .starter-gate/ for inspection // Needs Docker (MongoDB image mongo:7) and the npm registry (or a warm pnpm store). With the `nixpacks` CLI on @@ -125,13 +125,13 @@ async function main() { writeFileSync(answersFile, JSON.stringify(answers, null, 2)) const started = Date.now() const created = sh(work, 'pnpm', ['--config.auto-install-peers=false', '--config.dlx-cache-max-age=0', 'dlx', tarball, 'create', domain, '--answers', answersFile, '--plugin-spec', `file:${tarball}`], {}, { allowFail: true }) - check('ipal-kit create (install, skills, tokens, types, import map, typecheck, secret check, first commit)', created === 0, `${((Date.now() - started) / 1000).toFixed(0)} s`) + check('iapl create (install, skills, tokens, types, import map, typecheck, secret check, first commit)', created === 0, `${((Date.now() - started) / 1000).toFixed(0)} s`) const site = join(work, 'release-checkexample-web') // the site was made by THIS tarball: the bundle hash and commit the generator recorded, and the plugin it installed const made = JSON.parse(readFileSync(join(site, '.ipal', 'starter.json'), 'utf8')) - check('generated by this tarball (bundle sha256, plugin version)', made.source?.bundleSha256 === bundleSha256 && made.ipalKit === version, `${bundleSha256.slice(0, 12)} · ${version}`) + check('generated by this tarball (bundle sha256, plugin version)', made.source?.bundleSha256 === bundleSha256 && made.iapl === version, `${bundleSha256.slice(0, 12)} · ${version}`) check('bundle built from this commit', (made.source?.commit ?? '').replace(/-dirty$/, '') === commit, made.source?.commit ?? 'none') - const installed = join(site, 'node_modules', '@intecion', 'ipal-kit') + const installed = join(site, 'node_modules', '@intecion', 'IAPL') const installedSha = createHash('sha256').update(readFileSync(join(installed, 'dist', 'starter', 'template.json.gz'))).digest('hex') check('the site installed this tarball', installedSha === bundleSha256 && JSON.parse(readFileSync(join(installed, 'package.json'), 'utf8')).version === version) check('first commit, nothing left uncommitted', out('git', ['-C', site, 'status', '--porcelain']) === '' && out('git', ['-C', site, 'log', '--oneline']).split('\n').length === 1) @@ -140,9 +140,9 @@ async function main() { const env = { ALLOW_LOCAL_MEDIA: '1', // no R2 in the gate (never set in Coolify) DATABASE_URI: `mongodb://127.0.0.1:${mongoPort}/release-checkexample_dev`, - IPAL_COOKIE_SCAN_TOKEN: 'release-gate-token-0123456789', - IPAL_COOKIE_SCAN_URL: 'http://127.0.0.1:9', - IPAL_IP_HEADER: 'x-forwarded-for', + IAPL_COOKIE_SCAN_TOKEN: 'release-gate-token-0123456789', + IAPL_COOKIE_SCAN_URL: 'http://127.0.0.1:9', + IAPL_IP_HEADER: 'x-forwarded-for', NEXT_PUBLIC_SERVER_URL: `http://localhost:${PORT}`, PAYLOAD_SECRET: readFileSync(join(site, '.env'), 'utf8').match(/^PAYLOAD_SECRET=(.+)$/m)?.[1] ?? '', } @@ -174,13 +174,13 @@ async function main() { const llms = await (await fetch(`http://127.0.0.1:${PORT}/llms.txt`)).text() check('llms.txt names the site', llms.includes('Release Check')) - // 7. ipal-doctor, when this ipal-kit ships it - if (existsSync(join(site, 'node_modules', '.bin', 'ipal-doctor'))) { - const doctor = sh(site, 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'], env, { allowFail: true }) - check('ipal-doctor --strict: zero findings', doctor === 0) + // 7. iapl-doctor, when this IAPL ships it + if (existsSync(join(site, 'node_modules', '.bin', 'iapl-doctor'))) { + const doctor = sh(site, 'pnpm', ['exec', 'iapl-doctor', '--strict', '--offline'], env, { allowFail: true }) + check('iapl-doctor --strict: zero findings', doctor === 0) } else { - results.push({ detail: 'not in this ipal-kit yet', name: 'ipal-doctor --strict', ok: null }) - log('- ipal-doctor --strict — skipped: not in this ipal-kit yet') + results.push({ detail: 'not in this IAPL yet', name: 'iapl-doctor --strict', ok: null }) + log('- iapl-doctor --strict — skipped: not in this IAPL yet') } // 8. Coolify's build pack itself, when the nixpacks CLI is available diff --git a/scripts/vendor-external-skills.mjs b/scripts/vendor-external-skills.mjs index 85a11d3..4ad2678 100644 --- a/scripts/vendor-external-skills.mjs +++ b/scripts/vendor-external-skills.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // Maintainer script (not shipped): vendors the third-party agent skills into docs/agent/external/ -// at the commits pinned below. Projects never fetch anything — `ipal-skills --external` copies +// at the commits pinned below. Projects never fetch anything — `iapl-skills --external` copies // these vendored folders. To update a pin: change `commit`, run this script, review the diff // (`git diff docs/agent/external`), run `pnpm vitest run test/externalSkills.test.ts`, commit. // @@ -21,7 +21,7 @@ const outDir = join(root, 'docs', 'agent', 'external') const COMMON = `> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with > \`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md\`, the project's \`AGENTS.md\` or \`DESIGN.md\`, those win: -> ipal-kit features first (the \`ipal-reference\` skill), Payload 3 + Next 16 App Router, data from Server Components +> IAPL features first (the \`iapl-reference\` skill), Payload 3 + Next 16 App Router, data from Server Components > through Payload / \`@/lib/content\`, every visible text from the CMS, design values from \`DESIGN.md\` tokens. > Never add a dependency this skill suggests without the owner's decision.` @@ -58,7 +58,7 @@ const SOURCES = [ license: 'MIT', licenseFile: 'LICENSE', override: `> **Tools:** never run \`npx lighthouse\` / \`npx @axe-core/cli\` unpinned — add them as devDependencies at fixed versions -> first. Use the ipal-kit components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through +> first. Use the IAPL components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through > their props or a plugin gap report, not by copying them.`, }, { @@ -80,8 +80,8 @@ const SOURCES = [ publisher: 'Payload CMS', license: 'MIT', licenseFile: 'LICENSE.md', - override: `> **Reference only — Payload 3 (v3.92.1).** Never apply Payload 4 guidance. ipal-kit already provides users and roles, -> 2FA, SEO, forms, i18n, the site globals, revalidation and storage — check the \`ipal-reference\` skill before you + override: `> **Reference only — Payload 3 (v3.92.1).** Never apply Payload 4 guidance. IAPL already provides users and roles, +> 2FA, SEO, forms, i18n, the site globals, revalidation and storage — check the \`iapl-reference\` skill before you > write Payload config, hooks or access rules by hand.`, }, ] @@ -168,8 +168,8 @@ try { } writeFileSync(join(to, 'SOURCE.md'), `# ${src.name} -Vendored by @intecion/ipal-kit (\`ipal-skills --external\`). Do not edit — regenerate with -\`scripts/vendor-external-skills.mjs\` in the ipal-kit repository. +Vendored by @intecion/ipal-kit (\`iapl-skills --external\`). Do not edit — regenerate with +\`scripts/vendor-external-skills.mjs\` in the IAPL repository. | | | |---|---| diff --git a/services/cookie-crawler/README.md b/services/cookie-crawler/README.md index d18da5d..8ed6cce 100644 --- a/services/cookie-crawler/README.md +++ b/services/cookie-crawler/README.md @@ -1,11 +1,11 @@ # ipal cookie crawler -The browser half of ipal-kit's cookie scanner: one shared service that crawls a site twice (no +The browser half of IAPL's cookie scanner: one shared service that crawls a site twice (no consent / after "Accept all") and posts cookies, storage keys and third-party hosts back to the site. Sites never run a browser. Setup, Coolify deploy, env and network notes: `docs/cookie-scanner.md` → "Browser crawl" in the -ipal-kit repository (also shipped in `node_modules/@intecion/ipal-kit/docs/`). +IAPL repository (also shipped in `node_modules/@intecion/ipal-kit/docs/`). -- `node server.mjs` — the service (`IPAL_CRAWLER_SITES="acme.pl=TOKEN"`). +- `node server.mjs` — the service (`IAPL_CRAWLER_SITES="acme.pl=TOKEN"`). - `node cli.mjs https://acme.pl --pages 10` — the same crawl from a laptop or CI, JSON on stdout. diff --git a/services/cookie-crawler/package.json b/services/cookie-crawler/package.json index 48ccafe..58a1d3c 100644 --- a/services/cookie-crawler/package.json +++ b/services/cookie-crawler/package.json @@ -2,7 +2,7 @@ "name": "@intecion/ipal-cookie-crawler", "version": "1.0.0", "private": true, - "description": "Headless-browser cookie crawler for ipal-kit sites (Cookie review → Crawl site). Runs as one shared service, never inside a site.", + "description": "Headless-browser cookie crawler for IAPL sites (Cookie review → Crawl site). Runs as one shared service, never inside a site.", "license": "MIT", "type": "module", "scripts": { diff --git a/services/cookie-crawler/server.mjs b/services/cookie-crawler/server.mjs index d1d8834..3e56184 100644 --- a/services/cookie-crawler/server.mjs +++ b/services/cookie-crawler/server.mjs @@ -6,7 +6,7 @@ // The crawl runs in the background; the result is POSTed to callbackUrl with the // same bearer token. // -// Env: IPAL_CRAWLER_SITES="acme.pl=TOKEN,shop.example.com=TOKEN2" (required), PORT (3000), +// Env: IAPL_CRAWLER_SITES="acme.pl=TOKEN,shop.example.com=TOKEN2" (required), PORT (3000), // CRAWLER_CONCURRENCY (1), CRAWLER_QUEUE_MAX (20), CRAWLER_JOB_TIMEOUT_MS (600000), // CRAWLER_WAIT_MS (3000), CRAWLER_ALLOW_HTTP (unset; "1" only for local tests). import { createServer } from 'node:http' @@ -139,9 +139,9 @@ export function createCrawlerServer({ // Run directly: `node server.mjs` if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { - const sites = parseSites(process.env.IPAL_CRAWLER_SITES) + const sites = parseSites(process.env.IAPL_CRAWLER_SITES) if (!sites.length) { - console.error('[crawler] IPAL_CRAWLER_SITES is empty — set "host=token" pairs (token ≥ 16 chars).') + console.error('[crawler] IAPL_CRAWLER_SITES is empty — set "host=token" pairs (token ≥ 16 chars).') process.exit(1) } const { chromium } = await import('playwright') diff --git a/src/exports/doctor.ts b/src/exports/doctor.ts index db85f77..73c7a6b 100644 --- a/src/exports/doctor.ts +++ b/src/exports/doctor.ts @@ -1,9 +1,9 @@ /** * Entry point: @intecion/ipal-kit/doctor * - * ipal-doctor's building blocks — the rules, the runner, the formatters and the status + * iapl-doctor's building blocks — the rules, the runner, the formatters and the status * collector — for a project that wants to wrap, filter or extend the checks (docs/doctor.md). - * Node only (reads files, runs commands). The command itself: `pnpm exec ipal-doctor`. + * Node only (reads files, runs commands). The command itself: `pnpm exec iapl-doctor`. */ export { DOCTOR_USAGE, expandSites, parseDoctorArgs, runDoctorCli } from '../modules/doctor/cli.js' export { formatDriftTable, formatReport } from '../modules/doctor/format.js' diff --git a/src/exports/env.ts b/src/exports/env.ts index 2b8992a..254f768 100644 --- a/src/exports/env.ts +++ b/src/exports/env.ts @@ -8,10 +8,10 @@ * doesn't exist in target module"). * * // src/instrumentation.ts - * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' + * import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit/env' * export function register() { - * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true })) + * if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(iaplEnvRules({ storage: true })) * } */ -export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from '../modules/env/index.js' -export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from '../modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from '../modules/env/index.js' +export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from '../modules/env/index.js' diff --git a/src/exports/starter.ts b/src/exports/starter.ts index f3a4729..b13818a 100644 --- a/src/exports/starter.ts +++ b/src/exports/starter.ts @@ -1,7 +1,7 @@ /** * Entry point: @intecion/ipal-kit/starter * - * The building blocks of `ipal-kit create` (docs/project-starter.md): the answers schema, the variant and + * The building blocks of `iapl create` (docs/project-starter.md): the answers schema, the variant and * placeholder transforms, the bundle and the renderer — Node built-ins only, no Payload. Use them to script * your own generator or to check a reference tree; the command itself is `pnpm dlx @intecion/ipal-kit create`. */ diff --git a/src/exports/tokens.ts b/src/exports/tokens.ts index e27afca..1783ee6 100644 --- a/src/exports/tokens.ts +++ b/src/exports/tokens.ts @@ -2,7 +2,7 @@ * Entry point: @intecion/ipal-kit/tokens * * Design tokens with no Payload, React or Next import — safe in src/design/tokens.ts, - * the `ipal-tokens` CLI, next/og images and e-mail templates. docs/design-tokens.md. + * the `iapl-tokens` CLI, next/og images and e-mail templates. docs/design-tokens.md. */ export { COLOR_DEFAULTS, @@ -17,9 +17,9 @@ export { fluidClamp, INVERSE_SCOPE, INVERSE_SELECTOR, - IPAL_BREAKPOINTS, - IPAL_TOKENS, - ipalVar, + IAPL_BREAKPOINTS, + IAPL_TOKENS, + iaplVar, LEGACY_DARK_ROLES, LIGHT_SELECTOR, parseColor, @@ -27,4 +27,4 @@ export { STATIC_DEFAULTS, tokensToCss, } from '../modules/tokens/index.js' -export type { ColorInput, ColorRole, ContrastRow, FluidRange, IpalTokenName, RemValue, TokensInput } from '../modules/tokens/index.js' +export type { ColorInput, ColorRole, ContrastRow, FluidRange, IaplTokenName, RemValue, TokensInput } from '../modules/tokens/index.js' diff --git a/src/globals/CookieSettings/migrateSaveButton.ts b/src/globals/CookieSettings/migrateSaveButton.ts index 71fb673..ee4b5dd 100644 --- a/src/globals/CookieSettings/migrateSaveButton.ts +++ b/src/globals/CookieSettings/migrateSaveButton.ts @@ -31,9 +31,9 @@ export async function migrateCookieSettingsSaveButton(payload: BasePayload): Pro [{ $set: { 'buttons.savePreferences': '$buttons.save' } }], ) if (result.modifiedCount) { - payload.logger.info('[ipal] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).') + payload.logger.info('[iapl] Cookie Settings: buttons.save copied to buttons.savePreferences (1.11.1 rename).') } } catch (error) { - payload.logger.error({ err: error, msg: '[ipal] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' }) + payload.logger.error({ err: error, msg: '[iapl] Cookie Settings: could not migrate buttons.save → buttons.savePreferences' }) } } diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts index 03d25ae..6bf8c2c 100644 --- a/src/globals/Notifications/fields.ts +++ b/src/globals/Notifications/fields.ts @@ -121,7 +121,7 @@ const lightboxText = ( /** * The "Image viewer" group (`lightbox`) — labels of the image viewer (). - * Added by ipalKit `lightbox: true`; exported so a project can place it in its + * Added by iapl `lightbox: true`; exported so a project can place it in its * own global instead. */ export const lightboxNotificationFields: Field = { diff --git a/src/globals/Notifications/index.ts b/src/globals/Notifications/index.ts index d5663ef..257b056 100644 --- a/src/globals/Notifications/index.ts +++ b/src/globals/Notifications/index.ts @@ -7,7 +7,7 @@ import { lightboxNotificationFields, notificationsFields } from './fields.js' * Builds the Notifications global (shown as "Form messages") — localized action-result texts. Readable by * any authenticated panel user; server-side helpers read it with overrideAccess * so the frontend can resolve texts without a session. `lightbox` adds the - * image-viewer labels (ipalKit `lightbox: true`). + * image-viewer labels (iapl `lightbox: true`). */ export function buildNotifications({ lightbox = false }: { lightbox?: boolean } = {}): GlobalConfig { return { diff --git a/src/globals/SiteIntegrations/components/MaskedField.tsx b/src/globals/SiteIntegrations/components/MaskedField.tsx index 4c89244..9e2a913 100644 --- a/src/globals/SiteIntegrations/components/MaskedField.tsx +++ b/src/globals/SiteIntegrations/components/MaskedField.tsx @@ -5,7 +5,7 @@ import type { TextFieldClientComponent } from 'payload' import { FieldDescription, FieldLabel, useField, useTranslation } from '@payloadcms/ui' import { useState } from 'react' -import { ipalT } from '../../../modules/admin-i18n/t.js' +import { iaplT } from '../../../modules/admin-i18n/t.js' import { SECRET_CLEAR, SECRET_MASK } from '../../../modules/secrets/constants.js' /** @@ -55,15 +55,15 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { /> {stored ? ( ) : removing ? ( ) : ( )} @@ -76,7 +76,7 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { {stored || removing ? (

- {ipalT(t as never, stored ? 'maskedSet' : 'maskedRemoved')} + {iaplT(t as never, stored ? 'maskedSet' : 'maskedRemoved')}

) : null} diff --git a/src/globals/SiteIntegrations/components/TestEmailButton.tsx b/src/globals/SiteIntegrations/components/TestEmailButton.tsx index 89c3db3..247498e 100644 --- a/src/globals/SiteIntegrations/components/TestEmailButton.tsx +++ b/src/globals/SiteIntegrations/components/TestEmailButton.tsx @@ -3,7 +3,7 @@ import { useTranslation } from '@payloadcms/ui' import { useState } from 'react' -import { ipalT } from '../../../modules/admin-i18n/t.js' +import { iaplT } from '../../../modules/admin-i18n/t.js' /** * Admin UI: a small "send test e-mail" tool for the SiteIntegrations e-mail tab. @@ -15,7 +15,7 @@ import { ipalT } from '../../../modules/admin-i18n/t.js' */ export const TestEmailButton = () => { const { t } = useTranslation() - const text = (key: Parameters[1], vars?: Record) => ipalT(t as never, key, vars) + const text = (key: Parameters[1], vars?: Record) => iaplT(t as never, key, vars) const [to, setTo] = useState('') const [withFile, setWithFile] = useState(false) const [status, setStatus] = useState< diff --git a/src/globals/overrides.ts b/src/globals/overrides.ts index 3e68d58..fe54bff 100644 --- a/src/globals/overrides.ts +++ b/src/globals/overrides.ts @@ -1,7 +1,7 @@ import type { GlobalConfig } from 'payload' /** Slugs of the globals the plugin adds. */ -export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings' +export type IaplGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integrations' | 'site-settings' /** * A project's change to one plugin global: @@ -13,7 +13,7 @@ export type IpalGlobalSlug = 'cookie-settings' | 'notifications' | 'site-integra */ export type GlobalOverride = ((global: GlobalConfig) => GlobalConfig) | Partial -export type GlobalOverrides = Partial> +export type GlobalOverrides = Partial> type Hooks = NonNullable @@ -30,7 +30,7 @@ function mergeHooks(base: GlobalConfig['hooks'], extra: GlobalConfig['hooks']): export function applyGlobalOverrides(globals: GlobalConfig[], overrides: GlobalOverrides | undefined): GlobalConfig[] { if (!overrides) {return globals} return globals.map((global) => { - const override = overrides[global.slug as IpalGlobalSlug] + const override = overrides[global.slug as IaplGlobalSlug] if (!override) {return global} if (typeof override === 'function') {return override(global)} return { diff --git a/src/index.ts b/src/index.ts index 4c8bf76..df2c574 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ export { lightboxNotificationFields } from './globals/Notifications/fields.js' export { applyGlobalOverrides } from './globals/overrides.js' -export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js' +export type { GlobalOverride, GlobalOverrides, IaplGlobalSlug } from './globals/overrides.js' export type { AccessOption, Role } from './modules/access/index.js' export { adminOnly, @@ -55,7 +55,7 @@ export type { AccountsOptions } from './modules/access/types.js' export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/state.js' export type { A11yState } from './modules/accessibility/state.js' export { applyAdminI18n } from './modules/admin-i18n/apply.js' -export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, ipalT } from './modules/admin-i18n/index.js' +export { ADMIN_LANGUAGES, adminDocumentTitle, adminTexts, defineTexts, formatDateTime, formatNumber, iaplT } from './modules/admin-i18n/index.js' export type { AdminLanguage, AdminText, AdminTextKey } from './modules/admin-i18n/index.js' export { rowLabel } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js' @@ -216,8 +216,8 @@ export type { MailAdapterArgs } from './modules/email/mailAdapter.js' export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js' export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js' // Boot-time environment validation (fail fast on misconfigured deploys). -export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, ipalEnvRules } from './modules/env/index.js' -export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js' +export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules } from './modules/env/index.js' +export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures } from './modules/env/index.js' export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js' export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js' export { FORM_FILE_TYPES, formatFileSize, RISKY_FILE_EXTENSIONS } from './modules/forms/attachments/fileTypes.js' @@ -459,9 +459,9 @@ export { isTheme, isThemeSetting, LEGACY_THEME_STORAGE_KEY, THEME_ATTRIBUTE, THE export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js' // Imported from the file, not the turnstile barrel — that one re-exports verify, // which imports 'server-only'. -export { defineTokens, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js' -export type { IpalTokenName, TokensInput } from './modules/tokens/index.js' +export { defineTokens, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar } from './modules/tokens/index.js' +export type { IaplTokenName, TokensInput } from './modules/tokens/index.js' export { getTurnstileConfig, TURNSTILE_SECRET_ENV, turnstileSecretFromEnv } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' -export { ipalKit } from './plugin.js' -export type { IpalOptions, ThemeOptions } from './types.js' +export { iapl } from './plugin.js' +export type { IaplOptions, ThemeOptions } from './types.js' diff --git a/src/modules/access/panelRole.ts b/src/modules/access/panelRole.ts index 6095c7e..e260e92 100644 --- a/src/modules/access/panelRole.ts +++ b/src/modules/access/panelRole.ts @@ -30,7 +30,7 @@ export function resolvePanelRole(option: false | Role | undefined): null | Role if (option === false) {return null} const role = option ?? DEFAULT_PANEL_ROLE if (!ROLE_HIERARCHY.includes(role)) { - throw new Error(`[ipal] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`) + throw new Error(`[iapl] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`) } return role === ROLE_HIERARCHY[0] ? null : role } diff --git a/src/modules/access/passwordRule.ts b/src/modules/access/passwordRule.ts index e87a8a4..feeaf64 100644 --- a/src/modules/access/passwordRule.ts +++ b/src/modules/access/passwordRule.ts @@ -31,7 +31,7 @@ export function resolvePasswordRule(option: false | PasswordRuleOptions | undefi if (option === false) {return null} const minLength = option?.minLength ?? DEFAULT_PASSWORD_MIN_LENGTH if (typeof minLength !== 'number' || !Number.isInteger(minLength) || minLength < 1) { - throw new Error(`[ipal] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`) + throw new Error(`[iapl] accounts.password.minLength must be a whole number of 1 or more, got ${JSON.stringify(option?.minLength) ?? String(option?.minLength)}. Use accounts: { password: false } to turn the rule off.`) } return { minLength } } diff --git a/src/modules/access/predicates.ts b/src/modules/access/predicates.ts index e328599..0ad21da 100644 --- a/src/modules/access/predicates.ts +++ b/src/modules/access/predicates.ts @@ -23,14 +23,14 @@ type StaffConfig = { admin?: { user?: string }; custom?: unknown } type MaybePayload = Pick | StaffSource /** - * The staff lists of the configs ipalKit built in this process, by owner: the + * The staff lists of the configs iapl built in this process, by owner: the * running Payload instance once it exists, a token of the config before that. * Used when a predicate gets no source (`isAdmin(req.user)` in a hook). */ const registered = new Map() /** - * Called by ipalKit: at config time with a token, then with the Payload + * Called by iapl: at config time with a token, then with the Payload * instance (`replaces` = that config's token) on init and after every reload. * Not for projects. */ @@ -49,7 +49,7 @@ export const staffRegistrySize = (): number => registered.size /** * The staff collections every config in this process agrees on, or null when - * ipalKit never ran here (a browser bundle, Next middleware, the edge + * iapl never ran here (a browser bundle, Next middleware, the edge * runtime). Two configs with different lists: only what both call staff — a * call that does not say which config it means must not get the wider answer. */ @@ -83,7 +83,7 @@ export function staffCollectionSlugs(source?: MaybePayload): string[] { * Whether this account's roles may count at all: it belongs to a staff * collection. Checked before any role, and it fails closed: * - an account without `collection` (a user object built by hand) is not staff; - * - where the staff collections are not known — no source given and ipalKit + * - where the staff collections are not known — no source given and iapl * never ran in this bundle (client components, Next middleware, the edge * runtime) — nobody is staff. Pass the source there: `isAdmin(user, config)` * with the config from `useConfig()` (client components import from @@ -116,7 +116,7 @@ function highestRoleIndex(user: MaybeUser): number { * * Pass `req.payload` as the third argument where you have it (access * functions, hooks, endpoints); without it the staff collections of the - * config ipalKit built in this process are used — and where there is none + * config iapl built in this process are used — and where there is none * (a browser bundle, middleware) the answer is false: pass the config from * `useConfig()` or `{ staffCollections: ['users'] }` there. A client component * imports it from '@intecion/ipal-kit/client': the main entry does not build there with webpack. diff --git a/src/modules/access/ruleMark.ts b/src/modules/access/ruleMark.ts index 2a13383..3b4ca98 100644 --- a/src/modules/access/ruleMark.ts +++ b/src/modules/access/ruleMark.ts @@ -8,7 +8,7 @@ * The mark lets the plugin see that. It is on the function itself, so it: * - travels with every copy (it is the same function object); * - is on the function that ends up on the collection (set after the 2FA package wrapped the - * rule; ipal-kit's own 2FA guard gets a mark of its own for its wrapper); + * rule; IAPL's own 2FA guard gets a mark of its own for its wrapper); * - is the same for every instance of this module (`Symbol.for`): after a `next dev` reload the * config was built by one instance and is adopted by another. * It counts only on the very function it was made for (`self`): a Proxy around a marked rule, a diff --git a/src/modules/access/selfRegistration.ts b/src/modules/access/selfRegistration.ts index 7449c67..76f64f7 100644 --- a/src/modules/access/selfRegistration.ts +++ b/src/modules/access/selfRegistration.ts @@ -160,15 +160,15 @@ export function canHoldStaffRole(collection: Staffish): boolean { export type StaffAccountRules = { applied: string[]; ownRoles: boolean; slug?: string } /** - * The "seen" marker (`custom.ipalAccounts`): which collection ipalKit handled, and whether as a staff + * The "seen" marker (`custom.ipalAccounts`): which collection iapl handled, and whether as a staff * collection. Not a plain `true`: a later plugin may spread a collection into a new slug * (`{ ...staff, slug: 'copy' }`) and the marker travels with it; and in `next dev` a collection object can * outlive a reload in which it became staff. */ export type AccountsMarker = { /** - * The operations that had a rule in the project's config when ipalKit ran (before Payload and the 2FA package - * filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after ipalKit + * The operations that had a rule in the project's config when iapl ran (before Payload and the 2FA package + * filled the missing ones). A collection of the config that becomes staff LATER — a plugin listed after iapl * sets `admin.user` to it — keeps exactly those rules; an operation that had none gets the plugin's. */ own?: string[] @@ -182,7 +182,7 @@ const markerOf = (collection: { custom?: unknown }): AccountsMarker | undefined /** * BOTH rules must allow: the plugin's and the one the collection already has. For a collection - * that arrives after ipalKit ran (a later plugin), whose config is already sanitized: Payload has + * that arrives after iapl ran (a later plugin), whose config is already sanitized: Payload has * filled every missing rule with its default by then, and that default cannot be told from a * rule somebody wrote — not by its name (a production build minifies it away) and not safely by * identity. So nothing is guessed: the plugin's rule is put in FRONT of whatever is there. With @@ -230,10 +230,10 @@ const bothAllowField = * are involved. * * `mode`: - * - `'config'` (ipalKit is running, nothing is sanitized): an operation without a rule gets the plugin's; + * - `'config'` (iapl is running, nothing is sanitized): an operation without a rule gets the plugin's; * - `'late'` (a staff collection a later plugin added; the config is sanitized, so Payload's default cannot be * told from a written rule): the plugin's rule in front of every rule — except the operations named in `kept`: - * the collection was in the config when ipalKit ran and had a rule of the project's for them then (the marker's + * the collection was in the config when iapl ran and had a rule of the project's for them then (the marker's * `own`), so they are left as a rule the project wrote, exactly as at config time; * - `'copied'` (a late collection that is not staff, or that keeps its own rules — `custom.ipal.accountRules: * false`): the plugin's rule goes in front ONLY of a rule the plugin wrote for another collection (its mark, @@ -273,7 +273,7 @@ function ruleStaffCollection(collection: CollectionConfig, { create = true, plug if (mark && mark.slug !== slug) {copied = true} if (mode === 'config') { if (there || !enabled) {continue} // a rule the project wrote - access[operation] = rule // marked when ipalKit finishes (markStaffRules): the 2FA package wraps it first + access[operation] = rule // marked when iapl finishes (markStaffRules): the 2FA package wraps it first } else if ((mode === 'late' && enabled && !kept.includes(operation)) || mark) { access[operation] = markedStaffRule(bothAllow(rule, there), slug) } else {continue} @@ -352,7 +352,7 @@ export function applyStaffAccountAccess(config: Config, staffSlugs: string[], op collections: (config.collections ?? []).map((collection) => { if (!collection.auth) {return collection} // Which operations have a rule of the project's NOW — later nobody can tell (Payload and the 2FA package fill - // the missing ones). Kept in the marker for a collection that becomes staff after ipalKit ran. + // the missing ones). Kept in the marker for a collection that becomes staff after iapl ran. const own = OPERATIONS.filter((operation) => Boolean((collection.access as Record | undefined)?.[operation])) if (!staffSlugs.includes(collection.slug)) { return { ...collection, custom: { ...collection.custom, ipalAccounts: { slug: collection.slug, own, staff: false } satisfies AccountsMarker } } @@ -370,14 +370,14 @@ export type LateAdoption = { firstUser: boolean /** The operations whose rule from the project's config was left as it is (a config collection that became staff later). */ kept: string[] - /** True when the collection was in the config when ipalKit ran (and became staff afterwards); false when a later plugin added it. */ + /** True when the collection was in the config when iapl ran (and became staff afterwards); false when a later plugin added it. */ known: boolean password: boolean slug: string } /** - * Collections that were not in the config when ipalKit ran — a plugin listed after it added them. + * Collections that were not in the config when iapl ran — a plugin listed after it added them. * Called when a config goes live (start, dev reload) with THAT config: a late STAFF collection * gets the account rules (in front of whatever rules it has — `bothAllow`), the roles-field rule * and the password hook; every late auth collection gets the first-user endpoint. Changes the @@ -398,7 +398,7 @@ export function adoptLateAuthCollections( // a copy; a marker that says "not staff" on a collection that is staff now was made before it was named as one. const marker = markerOf(collection) if (marker?.slug === collection.slug && (marker.staff || !staff)) {continue} - // In the config when ipalKit ran, not staff then (a later plugin made it the panel's): the rules it had then stay. + // In the config when iapl ran, not staff then (a later plugin made it the panel's): the rules it had then stay. const known = marker?.slug === collection.slug const kept = known && Array.isArray(marker.own) ? marker.own : [] const done: LateAdoption = { slug: collection.slug, applied: [], firstUser: false, kept: [], known, password: false } @@ -429,7 +429,7 @@ export function adoptLateAuthCollections( /** * Puts the plugin's mark on the rules it filled in during this run (`custom.ipalAccountRules.applied`, for the * collection's own slug). Called AFTER the 2FA package has wrapped them — the mark must be on the function that is - * on the collection — and BEFORE ipal-kit's own 2FA guard, which carries the mark to its wrapper. Already marked + * on the collection — and BEFORE IAPL's own 2FA guard, which carries the mark to its wrapper. Already marked * functions are left, so it can run more than once. */ export function markStaffRules(config: Config): Config { @@ -449,7 +449,7 @@ export function markStaffRules(config: Config): Config { } /** - * Marks the auth collections ipalKit has seen at config time — with their slug and whether they are staff — so + * Marks the auth collections iapl has seen at config time — with their slug and whether they are staff — so * `adoptLateAuthCollections` leaves exactly those alone. */ export function markSeenAuthCollections(config: Config, staffSlugs: string[] = []): Config { @@ -518,7 +518,7 @@ export function buildFirstUserEndpoint(option: FirstUserRouteOption = 'panel'): export function applyFirstUserRoute(config: Config, option: FirstUserRouteOption = 'panel'): Config { if (option === 'all') {return config} if (option !== 'panel' && !Array.isArray(option)) { - throw new Error(`[ipal] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`) + throw new Error(`[iapl] accounts.firstUserRoute must be 'panel', 'all' or a list of collection slugs, got ${JSON.stringify(option)}.`) } return { ...config, diff --git a/src/modules/access/types.ts b/src/modules/access/types.ts index ea55503..156e191 100644 --- a/src/modules/access/types.ts +++ b/src/modules/access/types.ts @@ -11,7 +11,7 @@ export const ROLE_HIERARCHY = ['user', 'editor', 'admin'] as const export type Role = (typeof ROLE_HIERARCHY)[number] /** - * `ipalKit({ accounts })` — rules for the accounts of the staff collection. On by default + * `iapl({ accounts })` — rules for the accounts of the staff collection. On by default * where they apply; each one has its own switch, `accounts: false` turns them all off. */ export type AccountsOptions = { diff --git a/src/modules/admin-i18n/index.ts b/src/modules/admin-i18n/index.ts index ccb605e..8188a31 100644 --- a/src/modules/admin-i18n/index.ts +++ b/src/modules/admin-i18n/index.ts @@ -1,6 +1,6 @@ // Client-safe: types, texts and helpers. The config transform (applyAdminI18n) lives in apply.ts. export type { AdminLanguage, AdminText } from './define.js' export { ADMIN_LANGUAGES, defineTexts } from './define.js' -export { adminDocumentTitle, formatDateTime, formatNumber, ipalT } from './t.js' +export { adminDocumentTitle, formatDateTime, formatNumber, iaplT } from './t.js' export { adminTexts } from './texts/index.js' export type { AdminTextKey } from './texts/index.js' diff --git a/src/modules/admin-i18n/t.ts b/src/modules/admin-i18n/t.ts index 66ab7d8..003b60e 100644 --- a/src/modules/admin-i18n/t.ts +++ b/src/modules/admin-i18n/t.ts @@ -7,7 +7,7 @@ type TFunction = (key: never, vars?: Record) => string * components, `i18n.t` in server components), so a project's own * `i18n.translations..ipal.` wins over the plugin's. */ -export function ipalT(t: TFunction, key: AdminTextKey, vars?: Record): string { +export function iaplT(t: TFunction, key: AdminTextKey, vars?: Record): string { return t(`ipal:${key}` as never, vars) } diff --git a/src/modules/admin-ui/RowLabelComponent.tsx b/src/modules/admin-ui/RowLabelComponent.tsx index 9701538..009f477 100644 --- a/src/modules/admin-ui/RowLabelComponent.tsx +++ b/src/modules/admin-ui/RowLabelComponent.tsx @@ -3,7 +3,7 @@ import { useRowLabel, useTranslation } from '@payloadcms/ui' import type { AdminText } from '../admin-i18n/define.js' -import { ipalT } from '../admin-i18n/t.js' +import { iaplT } from '../admin-i18n/t.js' export type RowLabelProps = { /** @@ -48,6 +48,6 @@ export function RowLabel({ fallback, fields = ['heading', 'title', 'label', 'lin ? fallback : fallback ? ((fallback as Record)[i18n.language] ?? fallback.en ?? Object.values(fallback)[0]) - : ipalT(t, 'rowLabelItem') + : iaplT(t, 'rowLabelItem') return {`${name} ${String((rowNumber ?? 0) + 1).padStart(2, '0')}`} } diff --git a/src/modules/block-library/blocks/contact/Component.tsx b/src/modules/block-library/blocks/contact/Component.tsx index b5f247b..d9fff80 100644 --- a/src/modules/block-library/blocks/contact/Component.tsx +++ b/src/modules/block-library/blocks/contact/Component.tsx @@ -23,7 +23,7 @@ export const CONTACT_PARTS = { export async function ContactBlock(props: LibraryBlockProps) { const { classNames, content, ctx, form, header, isFirst, locale, settings, ui, variant } = props if (!ctx.sendForm || !ctx.content.getFormTexts) { - console.warn('[ipal] contact block: pass sendForm and content with getFormTexts to createBlockRegistry') + console.warn('[iapl] contact block: pass sendForm and content with getFormTexts to createBlockRegistry') return null } const c = parts(CONTACT_PARTS, classNames) diff --git a/src/modules/block-library/blocks/entryList/config.ts b/src/modules/block-library/blocks/entryList/config.ts index 7412098..54d8ffd 100644 --- a/src/modules/block-library/blocks/entryList/config.ts +++ b/src/modules/block-library/blocks/entryList/config.ts @@ -6,7 +6,7 @@ import { adminText, defineLibraryBlock, variantOption } from '../../define.js' export const ENTRY_LIST_VARIANTS = [variantOption('cards', 'Cards', 'Karty'), variantOption('list', 'List', 'Lista')] as const export type EntryListOptions = { - /** Content collections the editor picks from (they need URLs: ipalKit `content`). Default posts. */ + /** Content collections the editor picks from (they need URLs: iapl `content`). Default posts. */ collections?: readonly { label: AdminText; value: string }[] } & BlockOptions diff --git a/src/modules/block-library/manifest.ts b/src/modules/block-library/manifest.ts index e5b973e..b7df760 100644 --- a/src/modules/block-library/manifest.ts +++ b/src/modules/block-library/manifest.ts @@ -82,6 +82,6 @@ export function buildBlockLibraryManifest(): BlockLibraryManifest { /** * Names of the library's blocks, variants, primitives, field builders and templates — - * plain data for checks such as ipal-doctor. Built from the block configs themselves. + * plain data for checks such as iapl-doctor. Built from the block configs themselves. */ export const blockLibraryManifest: BlockLibraryManifest = buildBlockLibraryManifest() diff --git a/src/modules/block-library/options.ts b/src/modules/block-library/options.ts index 34dd432..d2c7424 100644 --- a/src/modules/block-library/options.ts +++ b/src/modules/block-library/options.ts @@ -47,7 +47,7 @@ export function pickVariants(defaults: readonly VariantOption[], chosen: BlockOp return chosen.map((v) => { if (typeof v !== 'string') {return v} const known = defaults.find((d) => d.value === v) - if (!known) {throw new Error(`[ipal] unknown variant "${v}" — pass { label, value } for a variant of your own`)} + if (!known) {throw new Error(`[iapl] unknown variant "${v}" — pass { label, value } for a variant of your own`)} return known }) } diff --git a/src/modules/block-library/templates/build.ts b/src/modules/block-library/templates/build.ts index 2659615..74ee358 100644 --- a/src/modules/block-library/templates/build.ts +++ b/src/modules/block-library/templates/build.ts @@ -102,6 +102,6 @@ export function buildTemplate(name: string, defaults: { slug: TemplateValue; tit } return [{ ...b, blockType: slug }] }) - if (missing.length) {console.warn(`[ipal] template ${name}: left out blocks that are off: ${missing.join(', ')}`)} + if (missing.length) {console.warn(`[iapl] template ${name}: left out blocks that are off: ${missing.join(', ')}`)} return { slug: options.slug ?? defaults.slug, layout, title: options.title ?? defaults.title } } diff --git a/src/modules/branding/adminGraphics.tsx b/src/modules/branding/adminGraphics.tsx index 33906fd..052cc49 100644 --- a/src/modules/branding/adminGraphics.tsx +++ b/src/modules/branding/adminGraphics.tsx @@ -1,6 +1,6 @@ import type { Payload } from 'payload' -import { ipalT } from '../admin-i18n/t.js' +import { iaplT } from '../admin-i18n/t.js' import { settingsTexts } from '../admin-i18n/texts/settings.js' import { secondFactorPassed } from '../security/totp/secondFactor.js' import { publicImageDataUri, siteOrigin } from './publicImage.js' @@ -9,7 +9,7 @@ import { publicImageDataUri, siteOrigin } from './publicImage.js' * White-label admin branding: the Payload admin panel's logo (login + nav) and * icon, pulled from the project's SiteSettings so each client sees THEIR brand, * set by the editor in the panel — not hardcoded per project. Wired - * automatically by `ipalKit({ whiteLabel: true })` (it injects + * automatically by `iapl({ whiteLabel: true })` (it injects * admin.components.graphics.Logo/Icon pointing here). * * Server Components — they read the SiteSettings global at render, using the @@ -85,7 +85,7 @@ async function loadBranding( } return { name, url } } catch (error) { - console.warn('[ipal] admin branding: falling back to Payload default:', error) + console.warn('[iapl] admin branding: falling back to Payload default:', error) return { name: null, url: null } } } @@ -130,14 +130,14 @@ export async function AdminIcon(props: BrandingProps = {}) { /** * Discreet vendor credit: "Technology support: Intecion.com". This is the - * PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client + * PLUGIN VENDOR's credit (Intecion ships IAPL, the framework), not client * data — a sensible default here is fine and A0-safe. The client's own brand * still owns the logo/name; this is a small line stating who supports the tech. * Text/URL overridable; turn it off with `whiteLabel: { credit: false }`. * The default text follows the admin language (`ipal:brandingCredit`, which a * project can also override in `i18n.translations`). * - * Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin + * Wired by iapl into admin.components.afterNavLinks (nav) AND afterLogin * (login screen footer). `variant` adjusts placement: * - 'nav' → left-aligned line under the nav links * - 'login' → centered line below the login form @@ -156,7 +156,7 @@ export function IntecionCredit( // A project's own text wins; otherwise the plugin's text in the admin language. const text = props.text ?? - (i18n ? ipalT(i18n.t, 'brandingCredit', { agency }) : settingsTexts.en.brandingCredit.replace('{{agency}}', agency)) + (i18n ? iaplT(i18n.t, 'brandingCredit', { agency }) : settingsTexts.en.brandingCredit.replace('{{agency}}', agency)) const style = variant === 'login' ? { diff --git a/src/modules/branding/adminMeta.ts b/src/modules/branding/adminMeta.ts index ec36116..ed8b231 100644 --- a/src/modules/branding/adminMeta.ts +++ b/src/modules/branding/adminMeta.ts @@ -193,6 +193,6 @@ export async function syncAdminMeta( if (!resolved.own.description && resolved.options.description !== false && description) {meta.description = description} if (!resolved.own.titleSuffix && resolved.options.titleSuffix !== false && titleSuffix) {meta.titleSuffix = titleSuffix} } catch (error) { - payload?.logger?.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' }) + payload?.logger?.warn({ err: error, msg: '[iapl] admin meta: could not read Site settings; Payload defaults stay.' }) } } diff --git a/src/modules/consent/consentLog.ts b/src/modules/consent/consentLog.ts index f2299cd..974f6c2 100644 --- a/src/modules/consent/consentLog.ts +++ b/src/modules/consent/consentLog.ts @@ -15,7 +15,7 @@ import { CONSENT_CATEGORY_LABELS } from './categoryLabels.js' * the time. NO IP address, user agent or other personal data — the id alone * links a record to the browser that holds the cookie. * - * Opt-in: `ipalKit({ consentLog: true })` adds the collection and the endpoint + * Opt-in: `iapl({ consentLog: true })` adds the collection and the endpoint * POST /api/ipal/consent; the layout passes ``. * Records older than `retentionDays` (default 3 years) are purged automatically. */ @@ -110,7 +110,7 @@ export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOpti purge(req.payload, { createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() } }) return Response.json({ ok: true }, { status: 201 }) } catch (err) { - req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`) + req.payload.logger.error(`[iapl] consent log write failed: ${err instanceof Error ? err.message : String(err)}`) return Response.json({ ok: false }, { status: 500 }) } }, diff --git a/src/modules/consent/getConsentTexts.ts b/src/modules/consent/getConsentTexts.ts index 58c6775..e91e650 100644 --- a/src/modules/consent/getConsentTexts.ts +++ b/src/modules/consent/getConsentTexts.ts @@ -142,7 +142,7 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom return page && typeof page === 'object' ? (page as PrivacyPage) : null } catch (error) { // No pages option / no privacyPolicy field / DB unreachable at build → no link. - console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error) + console.warn('[iapl] getConsentTexts: privacy page lookup failed, banner without link:', error) return null } } diff --git a/src/modules/consent/scanner/approval.ts b/src/modules/consent/scanner/approval.ts index 1985487..b6339b3 100644 --- a/src/modules/consent/scanner/approval.ts +++ b/src/modules/consent/scanner/approval.ts @@ -185,7 +185,7 @@ export function buildCookieApprovalEndpoints(options: CookieScannerOptions): End const result = await approveCookies({ addToList: options.syncAccepted !== false, ids, payload: req.payload, req, unknownCategory: approval.unknownCategory }) return Response.json({ ok: true, result }) } catch (err) { - req.payload.logger.error(`[ipal] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`) + req.payload.logger.error(`[iapl] cookie approval failed: ${err instanceof Error ? err.message : String(err)}`) return Response.json({ ok: false }, { status: 500 }) } }, diff --git a/src/modules/consent/scanner/collection.ts b/src/modules/consent/scanner/collection.ts index 989e343..03b258f 100644 --- a/src/modules/consent/scanner/collection.ts +++ b/src/modules/consent/scanner/collection.ts @@ -12,7 +12,7 @@ import { addToCookieList } from './sync.js' * Cookie review list — drafts from "Scan cookies" that an editor accepts, * edits or rejects. Accepting adds the cookie to Cookie Settings → Cookies * (the banner's detailed window and ). Opt-in: - * `ipalKit({ cookieScanner: true })`. + * `iapl({ cookieScanner: true })`. */ export const COOKIE_REVIEW_SLUG = 'cookie-review' @@ -46,7 +46,7 @@ function buildSyncHook(): CollectionAfterChangeHook { req, })) as unknown as { name: string } & CookieReviewValues const result = await addToCookieList({ entry: full, payload: req.payload, req }) - req.payload.logger.info(`[ipal] cookie review: "${full.name}" accepted → Cookie Settings (${result})`) + req.payload.logger.info(`[iapl] cookie review: "${full.name}" accepted → Cookie Settings (${result})`) if (!doc.listed) { await req.payload.update({ id: doc.id, diff --git a/src/modules/consent/scanner/crawl/config.ts b/src/modules/consent/scanner/crawl/config.ts index 4abff63..ae3b5cd 100644 --- a/src/modules/consent/scanner/crawl/config.ts +++ b/src/modules/consent/scanner/crawl/config.ts @@ -7,8 +7,8 @@ import { DEFAULT_TRACKER_HOSTS } from './violations.js' export const COOKIE_CRAWL_SLUG = 'cookie-crawl' export const COOKIE_CRAWL_PATH = '/ipal/cookie-crawl' export const COOKIE_CRAWL_RESULTS_PATH = '/ipal/cookie-crawl/results' -export const COOKIE_SCAN_URL_ENV = 'IPAL_COOKIE_SCAN_URL' -export const COOKIE_SCAN_TOKEN_ENV = 'IPAL_COOKIE_SCAN_TOKEN' +export const COOKIE_SCAN_URL_ENV = 'IAPL_COOKIE_SCAN_URL' +export const COOKIE_SCAN_TOKEN_ENV = 'IAPL_COOKIE_SCAN_TOKEN' /** A crawl still "running" after this long is treated as lost (the service never called back). */ export const CRAWL_TIMEOUT_MS = 30 * 60_000 diff --git a/src/modules/consent/scanner/crawl/endpoints.ts b/src/modules/consent/scanner/crawl/endpoints.ts index d292b6b..1c31d7c 100644 --- a/src/modules/consent/scanner/crawl/endpoints.ts +++ b/src/modules/consent/scanner/crawl/endpoints.ts @@ -122,7 +122,7 @@ export function buildCookieCrawlEndpoints({ if (!res.ok) {throw new Error(`scanner service answered HTTP ${res.status}`)} } catch (err) { const message = err instanceof Error ? err.message : String(err) - req.payload.logger.error(`[ipal] cookie crawl: could not start — ${message}`) + req.payload.logger.error(`[iapl] cookie crawl: could not start — ${message}`) await write(req, { error: 'The checking service could not be reached. Please try again later.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' }) return Response.json({ error: 'service_unreachable', ok: false }, { status: 502 }) } @@ -155,7 +155,7 @@ export function buildCookieCrawlEndpoints({ return Response.json({ ok: true }) } catch (err) { const message = err instanceof Error ? err.message : String(err) - req.payload.logger.error(`[ipal] cookie crawl: saving the result failed — ${message}`) + req.payload.logger.error(`[iapl] cookie crawl: saving the result failed — ${message}`) await write(req, { error: 'The result could not be saved. Please run the check again.', finishedAt: new Date().toISOString(), jobId: null, status: 'failed' }) return Response.json({ ok: false }, { status: 500 }) } diff --git a/src/modules/consent/scanner/crawl/notify.ts b/src/modules/consent/scanner/crawl/notify.ts index df10280..01c8ea8 100644 --- a/src/modules/consent/scanner/crawl/notify.ts +++ b/src/modules/consent/scanner/crawl/notify.ts @@ -53,7 +53,7 @@ ${pending ? `

${esc(fill(t('emailPending'), { count: pending }))} hosts`. */ trackerHosts?: (defaults: string[]) => string[] diff --git a/src/modules/content/createMarkdownRenderer.ts b/src/modules/content/createMarkdownRenderer.ts index 5952715..f3f044e 100644 --- a/src/modules/content/createMarkdownRenderer.ts +++ b/src/modules/content/createMarkdownRenderer.ts @@ -208,7 +208,7 @@ export function createMarkdownRoute( const md = await render({ slug, locale, payload: await getCachedPayload() }) return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) }) } catch (err) { - console.warn('[ipal] createMarkdownRoute: render failed:', err) + console.warn('[iapl] createMarkdownRoute: render failed:', err) return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 }) } }, diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index af2c0e0..4f9e174 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -99,7 +99,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) = ) } catch (err) { // DB unreachable (build) or unexpected — empty result rather than 500. - console.warn('[ipal] createSearchRoute: search failed:', err) + console.warn('[iapl] createSearchRoute: search failed:', err) return Response.json( { count: 0, query, results: [] }, { headers: { 'cache-control': 'no-store' }, status: 200 }, diff --git a/src/modules/content/resolveNotFoundPage.ts b/src/modules/content/resolveNotFoundPage.ts index 88b4a3c..7ef0f84 100644 --- a/src/modules/content/resolveNotFoundPage.ts +++ b/src/modules/content/resolveNotFoundPage.ts @@ -51,7 +51,7 @@ export async function resolveNotFoundPage({ }) return (doc as null | Record) ?? null } catch (error) { - console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error) + console.warn('[iapl] resolveNotFoundPage: falling back to built-in 404 view:', error) return null } } diff --git a/src/modules/doctor/cli.ts b/src/modules/doctor/cli.ts index ccf9dd9..d1a1b87 100644 --- a/src/modules/doctor/cli.ts +++ b/src/modules/doctor/cli.ts @@ -6,8 +6,8 @@ import type { DoctorReport, DoctorSeverity } from './types.js' import { formatDriftTable, formatReport } from './format.js' import { runDoctor } from './run.js' -export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options] - Checks a site against the ipal-kit team rules and lists every gap with a fix hint. +export const DOCTOR_USAGE = `Usage: iapl-doctor [dir] [options] + Checks a site against the IAPL team rules and lists every gap with a fix hint. --json machine-readable report (schema 1) --md Markdown table (with --sites: rule × site) @@ -24,10 +24,10 @@ export const DOCTOR_USAGE = `Usage: ipal-doctor [dir] [options] --sites many projects, e.g. '../*-web' (read-only report; never a gate) Exit: 0 ok · 1 findings at or above --fail-on · 2 could not run · 3 a rule crashed - Silence a rule with a reason in ipal-doctor.json — docs/doctor.md` + Silence a rule with a reason in iapl-doctor.json — docs/doctor.md` /** - * Whether this run stores first-seen dates in ipal-doctor.json: not with --sites or --json, and + * Whether this run stores first-seen dates in iapl-doctor.json: not with --sites or --json, and * never when CI is set (a CI run must not change a tracked file). */ export function shouldWriteSeen(args: { json?: boolean; sites?: unknown }, env: Record = process.env): boolean { @@ -113,18 +113,18 @@ export async function runDoctorCli(argv: string[], { cwd = process.cwd(), log = } const args = parseDoctorArgs(argv) if (typeof args === 'string') { - console.error(`ipal-doctor: ${args}\n\n${DOCTOR_USAGE}`) + console.error(`iapl-doctor: ${args}\n\n${DOCTOR_USAGE}`) return 2 } const dirs = args.sites ? expandSites(args.sites, cwd) : [resolve(cwd, args.dir)] if (!dirs.length) { - console.error(`ipal-doctor: no folder matches ${args.sites}`) + console.error(`iapl-doctor: no folder matches ${args.sites}`) return 2 } const reports: DoctorReport[] = [] for (const dir of dirs) { if (!existsSync(join(dir, 'package.json'))) { - console.error(`ipal-doctor: ${dir} is not a project root (no package.json)`) + console.error(`iapl-doctor: ${dir} is not a project root (no package.json)`) if (!args.sites) {return 2} continue } diff --git a/src/modules/doctor/format.ts b/src/modules/doctor/format.ts index 06bf319..2ee607e 100644 --- a/src/modules/doctor/format.ts +++ b/src/modules/doctor/format.ts @@ -9,7 +9,7 @@ const summaryLine = (r: DoctorReport) => /** Human-readable report: header, findings worst first with fix and doc link, summary. */ export function formatReport(report: DoctorReport, { color = false }: { color?: boolean } = {}): string { const c = (sev: DoctorSeverity, text: string) => (color ? `${COLOR[sev]}${text}\x1b[0m` : text) - const lines = [`ipal-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · ipal-kit ${report.site.plugin ?? 'not installed'}`, ''] + const lines = [`iapl-doctor ${report.rulesVersion} — ${report.site.path}`, `site: ${report.site.domain ?? '(no domain)'} · IAPL ${report.site.plugin ?? 'not installed'}`, ''] const active = report.findings.filter((f) => !f.silenced) if (!active.length) {lines.push('No findings.')} for (const f of active) { @@ -24,7 +24,7 @@ export function formatReport(report: DoctorReport, { color = false }: { color?: for (const f of silenced) {lines.push(` - ${f.rule}: ${f.message} — ${f.reason}`)} } if (report.skipped.length) {lines.push('', `Not run: ${report.skipped.join(', ')} (--url, --deep, or without --offline)`)} - lines.push('', `ipal-doctor: ${summaryLine(report)}`) + lines.push('', `iapl-doctor: ${summaryLine(report)}`) return lines.join('\n') } diff --git a/src/modules/doctor/probe.ts b/src/modules/doctor/probe.ts index 55188d9..f30a715 100644 --- a/src/modules/doctor/probe.ts +++ b/src/modules/doctor/probe.ts @@ -1,9 +1,9 @@ import type { SanitizedConfig } from 'payload' /** - * ipal-doctor --deep: run inside the project by `pnpm exec payload run `. + * iapl-doctor --deep: run inside the project by `pnpm exec payload run `. * Read-only Local API counts (collectDoctorStatus), an exact import-map comparison and the - * project's own env rules. Prints one line `IPAL_DOCTOR_STATUS ` and exits. + * project's own env rules. Prints one line `IAPL_DOCTOR_STATUS ` and exits. * * The import map is generated into a temporary file NEXT TO the committed one (the imports are * relative to it), compared, then removed. Nothing else is written. @@ -47,9 +47,9 @@ async function main() { Object.assign(status, await collectDoctorStatus(payload)) // The doctor passes the committed import map it found (relative to the project root). - const committed = config.admin?.importMap?.importMapFile ?? (process.env.IPAL_DOCTOR_IMPORT_MAP ? join(root, process.env.IPAL_DOCTOR_IMPORT_MAP) : '') + const committed = config.admin?.importMap?.importMapFile ?? (process.env.IAPL_DOCTOR_IMPORT_MAP ? join(root, process.env.IAPL_DOCTOR_IMPORT_MAP) : '') if (committed && existsSync(committed)) { - const temp = join(dirname(committed), 'importMap.ipal-doctor.tmp.js') + const temp = join(dirname(committed), 'importMap.iapl-doctor.tmp.js') try { const copy = { ...config, admin: { ...config.admin, importMap: { ...config.admin.importMap, importMapFile: temp } } } await generateImportMap(copy, { force: true, log: false }) @@ -67,5 +67,5 @@ try { } catch (err) { status.error = err instanceof Error ? (err.message.split('\n')[0] ?? 'failed') : String(err) } -process.stdout.write(`IPAL_DOCTOR_STATUS ${JSON.stringify(status)}\n`) +process.stdout.write(`IAPL_DOCTOR_STATUS ${JSON.stringify(status)}\n`) process.exit(0) diff --git a/src/modules/doctor/project.ts b/src/modules/doctor/project.ts index 21e0421..fd3da58 100644 --- a/src/modules/doctor/project.ts +++ b/src/modules/doctor/project.ts @@ -7,7 +7,7 @@ import { databaseNameFromUri } from '../env/databaseName.js' /** Everything a rule may read about the project. Files only — nothing is written. */ export type DoctorContext = { - /** Keys from `ipal-audit-skip: — ` lines in AGENTS.md, with the reason. */ + /** Keys from `iapl-audit-skip: — ` lines in AGENTS.md, with the reason. */ auditSkips: Map config: DoctorConfig configError: null | string @@ -75,11 +75,11 @@ export function bareHost(value: string): string { const isLocalHost = (host: string) => /^(?:localhost|127\.0\.0\.1|\[?::1\]?|0\.0\.0\.0)$|^[^.]+$/.test(host) -/** Reads `ipal-audit-skip: a, b — reason` lines (AGENT.md §0b). */ +/** Reads `iapl-audit-skip: a, b — reason` lines (AGENT.md §0b). */ export function readAuditSkips(agents: string): Map { const out = new Map() for (const line of agents.split('\n')) { - const m = line.match(/^[-* ]*ipal-audit-skip:(.*)$/i) + const m = line.match(/^[-* ]*iapl-audit-skip:(.*)$/i) if (!m) {continue} const [keys = '', ...rest] = m[1].trim().split(/\s+—\s+|\s+-\s+/) const reason = rest.join(' — ').trim() @@ -89,14 +89,14 @@ export function readAuditSkips(agents: string): Map { } export function loadDoctorConfig(root: string): { config: DoctorConfig; error: null | string } { - const file = join(root, 'ipal-doctor.json') + const file = join(root, 'iapl-doctor.json') if (!existsSync(file)) {return { config: {}, error: null }} try { const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'ipal-doctor.json must hold an object' }} + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {return { config: {}, error: 'iapl-doctor.json must hold an object' }} return { config: parsed as DoctorConfig, error: null } } catch (err) { - return { config: {}, error: `ipal-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` } + return { config: {}, error: `iapl-doctor.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` } } } @@ -161,7 +161,7 @@ export function createDoctorContext(options: ProjectOptions): DoctorContext { } const src = exists('src') ? 'src/' : '' - // Domain: ipal-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6). + // Domain: iapl-doctor.json → a non-local NEXT_PUBLIC_SERVER_URL → the folder name minus -web (docs: D6). const urls = [env.local?.NEXT_PUBLIC_SERVER_URL, env.example?.NEXT_PUBLIC_SERVER_URL].filter(Boolean).map((u) => bareHost(u!)) const fromDir = basename(root).replace(/-web$/, '') // The folder name (`intecioncom-web`) is already the domain without dots — enough for the database names. diff --git a/src/modules/doctor/rules/agents.ts b/src/modules/doctor/rules/agents.ts index a78ab0e..a4552f8 100644 --- a/src/modules/doctor/rules/agents.ts +++ b/src/modules/doctor/rules/agents.ts @@ -19,7 +19,7 @@ export function hashDir(dir: string): string { return hash.digest('hex') } -/** What `ipal-skills` would change in a skills folder: missing, stale (different content) and retired skills. */ +/** What `iapl-skills` would change in a skills folder: missing, stale (different content) and retired skills. */ export function planSkills({ dest, source }: { dest: string; source: string }): { missing: string[]; retired: string[]; stale: string[] } { const ls = (d: string) => { try { @@ -42,7 +42,7 @@ export const agentRules: DoctorRule[] = [ id: 'agents-md', check: (ctx) => { const agents = ctx.read('AGENTS.md') - if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec ipal-skills', message: 'no AGENTS.md', severity: 'error' }]} + if (!agents) {return [{ fix: 'AGENT.md §13 template, then pnpm exec iapl-skills', message: 'no AGENTS.md', severity: 'error' }]} const out: RuleFinding[] = [] const parts = agents.split(/^## Project decisions[ \t]*$/m) if (parts.length < 2) {out.push({ file: 'AGENTS.md', fix: 'add "## Project decisions" with the architecture answers (AGENT.md "Ask before you build")', message: 'AGENTS.md has no "## Project decisions" section', severity: 'error' })} @@ -50,12 +50,12 @@ export const agentRules: DoctorRule[] = [ const body = parts[1].split(/^## /m)[0].replace(//g, '') if (!/^\s*[-*] +\S/m.test(body)) {out.push({ file: 'AGENTS.md', message: '"## Project decisions" is empty', severity: 'warning' })} } - const pointer = agents.match(/[\s\S]*?## ipal-kit ([\w.-]+) — agent guide[\s\S]*?/) - if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: 'no ipal-kit pointer block in AGENTS.md', severity: 'warning' })} - else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec ipal-skills', message: `the pointer block names ipal-kit ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })} + const pointer = agents.match(/[\s\S]*?## IAPL ([\w.-]+) — agent guide[\s\S]*?/) + if (!pointer) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: 'no IAPL pointer block in AGENTS.md', severity: 'warning' })} + else if (ctx.pluginVersion && pointer[1] !== ctx.pluginVersion) {out.push({ file: 'AGENTS.md', fix: 'pnpm exec iapl-skills', message: `the pointer block names IAPL ${pointer[1]}, installed ${ctx.pluginVersion}`, severity: 'warning' })} const claude = ctx.read('CLAUDE.md') - if (!claude) {out.push({ fix: 'pnpm exec ipal-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })} - else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })} + if (!claude) {out.push({ fix: 'pnpm exec iapl-skills (creates CLAUDE.md with @AGENTS.md)', message: 'no CLAUDE.md', severity: 'warning' })} + else if (!/^@AGENTS\.md\s*$/m.test(claude) && !claude.includes('')) {out.push({ file: 'CLAUDE.md', fix: 'add a line @AGENTS.md', message: 'CLAUDE.md neither imports AGENTS.md nor has the pointer block', severity: 'warning' })} return out }, docs: 'docs/agent/AGENT.md#13-agentsmd-template-for-a-project', @@ -66,8 +66,8 @@ export const agentRules: DoctorRule[] = [ id: 'skills-current', check: (ctx) => { const dest = ['.agents/skills', '.claude/skills'].find((d) => ctx.list(d).some((n) => n.startsWith('ipal-'))) - if (!dest) {return [{ fix: 'pnpm exec ipal-skills', message: 'no ipal-* skills in .agents/skills or .claude/skills', severity: 'error' }]} - // Compare with the skills the project's installed plugin ships (what `pnpm exec ipal-skills` copies). + if (!dest) {return [{ fix: 'pnpm exec iapl-skills', message: 'no iapl-* skills in .agents/skills or .claude/skills', severity: 'error' }]} + // Compare with the skills the project's installed plugin ships (what `pnpm exec iapl-skills` copies). const installedSkills = join(ctx.root, 'node_modules/@intecion/ipal-kit/docs/agent/skills') const source = ctx.exists('node_modules/@intecion/ipal-kit/docs/agent/skills') ? installedSkills : join(ctx.packageRoot, 'docs/agent/skills') const plan = planSkills({ dest: join(ctx.root, dest), source }) @@ -76,7 +76,7 @@ export const agentRules: DoctorRule[] = [ plan.missing.length ? `missing ${plan.missing.join(', ')}` : '', plan.retired.length ? `retired ${plan.retired.join(', ')}` : '', ].filter(Boolean) - return parts.length ? [{ file: dest, fix: 'pnpm exec ipal-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : [] + return parts.length ? [{ file: dest, fix: 'pnpm exec iapl-skills and commit', message: `skills differ from the installed ipal-kit: ${parts.join('; ')}`, severity: 'warning' }] : [] }, docs: 'docs/agent/AGENT.md#14-skills-antigravity-claude-code-cursor', group: 'agents', diff --git a/src/modules/doctor/rules/blocks.ts b/src/modules/doctor/rules/blocks.ts index a0c9b38..e4c2077 100644 --- a/src/modules/doctor/rules/blocks.ts +++ b/src/modules/doctor/rules/blocks.ts @@ -109,7 +109,7 @@ export const blockRules: DoctorRule[] = [ const iface = config.match(/\binterfaceName\s*:\s*['"](\w+)['"]/)?.[1] if (!slug) {continue} if ((librarySlugs.has(slug) || (iface && libraryInterfaces.has(iface))) && !overrides.has(slug)) { - out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec ipal-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' }) + out.push({ file, fix: 'use the library block (+ variant), or eject it (pnpm exec iapl-blocks eject) and pass it in createBlockRegistry({ components })', message: `project block "${slug}" duplicates a library block`, severity: 'warning' }) } } return out diff --git a/src/modules/doctor/rules/env.ts b/src/modules/doctor/rules/env.ts index d594398..06c467c 100644 --- a/src/modules/doctor/rules/env.ts +++ b/src/modules/doctor/rules/env.ts @@ -16,7 +16,7 @@ export const envRules: DoctorRule[] = [ check: (ctx) => { const out: RuleFinding[] = [] if (!ctx.domain) { - return [{ fix: 'add "domain": "" to ipal-doctor.json', message: 'no site domain (ipal-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }] + return [{ fix: 'add "domain": "" to iapl-doctor.json', message: 'no site domain (iapl-doctor.json "domain", or a non-local NEXT_PUBLIC_SERVER_URL) — database names not checked', severity: 'warning' }] } const { dev, prod } = databaseNamesFor(ctx.domain) for (const [file, env] of [['.env', ctx.env.local], ['.env.example', ctx.env.example]] as const) { @@ -51,17 +51,17 @@ export const envRules: DoctorRule[] = [ const file = ctx.exists(`${ctx.src}instrumentation.ts`) ? `${ctx.src}instrumentation.ts` : 'instrumentation.ts' const code = stripComments(ctx.read(file)) if (!/assertEnv\s*\(/.test(code)) { - return [{ file, fix: "register(): assertEnv(ipalEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(ipalEnvRules(…))', severity: 'error' }] + return [{ file, fix: "register(): assertEnv(iaplEnvRules({ storage: true, ipHeader: true })) from '@intecion/ipal-kit/env'", message: 'instrumentation.ts does not call assertEnv(iaplEnvRules(…))', severity: 'error' }] } const out: RuleFinding[] = [] - if (!/ipalEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without ipalEnvRules — the plugin variables are not checked', severity: 'warning' })} + if (!/iaplEnvRules\s*\(/.test(code)) {out.push({ file, message: 'assertEnv without iaplEnvRules — the plugin variables are not checked', severity: 'warning' })} if (/from\s+['"]@intecion\/ipal-kit['"]/.test(code)) {out.push({ file, fix: "import from '@intecion/ipal-kit/env'", message: 'instrumentation.ts imports the package root (Edge build breaks)', severity: 'error' })} const cfg = stripComments(ctx.read(configFile(ctx) ?? '')) const flag = (name: string) => new RegExp(`\\b${name}\\s*:`).test(code) - if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'ipalEnvRules({ storage: true })', message: 'R2 is wired but ipalEnvRules has no storage flag', severity: 'warning' })} - if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'ipalEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but ipalEnvRules has no cookieCrawl flag', severity: 'warning' })} - if (!flag('ipHeader')) {out.push({ file, fix: 'ipalEnvRules({ ipHeader: true })', message: 'ipalEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })} - if (!flag('databaseName')) {out.push({ file, fix: "ipalEnvRules({ databaseName: { domain: '' } })", message: 'ipalEnvRules has no databaseName check', severity: 'info' })} + if (/buildR2Storage/.test(cfg) && !flag('storage')) {out.push({ file, fix: 'iaplEnvRules({ storage: true })', message: 'R2 is wired but iaplEnvRules has no storage flag', severity: 'warning' })} + if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg) && !flag('cookieCrawl')) {out.push({ file, fix: 'iaplEnvRules({ cookieCrawl: true })', message: 'cookieScanner.crawl is on but iaplEnvRules has no cookieCrawl flag', severity: 'warning' })} + if (!flag('ipHeader')) {out.push({ file, fix: 'iaplEnvRules({ ipHeader: true })', message: 'iaplEnvRules has no ipHeader flag — rate limits trust no client-IP header', severity: 'warning' })} + if (!flag('databaseName')) {out.push({ file, fix: "iaplEnvRules({ databaseName: { domain: '' } })", message: 'iaplEnvRules has no databaseName check', severity: 'info' })} return out }, docs: 'docs/env.md', @@ -74,15 +74,15 @@ export const envRules: DoctorRule[] = [ if (!ctx.env.example) {return [{ fix: 'add .env.example (names, placeholder values)', message: 'no .env.example', severity: 'error' }]} const out: RuleFinding[] = [] const cfg = stripComments(ctx.read(configFile(ctx) ?? '')) - const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IPAL_IP_HEADER'] + const want = ['DATABASE_URI', 'PAYLOAD_SECRET', 'NEXT_PUBLIC_SERVER_URL', 'IAPL_IP_HEADER'] if (/buildR2Storage/.test(cfg) && !ctx.auditSkips.has('r2')) {want.push('R2_BUCKET', 'R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_PUBLIC_URL')} - if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IPAL_COOKIE_SCAN_URL', 'IPAL_COOKIE_SCAN_TOKEN')} + if (/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(cfg)) {want.push('IAPL_COOKIE_SCAN_URL', 'IAPL_COOKIE_SCAN_TOKEN')} const missing = want.filter((v) => !(v in ctx.env.example!)) if (missing.length) {out.push({ file: '.env.example', fix: 'add the names (empty or placeholder values)', message: `.env.example lacks ${missing.join(', ')}`, severity: 'warning' })} // A real-looking credential in a committed file. const creds = (ctx.env.example.DATABASE_URI ?? '').match(/^[a-z+]+:\/\/([^@/]+)@/i)?.[1] if (creds && !PLACEHOLDER.test(creds)) {out.push({ file: '.env.example', fix: 'replace with USER:PASS', message: 'DATABASE_URI in .env.example carries credentials', severity: 'error' })} - for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IPAL_DOCTOR_TOKEN']) { + for (const key of ['PAYLOAD_SECRET', 'R2_SECRET_ACCESS_KEY', 'GRAPH_CLIENT_SECRET', 'IAPL_DOCTOR_TOKEN']) { const value = ctx.env.example[key] if (value && value.length >= 16 && !PLACEHOLDER.test(value)) {out.push({ file: '.env.example', fix: `leave ${key} empty`, message: `${key} in .env.example has a value`, severity: 'error' })} } diff --git a/src/modules/doctor/rules/layout.ts b/src/modules/doctor/rules/layout.ts index 631dd28..9ab043e 100644 --- a/src/modules/doctor/rules/layout.ts +++ b/src/modules/doctor/rules/layout.ts @@ -49,7 +49,7 @@ const has = (ctx: DoctorContext, dir: string, names: string[]) => names.some((n) /** * The frontend folder, found by structure rather than by name (a route group's name never reaches the URL): - * `ipal-doctor.json` `layout.frontend` wins; else every `app/()` except `(payload)`, and `app` itself, + * `iapl-doctor.json` `layout.frontend` wins; else every `app/()` except `(payload)`, and `app` itself, * holding the catch-all page — one with a `[locale]` page first. No match → `app/(frontend)` (the convention). */ export function findFrontend(ctx: DoctorContext): FrontendLayout { @@ -67,7 +67,7 @@ export function findFrontend(ctx: DoctorContext): FrontendLayout { return { ambiguous: best.filter((g) => g !== dir), dir, multi: localized.length > 0 } } -/** Files AGENT.md §3 expects — each as its accepted names — with the `ipal-audit-skip` key that drops it. */ +/** Files AGENT.md §3 expects — each as its accepted names — with the `iapl-audit-skip` key that drops it. */ function requiredFiles(ctx: DoctorContext, frontend: FrontendLayout): Array<[string[], string?]> { const fe = frontend.multi ? `${frontend.dir}/[locale]` : frontend.dir const ts = (base: string) => [`${base}.ts`, `${base}.tsx`] @@ -114,14 +114,14 @@ export const layoutRules: DoctorRule[] = [ const frontend = findFrontend(ctx) const out: RuleFinding[] = [] if (frontend.missingOverride) { - out.push({ file: 'ipal-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' }) + out.push({ file: 'iapl-doctor.json', fix: 'point layout.frontend at the folder that holds the pages, e.g. "src/app/(site)"', message: `layout.frontend "${frontend.missingOverride}" does not exist`, severity: 'error' }) } if (frontend.ambiguous.length) { - out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in ipal-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' }) + out.push({ fix: `set "layout": { "frontend": "${ctx.src}${frontend.dir}" } in iapl-doctor.json (or the other one)`, message: `several folders hold the site's pages: ${[frontend.dir, ...frontend.ambiguous].map((d) => `${ctx.src}${d}`).join(', ')} — checked ${ctx.src}${frontend.dir}`, severity: 'warning' }) } const missing = requiredFiles(ctx, frontend).filter(([names, key]) => !(key && ctx.auditSkips.has(key)) && !names.some((n) => ctx.exists(`${ctx.src}${n}`))) if (missing.length) { - out.push({ fix: 'the ipal-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' }) + out.push({ fix: 'the iapl-setup skill (stage named by the file)', message: `missing: ${missing.map(([names]) => `${ctx.src}${names[0]}`).join(', ')}`, severity: 'error' }) } return out }, @@ -149,7 +149,7 @@ export const layoutRules: DoctorRule[] = [ const allow = new Set([...(ctx.config.layout?.allow ?? []), ...DEFAULT_SRC_ALLOW]) const extra = ctx.list('src').filter((n) => !allow.has(n) && !n.startsWith('.')) return extra.length - ? [{ fix: 'move into the convention, or add to ipal-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }] + ? [{ fix: 'move into the convention, or add to iapl-doctor.json "layout": { "allow": [...] }', message: `src/ entries outside the convention: ${extra.join(', ')}`, severity: 'info' }] : [] }, docs: 'docs/agent/AGENT.md#3-project-structure-and-naming', @@ -236,7 +236,7 @@ export const layoutRules: DoctorRule[] = [ if (ctx.deep?.importMapCurrent === false) {out.push({ file: ctx.importMap, fix: 'pnpm payload generate:importmap and commit', message: 'the committed import map differs from a freshly generated one', severity: 'error' })} return out }, - docs: 'docs/agent/skills/ipal-reference/SKILL.md', + docs: 'docs/agent/skills/iapl-reference/SKILL.md', group: 'layout', source: 'static', }, diff --git a/src/modules/doctor/rules/live.ts b/src/modules/doctor/rules/live.ts index ff99b86..cc31275 100644 --- a/src/modules/doctor/rules/live.ts +++ b/src/modules/doctor/rules/live.ts @@ -19,7 +19,7 @@ export function createLiveFetcher(url: string, options: { adminRoute?: string; s (async () => { try { const res = await fetch(base + path, { - headers: { 'user-agent': 'ipal-doctor (+https://intecion.com; read-only)' }, + headers: { 'user-agent': 'iapl-doctor (+https://intecion.com; read-only)' }, redirect: init.redirect ?? 'follow', signal: AbortSignal.timeout(20_000), }) @@ -62,8 +62,8 @@ export const liveRules: DoctorRule[] = [ const home = await ctx.live!.fetch('/') if (!home.status) {return []} const isNoindex = noindex(home.text, home.headers.get('x-robots-tag')) - if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IPAL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]} - return isNoindex ? [{ fix: 'unset IPAL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : [] + if (ctx.live!.staging) {return isNoindex ? [] : [{ fix: 'IAPL_NOINDEX=1 on the staging app', message: 'the staging site is indexable', severity: 'error' }]} + return isNoindex ? [{ fix: 'unset IAPL_NOINDEX on production and redeploy', message: 'the production home page is noindex', severity: 'error' }] : [] }, docs: 'docs/seo.md', group: 'live', @@ -72,9 +72,9 @@ export const liveRules: DoctorRule[] = [ { id: 'live-seo', check: async (ctx) => { - // ipal-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP. - const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-seo-check/scripts/seo-check.mjs') - if (!existsSync(script)) {return [{ message: 'ipal-seo-check not found', severity: 'warning' }]} + // iapl-seo-check of the doctor's own version: robots, sitemap, canonical, hreflang, noindex, JSON-LD, llms, MCP. + const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-seo-check/scripts/seo-check.mjs') + if (!existsSync(script)) {return [{ message: 'iapl-seo-check not found', severity: 'warning' }]} const home = await ctx.live!.fetch('/', { redirect: 'manual' }) if (!home.status) {return []} const res = run(process.execPath, [script, ctx.live!.url, '--max', '10'], ctx.root, 300_000) @@ -84,10 +84,10 @@ export const liveRules: DoctorRule[] = [ const items = line.items.length ? `: ${line.items.slice(0, 3).join('; ')}${line.items.length > 3 ? ` … +${line.items.length - 3}` : ''}` : '' out.push({ fix: line.rule, message: `${line.title}${items}`, rule: `live-seo:${titleSlug(line.title.replace(/[\d/]+/g, ' '))}`, severity: line.level }) } - if (res.code === 2) {out.push({ message: `ipal-seo-check: ${res.stderr.trim()}`, severity: 'error' })} + if (res.code === 2) {out.push({ message: `iapl-seo-check: ${res.stderr.trim()}`, severity: 'error' })} return out }, - docs: 'docs/agent/skills/ipal-seo-check/SKILL.md', + docs: 'docs/agent/skills/iapl-seo-check/SKILL.md', group: 'live', source: 'live', }, diff --git a/src/modules/doctor/rules/security.ts b/src/modules/doctor/rules/security.ts index fe52202..ad49f77 100644 --- a/src/modules/doctor/rules/security.ts +++ b/src/modules/doctor/rules/security.ts @@ -104,9 +104,9 @@ export const securityRules: DoctorRule[] = [ const code = cfg(ctx) const twoFactor = code.match(/twoFactor\s*:([^\n]*)/)?.[1] ?? '' if (/\?\s*false\b|:\s*false\b|&&/.test(twoFactor) && /payloadTotp/.test(twoFactor)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor: { issuer, plugin: payloadTotp } without a switch', message: '2FA can be turned off at runtime (a condition on twoFactor)', severity: 'warning' })} - if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ twoFactor: { issuer: '', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })} + if (!/twoFactor\s*:[^\n]*payloadTotp|twoFactor\s*:\s*\{[\s\S]*?plugin\s*:\s*payloadTotp/.test(code)) {out.push({ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ twoFactor: { issuer: '', plugin: payloadTotp } })", message: '2FA is not on (twoFactor with plugin: payloadTotp)', severity: 'error' })} else if (!ctx.installed('@clocklimited/payload-2fa')) {out.push({ fix: 'pnpm add @clocklimited/payload-2fa', message: '@clocklimited/payload-2fa is not installed', severity: 'error' })} - if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in ipal-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })} + if (/requireSetup\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'remove twoFactor.requireSetup: false (or record the reason in iapl-doctor.json)', message: 'twoFactor.requireSetup is off: an account that has not set 2FA up opens everything with its password alone', severity: 'warning' })} if (/windowHours\s*:\s*(?:false|0)\b/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, fix: 'twoFactor.requireSetup.windowHours: 72 (the default)', message: 'no time limit for 2FA setup: an account that never sets it up can be taken over with its password at any time', severity: 'info' })} // Postgres / SQLite: the 2FA collection has the column `totp_setup_from` (whenever 2FA is on). Without a // migration that adds it, every query on the collection fails in production — nobody can log in. @@ -146,12 +146,12 @@ export const securityRules: DoctorRule[] = [ id: 'access-missing', check: (ctx) => { const code = cfg(ctx) - if (!/ipalKit\s*\(/.test(code)) {return []} + if (!/iapl\s*\(/.test(code)) {return []} // `access: { authCollection | defaultRole | … }`, an empty `access: {}`, or a variable whose name says so const set = /\baccess\s*:\s*\{\}/.test(code.replace(/\s+/g, '')) || /\baccess\s*:\s*\{[^{}]*\b(?:authCollection|defaultRole|authAccess|firstUserAdmin|staffCollections|panelRole|selfRegistration|password)\b/.test(code) || /\baccess\s*:\s*\w*[aA]ccess\w*\s*[,}]/.test(code) return set ? [] - : [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "ipalKit({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in ipal-doctor.json", message: 'ipalKit has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }] + : [{ file: configFile(ctx) ?? 'payload.config.ts', fix: "iapl({ access: { authCollection: 'users' } }) — roles admin > editor > user; or record the reason in iapl-doctor.json", message: 'iapl has no `access` option: there are no roles, so every account that can log in to the panel is an admin', severity: 'warning' }] }, docs: 'docs/access.md', group: 'security', @@ -175,7 +175,7 @@ export const securityRules: DoctorRule[] = [ id: 'open-signup', check: (ctx) => (ctx.deep?.openSignUp ?? []).map((slug) => ({ - fix: `intended (a customer zone)? silence it with a reason in ipal-doctor.json; otherwise give "${slug}" a create rule`, + fix: `intended (a customer zone)? silence it with a reason in iapl-doctor.json; otherwise give "${slug}" a create rule`, message: `sign-up is open on "${slug}": an anonymous request can create an account there`, severity: 'info' as const, })), @@ -261,7 +261,7 @@ export const securityRules: DoctorRule[] = [ check: (ctx) => { const code = cfg(ctx) if (!/cookieScanner\s*:/.test(code) || /cookieScanner\s*:\s*false/.test(code)) { - return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'ipalKit({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }] + return [{ file: configFile(ctx) ?? 'payload.config.ts', fix: 'iapl({ cookieScanner: { crawl: true } }) + generate:importmap', message: 'the cookie scanner is off', severity: 'error' }] } const out: RuleFinding[] = [] if (!/cookieScanner\s*:\s*\{[^}]*\bcrawl\s*:\s*(?!false)/.test(code)) {out.push({ fix: 'cookieScanner: { crawl: true } (shared cookie-crawler service)', message: 'cookie scanner without crawl — no scheduled site check', severity: 'info' })} @@ -277,7 +277,7 @@ export const securityRules: DoctorRule[] = [ check: async (ctx) => { const out: RuleFinding[] = [] const code = cfg(ctx) - if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need ipal-kit ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })} + if (lt(ctx.pluginVersion, '1.14.5')) {out.push({ message: `admin link previews (adminMeta) need IAPL ≥ 1.14.5 (installed ${ctx.pluginVersion ?? 'none'})`, severity: 'warning' })} if (/adminMeta\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'adminMeta: false — the panel has no link preview and no noindex from the plugin', severity: 'warning' })} if (/agency\s*:\s*false/.test(code)) {out.push({ file: configFile(ctx) ?? undefined, message: 'agency: false — no technology credit', severity: 'warning' })} if (ctx.live && !out.length) { diff --git a/src/modules/doctor/rules/seeds.ts b/src/modules/doctor/rules/seeds.ts index 66811ae..6342dc6 100644 --- a/src/modules/doctor/rules/seeds.ts +++ b/src/modules/doctor/rules/seeds.ts @@ -32,20 +32,20 @@ export const seedRules: DoctorRule[] = [ for (const [name, command] of Object.entries(ctx.pkg.scripts ?? {})) { if (!/seed/i.test(name)) {continue} if (/fresh|reset/i.test(name)) {out.push({ file: 'package.json', fix: 'remove it — seeds never delete (seeding.md)', message: `script "${name}" re-creates content from scratch`, severity: 'error' })} - if (/IPAL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IPAL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })} + if (/IAPL_SEED_ALLOW_FULL=1/.test(command)) {out.push({ file: 'package.json', fix: 'set IAPL_SEED_ALLOW_FULL=1 by hand for one run, only with the owner\'s OK', message: `script "${name}" switches the full-seed guard off`, severity: 'error' })} const entry = command.match(/(?:^|\s)([\w./@-]+\.[cm]?[jt]s)(?:\s|$)/)?.[1]?.replace(/^\.\//, '') if (!entry) {continue} if (!ctx.exists(entry)) {out.push({ file: 'package.json', message: `script "${name}" runs ${entry}, which does not exist`, severity: 'warning' }); continue} const files = seedFiles(ctx, entry) const code = files.map((f) => stripComments(ctx.read(f))).join('\n') - if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the ipal-kit seed helper`, severity: 'warning' })} + if (!/createSeeder\s*\(/.test(code)) {out.push({ file: entry, fix: "createSeeder(payload) from '@intecion/ipal-kit/seed' (only / SEED_ONLY, full-seed guard)", message: `script "${name}" does not use the IAPL seed helper`, severity: 'warning' })} const deleting = files.filter((f) => DELETES.test(stripComments(ctx.read(f)))) if (deleting.length) {out.push({ file: deleting[0], fix: 'seeds never delete — an editor removes records in the panel (seeding.md)', message: `script "${name}" deletes records (${deleting.join(', ')})`, severity: 'error' })} - if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IPAL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })} + if (/guard\s*:\s*false|allowFull\s*:\s*true/.test(code)) {out.push({ file: entry, fix: 'keep the guard; IAPL_SEED_ALLOW_FULL=1 for one run with the owner\'s OK', message: `script "${name}" turns the full-seed guard off in code`, severity: 'error' })} if (ctx.launched && /createSeeder\s*\(/.test(code) && !/\bonly\s*:/.test(code)) {out.push({ file: entry, fix: 'run it with SEED_ONLY="pages:,global:" or pass only: [...] (seeding.md → after launch)', message: `script "${name}" has no record list — after launch every run needs SEED_ONLY`, severity: 'warning' })} } for (const file of ['.env.example', '.env.production']) { - if (/^\s*IPAL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IPAL_SEED_ALLOW_FULL=1`, severity: 'error' })} + if (/^\s*IAPL_SEED_ALLOW_FULL\s*=\s*1/m.test(ctx.read(file))) {out.push({ file, message: `${file} sets IAPL_SEED_ALLOW_FULL=1`, severity: 'error' })} } return out }, diff --git a/src/modules/doctor/rules/tooling.ts b/src/modules/doctor/rules/tooling.ts index c69d9f0..2d62bd6 100644 --- a/src/modules/doctor/rules/tooling.ts +++ b/src/modules/doctor/rules/tooling.ts @@ -23,7 +23,7 @@ export function parseToolOutput(text: string): ToolLine[] { } /** - * ipal-audit titles that are a doctor rule of their own — the finding is reported under that id + * iapl-audit titles that are a doctor rule of their own — the finding is reported under that id * (one place per check: the audit script). Everything else lands under `audit`. */ export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [ @@ -37,7 +37,7 @@ export const AUDIT_RULE_MAP: Array<[RegExp, string]> = [ [/^middleware\.ts exists$/, 'layout-forbidden'], [/^barrel index\.ts$/, 'naming'], [/^hardcoded text in (blocks|components\/layout)$|^hardcoded Polish text in code$/, 'i18n-literals'], - [/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^ipal-tokens --check$/, 'blocks-tokens'], + [/^hex colors in (classes|inline styles)$|^design-token standard not wired$|^iapl-tokens --check$/, 'blocks-tokens'], [/^own block renderer switch$/, 'blocks-registry'], ] @@ -52,11 +52,11 @@ export const toolingRules: DoctorRule[] = [ id: 'audit', check: (ctx) => { // The audit script of the doctor's own version (the project's copy in .agents may be stale). - const script = join(ctx.packageRoot, 'docs/agent/skills/ipal-audit/scripts/audit.sh') - if (!existsSync(script)) {return [{ message: `ipal-audit not found (${script})`, severity: 'warning' }]} + const script = join(ctx.packageRoot, 'docs/agent/skills/iapl-audit/scripts/audit.sh') + if (!existsSync(script)) {return [{ message: `iapl-audit not found (${script})`, severity: 'warning' }]} if (!ctx.src) {return []} const res = run('bash', [script, '--quick'], ctx.root, 300_000) - if (res.code !== 0 && res.code !== 1) {return [{ message: `ipal-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]} + if (res.code !== 0 && res.code !== 1) {return [{ message: `iapl-audit --quick could not run (exit ${res.code}): ${res.stderr.trim().split('\n')[0] ?? ''}`, severity: 'warning' }]} const out: RuleFinding[] = [] for (const line of parseToolOutput(res.stdout)) { const mapped = AUDIT_RULE_MAP.find(([re]) => re.test(line.title))?.[1] @@ -76,7 +76,7 @@ export const toolingRules: DoctorRule[] = [ } return out }, - docs: 'docs/agent/skills/ipal-audit/SKILL.md', + docs: 'docs/agent/skills/iapl-audit/SKILL.md', group: 'audit', source: 'static', }, diff --git a/src/modules/doctor/rules/versions.ts b/src/modules/doctor/rules/versions.ts index 0062743..5506805 100644 --- a/src/modules/doctor/rules/versions.ts +++ b/src/modules/doctor/rules/versions.ts @@ -43,7 +43,7 @@ export const versionRules: DoctorRule[] = [ } return [] }, - docs: 'docs/agent/skills/ipal-upgrade/SKILL.md', + docs: 'docs/agent/skills/iapl-upgrade/SKILL.md', group: 'versions', source: 'static', }, @@ -145,12 +145,12 @@ export const versionRules: DoctorRule[] = [ const [a, b] = [parseVersion(ctx.pluginVersion)!, parseVersion(latest)!] const minorsBehind = a[0] < b[0] ? 99 : b[1] - a[1] return [{ - fix: `pnpm add ${PKG}@${latest} — then the ipal-upgrade skill`, + fix: `pnpm add ${PKG}@${latest} — then the iapl-upgrade skill`, message: `${PKG} ${ctx.pluginVersion} installed, ${latest} is out`, severity: minorsBehind >= 2 ? 'error' : 'warning', }] }, - docs: 'docs/agent/skills/ipal-upgrade/SKILL.md', + docs: 'docs/agent/skills/iapl-upgrade/SKILL.md', group: 'versions', source: 'registry', }, diff --git a/src/modules/doctor/run.ts b/src/modules/doctor/run.ts index abd706f..5f8c218 100644 --- a/src/modules/doctor/run.ts +++ b/src/modules/doctor/run.ts @@ -39,7 +39,7 @@ export const doctorRules: DoctorRule[] = [ ...deepRules, ] -/** `ipal-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */ +/** `iapl-audit-skip` keys (AGENTS.md) → doctor rules they silence (the audit script honours the rest itself). */ export const AUDIT_SKIP_RULES: Record = { csp: ['csp'], twofactor: ['2fa'], @@ -60,14 +60,14 @@ export type RunDoctorOptions = { /** The doctor's package root (bin/, docs/, dist/). */ packageRoot: string root: string - /** Extra rules (a project's own, `extraRules` in ipal-doctor.json are added too). */ + /** Extra rules (a project's own, `extraRules` in iapl-doctor.json are added too). */ rules?: DoctorRule[] skip?: string[] staging?: boolean today?: string - /** Live site; with IPAL_DOCTOR_TOKEN set (and no --deep) the deep rules read GET /api/ipal/doctor. */ + /** Live site; with IAPL_DOCTOR_TOKEN set (and no --deep) the deep rules read GET /api/ipal/doctor. */ url?: string - /** Store first-seen dates (CSP report-only) in ipal-doctor.json. Default: only outside CI. */ + /** Store first-seen dates (CSP report-only) in iapl-doctor.json. Default: only outside CI. */ writeSeen?: boolean } @@ -76,10 +76,10 @@ export function runDeepProbe(ctx: DoctorContext): DoctorStatus { const probe = join(ctx.packageRoot, 'dist/modules/doctor/probe.js') if (!existsSync(probe)) {return { error: `the probe is missing (${probe}) — build the plugin` }} const res = run('pnpm', ['exec', 'payload', 'run', probe], ctx.root, 300_000) - const line = res.stdout.split('\n').find((l) => l.startsWith('IPAL_DOCTOR_STATUS ')) + const line = res.stdout.split('\n').find((l) => l.startsWith('IAPL_DOCTOR_STATUS ')) if (!line) {return { error: `payload run gave no status (exit ${res.code}): ${(res.stderr || res.stdout).trim().split('\n').slice(-1)[0] ?? ''}` }} try { - return JSON.parse(line.slice('IPAL_DOCTOR_STATUS '.length)) as DoctorStatus + return JSON.parse(line.slice('IAPL_DOCTOR_STATUS '.length)) as DoctorStatus } catch { return { error: 'payload run printed an unreadable status' } } @@ -105,19 +105,19 @@ export function globToRegExp(glob: string): RegExp { const inFiles = (file: string | undefined, globs: string[] | undefined) => !globs?.length || (!!file && globs.some((g) => globToRegExp(g).test(file))) -/** Applies ipal-doctor.json `rules` and `ipal-audit-skip` lines: off (silenced, kept in JSON), severity, until. */ +/** Applies iapl-doctor.json `rules` and `iapl-audit-skip` lines: off (silenced, kept in JSON), severity, until. */ export function applySettings(findings: DoctorFinding[], ctx: DoctorContext): DoctorFinding[] { const settings = ctx.config.rules ?? {} const out: DoctorFinding[] = [] for (const [id, s] of Object.entries(settings)) { if (!s || typeof s !== 'object') {continue} - if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "" — an entry without one is ignored', message: `ipal-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })} - else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `ipal-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })} - else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `ipal-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })} + if (!s.reason?.trim()) {out.push({ fix: 'add "reason": "" — an entry without one is ignored', message: `iapl-doctor.json: rule "${id}" has no reason, so it is ignored`, rule: 'doctor-config', severity: 'error', source: 'static' })} + else if (s.severity && !SEVERITIES.includes(s.severity)) {out.push({ message: `iapl-doctor.json: rule "${id}" has an unknown severity "${s.severity}"`, rule: 'doctor-config', severity: 'error', source: 'static' })} + else if (s.until && ctx.today > s.until) {out.push({ fix: 'fix the finding, or extend "until" with a new reason', message: `iapl-doctor.json: the setting for "${id}" expired on ${s.until}`, rule: 'doctor-config', severity: 'warning', source: 'static' })} } const skips = new Map() for (const [key, reason] of ctx.auditSkips) { - for (const id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `ipal-audit-skip: ${key}`)} + for (const id of AUDIT_SKIP_RULES[key] ?? []) {skips.set(id, reason || `iapl-audit-skip: ${key}`)} } for (const f of findings) { const s = settings[f.rule] ?? settings[f.rule.split(':')[0]] @@ -152,8 +152,8 @@ export async function runDoctor(options: RunDoctorOptions): Promise= 32) {ctx.deep = await fetchDeepStatus(options.url, token)} @@ -182,9 +182,9 @@ export async function runDoctor(options: RunDoctorOptions): Promise f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'ipal-doctor.json'))) { + if (writeSeen && findings.some((f) => f.rule === 'csp' && /report-only/.test(f.message)) && !ctx.config.seen?.['csp-report-only'] && existsSync(join(root, 'iapl-doctor.json'))) { const current = loadDoctorConfig(root).config - writeFileSync(join(root, 'ipal-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`) + writeFileSync(join(root, 'iapl-doctor.json'), `${JSON.stringify({ ...current, seen: { ...current.seen, 'csp-report-only': ctx.today } }, null, 2)}\n`) } const final = applySettings(findings, ctx).sort((a, b) => Number(!!a.silenced) - Number(!!b.silenced) || RANK[a.severity] - RANK[b.severity]) diff --git a/src/modules/doctor/status.ts b/src/modules/doctor/status.ts index a548ad3..244d9c8 100644 --- a/src/modules/doctor/status.ts +++ b/src/modules/doctor/status.ts @@ -21,7 +21,7 @@ export function pluginVersion(): string { type CollectionLike = { fields?: Array<{ name?: string }>; slug: string } /** - * Read-only counts for ipal-doctor's deep rules: users without TOTP, cookies waiting for approval, + * Read-only counts for iapl-doctor's deep rules: users without TOTP, cookies waiting for approval, * the versions. Counts and booleans only — never names, e-mails or values. */ export async function collectDoctorStatus(payload: BasePayload): Promise { @@ -82,7 +82,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise isAdmin(req.user, req.payload)` (a staff admin; the second factor is checked for you). */ access?: (args: { req: PayloadRequest }) => boolean | Promise - /** Env variable that holds the token (≥ 32 characters). Default IPAL_DOCTOR_TOKEN. */ + /** Env variable that holds the token (≥ 32 characters). Default IAPL_DOCTOR_TOKEN. */ tokenVar?: string } @@ -93,17 +93,17 @@ const sameToken = (given: string, expected: string) => { } /** - * GET /api/ipal/doctor — the deep status for `ipal-doctor --url`. Off (404) until the token variable + * GET /api/ipal/doctor — the deep status for `iapl-doctor --url`. Off (404) until the token variable * holds at least 32 characters; then `Authorization: Bearer ` (or `access`) is required. - * Rate-limited per client IP. `ipalKit({ doctor: false })` removes the endpoint. + * Rate-limited per client IP. `iapl({ doctor: false })` removes the endpoint. */ export function buildDoctorEndpoint(options: DoctorEndpointOptions = {}): Endpoint { - const tokenVar = options.tokenVar ?? 'IPAL_DOCTOR_TOKEN' + const tokenVar = options.tokenVar ?? 'IAPL_DOCTOR_TOKEN' return { handler: async (req: PayloadRequest) => { const token = process.env[tokenVar]?.trim() ?? '' if (token.length < 32) {return Response.json({ error: 'Not found' }, { status: 404 })} - const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'ipal-doctor', windowMs: 60_000 }) + const limit = await consumeRateLimit({ key: clientIp(req.headers), max: 10, scope: 'iapl-doctor', windowMs: 60_000 }) if (!limit.ok) {return tooManyRequests(limit.retryAfter, { error: 'Too many requests' })} const given = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '').trim() const allowed = (given && sameToken(given, token)) || (options.access ? secondFactorPassed(req) && (await options.access({ req })) : false) diff --git a/src/modules/doctor/types.ts b/src/modules/doctor/types.ts index 9c6962c..1e36b94 100644 --- a/src/modules/doctor/types.ts +++ b/src/modules/doctor/types.ts @@ -12,7 +12,7 @@ export type DoctorFinding = { file?: string fix?: string message: string - /** Why the project silenced it (from ipal-doctor.json or an `ipal-audit-skip` line). */ + /** Why the project silenced it (from iapl-doctor.json or an `iapl-audit-skip` line). */ reason?: string rule: string severity: DoctorSeverity @@ -23,7 +23,7 @@ export type DoctorFinding = { /** What a rule returns — the runner adds rule, source and docs. */ export type RuleFinding = { rule?: string } & Omit -/** One silencing / override entry in ipal-doctor.json. */ +/** One silencing / override entry in iapl-doctor.json. */ export type DoctorRuleSetting = { /** Only findings in these files (globs: `*` within a folder, `**` across folders), e.g. an approved exception. */ files?: string[] @@ -34,7 +34,7 @@ export type DoctorRuleSetting = { until?: string } -/** ipal-doctor.json in the project root. Every key is optional. */ +/** iapl-doctor.json in the project root. Every key is optional. */ export type DoctorConfig = { /** The site's production domain (dots allowed) — the base of the database names. */ domain?: string diff --git a/src/modules/email/graphAdapter.ts b/src/modules/email/graphAdapter.ts index 8721a92..38a3645 100644 --- a/src/modules/email/graphAdapter.ts +++ b/src/modules/email/graphAdapter.ts @@ -167,7 +167,7 @@ export const graphAdapter = const env = readGraphEnv() if (!env) { payload.logger.error( - '[ipal] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.', + '[iapl] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.', ) return { code: 'graph-not-configured', @@ -192,7 +192,7 @@ export const graphAdapter = const to = toRecipients(message.to) if (to.length === 0) { - payload.logger.error('[ipal] Email not sent: no valid recipient.') + payload.logger.error('[iapl] Email not sent: no valid recipient.') return { error: 'Enter a valid recipient address.', sent: false } } @@ -226,7 +226,7 @@ export const graphAdapter = // Attachments: small ones ride in the same call; larger ones need a draft and an upload session. const attachments = toGraphAttachments(message) if (!attachments) { - payload.logger.error('[ipal] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.') + payload.logger.error('[iapl] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.') return { detail: 'Attachment content must be a Buffer or a string.', error: 'The e-mail was not sent.', sent: false } } const fetchImpl = args.fetchImpl ?? fetch @@ -245,7 +245,7 @@ export const graphAdapter = const roles = tokenRoles(token) if (roles && !roles.includes(GRAPH_LARGE_PERMISSION)) { const detail = `The Microsoft Graph app lacks the ${GRAPH_LARGE_PERMISSION} application permission, so it cannot send attachments of 3 MB and more.` - payload.logger.error(`[ipal] ${detail}`) + payload.logger.error(`[iapl] ${detail}`) return { code: 'graph-permission', detail, error: 'The e-mail was not sent.', sent: false } } const large = await sendLargeGraphMail(attachments, { @@ -277,11 +277,11 @@ export const graphAdapter = return { sent: true } } const detail = await res.text() - payload.logger.error(`[ipal] Graph sendMail failed (${res.status}): ${detail}`) + payload.logger.error(`[iapl] Graph sendMail failed (${res.status}): ${detail}`) return { detail: `Microsoft Graph refused the e-mail (${res.status}).`, error: 'The e-mail was not sent.', sent: false } } catch (err) { const msg = err instanceof Error ? err.message : String(err) - payload.logger.error(`[ipal] Graph send error: ${msg}`) + payload.logger.error(`[iapl] Graph send error: ${msg}`) return { detail: msg, error: 'The e-mail was not sent.', sent: false } } }, diff --git a/src/modules/email/graphAttachments.ts b/src/modules/email/graphAttachments.ts index 0a1a981..d160b5e 100644 --- a/src/modules/email/graphAttachments.ts +++ b/src/modules/email/graphAttachments.ts @@ -126,7 +126,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean method: 'POST', }) if (created.status === 401 || created.status === 403) { - log.error(`[ipal] ${permissionDetail} (${await describe(created)})`) + log.error(`[iapl] ${permissionDetail} (${await describe(created)})`) return { code: 'graph-permission', detail: permissionDetail, sent: false } } if (created.status !== 201 && created.status !== 200) { @@ -167,10 +167,10 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean if (sent.status !== 202) {throw new Error(`send failed (${await describe(sent)})`)} } catch (err) { const detail = err instanceof Error ? err.message : String(err) - log.error(`[ipal] Graph send with a large attachment failed: ${detail}`) + log.error(`[iapl] Graph send with a large attachment failed: ${detail}`) // Nothing went out: take the draft (and the file in it) out of the mailbox. if (draftId && !(await remove(draftId))) { - log.error(`[ipal] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`) + log.error(`[iapl] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`) } return { code: 'graph-error', detail, sent: false } } @@ -190,7 +190,7 @@ export async function sendLargeGraphMail(attachments: GraphAttachment[], { clean /* try again after the next delay */ } } - log.warn(`[ipal] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`) + log.warn(`[iapl] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`) return 'left' })() cleanup.catch(() => undefined) diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index 18dc01c..b984073 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -109,7 +109,7 @@ export const mailAdapter = // Panel asked for Graph but the agency creds aren't configured for // this project. Fall back to SMTP rather than silently dropping mail. payload.logger.warn( - '[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.', + '[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.', ) } diff --git a/src/modules/email/panelSmtpAdapter.ts b/src/modules/email/panelSmtpAdapter.ts index 8819dd4..c20dfd8 100644 --- a/src/modules/email/panelSmtpAdapter.ts +++ b/src/modules/email/panelSmtpAdapter.ts @@ -60,7 +60,7 @@ export const panelSmtpAdapter = if (!host || !user || !pass) { payload.logger.error( - '[ipal] Email not sent: SMTP host, user or password is empty in Site integrations → E-mail sending.', + '[iapl] Email not sent: SMTP host, user or password is empty in Site integrations → E-mail sending.', ) return { code: 'not-configured', error: 'Fill in the server, user name and password.', sent: false } } @@ -100,7 +100,7 @@ export const panelSmtpAdapter = } catch (err) { // Never surface SMTP internals to the caller — a form submission // shouldn't fail loudly because the mailbox is misconfigured. - payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`) + payload.logger.error(`[iapl] Email send failed: ${(err as Error).message}`) // `detail` is for the panel status (mailAdapter), not for end users. return { detail: (err as Error).message, error: 'The e-mail was not sent.', sent: false } } diff --git a/src/modules/email/sendEmail.ts b/src/modules/email/sendEmail.ts index dd8b771..3f0a5ab 100644 --- a/src/modules/email/sendEmail.ts +++ b/src/modules/email/sendEmail.ts @@ -89,7 +89,7 @@ export async function sendEmail({ }) return { messageId: info.messageId, sent: true } } catch (err) { - payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`) + payload.logger.error(`[iapl] Email send failed: ${(err as Error).message}`) return { error: 'The e-mail was not sent.', sent: false } } } diff --git a/src/modules/email/test/testEmailEndpoint.ts b/src/modules/email/test/testEmailEndpoint.ts index 2c06668..e2b7216 100644 --- a/src/modules/email/test/testEmailEndpoint.ts +++ b/src/modules/email/test/testEmailEndpoint.ts @@ -66,7 +66,7 @@ export const testEmailEndpoint: Endpoint = { try { const info = await req.payload.sendEmail({ ...(attachmentMB - ? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'ipal-kit test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] } + ? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'IAPL test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] } : {}), html: `

${escapeHtml(text)}

`, subject, @@ -84,7 +84,7 @@ export const testEmailEndpoint: Endpoint = { if (!sent) { const failed = info as { code?: string; detail?: string; error?: string } - req.payload.logger.error(`[ipal] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`) + req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`) const error = failed?.code === 'not-configured' ? serverText(i18n, 'testEmailNotConfigured') @@ -95,7 +95,7 @@ export const testEmailEndpoint: Endpoint = { return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true }) } catch (err) { const message = err instanceof Error ? err.message : String(err) - req.payload.logger.error(`[ipal] Test email failed: ${message}`) + req.payload.logger.error(`[iapl] Test email failed: ${message}`) return Response.json({ error: serverText(i18n, 'testEmailFailed'), ok: false }, { status: 502 }) } }, diff --git a/src/modules/env/assertEnv.ts b/src/modules/env/assertEnv.ts index 2237ec8..b7eb2cb 100644 --- a/src/modules/env/assertEnv.ts +++ b/src/modules/env/assertEnv.ts @@ -27,7 +27,7 @@ export type EnvRule = { export type AssertEnvOptions = { /** Source of values. Default process.env. */ env?: Record - /** Error prefix. Default '[ipal]'. */ + /** Error prefix. Default '[iapl]'. */ label?: string } @@ -86,8 +86,8 @@ function checkValue(rule: EnvRule, value: string): null | string { * aggregated error listing every problem at once (not just the first). Call it * once at boot — in payload.config.ts, or Next's instrumentation.ts register(). * - * import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit' - * assertEnv(ipalEnvRules({ storage: true, turnstile: true })) + * import { assertEnv, iaplEnvRules } from '@intecion/ipal-kit' + * assertEnv(iaplEnvRules({ storage: true, turnstile: true })) * * or with hand-written rules: * @@ -102,7 +102,7 @@ function checkValue(rule: EnvRule, value: string): null | string { */ export function assertEnv(rules: EnvRule[], options: AssertEnvOptions = {}): void { const env = options.env ?? process.env - const label = options.label ?? '[ipal]' + const label = options.label ?? '[iapl]' const problems: string[] = [] for (const rule of rules) { diff --git a/src/modules/env/ipalEnvRules.ts b/src/modules/env/iaplEnvRules.ts similarity index 91% rename from src/modules/env/ipalEnvRules.ts rename to src/modules/env/iaplEnvRules.ts index 6472d08..e52c2db 100644 --- a/src/modules/env/ipalEnvRules.ts +++ b/src/modules/env/iaplEnvRules.ts @@ -4,7 +4,7 @@ type TurnstileNames = { secretVar?: string; siteKeyVar?: string } import { checkDatabaseName } from './databaseName.js' -export type IpalEnvFeatures = { +export type IaplEnvFeatures = { /** * Cookie crawl (cookieScanner.crawl): the scanner service URL and the shared * token (at least 16 characters). Required in production only. @@ -22,7 +22,7 @@ export type IpalEnvFeatures = { /** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */ emailGraph?: boolean /** - * Require IPAL_IP_HEADER in production — the header the rate limit trusts for + * Require IAPL_IP_HEADER in production — the header the rate limit trusts for * the client IP (see clientIp). Outside production it stays optional. */ ipHeader?: boolean @@ -55,7 +55,7 @@ export type IpalEnvFeatures = { } /** - * The env schema for a standard ipal-kit deploy, assembled from the features the + * The env schema for a standard IAPL deploy, assembled from the features the * project actually uses — so a site on local-disk storage isn't forced to set * R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a * fixed required set (A0: the plugin never demands config a project doesn't use). @@ -64,16 +64,16 @@ export type IpalEnvFeatures = { * NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core. * Override any name via the options if your project names them differently. * - * assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true })) + * assertEnv(iaplEnvRules({ storage: true, emailGraph: true, turnstile: true })) * * Extend with project-specific vars by spreading: * * assertEnv([ - * ...ipalEnvRules({ storage: true }), + * ...iaplEnvRules({ storage: true }), * { name: 'MY_API_KEY', description: 'Third-party integration key' }, * ]) */ -export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { +export function iaplEnvRules(features: IaplEnvFeatures = {}): EnvRule[] { const { cookieCrawl = false, databaseName = false, @@ -95,7 +95,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { ...(secretMinLength > 0 && process.env.NODE_ENV === 'production' && { validate: (value: string) => value.length >= secretMinLength || - `${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or ipalEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`, + `${secretVar} must be at least ${secretMinLength} characters in production (got ${value.length}) — use a long random value, or iaplEnvRules({ secretMinLength }) to change the minimum (0 turns the check off)`, }), }, { name: serverUrlVar, description: 'Public site origin, e.g. https://example.com', kind: 'url' }, @@ -148,22 +148,22 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { if (ipHeader) { rules.push({ - name: 'IPAL_IP_HEADER', + name: 'IAPL_IP_HEADER', description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for', required: process.env.NODE_ENV === 'production', - validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IPAL_IP_HEADER must be a header name (got "${v}")`), + validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IAPL_IP_HEADER must be a header name (got "${v}")`), }) } if (cookieCrawl) { const required = process.env.NODE_ENV === 'production' rules.push( - { name: 'IPAL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required }, + { name: 'IAPL_COOKIE_SCAN_URL', description: 'Cookie crawler service base URL, e.g. https://cookie-crawler.example.com', kind: 'url', required }, { - name: 'IPAL_COOKIE_SCAN_TOKEN', - description: 'Token shared with the cookie crawler (this site\'s entry in IPAL_CRAWLER_SITES)', + name: 'IAPL_COOKIE_SCAN_TOKEN', + description: 'Token shared with the cookie crawler (this site\'s entry in IAPL_CRAWLER_SITES)', required, - validate: (v) => (v.length >= 16 ? true : 'IPAL_COOKIE_SCAN_TOKEN must be at least 16 characters'), + validate: (v) => (v.length >= 16 ? true : 'IAPL_COOKIE_SCAN_TOKEN must be at least 16 characters'), }, ) } @@ -183,7 +183,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] { } if (databaseName) { - const { domain, warn = (message: string) => console.warn(`[ipal] ${message}`) } = databaseName === true ? {} : databaseName + const { domain, warn = (message: string) => console.warn(`[iapl] ${message}`) } = databaseName === true ? {} : databaseName rules.push({ name: databaseVar, description: 'Database name: _prod / _dev (warning only)', diff --git a/src/modules/env/index.ts b/src/modules/env/index.ts index 37ffc10..cb87e3a 100644 --- a/src/modules/env/index.ts +++ b/src/modules/env/index.ts @@ -1,5 +1,5 @@ export { assertEnv } from './assertEnv.js' export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js' export { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from './databaseName.js' -export { ipalEnvRules } from './ipalEnvRules.js' -export type { IpalEnvFeatures } from './ipalEnvRules.js' +export { iaplEnvRules } from './iaplEnvRules.js' +export type { IaplEnvFeatures } from './iaplEnvRules.js' diff --git a/src/modules/forms/attachments/config.ts b/src/modules/forms/attachments/config.ts index fc384ed..f827c8d 100644 --- a/src/modules/forms/attachments/config.ts +++ b/src/modules/forms/attachments/config.ts @@ -20,7 +20,7 @@ export type FormFileScanInput = { export type FormFileScanResult = { ok: boolean; reason?: string } /** - * `ipalKit({ forms: { attachments } })` — files on panel forms. They are + * `iapl({ forms: { attachments } })` — files on panel forms. They are * NEVER stored: a file is checked, attached to the company e-mail, and dropped. */ export type FormAttachmentsOption = { diff --git a/src/modules/forms/attachments/delivery.ts b/src/modules/forms/attachments/delivery.ts index 2fd2f58..1537a6b 100644 --- a/src/modules/forms/attachments/delivery.ts +++ b/src/modules/forms/attachments/delivery.ts @@ -178,12 +178,12 @@ export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: str const detail = firstLine(outcomes.find((o) => o.detail)?.detail) delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' } - payload.logger.error(`[ipal] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`) + payload.logger.error(`[iapl] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`) await Promise.all(carriers.map((email) => send(payload, withFailureNotice(email, delivery.files, locale)))) return [] } catch (err) { delivery.result = { note: firstLine(err instanceof Error ? err.message : String(err)), state: 'failed' } - payload.logger.error(`[ipal] Form file delivery failed: ${(err as Error).message}`) + payload.logger.error(`[iapl] Form file delivery failed: ${(err as Error).message}`) return [] } } diff --git a/src/modules/forms/attachments/submitHandler.ts b/src/modules/forms/attachments/submitHandler.ts index 35f4e56..04481a5 100644 --- a/src/modules/forms/attachments/submitHandler.ts +++ b/src/modules/forms/attachments/submitHandler.ts @@ -310,7 +310,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise { open.delete(stream) if (settled) {return} // aborted: already answered, nothing to add stream.resume() - payload.logger.error(`[ipal] Form file could not be read: ${(err as Error).message}`) + payload.logger.error(`[iapl] Form file could not be read: ${(err as Error).message}`) stop({ reason: 'error', success: false }) }) }) @@ -335,7 +335,7 @@ export async function handleFormSubmit(req: PayloadRequest): Promise { stop(await storeSubmission({ ...(stored), files: (gate).accepted })) } } catch (err) { - payload.logger.error(`[ipal] Form submit failed: ${(err as Error).message}`) + payload.logger.error(`[iapl] Form submit failed: ${(err as Error).message}`) stop({ reason: 'error', success: false }) } conclude(outcome ?? { reason: 'error', success: false }) diff --git a/src/modules/forms/createSubmitAction.ts b/src/modules/forms/createSubmitAction.ts index cb8b737..229515b 100644 --- a/src/modules/forms/createSubmitAction.ts +++ b/src/modules/forms/createSubmitAction.ts @@ -11,7 +11,7 @@ import { HONEYPOT_FIELD, isHoneypotTripped } from './honeypot.js' import { submitForm } from './submitForm.js' type CreateSubmitActionArgs = { - /** Optional: IP options (default IPAL_IP_HEADER env / clientIp defaults). */ + /** Optional: IP options (default IAPL_IP_HEADER env / clientIp defaults). */ clientIp?: ClientIpOptions getCachedPayload: () => Promise /** @@ -69,7 +69,7 @@ export async function splitFormFiles(values: Record): Promise<{ * import { getCachedPayload } from '@/lib/content' * export const sendForm = createSubmitAction({ getCachedPayload, headers }) * - * Signature matches the ipal-form FormRenderer: `sendForm(formId, locale, values, + * Signature matches the iapl-form FormRenderer: `sendForm(formId, locale, values, * turnstileToken?)` — bind formId and locale in the block (`sendForm.bind(null, id, locale)`). * A tripped honeypot gets a fake success and stores nothing. */ diff --git a/src/modules/forms/emailLayout.ts b/src/modules/forms/emailLayout.ts index f2d0ca6..15896b3 100644 --- a/src/modules/forms/emailLayout.ts +++ b/src/modules/forms/emailLayout.ts @@ -203,7 +203,7 @@ export function buildEmailLayoutHook({ formsSlug = 'forms' }: { formsSlug?: stri }), })) } catch (err) { - payload.logger.error(`[ipal] E-mail layout skipped: ${(err as Error).message}`) + payload.logger.error(`[iapl] E-mail layout skipped: ${(err as Error).message}`) return emails } } diff --git a/src/modules/forms/formAnalyticsFields.ts b/src/modules/forms/formAnalyticsFields.ts index 8d463bc..9c9fb45 100644 --- a/src/modules/forms/formAnalyticsFields.ts +++ b/src/modules/forms/formAnalyticsFields.ts @@ -5,7 +5,7 @@ import type { Field } from 'payload' * `dataLayer` push fired on successful submit — without any code change. Add * them to the Forms collection via the plugin's `formOverrides`: * - * ipalKit({ + * iapl({ * forms: { * formOverrides: { * fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()], diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 97e21cc..21be8c4 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -195,7 +195,7 @@ function hideEmails(fields: Field[]): Field[] { } /** - * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption. + * Configures @payloadcms/plugin-form-builder from IAPL's FormsOption. * * Provides the forms / form-submissions collections and field types. E-mails * after a submission are the form-builder's own (Forms → Emails), sent through diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 3365771..b4cc4a7 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -25,7 +25,7 @@ export type SubmitFormArgs = { /** * Name of the GDPR consent checkbox. A field with this name must be checked * for the submission to succeed (enforced server-side). Defaults to - * ipalKit({ forms: { consentFieldName } }), then 'consent'. + * iapl({ forms: { consentFieldName } }), then 'consent'. */ consentFieldName?: string /** Submitted field data — shape matches the form's fields. */ @@ -212,7 +212,7 @@ export async function validateSubmitFields({ locale, payload, }: Pick): Promise<{ failure: SubmitFailure } | { validation: ValidSubmission }> { - // Explicit argument → ipalKit({ forms: { consentFieldName } }) → 'consent'. + // Explicit argument → iapl({ forms: { consentFieldName } }) → 'consent'. const configured = (payload.config?.custom as { ipal?: { consentFieldName?: unknown } } | undefined)?.ipal?.consentFieldName const consentField = consentFieldName ?? (typeof configured === 'string' && configured ? configured : undefined) const validation = await validateSubmission(payload, formId, data, consentField) @@ -342,7 +342,7 @@ export async function storeSubmission({ depth: 0, }) } catch (err) { - payload.logger.error(`[ipal] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`) + payload.logger.error(`[iapl] Could not record the file delivery on submission ${String(submission.id)}: ${(err as Error).message}`) } if (result.state === 'sent') {return { submissionId: submission.id, success: true }} // The message belongs at the File field and names the file — never the mail server's own words. @@ -356,7 +356,7 @@ export async function storeSubmission({ ...(fileField && !fileField.required ? { optional: true } : {}), } } catch (err) { - payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) + payload.logger.error(`[iapl] Form submission failed: ${(err as Error).message}`) return { reason: 'error', success: false } } finally { // The buffers are not needed past this point — drop the references now. @@ -402,8 +402,8 @@ export async function submitForm(args: SubmitFormArgs): Promise - /** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */ + /** Consent log endpoint, e.g. '/api/ipal/consent' (iapl consentLog: true). */ logEndpoint?: string /** * CSP nonce for a nonce-based policy (createProxy `csp`): read it in the layout @@ -50,7 +50,7 @@ export type SiteProvidersProps = { /** getSiteShell(locale) from lib/content. */ shell: SiteShell /** - * Built-in statistics (ipalKit stats: true): mounts . `true` or + * Built-in statistics (iapl stats: true): mounts . `true` or * `{ locale, endpoint }`. Default off. */ stats?: boolean | PageStatsProps diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 4a4e8f8..b986a67 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -78,7 +78,7 @@ type CreateContentHelpersArgs = { /** * Options for the ready-made `robots` handler, e.g. * `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or - * `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute). + * `{ adminRoute: false }` when the admin path is hidden (iapl adminRoute). */ robots?: RobotsOptions /** @@ -172,7 +172,7 @@ export type PageJsonLdOptions = { * * ```ts * // src/lib/content.ts - * import { createContentHelpers } from 'ipal-kit' + * import { createContentHelpers } from 'IAPL' * import config from '@/payload.config' * import { contentConfig } from '@/content.config' * @@ -270,7 +270,7 @@ export function createContentHelpers({ page = 1, ): Promise => { if (!i18n) { - throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.') + throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.') } pageMetadata ??= createPageMetadata({ baseUrl: origin || undefined, @@ -456,7 +456,7 @@ export function createContentHelpers({ const sitemap = cache(async (): Promise => { if (!i18n) { throw new Error( - '[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.', + '[iapl] createContentHelpers: pass `i18n` to use the sitemap handler.', ) } try { @@ -484,7 +484,7 @@ export function createContentHelpers({ // return an empty sitemap instead of failing the build. Runtime regeneration // produces the real one. See dynamic='force-dynamic'. console.warn( - '[ipal] sitemap: could not reach the database, returning empty entries ' + + '[iapl] sitemap: could not reach the database, returning empty entries ' + "(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " + 'generate at runtime and avoid build-time DB access):', error, @@ -647,7 +647,7 @@ export function createContentHelpers({ // reachable at runtime. Without this every project would need its own // try/catch here. (Same graceful-degradation as the sitemap handler.) console.warn( - '[ipal] generateStaticParams: database not reachable during build ' + + '[iapl] generateStaticParams: database not reachable during build ' + '(Docker/CI) — returning empty params; routes render on-demand at runtime:', err, ) @@ -665,7 +665,7 @@ export function createContentHelpers({ const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} }) const needI18n = (what: string): I18nConfig => { - if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)} + if (!i18n) {throw new Error(`[iapl] createContentHelpers: pass \`i18n\` to use ${what}.`)} return i18n } @@ -912,7 +912,7 @@ export type SiteShell = { formTexts: FormNotificationTexts /** Site-wide nodes (WebSite, Organization…) for . */ jsonLd: Record[] - /** Notifications → Lightbox (English fallbacks without ipalKit `lightbox`) — reads it. */ + /** Notifications → Lightbox (English fallbacks without iapl `lightbox`) — reads it. */ lightboxTexts?: LightboxTexts settings: Record /** Site Settings → Theme, for / and . */ diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index 3743b34..5fbcc58 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -86,11 +86,11 @@ type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> } export function createPageRoute(helpers: Helpers, options: PageRouteOptions) { const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options if (onMissing === 'redirectHome' && !redirect) { - throw new Error("[ipal] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.") + throw new Error("[iapl] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.") } const localeOf = (locale: string | undefined) => { const l = locale ?? helpers.i18n?.defaultLocale - if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')} + if (!l) {throw new Error('[iapl] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')} return l } diff --git a/src/modules/health/createHealthRoute.ts b/src/modules/health/createHealthRoute.ts index 000f502..3760ec8 100644 --- a/src/modules/health/createHealthRoute.ts +++ b/src/modules/health/createHealthRoute.ts @@ -61,7 +61,7 @@ export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise { diff --git a/src/modules/hooks/fillEmptyLocales.ts b/src/modules/hooks/fillEmptyLocales.ts index 08a8db4..71c4700 100644 --- a/src/modules/hooks/fillEmptyLocales.ts +++ b/src/modules/hooks/fillEmptyLocales.ts @@ -85,7 +85,7 @@ async function keepingLocale(req: PayloadRequest, fn: () => Promise) { try { await fn() } catch (err) { - req.payload?.logger?.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`) + req.payload?.logger?.error(`[iapl] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`) } finally { req.locale = locale req.fallbackLocale = fallbackLocale diff --git a/src/modules/i18n/validation.ts b/src/modules/i18n/validation.ts index 6eab6fa..5a58c44 100644 --- a/src/modules/i18n/validation.ts +++ b/src/modules/i18n/validation.ts @@ -10,7 +10,7 @@ export function validateI18nConfig(config: I18nConfig): void { const { defaultLocale, locales } = config if (!locales?.length) { - throw new Error('[ipal] i18n: "locales" must contain at least one locale.') + throw new Error('[iapl] i18n: "locales" must contain at least one locale.') } const codes = new Set() @@ -18,18 +18,18 @@ export function validateI18nConfig(config: I18nConfig): void { for (const locale of locales) { if (!locale.code || !locale.label) { throw new Error( - `[ipal] i18n: Every locale must have "code" and "label". Received: ${JSON.stringify(locale)}`, + `[iapl] i18n: Every locale must have "code" and "label". Received: ${JSON.stringify(locale)}`, ) } if (!LOCALE_CODE_PATTERN.test(locale.code)) { throw new Error( - `[ipal] i18n: Invalid locale code "${locale.code}". Expected format: "pl", "en", "pt-BR".`, + `[iapl] i18n: Invalid locale code "${locale.code}". Expected format: "pl", "en", "pt-BR".`, ) } if (codes.has(locale.code)) { - throw new Error(`[ipal] i18n: Duplicate locale code "${locale.code}".`) + throw new Error(`[iapl] i18n: Duplicate locale code "${locale.code}".`) } codes.add(locale.code) @@ -37,7 +37,7 @@ export function validateI18nConfig(config: I18nConfig): void { if (!codes.has(defaultLocale)) { throw new Error( - `[ipal] i18n: defaultLocale "${defaultLocale}" not found in locales [${[...codes].join(', ')}].`, + `[iapl] i18n: defaultLocale "${defaultLocale}" not found in locales [${[...codes].join(', ')}].`, ) } } diff --git a/src/modules/integrations/IntegrationStatusBanner.tsx b/src/modules/integrations/IntegrationStatusBanner.tsx index 90e39bb..3c0affe 100644 --- a/src/modules/integrations/IntegrationStatusBanner.tsx +++ b/src/modules/integrations/IntegrationStatusBanner.tsx @@ -3,7 +3,7 @@ import { useFormFields, useTranslation } from '@payloadcms/ui' import type { IntegrationBannerTexts } from './status.js' -import { formatDateTime, ipalT } from '../admin-i18n/t.js' +import { formatDateTime, iaplT } from '../admin-i18n/t.js' import { type IntegrationLabel, resolveLabel, STATUS_CODE_TEXTS } from './texts.js' type Props = { @@ -36,7 +36,7 @@ export function IntegrationStatusBanner({ label, statusField, texts = {} }: Prop return formatDateTime(iso, i18n.language) } // Project-provided keys are not in AdminTextKey; read them through `t` the same way. - const text = (key: string, vars?: Record) => ipalT(t as never, key as never, vars) + const text = (key: string, vars?: Record) => iaplT(t as never, key as never, vars) if (state === 'ok') { const sinceText = date(since) diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts index 751dd5b..29f6bc7 100644 --- a/src/modules/integrations/status.ts +++ b/src/modules/integrations/status.ts @@ -116,6 +116,6 @@ export async function recordIntegrationStatus( depth: 0, }) } catch (err) { - console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err) + console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err) } } diff --git a/src/modules/lightbox/texts.ts b/src/modules/lightbox/texts.ts index 3e02dcf..99e336e 100644 --- a/src/modules/lightbox/texts.ts +++ b/src/modules/lightbox/texts.ts @@ -2,7 +2,7 @@ import type { LightboxTexts } from './types.js' /** * English fallbacks, per field — the same philosophy as NOTIFICATION_FALLBACK. - * Editors translate them in Form messages → Image viewer (ipalKit `lightbox: true`). + * Editors translate them in Form messages → Image viewer (iapl `lightbox: true`). */ export const LIGHTBOX_FALLBACK: LightboxTexts = { close: 'Close', diff --git a/src/modules/lightbox/types.ts b/src/modules/lightbox/types.ts index d4e3af2..ccde6ec 100644 --- a/src/modules/lightbox/types.ts +++ b/src/modules/lightbox/types.ts @@ -22,7 +22,7 @@ export type LightboxImage = { /** * Labels of the viewer. The plugin's i18n: the Notifications global → Lightbox - * (ipalKit `lightbox: true`), read with getNotificationTexts(...).lightbox. + * (iapl `lightbox: true`), read with getNotificationTexts(...).lightbox. * Every missing text falls back to LIGHTBOX_FALLBACK (English). */ export type LightboxTexts = { diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 191eae9..61fe01e 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -71,7 +71,7 @@ export type CreateMcpRouteArgs = { * `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting). */ rateLimit?: { max?: number; windowMs?: number } | false - /** Server name advertised in `initialize`. Default 'ipal-site'. */ + /** Server name advertised in `initialize`. Default 'iapl-site'. */ serverName?: string /** Server version advertised in `initialize`. Default '1.0.0'. */ serverVersion?: string @@ -104,7 +104,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { getCachedPayload, isPathVisible, maxBatch = 10, - serverName = 'ipal-site', + serverName = 'iapl-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField, @@ -306,7 +306,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) { // Log the real error server-side; return a GENERIC message to the // (anonymous) caller so internal details — DB schema, host, stack — // never leak over a public endpoint. - console.warn('[ipal] createMcpRoute: tool execution failed:', err) + console.warn('[iapl] createMcpRoute: tool execution failed:', err) return rpcResult(id, toolText('Tool execution failed.', true)) } } diff --git a/src/modules/media/optimizeUpload.ts b/src/modules/media/optimizeUpload.ts index 5f67bd4..eb9ac66 100644 --- a/src/modules/media/optimizeUpload.ts +++ b/src/modules/media/optimizeUpload.ts @@ -163,7 +163,7 @@ export function buildOptimizeUploadHook( } if (!sharp) { - req.payload.logger?.error?.('[ipal] Image optimisation needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.') + req.payload.logger?.error?.('[iapl] Image optimisation needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.') throw new APIError( pl ? 'Optymalizacja obrazów nie jest dostępna na tym serwerze. Zapytaj administratora.' diff --git a/src/modules/media/placeholder.ts b/src/modules/media/placeholder.ts index 24320f3..cfe8461 100644 --- a/src/modules/media/placeholder.ts +++ b/src/modules/media/placeholder.ts @@ -57,7 +57,7 @@ export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field? } } catch (err) { // A placeholder is a nicety — never block the upload. - req.payload.logger.warn(`[ipal] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`) + req.payload.logger.warn(`[iapl] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`) } } } diff --git a/src/modules/notifications/types.ts b/src/modules/notifications/types.ts index 3025837..ee0cdfc 100644 --- a/src/modules/notifications/types.ts +++ b/src/modules/notifications/types.ts @@ -41,7 +41,7 @@ export type FormNotificationTexts = { export type NotificationTexts = { form: FormNotificationTexts - /** Image viewer labels — pass to . Fallbacks when ipalKit `lightbox` is off. */ + /** Image viewer labels — pass to . Fallbacks when iapl `lightbox` is off. */ lightbox: LightboxTexts } diff --git a/src/modules/pages/NotFoundLoader.tsx b/src/modules/pages/NotFoundLoader.tsx index 4bec4a3..9ca4326 100644 --- a/src/modules/pages/NotFoundLoader.tsx +++ b/src/modules/pages/NotFoundLoader.tsx @@ -36,7 +36,7 @@ export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderP }) .catch((error: unknown) => { // the status is already 404 — without the content the page stays empty, the error goes to the console - console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error) + console.error('[iapl] NotFoundLoader: the 404 content could not be loaded', error) }) return () => { active = false diff --git a/src/modules/secrets/writeOnly.ts b/src/modules/secrets/writeOnly.ts index e573543..eb45485 100644 --- a/src/modules/secrets/writeOnly.ts +++ b/src/modules/secrets/writeOnly.ts @@ -2,7 +2,7 @@ import type { CollectionAfterReadHook, Field, FieldHook, GlobalAfterReadHook } f import { ValidationError } from 'payload' -import { ipalT } from '../admin-i18n/t.js' +import { iaplT } from '../admin-i18n/t.js' import { SECRET_CLEAR, SECRET_MASK } from './constants.js' /** @@ -98,7 +98,7 @@ export function buildKeepSecret({ appliesWhen, boundTo = [] }: WriteOnlySecretOp const value = siblingData && name ? (siblingData as Record)[name] : given if (value === SECRET_CLEAR) {return null} const refuse = (key: 'secretNotText' | 'secretReenter', fallback: string): never => { - const message = req?.t ? ipalT(req.t as never, key) : fallback + const message = req?.t ? iaplT(req.t as never, key) : fallback throw new ValidationError({ collection: collection?.slug, errors: [{ message, path: path.join('.') }], global: global?.slug }, req?.t) } const nothing = value === undefined || value === null || value === '' || value === SECRET_MASK diff --git a/src/modules/security/buildSecurityHeaders.ts b/src/modules/security/buildSecurityHeaders.ts index 6552870..6d4a92a 100644 --- a/src/modules/security/buildSecurityHeaders.ts +++ b/src/modules/security/buildSecurityHeaders.ts @@ -124,7 +124,7 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop }) } - // Staging / preview (IPAL_NOINDEX=1): keep every response out of search engines. + // Staging / preview (IAPL_NOINDEX=1): keep every response out of search engines. if (isSiteNoindex()) { headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' }) } diff --git a/src/modules/security/totp/SafeTotpView.tsx b/src/modules/security/totp/SafeTotpView.tsx index 77568b3..4d52d59 100644 --- a/src/modules/security/totp/SafeTotpView.tsx +++ b/src/modules/security/totp/SafeTotpView.tsx @@ -37,7 +37,7 @@ const CLIENT_PROPS = ['browseByFolderSlugs', 'clientConfig', 'collectionSlug', ' * the wrapped factory) gets only what can cross to the browser — Payload's client props, its own * `clientProps`, `searchParams` and `back`, both checked. * - * ipalKit registers it (twoFactor.safeBack, on by default). A project that registers 2FA views + * iapl registers it (twoFactor.safeBack, on by default). A project that registers 2FA views * itself can use it too: `wrapTotpViews`, or give it `ipalTotpView` and list that path in * `admin.dependencies`. */ @@ -53,7 +53,7 @@ export function SafeTotpView(props: SafeTotpViewProps): React.ReactNode { if (!getFromImportMap({ importMap: props.importMap, PayloadComponent: ipalTotpView, schemaPath: '', silent: true })) { throw new Error( - `[ipal] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen ipal-kit puts its back-link check in front of). ` + + `[iapl] The admin import map has no "${totpViewImportKey(ipalTotpView)}" (the 2FA screen IAPL puts its back-link check in front of). ` + 'Run `pnpm payload generate:importmap` and commit the result.', ) } diff --git a/src/modules/security/totp/TotpRedirectProvider.tsx b/src/modules/security/totp/TotpRedirectProvider.tsx index 5ddd4ba..9859ae9 100644 --- a/src/modules/security/totp/TotpRedirectProvider.tsx +++ b/src/modules/security/totp/TotpRedirectProvider.tsx @@ -8,7 +8,7 @@ import { useEffect } from 'react' import type { TotpUser } from './totpRedirect.js' -import { formatDateTime, ipalT } from '../../admin-i18n/t.js' +import { formatDateTime, iaplT } from '../../admin-i18n/t.js' import { totpAdminPath, totpRedirectTarget } from './totpRedirect.js' export type TotpRedirectProviderProps = { @@ -94,10 +94,10 @@ export function TotpRedirectProvider({ children, forceSetup = true, requireSetup const deadline = setupWindowHours > 0 && Number.isFinite(start) ? start + setupWindowHours * 3_600_000 : null const closed = deadline !== null && deadline < Date.now() const notice = closed - ? ipalT(t as never, 'twoFactorSetupClosed') + ? iaplT(t as never, 'twoFactorSetupClosed') : deadline !== null - ? ipalT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) }) - : ipalT(t as never, 'twoFactorSetupRequired') + ? iaplT(t as never, 'twoFactorSetupDeadline', { date: formatDateTime(new Date(deadline).toISOString(), i18n.language) }) + : iaplT(t as never, 'twoFactorSetupRequired') setup = (
[1]) => ipalT(t as never, key) + const text = (key: Parameters[1]) => iaplT(t as never, key) const { config } = useConfig() const [busy, setBusy] = useState(false) diff --git a/src/modules/security/totp/importMapCheck.ts b/src/modules/security/totp/importMapCheck.ts index fca8610..abf4199 100644 --- a/src/modules/security/totp/importMapCheck.ts +++ b/src/modules/security/totp/importMapCheck.ts @@ -1,7 +1,7 @@ /** * Is the project's committed admin import map older than the config? * - * ipalKit registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components + * iapl registers `SafeTotpView` in front of the 2FA screens. Payload resolves view components * through the import map file, and a path that is not in it renders NOTHING: the 2FA screen comes * back empty (HTTP 200, no code form), so nobody can sign in — after an upgrade where * `pnpm payload generate:importmap` was forgotten. In development Payload regenerates the file diff --git a/src/modules/security/totp/safeBack.ts b/src/modules/security/totp/safeBack.ts index 8eb6ab9..17fcee0 100644 --- a/src/modules/security/totp/safeBack.ts +++ b/src/modules/security/totp/safeBack.ts @@ -7,7 +7,7 @@ * URL sends the user off-site straight after a genuine login step (GHSA-rffw-fq79-g3ch in the * original `payload-totp`, fixed there in 3.0.5; the fork does not have the fix). * - * ipal-kit therefore cleans the value on the server before the package's view sees it + * IAPL therefore cleans the value on the server before the package's view sees it * (SafeTotpView.tsx): `twoFactor.safeBack` — on by default, a function replaces the rule, * `false` turns it off. */ @@ -75,7 +75,7 @@ export const safeAdminBack: SafeBackRule = (back, { adminRoute, origin }) => { /** The package's views that take `back` — matched by the route the package gives them. */ const TOTP_VIEW_PATH = /^\/?(?:setup|verify)-totp$/ -/** Import-map path of the wrapper ipalKit registers. */ +/** Import-map path of the wrapper iapl registers. */ export const SAFE_TOTP_VIEW = '@intecion/ipal-kit/admin#SafeTotpView' /** A view component as it stands in a Payload config. */ @@ -94,9 +94,9 @@ export const totpViewImportKey = (component: TotpViewComponent): string => { export const totpViewDependencyKey = (component: TotpViewComponent) => `ipal-totp-view:${totpViewImportKey(component)}` /** - * Puts ipal-kit's wrapper in front of the 2FA views for which `added(key)` is true and whose + * Puts IAPL's wrapper in front of the 2FA views for which `added(key)` is true and whose * route is `setup-totp` / `verify-totp`: the wrapper cleans `back` and renders the original - * view, which it finds in the import map (`admin.dependencies` keeps it there). ipal-kit still + * view, which it finds in the import map (`admin.dependencies` keeps it there). IAPL still * never imports the optional package. The original's `serverProps` stay server props; its * `clientProps` travel as `ipalTotpClientProps`, so the wrapper can hand them to a client view. */ diff --git a/src/modules/security/totp/sameOrigin.ts b/src/modules/security/totp/sameOrigin.ts index da006fa..e427a3b 100644 --- a/src/modules/security/totp/sameOrigin.ts +++ b/src/modules/security/totp/sameOrigin.ts @@ -101,7 +101,7 @@ export function reportRefusedOrigin(req: RequestLike, extra: string[] = []): boo `or pass twoFactor: { sameOrigin: { origins: ['${originOf(origin)}'] } }, or make the proxy send X-Forwarded-Host. ` : 'The browser did not name an origin this site knows. ' req.payload?.logger?.warn( - `[ipal] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + + `[iapl] 2FA: a code from ${origin ? `origin "${origin}"` : `a ${key} request`} was refused and not counted — it is not one of this site's own origins (${known}). ` + how + 'If it is a foreign page, this is the protection working. twoFactor: { sameOrigin: false } turns the check off (docs/security.md "Verify and setup attempts only from the site\'s own origin"). Said once per origin.', ) diff --git a/src/modules/security/totp/secondFactor.ts b/src/modules/security/totp/secondFactor.ts index 747a43f..e1cdfcf 100644 --- a/src/modules/security/totp/secondFactor.ts +++ b/src/modules/security/totp/secondFactor.ts @@ -3,14 +3,14 @@ import type { BasePayload, CollectionConfig, Config, GlobalConfig } from 'payloa import { carryStaffRule } from '../../access/ruleMark.js' /** - * ipal-kit's own second-factor check, next to the access wrapper of + * IAPL's own second-factor check, next to the access wrapper of * @clocklimited/payload-2fa. * * Why it exists: the package wraps the `access` functions of the collections * and globals that are in the config at the moment it runs. Whatever is added - * afterwards — ipal-kit's globals and collections, a plugin listed after - * ipalKit — was left unwrapped, so a staff password without the TOTP code - * opened it over the API. This check does not depend on that order: ipalKit + * afterwards — IAPL's globals and collections, a plugin listed after + * iapl — was left unwrapped, so a staff password without the TOTP code + * opened it over the API. This check does not depend on that order: iapl * applies it to everything in the config when it finishes, and again in onInit * to whatever other plugins added later; `userMeetsRole` asks it too. * @@ -19,7 +19,7 @@ import { carryStaffRule } from '../../access/ruleMark.js' * 2. 2FA off or `twoFactor.guard: false` → there is no check (the project's choice); * 3. an account of another auth collection → 2FA is about ONE collection; such an * account is not staff unless the project names its collection in - * `access.staffCollections` (then it is staff WITHOUT a second factor — ipalKit + * `access.staffCollections` (then it is staff WITHOUT a second factor — iapl * logs a warning at start); * 4. `_strategy === 'totp'` → set by the package's strategy after password and code; * 5. `_strategy === 'api-key'` → an API key is its own credential (the package's rule); @@ -52,7 +52,7 @@ import { carryStaffRule } from '../../access/ruleMark.js' * and its code. The package alone only redirects such an account in the panel. */ -/** What ipalKit records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */ +/** What iapl records in `config.custom.ipal.twoFactor` when 2FA is on and the guard is not switched off. */ export type TwoFactorGuardConfig = { collection: string /** The project's exemption for accounts that never set TOTP up (a service account logging in with a password). */ @@ -169,8 +169,8 @@ type ConfigCustom = { totp?: { pluginOptions?: { disableAccessWrapper?: boolean * Per-entity opt-out, operation by operation — the project's decision that * this collection or global may be reached with the password alone: * - the 2FA package's own key: `custom.totp.disableAccessWrapper.: true` - * (the package leaves that operation unwrapped; so does ipal-kit); - * - ipal-kit's key, for entities the package never sees (added after it ran): + * (the package leaves that operation unwrapped; so does IAPL); + * - IAPL's key, for entities the package never sees (added after it ran): * `custom.ipal.secondFactor: false` (every operation) or `{ : false }`. */ function optedOut(entity: GuardedEntity, operation: string): boolean { @@ -183,7 +183,7 @@ function optedOut(entity: GuardedEntity, operation: string): boolean { } /** - * Before the 2FA package runs: ipal-kit's opt-out written in the package's own + * Before the 2FA package runs: IAPL's opt-out written in the package's own * key as well, so the package leaves those operations unwrapped too. */ export function passOptOutsToPackage(config: Config): Config { @@ -255,7 +255,7 @@ export function guardConfigAccess(config: Config): Config { } /** - * The same for a running Payload, in place: what plugins listed after ipalKit + * The same for a running Payload, in place: what plugins listed after iapl * added, and what Payload itself adds when it sanitizes the config. Returns * the slugs it had to guard. * @@ -309,7 +309,7 @@ export function ensurePayloadGuarded(payload: Pick): null * onInit) `onConfig` is called — before any request or Local API call can use * the new config. Without it the first HTTP request would do the same (the * guard strategy), but a Local API call made before that request would meet - * unguarded entities from plugins listed after ipalKit. Never throws. + * unguarded entities from plugins listed after iapl. Never throws. */ export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: BasePayload) => void): void { try { @@ -334,13 +334,13 @@ export function watchPayloadConfig(payload: BasePayload, onConfig: (payload: Bas } } -/** Name of the auth strategy ipalKit adds to the 2FA collection (see buildGuardStrategy). */ +/** Name of the auth strategy iapl adds to the 2FA collection (see buildGuardStrategy). */ export const GUARD_STRATEGY_NAME = 'ipal-second-factor-guard' /** * An auth strategy that authenticates nobody. Payload runs every strategy at * the start of every request, before any access function, so this is the one - * place ipal-kit is called on each request with the config that is live right + * place IAPL is called on each request with the config that is live right * now. It makes sure that config is guarded — also after a dev hot reload, * where Payload swaps in a freshly built config and does not run onInit, and * when Payload was started with `disableOnInit`. @@ -443,7 +443,7 @@ export function guardNewEntityEndpoints c.slug === collection) diff --git a/src/modules/security/totp/setupRequired.ts b/src/modules/security/totp/setupRequired.ts index 6d6ce53..22e455d 100644 --- a/src/modules/security/totp/setupRequired.ts +++ b/src/modules/security/totp/setupRequired.ts @@ -5,7 +5,7 @@ import { serverText } from '../../integrations/texts.js' import { secondFactorPassed, SETUP_FROM_FIELD } from './secondFactor.js' /** - * "2FA setup required": the pieces ipalKit adds to the 2FA collection and the + * "2FA setup required": the pieces iapl adds to the 2FA collection and the * config when the mode is on (the default with `twoFactor`). * * - the date field `totpSetupFrom` — when the current setup window opened; @@ -58,7 +58,7 @@ export function resolveRequireSetup(option: false | RequireSetupOptions | undefi const given = option?.windowHours if (given !== undefined && given !== false && (typeof given !== 'number' || !Number.isFinite(given) || given < 0)) { throw new Error( - `[ipal] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` + + `[iapl] twoFactor.requireSetup.windowHours must be a number of hours (0 or more) or false, got ${JSON.stringify(given) ?? String(given)}. ` + 'Use 72 (the default), another number, or false / 0 for no time limit.', ) } @@ -84,12 +84,12 @@ const ASYNC_FUNCTION: unknown = (async () => {}).constructor */ export function strictExempt(exempt: unknown): NonNullable { if (typeof exempt !== 'function') { - throw new Error('[ipal] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.') + throw new Error('[iapl] twoFactor.requireSetup.exempt must be a function: ({ user }) => boolean.') } // by the constructor itself, not by its name if (exempt.constructor === ASYNC_FUNCTION) { throw new Error( - '[ipal] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' + + '[iapl] twoFactor.requireSetup.exempt must not be async: it is called in access checks, which cannot wait, and a Promise ' + 'would count as "exempt" for every account. Return true or false at once (decide from the fields on `user`).', ) } @@ -97,7 +97,7 @@ export function strictExempt(exempt: unknown): NonNullable { let answer: unknown @@ -121,7 +121,7 @@ export function strictExempt(exempt: unknown): NonNullable mine.count ? kept : mine if (worst.count <= max) {return null} const retryAfter = Math.max(1, Math.ceil((worst.resetAt - now) / 1000)) - req.payload.logger.warn(`[ipal] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`) + req.payload.logger.warn(`[iapl] 2FA: too many verify attempts for ${collection} ${id}; refused for ${retryAfter} s.`) return Response.json( { message: serverText(req.i18n as never, 'twoFactorTooManyAttempts', { minutes: Math.ceil(retryAfter / 60) }), ok: false }, { headers: { 'Retry-After': String(retryAfter) }, status: 429 }, diff --git a/src/modules/seed/seeder.ts b/src/modules/seed/seeder.ts index c4f5198..dfec7c1 100644 --- a/src/modules/seed/seeder.ts +++ b/src/modules/seed/seeder.ts @@ -29,9 +29,9 @@ import { * - every locale is written with `fallbackLocale: false` onto the same row ids; * - `update: true` overwrites only records nobody edited since seeding; * - `update: true` is refused on production / a non-local database unless - * IPAL_SEED_ALLOW_PROD_UPDATE=1; + * IAPL_SEED_ALLOW_PROD_UPDATE=1; * - after launch a seed touches named records only (`only` / SEED_ONLY): a run with no - * record list is refused on production / a non-local database unless IPAL_SEED_ALLOW_FULL=1; + * record list is refused on production / a non-local database unless IAPL_SEED_ALLOW_FULL=1; * - every write carries `context` (ipalSkipIndexNow, disableRevalidate, ipalSeed); * - one line per record and summary() with the counts. * @@ -92,10 +92,10 @@ export type SeederOptions = { | { /** * A run without `only` on production / a non-local database (a full seed of a live site). - * Default IPAL_SEED_ALLOW_FULL=1 — only with the owner's explicit OK. + * Default IAPL_SEED_ALLOW_FULL=1 — only with the owner's explicit OK. */ allowFull?: boolean - /** Default IPAL_SEED_ALLOW_PROD_UPDATE=1. */ + /** Default IAPL_SEED_ALLOW_PROD_UPDATE=1. */ allowProdUpdate?: boolean /** Database URL checked for "local". Default the var SEED_DB_URL_ENV names (DATABASE_URI). */ databaseUrl?: string @@ -211,15 +211,15 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): if (guard) { const production = guard.production ?? env.NODE_ENV === 'production' const prodLike = production || !local - const allowProdUpdate = guard.allowProdUpdate ?? env.IPAL_SEED_ALLOW_PROD_UPDATE === '1' - const allowFull = guard.allowFull ?? env.IPAL_SEED_ALLOW_FULL === '1' + const allowProdUpdate = guard.allowProdUpdate ?? env.IAPL_SEED_ALLOW_PROD_UPDATE === '1' + const allowFull = guard.allowFull ?? env.IAPL_SEED_ALLOW_FULL === '1' if (!dryRun && !only?.length && prodLike && !allowFull) { throw new Error( `${label} full seed refused: ${production ? 'NODE_ENV=production' : 'the database is not local'} and no record list.\n` + ' A live site keeps the owner\'s edits — after launch a seed touches named records only.\n' + ' 1. List them: SEED_ONLY="pages:kontakt,global:header" (or createSeeder(payload, { only: [...] })).\n' + ' 2. Run with SEED_DRY_RUN=1 and read the plan; back up the database.\n' + - ' 3. A full seed of a live database only with the owner\'s explicit OK: IPAL_SEED_ALLOW_FULL=1.', + ' 3. A full seed of a live database only with the owner\'s explicit OK: IAPL_SEED_ALLOW_FULL=1.', ) } if (update && prodLike && !allowProdUpdate) { @@ -227,13 +227,13 @@ export function createSeeder(payload: BasePayload, options: SeederOptions = {}): `${label} update refused: ${production ? 'NODE_ENV=production' : 'the database is not local'}.\n` + ' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' + ' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' + - ' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.', + ' 3. Run again with IAPL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.', ) } if (force && guard.forceOnlyLocal !== false && prodLike) { throw new Error(`${label} force refused: it overwrites editors' changes and works only on a local database.`) } - if (update && prodLike) {log(`${label} Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?`)} + if (update && prodLike) {log(`${label} Updating a production-like database (IAPL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?`)} } const { codes, defaultLocale } = localesOf(payload) diff --git a/src/modules/seo/FaviconCheck.tsx b/src/modules/seo/FaviconCheck.tsx index 7987118..09d115c 100644 --- a/src/modules/seo/FaviconCheck.tsx +++ b/src/modules/seo/FaviconCheck.tsx @@ -2,7 +2,7 @@ import { useConfig, useFormFields, useTranslation } from '@payloadcms/ui' import { useEffect, useState } from 'react' -import { ipalT } from '../admin-i18n/t.js' +import { iaplT } from '../admin-i18n/t.js' import { faviconProblems } from './faviconProblems.js' export type FaviconCheckProps = { @@ -48,7 +48,7 @@ export function FaviconCheck({ fieldPath, mediaSlug = 'media', path }: FaviconCh }) const media = res.ok ? ((await res.json()) as { height?: number; mimeType?: string; width?: number }) : null const found = media ? faviconProblems(media) : [] - setProblems(found.map((p) => ipalT(t, p.key, { height: p.height, width: p.width }))) + setProblems(found.map((p) => iaplT(t, p.key, { height: p.height, width: p.width }))) } catch { // aborted or offline — a hint is not worth an error } diff --git a/src/modules/seo/MetaDescriptionCheck.tsx b/src/modules/seo/MetaDescriptionCheck.tsx index 65eccca..c8092dd 100644 --- a/src/modules/seo/MetaDescriptionCheck.tsx +++ b/src/modules/seo/MetaDescriptionCheck.tsx @@ -2,7 +2,7 @@ import { useConfig, useDocumentInfo, useFormFields, useLocale, useTranslation } from '@payloadcms/ui' import { useEffect, useState } from 'react' -import { ipalT } from '../admin-i18n/t.js' +import { iaplT } from '../admin-i18n/t.js' export type MetaDescriptionCheckProps = { /** An empty description is filled from the page content on save (autoFill). */ @@ -48,8 +48,8 @@ export function MetaDescriptionCheck({ if (!description) { setWarning( autoFill - ? { text: ipalT(t, 'seoDescEmptyAutoFill'), tone: 'info' } - : { text: ipalT(t, 'seoDescEmpty'), tone: 'warn' }, + ? { text: iaplT(t, 'seoDescEmptyAutoFill'), tone: 'info' } + : { text: iaplT(t, 'seoDescEmpty'), tone: 'warn' }, ) return } @@ -67,7 +67,7 @@ export function MetaDescriptionCheck({ try { const settings = await get(`${base}/globals/${settingsSlug}?depth=0&locale=${locale}`) if (settings && norm(settings[siteDescriptionField]) === description) { - setWarning({ text: ipalT(t, 'seoDescSameAsSite'), tone: 'warn' }) + setWarning({ text: iaplT(t, 'seoDescSameAsSite'), tone: 'warn' }) return } @@ -82,7 +82,7 @@ export function MetaDescriptionCheck({ const twin = (found?.docs as Record[] | undefined)?.[0] if (twin) { const name = norm(twin[titleField]) || String(twin.id) - setWarning({ text: ipalT(t, 'seoDescSameAs', { name }), tone: 'warn' }) + setWarning({ text: iaplT(t, 'seoDescSameAs', { name }), tone: 'warn' }) return } setWarning(null) diff --git a/src/modules/seo/buildManifest.ts b/src/modules/seo/buildManifest.ts index 1b081a9..461bd0e 100644 --- a/src/modules/seo/buildManifest.ts +++ b/src/modules/seo/buildManifest.ts @@ -77,7 +77,7 @@ export function createManifestHandler(opts: { .catch(() => null)) as null | SettingsShape } catch (err) { console.warn( - '[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:', + '[iapl] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:', err, ) return fallback diff --git a/src/modules/seo/buildRobots.ts b/src/modules/seo/buildRobots.ts index c447a70..a391824 100644 --- a/src/modules/seo/buildRobots.ts +++ b/src/modules/seo/buildRobots.ts @@ -41,7 +41,7 @@ export type AiBotRule = { access: 'allow' | 'disallow'; userAgent: string } export type RobotsOptions = { /** * Admin path to disallow. Default '/admin'. With a hidden panel - * (ipalKit adminRoute) pass `false`: robots.txt is public, so listing the + * (iapl adminRoute) pass `false`: robots.txt is public, so listing the * path would reveal it — the admin is noindex anyway. */ adminRoute?: false | string @@ -140,7 +140,7 @@ export function buildRobots({ sitemap = true, }: BuildRobotsArgs): RobotsRules { const origin = baseUrl.replace(/\/$/, '') - // Staging / preview (IPAL_NOINDEX=1): nothing may be crawled. + // Staging / preview (IAPL_NOINDEX=1): nothing may be crawled. if (isSiteNoindex()) {return { rules: { disallow: ['/'], userAgent: '*' } }} const defaults = [...(adminRoute ? [adminRoute] : []), '/api'] diff --git a/src/modules/seo/buildSiteNavigationJsonLd.ts b/src/modules/seo/buildSiteNavigationJsonLd.ts index 6c68f1e..cf7dc6b 100644 --- a/src/modules/seo/buildSiteNavigationJsonLd.ts +++ b/src/modules/seo/buildSiteNavigationJsonLd.ts @@ -51,7 +51,7 @@ type BuildNavigationJsonLdArgs = { config: I18nConfig /** Child items. Default `item.subItems`. Return [] to list top level only. */ getChildren?: (item: NavSource) => unknown - /** Link of an item. Default `item.link` (ipal-nav template, buildLinkField). */ + /** Link of an item. Default `item.link` (iapl-nav template, buildLinkField). */ getLink?: (item: NavSource) => LinkValue | null | undefined /** Homepage slug(s) so the home link collapses to /{locale}. */ homeSlug?: Record | string diff --git a/src/modules/seo/indexNow.ts b/src/modules/seo/indexNow.ts index 26a2a60..9175aea 100644 --- a/src/modules/seo/indexNow.ts +++ b/src/modules/seo/indexNow.ts @@ -12,7 +12,7 @@ import { isSiteNoindex } from './siteNoindex.js' * Search and Copilot, so new content reaches AI answers in minutes instead of * waiting for a crawl. Google doesn't use IndexNow (it reads the sitemap). * - * Opt-in: `ipalKit({ indexNow: true })` adds the hook to the pages and content + * Opt-in: `iapl({ indexNow: true })` adds the hook to the pages and content * collections; or add `buildIndexNowHook(…)` yourself. Needs the key file route * (createIndexNowKeyRoute) and a key: Site Integrations → IndexNow (generated on * the first save) or the INDEXNOW_KEY env var. Sends only from production with @@ -82,7 +82,7 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload: /** * True when submissions may leave this machine: production + a public https - * origin, and not a staging copy (IPAL_NOINDEX) — a staging build runs with + * origin, and not a staging copy (IAPL_NOINDEX) — a staging build runs with * NODE_ENV=production too, and its URLs must not reach Bing. */ function publicOrigin(baseUrl?: string): null | string { @@ -116,12 +116,12 @@ export async function submitToIndexNow({ }) // 200 = accepted, 202 = accepted, key validation pending. if (res.status !== 200 && res.status !== 202) { - console.warn(`[ipal] IndexNow: ${res.status} for ${urls.length} URL(s) — check the key file at ${origin}${INDEXNOW_KEY_PATH}`) + console.warn(`[iapl] IndexNow: ${res.status} for ${urls.length} URL(s) — check the key file at ${origin}${INDEXNOW_KEY_PATH}`) return false } return true } catch (err) { - console.warn('[ipal] IndexNow: request failed:', err instanceof Error ? err.message : err) + console.warn('[iapl] IndexNow: request failed:', err instanceof Error ? err.message : err) return false } } @@ -186,7 +186,7 @@ export function buildIndexNowHook({ await submitToIndexNow({ baseUrl: origin, payload: req.payload, urls }) } // Background: never block or fail the save. - void run().catch((err: unknown) => console.warn('[ipal] IndexNow hook failed:', err instanceof Error ? err.message : err)) + void run().catch((err: unknown) => console.warn('[iapl] IndexNow hook failed:', err instanceof Error ? err.message : err)) return doc } } diff --git a/src/modules/seo/routeHandlers.ts b/src/modules/seo/routeHandlers.ts index a63f552..9803af9 100644 --- a/src/modules/seo/routeHandlers.ts +++ b/src/modules/seo/routeHandlers.ts @@ -75,7 +75,7 @@ export function createLlmsTxtRoute(opts: { } catch (err) { // DB unreachable at build (container) — return a minimal valid file so the // route doesn't 500; it fills in at runtime. No per-project try/catch. - console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err) + console.warn('[iapl] createLlmsTxtRoute: could not build llms.txt:', err) return new Response('# llms.txt\n', { headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' }, }) @@ -215,7 +215,7 @@ export function createSitemapRouteHandler( const headers = all.length ? xmlHeaders : { ...xmlHeaders, 'Cache-Control': 'no-store' } return new Response(buildSitemapXml(all, { cssUrl }), { headers }) } catch (err) { - console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err) + console.warn('[iapl] createSitemapRouteHandler: could not build sitemap:', err) // At runtime: 503 + Retry-After — crawlers come back later, while an empty // sitemap with 200 would tell them the site has no pages. if (process.env.NEXT_PHASE !== 'phase-production-build') { diff --git a/src/modules/seo/seoPluginConfig.ts b/src/modules/seo/seoPluginConfig.ts index 37dc6ff..9e243b1 100644 --- a/src/modules/seo/seoPluginConfig.ts +++ b/src/modules/seo/seoPluginConfig.ts @@ -91,7 +91,7 @@ function afterDescription(fields: Field[], extra: Field | null): Field[] { } /** - * Configures @payloadcms/plugin-seo from IPAL's SeoOption. + * Configures @payloadcms/plugin-seo from IAPL's SeoOption. * * Adds the `meta` field group (title, description, image) to the client's * chosen collections. tabbedUI is intentionally NOT used — it merges tabs by diff --git a/src/modules/seo/siteNoindex.ts b/src/modules/seo/siteNoindex.ts index 64a305a..a857144 100644 --- a/src/modules/seo/siteNoindex.ts +++ b/src/modules/seo/siteNoindex.ts @@ -1,12 +1,12 @@ /** - * Whole-site noindex for staging, previews and test copies: set IPAL_NOINDEX=1 + * Whole-site noindex for staging, previews and test copies: set IAPL_NOINDEX=1 * in that environment's env. Then robots.txt disallows everything, every page * gets `robots: noindex, nofollow`, and buildSecurityHeaders adds * `X-Robots-Tag: noindex, nofollow` to every response (files and API too). * Production never sets it — a forgotten staging copy indexed by Google is a * duplicate of the real site. */ -export const SITE_NOINDEX_ENV = 'IPAL_NOINDEX' +export const SITE_NOINDEX_ENV = 'IAPL_NOINDEX' export function isSiteNoindex(): boolean { const v = process.env[SITE_NOINDEX_ENV]?.trim().toLowerCase() diff --git a/src/modules/seo/titleSeparator.ts b/src/modules/seo/titleSeparator.ts index a9815ad..ad15497 100644 --- a/src/modules/seo/titleSeparator.ts +++ b/src/modules/seo/titleSeparator.ts @@ -60,11 +60,11 @@ export async function migrateTitleSeparator(payload: BasePayload, settingsSlug = for (const [char, name] of Object.entries(NAME_OF_CHAR)) { const result = await globals.collection.updateOne({ globalType: settingsSlug, titleSeparator: char }, { $set: { titleSeparator: name } }) if (result.modifiedCount) { - payload.logger.info(`[ipal] Site Settings: title separator '${char}' stored as '${name}' (GraphQL-safe value).`) + payload.logger.info(`[iapl] Site Settings: title separator '${char}' stored as '${name}' (GraphQL-safe value).`) } } } catch (error) { - payload.logger.error({ err: error, msg: '[ipal] Site Settings: could not migrate the title separator' }) + payload.logger.error({ err: error, msg: '[iapl] Site Settings: could not migrate the title separator' }) } } diff --git a/src/modules/seo/validateFavicon.ts b/src/modules/seo/validateFavicon.ts index f6efb69..7a88f37 100644 --- a/src/modules/seo/validateFavicon.ts +++ b/src/modules/seo/validateFavicon.ts @@ -26,8 +26,8 @@ export const validateFaviconField: FieldHook = async ({ req, value }) => { for (const { height, key, width } of faviconProblems(media as { height?: number; mimeType?: string; width?: number })) { req.payload.logger.warn( key === 'faviconTooSmall' - ? `[ipal] Favicon is ${width}×${height}px. Google requires ≥48×48 to display it in search results. Upload a larger square icon (96 or 192px).` - : `[ipal] Favicon is not square (${width}×${height}). Use a square icon so it isn't cropped in the browser tab or search results.`, + ? `[iapl] Favicon is ${width}×${height}px. Google requires ≥48×48 to display it in search results. Upload a larger square icon (96 or 192px).` + : `[iapl] Favicon is not square (${width}×${height}). Use a square icon so it isn't cropped in the browser tab or search results.`, ) } } catch { diff --git a/src/modules/shared/purge.ts b/src/modules/shared/purge.ts index 7367ee7..4da0f64 100644 --- a/src/modules/shared/purge.ts +++ b/src/modules/shared/purge.ts @@ -23,7 +23,7 @@ export function createDailyPurge(collection: string) { .then(() => payload.db.deleteMany({ collection: collection as never, where })) .catch((err: unknown) => { lastPurge = 0 - payload.logger.error(`[ipal] ${collection} retention purge failed: ${err instanceof Error ? err.message : String(err)}`) + payload.logger.error(`[iapl] ${collection} retention purge failed: ${err instanceof Error ? err.message : String(err)}`) }) } } diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index ea1c202..27967d7 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -71,7 +71,7 @@ type CheckArgs = { cost?: number } & RateLimitArgs /** * Requests with no usable client IP (a proxy that strips the header, a - * misconfigured IPAL_IP_HEADER) share one bucket with a roomier limit. Letting + * misconfigured IAPL_IP_HEADER) share one bucket with a roomier limit. Letting * them through unlimited meant a client that simply omits the header walked * past every limiter; one shared bucket keeps real visitors flowing while * capping the flood. @@ -153,7 +153,7 @@ export async function consumeRateLimit({ try { bucket = await store.hit(id, cost, windowMs) } catch (err) { - console.warn('[ipal] rate limit store failed, allowing request:', err instanceof Error ? err.message : err) + console.warn('[iapl] rate limit store failed, allowing request:', err instanceof Error ? err.message : err) return { ok: true, retryAfter: 0 } } } else { @@ -173,7 +173,7 @@ export function retryAfterSeconds(key: string, scope = 'form'): number { export type ClientIpOptions = { /** * Read the IP from this header only (e.g. 'cf-connecting-ip' behind - * Cloudflare, 'x-real-ip' behind nginx). Falls back to the IPAL_IP_HEADER env + * Cloudflare, 'x-real-ip' behind nginx). Falls back to the IAPL_IP_HEADER env * var. Pin it in production: without it the headers below are tried in turn, * and a client that reaches the app directly could set any of them. */ @@ -203,12 +203,12 @@ let warnedUnpinned = false export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string { const h = source instanceof Headers ? source : source.headers - const pinned = options.header ?? process.env.IPAL_IP_HEADER + const pinned = options.header ?? process.env.IAPL_IP_HEADER if (!pinned && !warnedUnpinned && process.env.NODE_ENV === 'production') { warnedUnpinned = true console.warn( - '[ipal] IPAL_IP_HEADER is not set — the rate limit trusts whichever IP header a request carries, ' + - 'so a client reaching the app directly can spoof it. Set IPAL_IP_HEADER=cf-connecting-ip ' + + '[iapl] IAPL_IP_HEADER is not set — the rate limit trusts whichever IP header a request carries, ' + + 'so a client reaching the app directly can spoof it. Set IAPL_IP_HEADER=cf-connecting-ip ' + '(behind Cloudflare) or x-forwarded-for (behind Traefik/nginx only).', ) } diff --git a/src/modules/starter/answers.ts b/src/modules/starter/answers.ts index 88e9a78..008e902 100644 --- a/src/modules/starter/answers.ts +++ b/src/modules/starter/answers.ts @@ -1,5 +1,5 @@ /** - * The architecture questions (AGENT.md "Ask before you build", ipal-setup stage 0) as data: + * The architecture questions (AGENT.md "Ask before you build", iapl-setup stage 0) as data: * the shape of `--answers `, validation, and the flags the answers turn on. * Nothing here has a silent default — a missing answer is an error the owner must fill in. */ @@ -11,7 +11,7 @@ export type ContentCollection = 'caseStudies' | 'posts' export type StarterAnswers = { admin: { adminMeta: boolean - /** Required when `adminMeta` is false — goes to ipal-doctor.json and "Project decisions". */ + /** Required when `adminMeta` is false — goes to iapl-doctor.json and "Project decisions". */ adminMetaOffReason?: string agency: 'intecion' | 'none' | { name: string; url: string } twoFactor: boolean @@ -23,7 +23,7 @@ export type StarterAnswers = { consentMode: 'advanced' | 'basic' cookieScanner: boolean cookieScannerOffReason?: string - /** Browser crawl through the shared cookie-crawler service (needs IPAL_COOKIE_SCAN_* in Coolify). */ + /** Browser crawl through the shared cookie-crawler service (needs IAPL_COOKIE_SCAN_* in Coolify). */ crawl: boolean tools: AnalyticsTool[] } @@ -104,7 +104,7 @@ export function validateAnswers(input: unknown): string[] { need(new Set(codes).size === codes.length, 'languages.locales: a code is listed twice') // Not in this version (owner's decision: later): the base seed writes Polish + English text with Polish // default-locale slugs, and the reference site has a [locale] segment (reference/src/seed/base.ts). - const manual = 'is not supported by `ipal-kit create` yet — set the site up by hand with the ipal-setup skill (stages 1–11)' + const manual = 'is not supported by `iapl create` yet — set the site up by hand with the iapl-setup skill (stages 1–11)' need(codes.length !== 1, `languages: a single-language site ${manual}`) need(codes.length === 1 || langs?.default === 'pl', `languages: a default language other than "pl" (here "${String(langs?.default)}") ${manual}`) need(codes.length <= 1 || codes.includes('en'), `languages: a site without "en" ${manual}`) diff --git a/src/modules/starter/bundle.ts b/src/modules/starter/bundle.ts index 2dc1e44..e904fa4 100644 --- a/src/modules/starter/bundle.ts +++ b/src/modules/starter/bundle.ts @@ -103,6 +103,6 @@ export function packBundle(bundle: StarterBundle): Buffer { export function unpackBundle(data: Buffer): StarterBundle { const bundle = JSON.parse(gunzipSync(data).toString('utf8')) as StarterBundle - if (bundle.schema !== 1) {throw new Error('starter bundle: unknown schema — use the ipal-kit version that built it')} + if (bundle.schema !== 1) {throw new Error('starter bundle: unknown schema — use the IAPL version that built it')} return bundle } diff --git a/src/modules/starter/cli.ts b/src/modules/starter/cli.ts index 257b507..f2f7b6d 100644 --- a/src/modules/starter/cli.ts +++ b/src/modules/starter/cli.ts @@ -1,5 +1,5 @@ /** - * `ipal-kit create ` — a new client site from the reference site, following every team + * `iapl create ` — a new client site from the reference site, following every team * convention (docs/project-starter.md). Run with `pnpm dlx @intecion/ipal-kit@ create `. */ import { spawnSync } from 'node:child_process' @@ -17,7 +17,7 @@ import { askInTerminal } from './prompts.js' import { renderSite } from './render.js' import { secretFindings } from './secrets.js' -export const CREATE_USAGE = `Usage: ipal-kit create [options] +export const CREATE_USAGE = `Usage: iapl create [options] pnpm dlx @intecion/ipal-kit@ create intecion.com --dir target folder (default ./-web); must be new or empty @@ -68,7 +68,7 @@ function value(args: string[], name: string): string | undefined { export function parseCreateArgs(args: string[]): CreateOptions { const domain = args.find((arg, i) => !arg.startsWith('--') && !['--answers', '--dir', '--external', '--plugin-spec'].includes(args[i - 1] ?? '')) - if (!domain) {throw new Error('the production domain is required, e.g. `ipal-kit create intecion.com`')} + if (!domain) {throw new Error('the production domain is required, e.g. `iapl create intecion.com`')} const ext = args.indexOf('--external') const extNext = ext >= 0 ? args[ext + 1] : undefined return { @@ -105,7 +105,7 @@ function loadBundle(): { bundle: StarterBundle; sha256: string } { const bundle = collectBundle(reference) return { bundle, sha256: sha(packBundle(bundle)) } } - throw new Error('no starter templates in this ipal-kit (dist/starter/template.json.gz) — use a released version') + throw new Error('no starter templates in this IAPL (dist/starter/template.json.gz) — use a released version') } function pluginVersion(): string { @@ -159,25 +159,25 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. options = parseCreateArgs(args) domain = normalizeDomain(options.domain) } catch (error) { - log(`ipal-kit create: ${(error as Error).message}\n\n${CREATE_USAGE}`) + log(`iapl create: ${(error as Error).message}\n\n${CREATE_USAGE}`) return 1 } const flat = domain.replace(/\./g, '') const cwd = process.cwd() const dir = resolve(options.dir ?? `${flat}-web`) if (existsSync(dir) && readdirSync(dir).length) { - log(`ipal-kit create: ${dir} is not empty — pick a new folder with --dir`) + log(`iapl create: ${dir} is not empty — pick a new folder with --dir`) return 1 } if (!options.dir && existsSync(join(cwd, 'package.json'))) { - log('ipal-kit create: this folder is a project — pass --dir ../-web to create the site next to it') + log('iapl create: this folder is a project — pass --dir ../-web to create the site next to it') return 1 } const answers = await readAnswers(options) const errors = validateAnswers(answers) if (errors.length) { - log(`ipal-kit create: the answers are incomplete — nothing was written:\n - ${errors.join('\n - ')}`) + log(`iapl create: the answers are incomplete — nothing was written:\n - ${errors.join('\n - ')}`) return 1 } const ctx: SiteContext = { @@ -193,7 +193,7 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. ctx.source = { bundleSha256: sha256, commit: bundle.source?.commit ?? null } files = renderSite(bundle, answers, ctx) } catch (error) { - log(`ipal-kit create: ${(error as Error).message}`) + log(`iapl create: ${(error as Error).message}`) return 1 } if (options.pluginSpec) { @@ -219,13 +219,13 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. if (options.install) { step('install', 'pnpm', ['install', '--ignore-workspace']) if (!failed.length) { - step('skills', 'pnpm', ['exec', 'ipal-skills', ...(answers.tooling.external.length ? ['--external', answers.tooling.external.join(',')] : [])]) - step('tokens (contrast check)', 'pnpm', ['exec', 'ipal-tokens']) + step('skills', 'pnpm', ['exec', 'iapl-skills', ...(answers.tooling.external.length ? ['--external', answers.tooling.external.join(',')] : [])]) + step('tokens (contrast check)', 'pnpm', ['exec', 'iapl-tokens']) step('types', 'pnpm', ['generate:types']) step('import map', 'pnpm', ['generate:importmap']) step('typecheck', 'pnpm', ['typecheck']) - if (existsSync(join(dir, 'node_modules', '.bin', 'ipal-doctor'))) {step('ipal-doctor', 'pnpm', ['exec', 'ipal-doctor', '--strict', '--offline'])} - else {log('ipal-doctor is not in this ipal-kit version yet — run it once it ships.')} + if (existsSync(join(dir, 'node_modules', '.bin', 'iapl-doctor'))) {step('iapl-doctor', 'pnpm', ['exec', 'iapl-doctor', '--strict', '--offline'])} + else {log('iapl-doctor is not in this IAPL version yet — run it once it ships.')} } } if (options.git && !failed.length) { @@ -236,7 +236,7 @@ export async function runCreateCli(args: string[], log: Log = (line) => process. log(`Not committed — possible secrets:\n ${findings.join('\n ')}`) failed.push('secret check') } else { - step('first commit', 'git', ['commit', '-q', '-m', `chore: create site with ipal-kit create ${ctx.pluginVersion}`]) + step('first commit', 'git', ['commit', '-q', '-m', `chore: create site with iapl create ${ctx.pluginVersion}`]) } } log(report(answers, ctx, dir, options, failed)) @@ -249,12 +249,12 @@ function report(a: StarterAnswers, ctx: SiteContext, dir: string, options: Creat failed.length ? `Created with problems in: ${failed.join(', ')} — fix them, then rerun the step.` : `Created ${ctx.domain} in ${dir}.`, '', 'Next:', - ...(options.install ? [] : [' pnpm install && pnpm exec ipal-skills && pnpm exec ipal-tokens && pnpm generate:types && pnpm generate:importmap']), + ...(options.install ? [] : [' pnpm install && pnpm exec iapl-skills && pnpm exec iapl-tokens && pnpm generate:types && pnpm generate:importmap']), ` 1. Local MongoDB with the database ${ctx.dbNames.dev} (DATABASE_URI in .env), then: pnpm dev`, ` 2. pnpm seed (system pages, navigation, the forms to ${a.forms.recipient} — before launch only), then /admin → first user + 2FA`, - ' 3. Panel steps and the full checklist: .agents/skills/ipal-setup/SKILL.md §11; architecture answers: AGENTS.md', + ' 3. Panel steps and the full checklist: .agents/skills/iapl-setup/SKILL.md §11; architecture answers: AGENTS.md', ` 4. Deploy: docs/DEPLOY.md — Coolify app from the repo, MongoDB resource ${ctx.dbNames.prod}, DNS records for ${ctx.domain}`, - ...(a.consent.crawl ? [' 5. Coolify env: IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN (shared cookie-crawler)'] : []), + ...(a.consent.crawl ? [' 5. Coolify env: IAPL_COOKIE_SCAN_URL / IAPL_COOKIE_SCAN_TOKEN (shared cookie-crawler)'] : []), ] return lines.join('\n') } diff --git a/src/modules/starter/generate.ts b/src/modules/starter/generate.ts index 7570ced..89110a2 100644 --- a/src/modules/starter/generate.ts +++ b/src/modules/starter/generate.ts @@ -1,6 +1,6 @@ /** * Files and sections the starter writes from the answers instead of copying them from the reference - * site: the language list, the brand tokens and DESIGN.md, the AGENTS.md decisions, ipal-doctor.json, + * site: the language list, the brand tokens and DESIGN.md, the AGENTS.md decisions, iapl-doctor.json, * the fonts in the root layout and the package.json rewrite. */ import type { StarterAnswers } from './answers.js' @@ -10,10 +10,10 @@ export type SiteContext = { date: string dbNames: { dev: string; prod: string } domain: string - /** The exact ipal-kit version written into package.json. */ + /** The exact IAPL version written into package.json. */ pluginVersion: string serverUrl: string - /** Which starter bundle made the site (recorded in `.ipal/starter.json`; the release gate compares it). */ + /** Which starter bundle made the site (recorded in `.iapl/starter.json`; the release gate compares it). */ source?: { bundleSha256: string; commit: null | string } } @@ -71,7 +71,7 @@ export function renderDesignMd(a: StarterAnswers): string { return `# DESIGN.md — ${a.siteName} The human source of the look. Its machine form is \`src/design/tokens.ts\`; the two must agree -(\`ipal-doctor\` compares them). Values go into \`tokens.ts\`, never into components. +(\`iapl-doctor\` compares them). Values go into \`tokens.ts\`, never into components. Sections are fixed: fill every one, write "default" where the brand keeps the standard. ## 1. Brand in one sentence @@ -86,7 +86,7 @@ The one memorable element (where the boldness goes): [TO FILL]. Everything else | accent | ${s.accent ?? 'default (= primary)'} | | badges, highlights | | bg / surface / surface-muted | default | default | page, cards, alternate sections | -Contrast (paste \`pnpm exec ipal-tokens --report\`; every ✗ fixed before launch): +Contrast (paste \`pnpm exec iapl-tokens --report\`; every ✗ fixed before launch): \`\`\` [TO FILL: report] \`\`\` @@ -128,7 +128,7 @@ function agencyText(agency: StarterAnswers['admin']['agency']): string { export function renderDecisions(a: StarterAnswers, ctx: SiteContext): string { const lines = [ `- Languages: ${a.languages.locales.map((l) => l.code).join(', ')} (default ${a.languages.default}), every language with a URL prefix; \`/\` redirects to \`/${a.languages.default}\`.`, - `- Styling: the ipal-kit token standard (\`src/design/tokens.ts\` → \`pnpm tokens\`); primary ${a.styling.primary}${a.styling.secondary ? `, secondary ${a.styling.secondary}` : ''}${a.styling.accent ? `, accent ${a.styling.accent}` : ''}; ${a.styling.fontBody} (body) + ${a.styling.fontHeading} (headings); radius ${a.styling.radius}; ${a.styling.fluid === 'wide' ? 'fluid-wide' : 'fluid'}; theme ${a.styling.theme}, default ${a.styling.defaultTheme}.`, + `- Styling: the IAPL token standard (\`src/design/tokens.ts\` → \`pnpm tokens\`); primary ${a.styling.primary}${a.styling.secondary ? `, secondary ${a.styling.secondary}` : ''}${a.styling.accent ? `, accent ${a.styling.accent}` : ''}; ${a.styling.fontBody} (body) + ${a.styling.fontHeading} (headings); radius ${a.styling.radius}; ${a.styling.fluid === 'wide' ? 'fluid-wide' : 'fluid'}; theme ${a.styling.theme}, default ${a.styling.defaultTheme}.`, `- Pages and content: ${a.content.pages.join('; ')}. Collections: ${a.content.collections.length ? a.content.collections.join(', ') : 'none'}.`, `- Forms: ${a.forms.list.length ? a.forms.list.join(', ') : 'none'}; submissions to ${a.forms.recipient}; e-mail via ${a.forms.transport === 'graph' ? 'Microsoft Graph' : 'SMTP from Site integrations'}; Turnstile on.`, `- Analytics and consent: ${a.consent.tools.length ? a.consent.tools.join(', ') : 'no analytics tools'}; Consent Mode ${a.consent.consentMode}; banner \`settings="${a.consent.banner}"\`; consent log on; cookie scanner ${yesNo(a.consent.cookieScanner)}${a.consent.cookieScanner ? `, crawl ${yesNo(a.consent.crawl)}` : ` — ${a.consent.cookieScannerOffReason}`}.`, @@ -140,14 +140,14 @@ export function renderDecisions(a: StarterAnswers, ctx: SiteContext): string { '- Approved exception: the `/design` styleguide has its labels in code (token names, a technical page, noindex) — the "texts from the panel" rule does not apply to it.', '- Approved exception: `ALLOW_LOCAL_MEDIA=1` (instrumentation.ts, next.config.ts) lets a production build run without R2 for local checks and CI only; never set in Coolify.', `- Agent tooling: skills in \`.agents/skills\`${a.tooling.external.length ? `; external skills ${a.tooling.external.join(', ')}` : '; no external skills'}.`, - `- Created with \`ipal-kit create\` ${ctx.pluginVersion} on ${ctx.date}.`, + `- Created with \`iapl create\` ${ctx.pluginVersion} on ${ctx.date}.`, ] const skip = auditSkips(a) - if (skip.length) {lines.push(`- ipal-audit-skip: ${skip.map((s) => s.key).join(', ')} — ${skip.map((s) => s.reason).join('; ')}`)} + if (skip.length) {lines.push(`- iapl-audit-skip: ${skip.map((s) => s.key).join(', ')} — ${skip.map((s) => s.reason).join('; ')}`)} return `## Project decisions\n${lines.join('\n')}\n` } -/** Modules the owner turned off: the `ipal-audit-skip` keys and the matching ipal-doctor rules. */ +/** Modules the owner turned off: the `iapl-audit-skip` keys and the matching iapl-doctor rules. */ function auditSkips(a: StarterAnswers): { doctor?: string; key: string; reason: string }[] { const out: { doctor?: string; key: string; reason: string }[] = [] if (!a.admin.twoFactor) {out.push({ doctor: '2fa', key: 'twofactor', reason: a.admin.twoFactorOffReason ?? '' })} @@ -180,8 +180,8 @@ export function renderAgentsMd(reference: string, a: StarterAnswers, ctx: SiteCo type DoctorRule = { [key: string]: unknown; off?: boolean; reason: string; until?: string } /** - * ipal-doctor.json: the domain, not launched yet, and every deliberate difference silenced with its reason — - * the reference site's own silences (`inherited`, from its ipal-doctor.json) while the files they cover are in + * iapl-doctor.json: the domain, not launched yet, and every deliberate difference silenced with its reason — + * the reference site's own silences (`inherited`, from its iapl-doctor.json) while the files they cover are in * the site, CSP report-only for 28 days, and each module the owner turned off. A temporary silence of the * reference site (one with `until`, a follow-up of its own) is not inherited: a new site starts with that check on. */ diff --git a/src/modules/starter/manifest.ts b/src/modules/starter/manifest.ts index 7c8fbf0..c0b794a 100644 --- a/src/modules/starter/manifest.ts +++ b/src/modules/starter/manifest.ts @@ -63,7 +63,7 @@ export function assertManifest(value: unknown): asserts value is StarterManifest const m = value as null | Partial const problems: string[] = [] if (!m || typeof m !== 'object') {throw new Error('starter.manifest.json: not an object')} - if (m.schema !== 1) {problems.push(`schema ${String(m.schema)} (this ipal-kit reads schema 1)`)} + if (m.schema !== 1) {problems.push(`schema ${String(m.schema)} (this IAPL reads schema 1)`)} for (const key of ['drop', 'keep', 'template'] as const) { if (!Array.isArray(m[key])) {problems.push(`"${key}" must be a list of globs`)} } diff --git a/src/modules/starter/render.ts b/src/modules/starter/render.ts index 46f59de..d1e435a 100644 --- a/src/modules/starter/render.ts +++ b/src/modules/starter/render.ts @@ -22,7 +22,7 @@ type Generator = (a: StarterAnswers, ctx: SiteContext, reference: string | undef const GENERATORS: Record = { 'DESIGN.md': (a) => renderDesignMd(a), - 'ipal-doctor.json': (a, ctx, reference) => renderDoctorConfig(a, ctx, reference ? (JSON.parse(reference) as { rules?: Record }).rules : {}), + 'iapl-doctor.json': (a, ctx, reference) => renderDoctorConfig(a, ctx, reference ? (JSON.parse(reference) as { rules?: Record }).rules : {}), 'src/design/tokens.ts': (a) => renderTokens(a), 'src/i18n.config.ts': (a) => renderI18nConfig(a), } @@ -56,10 +56,10 @@ export function renderSite(bundle: StarterBundle, a: StarterAnswers, ctx: SiteCo const { manifest } = bundle const flags = flagsFromAnswers(a) const unknown = bundleFlags(bundle).filter((flag) => !(flag in flags)) - if (unknown.length) {throw new Error(`the reference site uses flags this ipal-kit does not set: ${unknown.join(', ')}`)} + if (unknown.length) {throw new Error(`the reference site uses flags this IAPL does not set: ${unknown.join(', ')}`)} const values = placeholderValues(a, ctx) const missing = Object.keys(manifest.placeholders).filter((token) => !(token in values)) - if (missing.length) {throw new Error(`the manifest uses placeholders this ipal-kit does not fill: ${missing.join(', ')}`)} + if (missing.length) {throw new Error(`the manifest uses placeholders this IAPL does not fill: ${missing.join(', ')}`)} // a fake value the site legitimately shares (e.g. the business type "ProfessionalService") is not a leftover const fakes = Object.fromEntries(Object.entries(manifest.placeholders).filter(([token, fake]) => !(values[token] ?? '').includes(fake))) @@ -82,13 +82,13 @@ export function renderSite(bundle: StarterBundle, a: StarterAnswers, ctx: SiteCo for (const path of manifest.generate ?? []) { const generate = GENERATORS[path] if (!generate) { - problems.push(`${path}: listed under "generate" but this ipal-kit has no generator for it`) + problems.push(`${path}: listed under "generate" but this IAPL has no generator for it`) continue } out[path] = generate(a, ctx, bundle.files[path]) } if (problems.length) {throw new Error(`rendering the site:\n ${problems.join('\n ')}`)} out['pnpm-lock.yaml'] = bundle.lockfile - out['.ipal/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, ipalKit: ctx.pluginVersion, ...(ctx.source ? { source: ctx.source } : {}) }, null, 2)}\n` + out['.iapl/starter.json'] = `${JSON.stringify({ answers: a, createdAt: ctx.date, domain: ctx.domain, iapl: ctx.pluginVersion, ...(ctx.source ? { source: ctx.source } : {}) }, null, 2)}\n` return out } diff --git a/src/modules/stats/PageStats.tsx b/src/modules/stats/PageStats.tsx index 56ba252..fead3f0 100644 --- a/src/modules/stats/PageStats.tsx +++ b/src/modules/stats/PageStats.tsx @@ -29,7 +29,7 @@ function ensureVisitorId(): string { } export type PageStatsProps = { - /** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */ + /** The hit endpoint. Default '/api/ipal/hit' (iapl({ stats: true })). */ endpoint?: string /** Current locale code, stored with the visit. */ locale?: string diff --git a/src/modules/stats/admin/StatsView.tsx b/src/modules/stats/admin/StatsView.tsx index 1b21c3d..97af254 100644 --- a/src/modules/stats/admin/StatsView.tsx +++ b/src/modules/stats/admin/StatsView.tsx @@ -76,7 +76,7 @@ function VisitorHistory({ base, i18n, timeZone, visitorId, visits }: { base: str } /** - * Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the + * Admin view at /admin/stats (iapl({ stats: true })): visits per day for the * last 30 days, top pages, entry pages, referrers, devices, and — for visitors * who accepted analytics cookies — a per-visitor history (?visitor=). * For users the stats-visits collection lets read (admins by default). diff --git a/src/modules/stats/admin/statsI18n.ts b/src/modules/stats/admin/statsI18n.ts index af03824..e845dbf 100644 --- a/src/modules/stats/admin/statsI18n.ts +++ b/src/modules/stats/admin/statsI18n.ts @@ -1,6 +1,6 @@ import type { AdminTextKey } from '../../admin-i18n/texts/index.js' -import { formatNumber, ipalT } from '../../admin-i18n/t.js' +import { formatNumber, iaplT } from '../../admin-i18n/t.js' import { adminTexts } from '../../admin-i18n/texts/index.js' /** The part of Payload's server `i18n` the stats components use. */ @@ -17,7 +17,7 @@ const englishOnly: StatsI18n = { export const statsI18n = (i18n?: null | StatsI18n): StatsI18n => i18n ?? englishOnly -export const tr = (i18n: StatsI18n, key: AdminTextKey, vars?: Record) => ipalT(i18n.t, key, vars) +export const tr = (i18n: StatsI18n, key: AdminTextKey, vars?: Record) => iaplT(i18n.t, key, vars) /** Number in the admin language, e.g. 1 234 (pl) / 1,234 (en). */ export const num = (i18n: StatsI18n, n: number, options?: Intl.NumberFormatOptions) => diff --git a/src/modules/stats/endpoint.ts b/src/modules/stats/endpoint.ts index 5857257..b46cfad 100644 --- a/src/modules/stats/endpoint.ts +++ b/src/modules/stats/endpoint.ts @@ -142,7 +142,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars purge(req.payload, { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } }) } catch (err) { - req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`) + req.payload.logger.error(`[iapl] stats hit failed: ${err instanceof Error ? err.message : String(err)}`) } return done }, diff --git a/src/modules/stats/index.ts b/src/modules/stats/index.ts index f5062b0..aa2c088 100644 --- a/src/modules/stats/index.ts +++ b/src/modules/stats/index.ts @@ -1,4 +1,4 @@ -// Server-safe: collection + hit endpoint (wired by ipalKit({ stats })). +// Server-safe: collection + hit endpoint (wired by iapl({ stats })). // is client-side (./client); the admin view and dashboard card are in /admin. export { buildStatsCollection, STATS_SLUG } from './collection.js' export type { StatsOptions, StatsPage, StatsVisit } from './collection.js' diff --git a/src/modules/storage/buildR2Storage.ts b/src/modules/storage/buildR2Storage.ts index 8e22d37..4f4709f 100644 --- a/src/modules/storage/buildR2Storage.ts +++ b/src/modules/storage/buildR2Storage.ts @@ -87,13 +87,13 @@ export const buildR2Storage = ( return (config) => { if (readOnly) { console.warn( - `[ipal] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` + + `[iapl] R2 storage: read-only media from ${readOnly} (R2_PUBLIC_URL without credentials) — ` + 'uploads are disabled. Set all R2_* to upload, or none for local disk.', ) } else if (bucket || endpoint || accessKeyId || secretAccessKey) { // Only warn when SOME vars are set (partial config = likely a mistake). console.warn( - '[ipal] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' + + '[iapl] R2 storage: incomplete env (need R2_BUCKET, R2_ENDPOINT, ' + 'R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY). Falling back to local disk.', ) } @@ -107,7 +107,7 @@ export const buildR2Storage = ( // (media.klient.pl → bucket) set R2_PUBLIC_URL so Payload generates URLs // pointing there. Without it, uploads work but images don't display publicly. // See docs/storage.md. - // Site-relative value ('/media', dev only — ipalEnvRules rejects it in production) + // Site-relative value ('/media', dev only — iaplEnvRules rejects it in production) // → prefixed with NEXT_PUBLIC_SERVER_URL so Payload still stores absolute URLs. const rawPublicUrl = process.env.R2_PUBLIC_URL?.trim().replace(/\/$/, '') // strip trailing slash const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL?.trim().replace(/\/$/, '') @@ -127,7 +127,7 @@ export const buildR2Storage = ( // than silently storing media on the container disk (lost on redeploy). if (!s3Storage) { throw new Error( - '[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + + '[iapl] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + "Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " + "with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.", ) @@ -213,7 +213,7 @@ function withReadOnlyMedia( }).req if (operation === 'delete' || ((operation === 'create' || operation === 'update') && req?.file)) { req?.payload?.logger?.warn( - '[ipal] R2 storage: media is read-only (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.', + '[iapl] R2 storage: media is read-only (R2_PUBLIC_URL without R2 credentials). Set all R2_* to upload or delete files.', ) throw new APIError( req?.i18n?.language === 'pl' diff --git a/src/modules/theme/theme.ts b/src/modules/theme/theme.ts index e8aeba9..f283afd 100644 --- a/src/modules/theme/theme.ts +++ b/src/modules/theme/theme.ts @@ -15,7 +15,7 @@ export type ThemeSetting = 'system' | Theme /** * Default localStorage key of the visitor's choice: `theme`, values `light` / `dark` — * the same key and values as next-themes (a project using both shares one choice). - * Change it with `ipalKit({ theme: { storageKey } })`. + * Change it with `iapl({ theme: { storageKey } })`. */ export const THEME_STORAGE_KEY = 'theme' /** The key before 1.15 — a choice stored under it is moved to the current key once, then removed. */ @@ -36,7 +36,7 @@ export type ThemeConfig = { allowToggle: boolean /** null: no Site Settings — no attribute, the base (light) CSS applies. */ defaultTheme: null | ThemeSetting - /** localStorage key of the visitor's choice (`ipalKit({ theme: { storageKey } })`). Default `theme`. */ + /** localStorage key of the visitor's choice (`iapl({ theme: { storageKey } })`). Default `theme`. */ storageKey?: string /** Accessible name of the switch, e.g. "Dark mode" (Site Settings → Theme). */ toggleLabel: null | string diff --git a/src/modules/tokens/catalog.ts b/src/modules/tokens/catalog.ts index b71e1ec..c015f4c 100644 --- a/src/modules/tokens/catalog.ts +++ b/src/modules/tokens/catalog.ts @@ -139,7 +139,7 @@ export const FLUID_TOKENS = [ export type FluidToken = (typeof FLUID_TOKENS)[number] -export type IpalTokenName = `${(typeof LEGACY_DARK_ROLES)[number]}-dark` | ColorRole | FluidToken | StaticToken +export type IaplTokenName = `${(typeof LEGACY_DARK_ROLES)[number]}-dark` | ColorRole | FluidToken | StaticToken /** Standard breakpoints in rem (Tailwind 4 defaults). CSS variables can't be used in `@media`. */ -export const IPAL_BREAKPOINTS = { '2xl': 96, lg: 64, md: 48, sm: 40, xl: 80 } as const +export const IAPL_BREAKPOINTS = { '2xl': 96, lg: 64, md: 48, sm: 40, xl: 80 } as const diff --git a/src/modules/tokens/cli.ts b/src/modules/tokens/cli.ts index 48b9a54..40bc4db 100644 --- a/src/modules/tokens/cli.ts +++ b/src/modules/tokens/cli.ts @@ -6,9 +6,9 @@ import { contrastReport, type ContrastRow } from './contrast.js' import { tokensToCss } from './css.js' import { defineTokens, type TokensInput } from './define.js' -export const TOKENS_CLI_USAGE = `Usage: ipal-tokens [--in src/design/tokens.ts] [--out src/design/tokens.css] [--check] [--report] [--warn-only] +export const TOKENS_CLI_USAGE = `Usage: iapl-tokens [--in src/design/tokens.ts] [--out src/design/tokens.css] [--check] [--report] [--warn-only] Generates the brand CSS from the tokens file and checks WCAG contrast. - --check fail when the CSS file is out of date (CI, ipal-doctor); writes nothing + --check fail when the CSS file is out of date (CI, iapl-doctor); writes nothing --report print every checked pair (for DESIGN.md), not only the failures --warn-only report contrast failures without failing` @@ -46,7 +46,7 @@ async function loadTokens(file: string): Promise { } } -/** The `ipal-tokens` command. Returns the exit code. */ +/** The `iapl-tokens` command. Returns the exit code. */ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = (line: string) => process.stdout.write(`${line}\n`) }: { cwd?: string; log?: Log } = {}): Promise { if (args.includes('--help') || args.includes('-h')) { log(TOKENS_CLI_USAGE) @@ -56,7 +56,7 @@ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = const input = resolve(cwd, arg(args, '--in', 'src/design/tokens.ts')) const output = resolve(cwd, arg(args, '--out', 'src/design/tokens.css')) if (!existsSync(input)) { - log(`ipal-tokens: ${relative(cwd, input)} not found (copy the template from .agents/skills/ipal-setup/resources/tokens.ts)`) + log(`iapl-tokens: ${relative(cwd, input)} not found (copy the template from .agents/skills/iapl-setup/resources/tokens.ts)`) return 1 } const tokens = defineTokens(await loadTokens(input)) @@ -65,7 +65,7 @@ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = let code = 0 if (args.includes('--check')) { if (current !== css) { - log(`✗ ${relative(cwd, output)} is out of date — run \`pnpm exec ipal-tokens\``) + log(`✗ ${relative(cwd, output)} is out of date — run \`pnpm exec iapl-tokens\``) code = 1 } else {log(`✓ ${relative(cwd, output)} is up to date`)} } else if (current !== css) { @@ -85,7 +85,7 @@ export async function runTokensCli(args: string[], { cwd = process.cwd(), log = } return code } catch (error) { - log(`ipal-tokens: ${(error as Error).message}`) + log(`iapl-tokens: ${(error as Error).message}`) return 1 } } diff --git a/src/modules/tokens/contrast.ts b/src/modules/tokens/contrast.ts index e8f539c..42e231e 100644 --- a/src/modules/tokens/contrast.ts +++ b/src/modules/tokens/contrast.ts @@ -51,7 +51,7 @@ const INVERSE_PAIRS: Pair[] = [ /** * WCAG contrast for every text/background pair the token roles promise, in each - * theme and inside the inverse scope. `ipal-tokens` prints it and fails on an error row. + * theme and inside the inverse scope. `iapl-tokens` prints it and fails on an error row. */ export function contrastReport(input: TokensInput = {}): ContrastRow[] { const themes = input.theme === 'light' || input.theme === 'dark' ? [input.theme] : (['light', 'dark'] as const) diff --git a/src/modules/tokens/css.ts b/src/modules/tokens/css.ts index 8f1599a..0831b6b 100644 --- a/src/modules/tokens/css.ts +++ b/src/modules/tokens/css.ts @@ -54,7 +54,7 @@ export function defaultTokensCss(): string { * * Light values on :root, dark values on [data-theme="dark"] (on set by , * storage key "theme"; on any element for a dark panel). A brand overrides them in src/design/tokens.css, generated by - * \`ipal-tokens\` from src/design/tokens.ts and imported after this file. + * \`iapl-tokens\` from src/design/tokens.ts and imported after this file. * Components read only the role names, never "-dark": the roles switch with the theme. * The type and space scale is in fluid.css / fluid-wide.css — import one of them as well. */`, @@ -84,14 +84,14 @@ const changed = (theme: 'dark' | 'light', colors: Record): En /** * The brand's CSS: only what differs from the defaults in tokens.css. This is what - * `ipal-tokens` writes to src/design/tokens.css. + * `iapl-tokens` writes to src/design/tokens.css. */ export function tokensToCss(input: TokensInput, { source = 'src/design/tokens.ts' }: { source?: string } = {}): string { const theme = input.theme ?? 'both' const { dark, light } = resolveColors(input) const header = `/* - * GENERATED by \`ipal-tokens\` from ${source} — do not edit; change ${source} and run - * \`pnpm exec ipal-tokens\`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css). + * GENERATED by \`iapl-tokens\` from ${source} — do not edit; change ${source} and run + * \`pnpm exec iapl-tokens\`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css). */` const statics = Object.entries(staticOverrides(input)) const parts = [header] diff --git a/src/modules/tokens/define.ts b/src/modules/tokens/define.ts index c413181..c8ce436 100644 --- a/src/modules/tokens/define.ts +++ b/src/modules/tokens/define.ts @@ -48,7 +48,7 @@ export const BRAND_ROLES: readonly ColorRole[] = [ function check(keys: Iterable, known: Record, where: string) { for (const key of keys) { - if (!(key in known)) {throw new Error(`ipal-kit tokens: unknown ${where} "${key}"`)} + if (!(key in known)) {throw new Error(`IAPL tokens: unknown ${where} "${key}"`)} } } @@ -62,7 +62,7 @@ export function defineTokens(input: T): T { check(Object.keys(input.fs ?? {}).map((k) => `fs-${k}`), FLUID_SCALE, 'fs size') check(Object.keys(input.space ?? {}).map((k) => `space-${k}`), FLUID_SCALE, 'space size') if (input.theme && !['both', 'dark', 'light'].includes(input.theme)) { - throw new Error(`ipal-kit tokens: theme must be 'both', 'light' or 'dark'`) + throw new Error(`IAPL tokens: theme must be 'both', 'light' or 'dark'`) } return input } diff --git a/src/modules/tokens/fluid.ts b/src/modules/tokens/fluid.ts index 269167c..f40c30b 100644 --- a/src/modules/tokens/fluid.ts +++ b/src/modules/tokens/fluid.ts @@ -40,7 +40,7 @@ const ROOT_PX = 16 export function toRem(value: RemValue): number { if (typeof value === 'number') {return value} const m = /^\s*(-?(?:\d+(?:\.\d+)?|\.\d+))\s*(?:(rem|px)\s*)?$/.exec(value) - if (!m) {throw new Error(`ipal-kit tokens: "${value}" is not a size in rem or px`)} + if (!m) {throw new Error(`IAPL tokens: "${value}" is not a size in rem or px`)} return m[2] === 'px' ? Number(m[1]) / ROOT_PX : Number(m[1]) } diff --git a/src/modules/tokens/index.ts b/src/modules/tokens/index.ts index d27f4c4..e04b500 100644 --- a/src/modules/tokens/index.ts +++ b/src/modules/tokens/index.ts @@ -1,5 +1,5 @@ -export { COLOR_DEFAULTS, FLUID_TOKENS, INVERSE_SCOPE, IPAL_BREAKPOINTS, LEGACY_DARK_ROLES, STATIC_DEFAULTS } from './catalog.js' -export type { ColorRole, IpalTokenName } from './catalog.js' +export { COLOR_DEFAULTS, FLUID_TOKENS, INVERSE_SCOPE, IAPL_BREAKPOINTS, LEGACY_DARK_ROLES, STATIC_DEFAULTS } from './catalog.js' +export type { ColorRole, IaplTokenName } from './catalog.js' export { contrastRatio, parseColor } from './color.js' export { contrastReport } from './contrast.js' export type { ContrastRow } from './contrast.js' @@ -8,4 +8,4 @@ export { defineTokens, resolveColors } from './define.js' export type { ColorInput, TokensInput } from './define.js' export { FLUID_RANGES, FLUID_SCALE, fluidClamp } from './fluid.js' export type { FluidRange, RemValue } from './fluid.js' -export { IPAL_TOKENS, ipalVar } from './names.js' +export { IAPL_TOKENS, iaplVar } from './names.js' diff --git a/src/modules/tokens/names.ts b/src/modules/tokens/names.ts index 97b8296..a97fc57 100644 --- a/src/modules/tokens/names.ts +++ b/src/modules/tokens/names.ts @@ -1,7 +1,7 @@ import { COLOR_DEFAULTS, FLUID_TOKENS, - type IpalTokenName, + type IaplTokenName, LEGACY_DARK_ROLES, STATIC_DEFAULTS, } from './catalog.js' @@ -11,17 +11,17 @@ const NAMES = [ ...FLUID_TOKENS, ...Object.keys(STATIC_DEFAULTS), ...LEGACY_DARK_ROLES.map((role) => `${role}-dark`), -] as IpalTokenName[] +] as IaplTokenName[] /** * Every token as a ready `var(--ipal-…)` string, keyed by name without the prefix — - * for inline styles, charts, canvas or a styleguide page: `IPAL_TOKENS.primary`. + * for inline styles, charts, canvas or a styleguide page: `IAPL_TOKENS.primary`. */ -export const IPAL_TOKENS = Object.freeze( - Object.fromEntries(NAMES.map((name) => [name, `var(--ipal-${name})`])) as Record, +export const IAPL_TOKENS = Object.freeze( + Object.fromEntries(NAMES.map((name) => [name, `var(--ipal-${name})`])) as Record, ) -/** `var(--ipal-)`, with an optional fallback: `ipalVar('surface', '#fff')`. */ -export function ipalVar(name: IpalTokenName, fallback?: string): string { +/** `var(--ipal-)`, with an optional fallback: `iaplVar('surface', '#fff')`. */ +export function iaplVar(name: IaplTokenName, fallback?: string): string { return fallback === undefined ? `var(--ipal-${name})` : `var(--ipal-${name}, ${fallback})` } diff --git a/src/modules/turnstile/config.ts b/src/modules/turnstile/config.ts index 3ec5d27..de95ad6 100644 --- a/src/modules/turnstile/config.ts +++ b/src/modules/turnstile/config.ts @@ -7,7 +7,7 @@ type IntegrationsWithTurnstileKeys = { turnstileSiteKey?: null | string } -/** Env fallbacks — the same names ipalEnvRules({ turnstile: true }) requires. */ +/** Env fallbacks — the same names iaplEnvRules({ turnstile: true }) requires. */ export const TURNSTILE_SITE_KEY_ENV = 'NEXT_PUBLIC_TURNSTILE_SITE_KEY' export const TURNSTILE_SECRET_ENV = 'TURNSTILE_SECRET_KEY' @@ -35,7 +35,7 @@ export function warnTurnstileEnvSecret(integrations: IntegrationsWithTurnstileKe if (warnedEnvSecret || !turnstileSecretFromEnv(integrations)) {return} warnedEnvSecret = true console.warn( - `[ipal] Deprecated: the Turnstile secret key comes from the ${TURNSTILE_SECRET_ENV} environment variable. ` + + `[iapl] Deprecated: the Turnstile secret key comes from the ${TURNSTILE_SECRET_ENV} environment variable. ` + 'Put it into Site integrations → Spam protection → Secret key (the panel is the source of this secret). ' + 'The environment value keeps working for now and will be removed in a later release, named in the changelog.', ) @@ -98,7 +98,7 @@ export async function getTurnstileConfig(payload: BasePayload): Promise => { const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}` - console.warn(`[ipal] Turnstile degraded (${code}): ${message}${LOG_DETAIL[code] ? ` (${LOG_DETAIL[code]})` : ''}`) + console.warn(`[iapl] Turnstile degraded (${code}): ${message}${LOG_DETAIL[code] ? ` (${LOG_DETAIL[code]})` : ''}`) await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' }) return { code, outcome: 'degraded' } } @@ -122,14 +122,14 @@ export async function checkTurnstile({ if (res.status >= 500) {return degraded('internal-error')} data = (await res.json()) as SiteverifyResponse } catch (err) { - console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err) + console.warn('[iapl] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err) return degraded('network-error') } if (typeof data?.success !== 'boolean') {return degraded('bad-response')} if (data.success) { if (hostnames?.length && !hostnames.some((h) => h.toLowerCase() === data.hostname?.toLowerCase())) { - console.warn(`[ipal] Turnstile rejected: token solved on "${data.hostname ?? '?'}", expected ${hostnames.join(', ')}`) + console.warn(`[iapl] Turnstile rejected: token solved on "${data.hostname ?? '?'}", expected ${hostnames.join(', ')}`) return { code: 'hostname-mismatch', outcome: 'reject' } } await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' }) @@ -141,7 +141,7 @@ export async function checkTurnstile({ if (configCode) {return degraded(configCode)} // Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request. - console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`) + console.warn(`[iapl] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`) return { code: codes[0] ?? 'unknown', outcome: 'reject' } } diff --git a/src/plugin.ts b/src/plugin.ts index aaacf4f..7446260 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -4,7 +4,7 @@ import { deepMergeSimple } from 'payload/shared' import type { AccountsOptions, Role } from './modules/access/types.js' import type { ResolvedAdminMeta } from './modules/branding/adminMeta.js' -import type { IpalOptions, TotpPluginFactory } from './types.js' +import type { IaplOptions, TotpPluginFactory } from './types.js' import { buildCookieSettings } from './globals/CookieSettings/index.js' import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrateSaveButton.js' @@ -62,21 +62,21 @@ import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' -/** The admin provider @clocklimited/payload-2fa registers; ipal-kit swaps it (twoFactor.provider). */ +/** The admin provider @clocklimited/payload-2fa registers; IAPL swaps it (twoFactor.provider). */ const TOTP_PACKAGE_PROVIDER = '@clocklimited/payload-2fa/rsc#TOTPProvider' -/** ipal-kit's own redirect provider (twoFactor.provider default). */ +/** IAPL's own redirect provider (twoFactor.provider default). */ const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider' /** - * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3. + * IAPL (Intecion Advanced Payload Library) plugin for Payload CMS 3. * * @example * ```ts - * import { ipalKit } from 'ipal-kit' + * import { iapl } from 'IAPL' * * export default buildConfig({ * plugins: [ - * ipalKit({ + * iapl({ * i18n: { * locales: [ * { code: 'pl', label: 'Polski' }, @@ -90,7 +90,7 @@ const TOTP_REDIRECT_PROVIDER = '@intecion/ipal-kit/admin#TotpRedirectProvider' * }) * ``` */ -export const ipalKit = (options: IpalOptions): Plugin => { +export const iapl = (options: IaplOptions): Plugin => { // Validate eagerly — fail fast before Payload boots validateI18nConfig(options.i18n) @@ -159,7 +159,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { : {}), admin: { useAsTitle: 'email' }, auth: true, - // these rules are the plugin's, written for this slug (marked as such when ipalKit finishes) — not the ones + // these rules are the plugin's, written for this slug (marked as such when iapl finishes) — not the ones // the project passed in access.authAccess ...(hasRoles ? { custom: { ipalAccountRules: { slug: authSlug, applied: ['create', 'delete', 'read', 'unlock', 'update'].filter((k) => !(k in (options.access?.authAccess ?? {}))), ownRoles: false } } } @@ -178,11 +178,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- enforced 2FA (TOTP) via @clocklimited/payload-2fa --- // Enforced by default (forceSetup) unless twoFactor is explicitly false. The - // package is an optional PEER the project injects — ipal-kit doesn't bundle + // package is an optional PEER the project injects — IAPL doesn't bundle // or import it, so projects that opt out (twoFactor: false) needn't install it. // Wrapping access control (not just admin UI) means TOTP gates data access — // no API bypass. - // ipal-kit's own second-factor check (secondFactor.ts) covers what the 2FA + // IAPL's own second-factor check (secondFactor.ts) covers what the 2FA // package cannot: everything added to the config after the package ran. let secondFactorGuard = false /** The 2FA collection, when 2FA is on. */ @@ -193,12 +193,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { const staffToken = {} /** * A config has gone live on this instance (start, or a dev hot reload): guard what plugins - * listed after ipalKit added, and file its staff collections under the instance. + * listed after iapl added, and file its staff collections under the instance. */ const adoptConfig = (payload: BasePayload) => { const token = (payload.config.custom as { ipal?: { staffToken?: object } } | undefined)?.ipal?.staffToken registerStaffCollections(payload, staffCollectionSlugs(payload), token) - // Auth collections a plugin listed after ipalKit added: the account rules for them too — BEFORE the + // Auth collections a plugin listed after iapl added: the account rules for them too — BEFORE the // 2FA guard below wraps their access (it needs the rule inside its wrapper). if (accounts) { const rule = resolvePasswordRule(accounts.password) @@ -213,12 +213,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { for (const late of lateAccounts) { const parts = [late.applied.length ? `access rules for ${late.applied.join(', ')}` : '', late.password ? 'the password rule' : '', late.firstUser ? 'the first-user endpoint' : ''].filter(Boolean) const kept = late.kept.length ? ` Its own rules for ${late.kept.join(', ')} are kept as written.` : '' - payload.logger.info(`[ipal] "${late.slug}" ${late.known ? 'became a staff collection after ipalKit ran' : 'was added after ipalKit'}: put on it — ${parts.join('; ')}.${kept}`) + payload.logger.info(`[iapl] "${late.slug}" ${late.known ? 'became a staff collection after iapl ran' : 'was added after iapl'}: put on it — ${parts.join('; ')}.${kept}`) } } if (!secondFactorGuard) {return} const late = ensurePayloadGuarded(payload) - if (late?.length) {payload.logger.info(`[ipal] 2FA also enforced on entities added after ipalKit: ${late.join(', ')}.`)} + if (late?.length) {payload.logger.info(`[iapl] 2FA also enforced on entities added after iapl: ${late.join(', ')}.`)} } /** 2FA collection when "setup required" is on — its existing accounts get their setup window in onInit. */ let setupRequiredFor: null | string = null @@ -246,7 +246,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { const tf = options.twoFactor if (!tf?.issuer) { throw new Error( - '[ipal] twoFactor.issuer is required (name shown in the authenticator ' + + '[iapl] twoFactor.issuer is required (name shown in the authenticator ' + 'app). Pass twoFactor: { issuer: "Your Site" }, or twoFactor: false to ' + 'opt out (discouraged).', ) @@ -258,7 +258,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { if (typeof totp !== 'function') { throw new Error( - '[ipal] 2FA is enforced but no 2FA plugin was injected. Add ' + + '[iapl] 2FA is enforced but no 2FA plugin was injected. Add ' + '`import { payloadTotp } from "@clocklimited/payload-2fa"` and pass ' + '`twoFactor: { issuer, plugin: payloadTotp }`. Or set twoFactor: false ' + 'to opt out (discouraged).', @@ -276,13 +276,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { const target = tf.collectionSlug ?? adminSlug if (!authSlugs.includes(target)) { throw new Error( - `[ipal] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` + + `[iapl] twoFactor: "${target}" is not an auth collection, so 2FA would protect nothing. ` + `Auth collections: ${authSlugs.join(', ') || 'none'}. Fix twoFactor.collectionSlug.`, ) } if (target !== adminSlug && !tf.allowCollectionMismatch) { throw new Error( - `[ipal] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` + + `[iapl] twoFactor wraps "${target}" but the admin panel logs in with "${adminSlug}" ` + '(admin.user) — those accounts would skip 2FA. Point twoFactor.collectionSlug at ' + `"${adminSlug}", or pass twoFactor.allowCollectionMismatch: true if that is deliberate.`, ) @@ -297,7 +297,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { const entityEndpointsBefore = new Map>( [...(config.collections ?? []), ...(config.globals ?? [])].map((e) => [e.slug, new Set(Array.isArray(e.endpoints) ? e.endpoints : [])]), ) - // custom.ipal.secondFactor (ipal-kit's per-entity opt-out) → the package's own key + // custom.ipal.secondFactor (IAPL's per-entity opt-out) → the package's own key config = passOptOutsToPackage(config) config = await totp({ collection: target, @@ -335,13 +335,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { // field joins it below, when the mode is on. Validates requireSetup at start either way. if (tf.requireSetup !== false) {resolveRequireSetup(tf.requireSetup)} // The views the 2FA package registered, by object: it REPLACES a view the project (or an - // earlier run of the package, or of ipalKit) already had under its keys, so a key that + // earlier run of the package, or of iapl) already had under its keys, so a key that // existed before is no sign that the view is the project's own. Taken here, before the // texts step below re-creates those objects. const viewsFromPackage = changedViewKeys(viewsBefore, { ...config.admin?.components?.views }) - // The package wraps only what is in the config right now. ipal-kit's own - // globals and collections come later, so they get ipal-kit's guard at the + // The package wraps only what is in the config right now. IAPL's own + // globals and collections come later, so they get IAPL's guard at the // end of this function (and other plugins' in onInit). The guard reads the // package's `totp` strategy and `hasTotp` field: when those are not there, // this is a version it was not written for — refuse to start rather than @@ -350,8 +350,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { const missing = missingTotpParts(config, target) if (missing.length) { throw new Error( - `[ipal] twoFactor: the injected 2FA plugin did not add ${missing.join(', ')} to "${target}". ` + - 'ipal-kit enforces the second factor on its own globals and collections through them, so it ' + + `[iapl] twoFactor: the injected 2FA plugin did not add ${missing.join(', ')} to "${target}". ` + + 'IAPL enforces the second factor on its own globals and collections through them, so it ' + 'cannot do that with this version of @clocklimited/payload-2fa. Use a supported version, or pass ' + 'twoFactor.guard: false to rely on the package alone (docs/security.md — not recommended).', ) @@ -388,7 +388,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // An admin resets an account's TOTP (lost phone) / reopens its setup window. config.endpoints = [...(config.endpoints ?? []), buildTwoFactorResetEndpoint(target, { access: tf.resetAccess })] // Called by Payload on every request before any access function: guards whatever - // the live config has that was added after ipalKit (start, dev hot reload). + // the live config has that was added after iapl (start, dev hot reload). const sweep = buildGuardStrategy(adoptConfig) config.collections = (config.collections ?? []).map((c) => c.slug === target && typeof c.auth === 'object' @@ -402,7 +402,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { c.slug === target ? { ...c, fields: [...c.fields, ...buildSetupFields({ statusField })] } : c, ) - // The package's texts are long and informal: ipal-kit's (admin-ux.md) go over + // The package's texts are long and informal: IAPL's (admin-ux.md) go over // them, the project's own i18n.translations over both. The 2FA screens get a // tab title instead of "Payload" (view meta is a plain string: the site's language). if (tf.texts !== false) { @@ -432,7 +432,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // The package's TOTPProvider reads the path from an `x-pathname` header // no proxy sets on /admin, so it redirected the setup screen to itself - // (`setup-totp?back=null`). Swap in ipal-kit's client-side provider, or + // (`setup-totp?back=null`). Swap in IAPL's client-side provider, or // the project's (`provider`); `provider: false` keeps the package's. if (tf.provider !== false) { const custom = tf.provider @@ -458,7 +458,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // The package's setup and verify screens send the browser to the `back` query // value after a valid code, unchecked: a crafted link runs script in the panel - // or leaves the site (safeBack.ts). ipal-kit's view goes in front of them and + // or leaves the site (safeBack.ts). IAPL's view goes in front of them and // hands the package's view a checked value. `safeBack: false` leaves them as // the package registered them; a function replaces the rule. if (tf.safeBack !== false) { @@ -489,7 +489,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { components: { ...config.admin?.components, providers: providers.map((p) => - p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // ipal-kit's own provider only + p && typeof p === 'object' && p.path === TOTP_REDIRECT_PROVIDER // IAPL's own provider only ? { ...p, clientProps: { ...p.clientProps, staleImportMap: true } } : p, ), @@ -614,7 +614,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { if (panelRole && options.access.firstUserAdmin === false && ROLE_HIERARCHY.indexOf(firstRole) < ROLE_HIERARCHY.indexOf(panelRole)) { if (accounts?.panelRole !== undefined) { throw new Error( - `[ipal] access.firstUserAdmin: false with accounts.panelRole: '${panelRole}' leaves a fresh site with nobody who can open the panel: ` + + `[iapl] access.firstUserAdmin: false with accounts.panelRole: '${panelRole}' leaves a fresh site with nobody who can open the panel: ` + `the first account gets the role '${firstRole}', which is below the panel role. Set access.defaultRole to '${panelRole}' or higher, ` + "or accounts: { panelRole: false }, or drop access.firstUserAdmin: false (docs/access.md \"Account rules\").", ) @@ -648,7 +648,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- seo: apply @payloadcms/plugin-seo directly --- // NOTE: apply the plugin function to the config immediately rather than // pushing it onto config.plugins. Payload has already iterated the plugins - // array by the time IPAL runs, so nested plugins added to that list are + // array by the time IAPL runs, so nested plugins added to that list are // never executed. Calling the plugin as (config) => config applies its // transform now. if (options.seo) { @@ -742,7 +742,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint] - // --- ipal-doctor status (404 until IPAL_DOCTOR_TOKEN is set; docs/doctor.md) --- + // --- iapl-doctor status (404 until IAPL_DOCTOR_TOKEN is set; docs/doctor.md) --- if (options.doctor !== false) { config.endpoints = [...(config.endpoints ?? []), buildDoctorEndpoint(options.doctor ?? {})] } @@ -911,7 +911,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { const unknownStaff = unknownStaffCollections(payload.config as never, [...new Set([options.access?.authCollection, ...(options.access?.staffCollections ?? [])].filter((s): s is string => Boolean(s)))]) if (unknownStaff.length) { throw new Error( - `[ipal] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` + + `[iapl] access names ${unknownStaff.map((s) => `"${s}"`).join(', ')} as a staff collection, but this config has no auth collection with that slug ` + `(auth collections: ${payload.config.collections.filter((c) => c.auth).map((c) => c.slug).join(', ') || 'none'}). ` + 'Fix the slug in access.authCollection / access.staffCollections, or add the collection (docs/access.md "Who is staff").', ) @@ -921,7 +921,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { watchPayloadConfig(payload, adoptConfig) if (staleImportMap) { payload.logger.error( - `[ipal] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` + + `[iapl] The admin import map may be out of date: ${staleImportMap}. If the 2FA setup and verify screens are ` + 'EMPTY (no code form), nobody can sign in to the panel: run `pnpm payload generate:importmap`, commit ' + 'importMap.js, rebuild and redeploy. If the screens work, the file on disk is not the map the build used — ' + 'set twoFactor.importMapCheck: false (docs/security.md "A stale import map").', @@ -932,14 +932,14 @@ export const ipalKit = (options: IpalOptions): Plugin => { const uncovered = staffCollectionSlugs(payload).filter((slug) => slug !== twoFactorCollection) if (uncovered.length) { payload.logger.warn( - `[ipal] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` + + `[iapl] 2FA covers "${twoFactorCollection}" only. Staff accounts of ${uncovered.map((s) => `"${s}"`).join(', ')} ` + 'pass the staff checks with a password alone (docs/access.md "Who is staff").', ) } } if (panelRoleSkipped) { payload.logger.warn( - `[ipal] The panel role (accounts.panelRole, 'editor' by default) is NOT applied: ${panelRoleSkipped}, so nobody could open the panel on a fresh site. ` + + `[iapl] The panel role (accounts.panelRole, 'editor' by default) is NOT applied: ${panelRoleSkipped}, so nobody could open the panel on a fresh site. ` + 'Every account of the login collection can open the panel. To keep the lowest role out, set access.defaultRole to \'editor\' or drop access.firstUserAdmin: false (docs/access.md "Account rules").', ) } @@ -948,13 +948,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { const { stuck, unchecked } = await staffCollectionsNobodyManages(payload as never, staffCollectionSlugs(payload), options.access?.authCollection) if (stuck.length) { payload.logger.warn( - `[ipal] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` + + `[iapl] No staff account holds the role "admin", so NOBODY can create, delete or unlock accounts in ${stuck.map((s) => `"${s}"`).join(', ')} ` + "(only an admin does there: the collection's roles can hold \"editor\" or \"admin\"). Give one account the role with a script " + '(payload.update, Local API), or write the collection\'s own access.create / update / delete rules (docs/access.md "Account rules").', ) } else if (unchecked.length) { payload.logger.warn( - `[ipal] Could not check whether an account of ${unchecked.map((s) => `"${s}"`).join(', ')} holds the role "admin" (no other staff account does). ` + + `[iapl] Could not check whether an account of ${unchecked.map((s) => `"${s}"`).join(', ')} holds the role "admin" (no other staff account does). ` + 'If none does, nobody can create, delete or unlock accounts in the staff collections that are managed by admins only (docs/access.md "Account rules").', ) } @@ -965,12 +965,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { const { all, below } = await countBelowPanelRole(payload, panelRoleFor.slug, panelRoleFor.role) if (all && below === all) { payload.logger.error( - `[ipal] No account of "${panelRoleFor.slug}" has the role "${panelRoleFor.role}" or higher, so NOBODY can open the admin panel ` + + `[iapl] No account of "${panelRoleFor.slug}" has the role "${panelRoleFor.role}" or higher, so NOBODY can open the admin panel ` + '(accounts.panelRole). Give an account the role with a script (payload.update, Local API), or set accounts: { panelRole: false } and redeploy (docs/access.md "Account rules").', ) } else if (below) { payload.logger.warn( - `[ipal] ${below} account(s) of "${panelRoleFor.slug}" are below the role "${panelRoleFor.role}" and cannot open the admin panel ` + + `[iapl] ${below} account(s) of "${panelRoleFor.slug}" are below the role "${panelRoleFor.role}" and cannot open the admin panel ` + '(accounts.panelRole). Give them a higher role, or set accounts: { panelRole: \'user\' } (docs/access.md "Account rules").', ) } @@ -983,7 +983,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { const started = await backfillSetupFrom(payload, setupRequiredFor) if (started) { payload.logger.warn( - `[ipal] 2FA: ${started} existing account(s) without two-step verification. ` + + `[iapl] 2FA: ${started} existing account(s) without two-step verification. ` + (setupWindowHours ? `They have ${setupWindowHours} h from now to set it up; after that an administrator must reopen setup.` : 'They cannot use the panel until they set it up.'), ) } @@ -991,7 +991,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { await migrateCookieSettingsSaveButton(payload) await migrateTitleSeparator(payload, settingsSlug) if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })} - payload.logger.info('[ipal] Plugin initialized.') + payload.logger.info('[iapl] Plugin initialized.') } // Every auth collection of this config has been seen: what appears later is a late one (adoptConfig). diff --git a/src/styles/tokens.css b/src/styles/tokens.css index 7c55f55..33fa5ee 100644 --- a/src/styles/tokens.css +++ b/src/styles/tokens.css @@ -4,7 +4,7 @@ * * Light values on :root, dark values on [data-theme="dark"] (on set by , * storage key "theme"; on any element for a dark panel). A brand overrides them in src/design/tokens.css, generated by - * `ipal-tokens` from src/design/tokens.ts and imported after this file. + * `iapl-tokens` from src/design/tokens.ts and imported after this file. * Components read only the role names, never "-dark": the roles switch with the theme. * The type and space scale is in fluid.css / fluid-wide.css — import one of them as well. */ diff --git a/src/types.ts b/src/types.ts index f6e8680..35cbf5c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -30,10 +30,10 @@ import type { SeoOption } from './modules/seo/types.js' import type { StatsOptions } from './modules/stats/collection.js' /** - * Configuration options for the IPAL plugin. + * Configuration options for the IAPL plugin. * Passed by the client project in payload.config.ts. */ -export type IpalOptions = { +export type IaplOptions = { /** * Role-based access control. Injects a fixed `roles` field * (admin > editor > user) into the client's auth collection. @@ -120,8 +120,8 @@ export type IpalOptions = { dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' } /** - * GET /api/ipal/doctor — read-only counts for `ipal-doctor --url` (users without 2FA, cookies - * waiting for approval, versions). Answers 404 until IPAL_DOCTOR_TOKEN (≥ 32 characters) is set; + * GET /api/ipal/doctor — read-only counts for `iapl-doctor --url` (users without 2FA, cookies + * waiting for approval, versions). Answers 404 until IAPL_DOCTOR_TOKEN (≥ 32 characters) is set; * then a `Bearer` token is required. `false` = no endpoint; `{ tokenVar, access }` to adapt it. * docs/doctor.md. */ @@ -270,8 +270,8 @@ export type IpalOptions = { */ collectionSlug?: CollectionSlug /** - * ipal-kit's own second-factor check on every collection and global — - * also the ones added after the 2FA package ran (ipal-kit's own, other + * IAPL's own second-factor check on every collection and global — + * also the ones added after the 2FA package ran (IAPL's own, other * plugins') — and in `userMeetsRole`. On by default. `false` leaves only * the package's wrapper, which does not cover those: a staff password * without the TOTP code then reads them over the API. Only for a 2FA @@ -292,7 +292,7 @@ export type IpalOptions = { /** * The 2FA plugin factory, INJECTED from the project: * `import { payloadTotp } from '@clocklimited/payload-2fa'`. Injecting it - * (the same pattern as NextResponse / revalidatePath) means ipal-kit never + * (the same pattern as NextResponse / revalidatePath) means IAPL never * imports the optional peer itself — Next can't bundle such an import * ("Cannot find module '@clocklimited/payload-2fa'", even on public * pages), and serverExternalPackages is no fix (the package imports its @@ -302,7 +302,7 @@ export type IpalOptions = { plugin: TotpPluginFactory /** * Admin provider that sends users to the TOTP setup / verify screens. - * Default: ipal-kit's `@intecion/ipal-kit/admin#TotpRedirectProvider` + * Default: IAPL's `@intecion/ipal-kit/admin#TotpRedirectProvider` * (reads the path in the browser). The package's own provider needs an * `x-pathname` request header on every /admin request; without it the * setup screen redirects to itself (`setup-totp?back=null`). Pass your @@ -331,7 +331,7 @@ export type IpalOptions = { * Check on the `back` query value of the 2FA setup and verify screens. The * 2FA package sends the browser there after a valid code without looking at * it, so a crafted link could run script in the panel (`javascript:`) or - * leave the site. On by default: ipal-kit's `SafeTotpView` goes in front of + * leave the site. On by default: IAPL's `SafeTotpView` goes in front of * the package's views and passes on a value that stays on the site's origin, * inside the admin route — anything else becomes the admin root * (`safeAdminBack`). A function replaces the rule; `false` leaves the @@ -350,7 +350,7 @@ export type IpalOptions = { */ sameOrigin?: { origins?: string[] } | false /** - * Texts of the 2FA screens and user field. Default: ipal-kit's English and + * Texts of the 2FA screens and user field. Default: IAPL's English and * Polish (`TOTP_TEXTS`), merged over the package's; your own * `i18n.translations..totpPlugin` still wins. `false` keeps the package's. */ @@ -414,7 +414,7 @@ export type IpalOptions = { | boolean } -/** `ipalKit({ theme })` — every key optional. */ +/** `iapl({ theme })` — every key optional. */ export type ThemeOptions = { /** localStorage key of the visitor's light / dark choice. Default `'theme'`. */ storageKey?: string diff --git a/test/access.test.ts b/test/access.test.ts index 88766f5..bb9d773 100644 --- a/test/access.test.ts +++ b/test/access.test.ts @@ -43,7 +43,7 @@ describe('role predicates', () => { }) test('where the staff collections are not known, nobody is staff (browser bundle, middleware)', () => { - // no ipalKit config in this process (test/setup.ts clears the registry) and no source given + // no iapl config in this process (test/setup.ts clears the registry) and no source given expect(isAdmin(admin)).toBe(false) expect(isAdmin({ collection: 'customers', roles: ['admin'] })).toBe(false) expect(hasMinimumRole(user, 'user')).toBe(false) diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts index 9c8a135..b5fceeb 100644 --- a/test/accessControl.test.ts +++ b/test/accessControl.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { @@ -28,7 +28,7 @@ const run = (fn: Access | undefined, u: unknown) => describe('injected auth collection', () => { test('with roles: a plain user can only see and edit itself, never create or delete', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {} expect(run(access.update, user)).toEqual({ id: { equals: 3 } }) @@ -45,7 +45,7 @@ describe('injected auth collection', () => { test("the project's own auth collection keeps its own access", async () => { const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] } - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })( + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })( empty({ collections: [own] as CollectionConfig[] }), ) const access = config.collections?.find((c) => c.slug === 'users')?.access @@ -53,7 +53,7 @@ describe('injected auth collection', () => { expect(access?.read).toBe(own.access.read) // …and the account rules fill in only what it left out (accounts.*; `accounts: false` = nothing added) expect(access?.admin).toBeTypeOf('function') - const untouched = await ipalKit({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })( + const untouched = await iapl({ access: { authCollection: 'users' }, accounts: false, i18n, twoFactor: false })( empty({ collections: [own] as CollectionConfig[] }), ) expect(untouched.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access) @@ -65,7 +65,7 @@ describe('2FA wraps the auth collection people log in with', () => { test('defaults to access.authCollection, not a literal "users"', async () => { const plugin = totp() - await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + await iapl({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( empty(), ) expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) @@ -73,7 +73,7 @@ describe('2FA wraps the auth collection people log in with', () => { test('defaults to admin.user when access is not configured', async () => { const plugin = totp() - await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + await iapl({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( empty({ admin: { user: 'staff' } } as Partial), ) expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' })) @@ -91,20 +91,20 @@ describe('2FA wraps the auth collection people log in with', () => { test('admin.user wins over access.authCollection as the default target', async () => { const plugin = totp() - await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth()) + await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth()) expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) }) test('a target other than the panel login collection fails at init…', async () => { const plugin = totp() await expect( - ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()), + iapl({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()), ).rejects.toThrow(/admin panel logs in with "admins"/) }) test('…unless allowCollectionMismatch says it is deliberate', async () => { const plugin = totp() - await ipalKit({ + await iapl({ i18n, twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never }, })(twoAuth()) @@ -114,7 +114,7 @@ describe('2FA wraps the auth collection people log in with', () => { test('a target that is not an auth collection always fails', async () => { const plugin = totp() await expect( - ipalKit({ + iapl({ i18n, twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never }, })(twoAuth()), @@ -124,7 +124,7 @@ describe('2FA wraps the auth collection people log in with', () => { describe('globals: public read, editor+ write', () => { test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {} expect(run(access.read, null)).toBe(true) expect(run(access.update, user)).toBe(false) @@ -136,7 +136,7 @@ describe('globals: public read, editor+ write', () => { describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => { const build = async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty()) + const config = await iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty()) return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig } @@ -161,7 +161,7 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain describe('roles field: the first-register account becomes admin', () => { const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } } const count = vi.fn(async () => ({ totalDocs })) @@ -188,12 +188,12 @@ describe('roles field: the first-register account becomes admin', () => { describe('every access default can be overridden by the project', () => { test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => { - const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const base = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {} expect(run(def.unlock, user)).toBe(false) expect(run(def.unlock, admin)).toBe(true) - const config = await ipalKit({ + const config = await iapl({ access: { authAccess: { read: () => true }, authCollection: 'users' }, i18n, twoFactor: false, @@ -204,14 +204,14 @@ describe('every access default can be overridden by the project', () => { }) test('access.firstUserAdmin: false keeps what the first-register form sent', async () => { - const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty()) + const config = await iapl({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty()) const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown } expect(roles.hooks).toBeUndefined() }) test('globalOverrides: an object merges access (project wins), a function takes over', async () => { - const config = await ipalKit({ + const config = await iapl({ access: { authCollection: 'users' }, globalOverrides: { 'cookie-settings': (g) => ({ ...g, label: 'Cookies' }), @@ -229,7 +229,7 @@ describe('every access default can be overridden by the project', () => { }) test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => { - const config = await ipalKit({ + const config = await iapl({ access: { authCollection: 'users' }, forms: { formOverrides: { diff --git a/test/accountCopyTableSuite.ts b/test/accountCopyTableSuite.ts index 206073d..9099e97 100644 --- a/test/accountCopyTableSuite.ts +++ b/test/accountCopyTableSuite.ts @@ -1,7 +1,7 @@ /** * The copy rules as ONE table (review round 4 of the follow-ups: "a rule that cannot widen"). * - * A plugin listed after ipalKit copies staff collections, reuses their access objects, wraps their rules, writes + * A plugin listed after iapl copies staff collections, reuses their access objects, wraps their rules, writes * rules of its own next to them — every shape the reviews of 1.16.7's follow-ups tried (zzcopy3's table, R4-1, F-1, * F-2, G-1, G-2, H-1, J-1, J-2). For every shape, every kind of account and every operation two things must hold: * @@ -26,7 +26,7 @@ import path from 'path' import { getPayload } from 'payload' import { expect, test } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer } from './http/server.js' @@ -131,7 +131,7 @@ export function copyTableSuite(twoFactor: boolean): void { db: testDatabase(twoFactor ? 'copy_table_2fa' : 'copy_table'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users', staffCollections: ['agents', 'crew', 'team', 'proj', ...staffShapes(names)] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false, diff --git a/test/accountRulesAdminValueSuite.ts b/test/accountRulesAdminValueSuite.ts index 7c025e2..fdde1bb 100644 --- a/test/accountRulesAdminValueSuite.ts +++ b/test/accountRulesAdminValueSuite.ts @@ -18,7 +18,7 @@ import path from 'path' import { getPayload } from 'payload' import { expect, test } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer } from './http/server.js' @@ -79,7 +79,7 @@ export function adminValueSuite(twoFactor: boolean): void { db: testDatabase(twoFactor ? 'admin_value_2fa' : 'admin_value'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users', staffCollections: ['crew', 'agents', 'team', 'late-crew', 'viewers', 'text-roles', 'json-roles', 'late-text', 'rel-roles', ...SINGLE.map((x) => x.slug)] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false, diff --git a/test/accountRulesLateStaffSuite.ts b/test/accountRulesLateStaffSuite.ts index 5202a49..b1533ac 100644 --- a/test/accountRulesLateStaffSuite.ts +++ b/test/accountRulesLateStaffSuite.ts @@ -1,6 +1,6 @@ /** * A collection of the config that becomes staff LATER (review of the copy rules, L-2): `people` is in the config and - * is not named as staff; a plugin listed after ipalKit sets `admin.user` to it. At config time the plugin saw which + * is not named as staff; a plugin listed after iapl sets `admin.user` to it. At config time the plugin saw which * operations had a rule of the project's (the marker's `own`); when the collection is handled again at start: * - an operation that HAD a rule keeps it, exactly as written (here `create`: any signed-in account); * - an operation that had none gets the plugin's rule (on 1.16.7 a visitor account changed and deleted panel @@ -16,7 +16,7 @@ import path from 'path' import { getPayload } from 'payload' import { expect, test } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer } from './http/server.js' @@ -39,7 +39,7 @@ export function lateStaffSuite(twoFactor: boolean): void { db: testDatabase(twoFactor ? 'late_staff_2fa' : 'late_staff'), editor: lexicalEditor(), plugins: [ - ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), + iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), panelIsPeople, ], secret: 'integration-test-secret-0123456789', diff --git a/test/accountRulesNobodyManagesSuite.ts b/test/accountRulesNobodyManagesSuite.ts index 8a619f5..9f3fa01 100644 --- a/test/accountRulesNobodyManagesSuite.ts +++ b/test/accountRulesNobodyManagesSuite.ts @@ -15,7 +15,7 @@ import { getPayload } from 'payload' import { expect, test } from 'vitest' import { staffCollectionsNobodyManages } from '../src/modules/access/selfRegistration.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' @@ -50,7 +50,7 @@ export function nobodyManagesSuite(twoFactor: boolean): void { db: testDatabase(twoFactor ? 'nobody_2fa' : 'nobody'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users', staffCollections: [...SHAPES.map((shape) => shape.slug), 'own-rules'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false, diff --git a/test/accountRulesOff.test.ts b/test/accountRulesOff.test.ts index 370b23d..f254b5e 100644 --- a/test/accountRulesOff.test.ts +++ b/test/accountRulesOff.test.ts @@ -11,7 +11,7 @@ import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, expect, test, vi } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' @@ -36,7 +36,7 @@ beforeAll(async () => { ], db: testDatabase('accounts_off'), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['staff2'] }, accounts: false, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], secret: 'integration-test-secret-0123456789', telemetry: false, }) diff --git a/test/accountRulesOwnRoles.test.ts b/test/accountRulesOwnRoles.test.ts index e0c9e59..be01b65 100644 --- a/test/accountRulesOwnRoles.test.ts +++ b/test/accountRulesOwnRoles.test.ts @@ -14,7 +14,7 @@ import { getPayload } from 'payload' import { afterAll, beforeAll, expect, test, vi } from 'vitest' import { staffCollectionsOpenToOthers } from '../src/modules/access/selfRegistration.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' @@ -56,7 +56,7 @@ beforeAll(async () => { ], db: testDatabase('accounts_own_roles'), editor: lexicalEditor(), - plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })], + plugins: [iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } })], secret: 'integration-test-secret-0123456789', telemetry: false, }) @@ -117,7 +117,7 @@ test('a staff collection that does not exist stops the start, with the slug and collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], db: testDatabase('accounts_ghost'), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['ghost-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], secret: 'integration-test-secret-0123456789', telemetry: false, }) diff --git a/test/accountRulesReloadSuite.ts b/test/accountRulesReloadSuite.ts index 3d84ae0..01feee6 100644 --- a/test/accountRulesReloadSuite.ts +++ b/test/accountRulesReloadSuite.ts @@ -1,6 +1,6 @@ /** * A dev reload (review round 3, R3-2): Payload swaps `payload.config` and runs no onInit. A staff collection that a - * plugin listed after ipalKit adds must keep the account rules on the new config — with 2FA off and on. + * plugin listed after iapl adds must keep the account rules on the new config — with 2FA off and on. * Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI. */ import type { Config, Payload, Plugin, SanitizedConfig } from 'payload' @@ -12,7 +12,7 @@ import path from 'path' import { getPayload } from 'payload' import { expect, test } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer } from './http/server.js' @@ -32,7 +32,7 @@ const makeConfig = (twoFactor: boolean) => db: testDatabase(twoFactor ? 'reload_2fa' : 'reload'), editor: lexicalEditor(), plugins: [ - ipalKit({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), + iapl({ access: { authCollection: 'users', staffCollections: ['late-staff'] }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), late, ], secret: 'integration-test-secret-0123456789', diff --git a/test/accountRulesSingleLoginSuite.ts b/test/accountRulesSingleLoginSuite.ts index bbcbd05..1f8bece 100644 --- a/test/accountRulesSingleLoginSuite.ts +++ b/test/accountRulesSingleLoginSuite.ts @@ -15,7 +15,7 @@ import path from 'path' import { getPayload } from 'payload' import { expect, test } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer } from './http/server.js' @@ -36,7 +36,7 @@ export function singleLoginSuite(twoFactor: boolean): void { ], db: testDatabase(twoFactor ? 'single_login_2fa' : 'single_login'), editor: lexicalEditor(), - plugins: [ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })], + plugins: [iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false })], secret: 'integration-test-secret-0123456789', telemetry: false, }) diff --git a/test/accountRulesSuite.ts b/test/accountRulesSuite.ts index 3f06589..4545a7d 100644 --- a/test/accountRulesSuite.ts +++ b/test/accountRulesSuite.ts @@ -23,7 +23,7 @@ import { buildPasswordRuleHook, checkPassword, resolvePasswordRule } from '../sr import { isPasswordRuleHook, markedStaffRule, staffRuleOf } from '../src/modules/access/ruleMark.js' import { adoptLateAuthCollections, bothAllow, canHoldStaffRole, hasPluginRoles, openSignUpCollections, rolesAreAList, rolesNotOwn, sameStaffCollectionAccess, staffCollectionsNobodyManages, staffCollectionsOnOwnRoles, staffCollectionsOpenToOthers, staffCreateAccess, staffReadAccess, staffUpdateAccess, unknownStaffCollections } from '../src/modules/access/selfRegistration.js' import { requireSecondFactor } from '../src/modules/security/totp/secondFactor.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig, withTotpParts } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' @@ -31,7 +31,7 @@ import { totp } from './http/totp.js' const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' -/** A plugin the project lists AFTER ipalKit: its auth collections did not exist when ipalKit ran (review round 2, R2-3). */ +/** A plugin the project lists AFTER iapl: its auth collections did not exist when iapl ran (review round 2, R2-3). */ const latePlugin: Plugin = (config: Config) => ({ ...config, collections: [ @@ -98,7 +98,7 @@ export function accountRulesSuite(twoFactor: boolean): void { ], db: testDatabase(twoFactor ? 'accounts_2fa' : 'accounts'), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin], + plugins: [iapl({ access: { authCollection: 'users', staffCollections: ['staff2', 'crew', 'agents', 'late-staff'] }, i18n, twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp, verifyLimit: false } : false }), latePlugin], secret: 'integration-test-secret-0123456789', telemetry: false, }) @@ -341,7 +341,7 @@ export function accountRulesSuite(twoFactor: boolean): void { }) // Review round 2 (R2-3): a staff collection a later plugin adds. - test('a staff collection added by a plugin listed after ipalKit has the same rules', async () => { + test('a staff collection added by a plugin listed after iapl has the same rules', async () => { // (the first-user spellings above created nothing: counted there) expect((await post('/late-staff', { email: 'x@late.example.com', password: PASSWORD, roles: ['admin'] }, visitor)).status).toBe(403) expect((await post('/late-staff', { email: 'x@late.example.com', password: PASSWORD, roles: ['admin'] }, editor)).status).toBe(403) @@ -484,7 +484,7 @@ export function accountRulesSuite(twoFactor: boolean): void { expect(checkPassword('abcd', { minLength: 4 })).toBeNull() expect(checkPassword('Someone@Example.com ', { email: 'someone@example.com', minLength: 4 })).toBe('email') const hooks = async (options: Record) => - (await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0]) + (await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0]) expect(await hooks({})).toEqual([['customers', 0], ['users', 1]]) expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 0], ['users', 0]]) expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]]) @@ -493,7 +493,7 @@ export function accountRulesSuite(twoFactor: boolean): void { describe('accounts.panelRole: the config', () => { const build = (options: Record, incoming: Partial = {}) => - ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config) + iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config) const adminRule = (config: Config) => config.collections!.find((c) => c.slug === 'users')!.access?.admin test('on by default at editor; a role, false and accounts: false change it', async () => { @@ -507,7 +507,7 @@ export function accountRulesSuite(twoFactor: boolean): void { expect(adminRule(await build({ accounts: { panelRole: false } }))).toBeUndefined() expect(adminRule(await build({ accounts: false }))).toBeUndefined() // without `access` there are no roles to ask about - expect(adminRule(await ipalKit({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined() + expect(adminRule(await iapl({ i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config))).toBeUndefined() }) test("the project's own rule wins: on its own collection, and through access.authAccess", async () => { @@ -537,7 +537,7 @@ export function accountRulesSuite(twoFactor: boolean): void { describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => { const build = (options: Record, incoming: Partial = {}) => - ipalKit({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({ + iapl({ access: { authCollection: 'users', staffCollections: ['staff2'] }, i18n, twoFactor: false, ...options } as never)({ collections: [{ slug: 'staff2', auth: true, fields: [] }, { slug: 'customers', access: { create: () => true }, auth: true, fields: [] }, { slug: 'pages', fields: [] }], secret: 'x', ...incoming, @@ -646,7 +646,7 @@ export function accountRulesSuite(twoFactor: boolean): void { expect(of(noEndpoints, 'staff2').endpoints).toBe(false) // without `access` the rules still apply to the panel's login collection — as "an account of this collection": // without the plugin's roles nobody is an admin to it - const noAccess = await ipalKit({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config) + const noAccess = await iapl({ i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as unknown as Config) expect(of(noAccess, 'users').access?.create).toBeTypeOf('function') expect(await (of(noAccess, 'users').access!.create as (a: unknown) => unknown)({ req: { payload: { staffCollections: ['users'] }, user: { id: 1, collection: 'users' } } })).toBe(true) }) @@ -685,8 +685,8 @@ export function accountRulesSuite(twoFactor: boolean): void { test('a config collection that becomes staff later keeps the rules it had at config time', async () => { const own = ({ req }: { req: { user: unknown } }) => Boolean(req.user) const rolesField = () => ({ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'] }) - const { ipalKit } = await import('../src/plugin.js') - const built = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({ + const { iapl } = await import('../src/plugin.js') + const built = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({ admin: { user: 'users' }, collections: [ { slug: 'users', auth: true, fields: [] }, @@ -775,7 +775,7 @@ export function accountRulesSuite(twoFactor: boolean): void { // a late auth collection that is not staff: the first-user endpoint only expect(visitors.access.create).toBe(g) expect(asIs.access.create).toBe(g) - // what ipalKit saw at config time, and what is not an auth collection: untouched + // what iapl saw at config time, and what is not an auth collection: untouched expect(seen.access.create).toBe(g) expect([seen.endpoints.length, pages.endpoints.length]).toEqual([0, 0]) // a second call (a request after the start) changes nothing @@ -817,7 +817,7 @@ export function accountRulesSuite(twoFactor: boolean): void { const withFactory = await build({ twoFactor: { issuer: 'A', plugin: wrapping } }) expect(['create', 'update', 'delete', 'unlock', 'read', 'readVersions'].map((op) => staffRuleOf((of(withFactory, 'staff2').access as Record)[op])?.slug)).toEqual(Array(6).fill('staff2')) expect(staffRuleOf(of(withFactory, 'customers').access?.create)).toBeUndefined() // the project's own rule - // …and marking does not undo ipal-kit's 2FA guard: a plain 2FA config has nothing left to guard at start + // …and marking does not undo IAPL's 2FA guard: a plain 2FA config has nothing left to guard at start const { ensurePayloadGuarded } = await import('../src/modules/security/totp/secondFactor.js') const plain = await build({ twoFactor: { issuer: 'A', plugin: ((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)) as never } }) expect([ensurePayloadGuarded({ config: plain } as never), ensurePayloadGuarded({ config: withFactory } as never)]).toEqual([[], []]) diff --git a/test/adminMeta.test.ts b/test/adminMeta.test.ts index c977a49..e9fecfe 100644 --- a/test/adminMeta.test.ts +++ b/test/adminMeta.test.ts @@ -4,7 +4,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest' import { buildAdminImageEndpoints } from '../src/modules/branding/adminImages.js' import { adminMetaForSite, adminMetaStore, buildAdminMeta, DEFAULT_AGENCY, syncAdminMeta } from '../src/modules/branding/adminMeta.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } const base = (meta?: Record): Config => @@ -97,7 +97,7 @@ describe('admin meta defaults', () => { describe('plugin wiring', () => { test('on by default: meta, endpoints, Site settings hook; agency in the credit', async () => { - const config = await ipalKit({ i18n, twoFactor: false, whiteLabel: true } as never)(base()) + const config = await iapl({ i18n, twoFactor: false, whiteLabel: true } as never)(base()) expect(config.admin?.meta?.robots).toEqual({ follow: false, index: false }) const paths = (config.endpoints ?? []).map((e) => e.path) expect(paths).toEqual(expect.arrayContaining(['/ipal/admin-og', '/ipal/admin-icon'])) @@ -108,7 +108,7 @@ describe('plugin wiring', () => { }) test('every plugin global afterChange hook resolves with req: {} (no Payload instance)', async () => { - const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base()) + const config = await iapl({ cookieScanner: { crawl: true }, i18n, twoFactor: false, whiteLabel: true } as never)(base()) const calls = (config.globals ?? []).flatMap((g) => (g.hooks?.afterChange ?? []).map((h) => h({ context: {}, doc: {}, global: g, previousDoc: {}, req: {} } as never)), ) @@ -117,14 +117,14 @@ describe('plugin wiring', () => { }) test('adminMeta: false and agency: false switch the pieces off', async () => { - const config = await ipalKit({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base()) + const config = await iapl({ adminMeta: false, agency: false, i18n, twoFactor: false, whiteLabel: true } as never)(base()) expect(config.admin?.meta?.robots).toBeUndefined() expect((config.endpoints ?? []).some((e) => e.path === '/ipal/admin-og')).toBe(false) expect(config.admin?.components?.afterLogin ?? []).toEqual([]) }) test('a custom agency reaches the credit; whiteLabel.credit text still wins', async () => { - const config = await ipalKit({ + const config = await iapl({ agency: { name: 'Studio X', url: 'https://studio.example' }, i18n, twoFactor: false, diff --git a/test/adminUx.test.ts b/test/adminUx.test.ts index a5834b5..3df9709 100644 --- a/test/adminUx.test.ts +++ b/test/adminUx.test.ts @@ -5,7 +5,7 @@ import { describe, expect, test } from 'vitest' import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js' import { applyAdminI18n } from '../src/modules/admin-i18n/apply.js' import { adminTexts } from '../src/modules/admin-i18n/index.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' /** * docs/dev/admin-ux.md, enforced: every admin string the plugin adds has an @@ -45,7 +45,7 @@ const project = (): Config => }) as unknown as Config const fullConfig = () => - ipalKit({ + iapl({ access: { authCollection: 'users' }, consentLog: true, content: { collections: [{ slug: 'posts' }] }, @@ -149,7 +149,7 @@ function checkCollection(collection: CollectionConfig, problems: Problem[]) { walk(collection.fields, collection.slug, problems) } -// Collections the plugin creates; fields of other plugins (form-builder, plugin-seo) are checked where ipal-kit sets them. +// Collections the plugin creates; fields of other plugins (form-builder, plugin-seo) are checked where IAPL sets them. const PLUGIN_COLLECTIONS = ['consent-records', 'cookie-review', 'stats-visits'] describe('admin wording (docs/dev/admin-ux.md)', () => { diff --git a/test/adminUxFollowUps.test.ts b/test/adminUxFollowUps.test.ts index b967a1f..11fd448 100644 --- a/test/adminUxFollowUps.test.ts +++ b/test/adminUxFollowUps.test.ts @@ -2,13 +2,13 @@ import type { BasePayload, Config, Field, GlobalConfig, PayloadRequest } from 'p import { describe, expect, test, vi } from 'vitest' -import { adminDocumentTitle, adminTexts, ipalT } from '../src/modules/admin-i18n/index.js' +import { adminDocumentTitle, adminTexts, iaplT } from '../src/modules/admin-i18n/index.js' import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js' import { DEFAULT_COOKIE_INTEGRATIONS, integrationLabel } from '../src/modules/consent/scanner/integrations.js' import { collectCookieFindings } from '../src/modules/consent/scanner/scan.js' import { constructionCloseLabel } from '../src/modules/construction/texts.js' import { faviconProblems } from '../src/modules/seo/faviconProblems.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' vi.mock('server-only', () => ({})) @@ -28,8 +28,8 @@ const fakePayload = (integrations: Record = {}) => describe('statistics page title', () => { test('tab title in the admin language, with the title suffix', () => { - expect(adminDocumentTitle(ipalT(tFor('pl'), 'statsTitle'), '- Payload')).toBe('Statystyki - Payload') - expect(adminDocumentTitle(ipalT(tFor('en'), 'statsTitle'), '- Acme')).toBe('Statistics - Acme') + expect(adminDocumentTitle(iaplT(tFor('pl'), 'statsTitle'), '- Payload')).toBe('Statystyki - Payload') + expect(adminDocumentTitle(iaplT(tFor('en'), 'statsTitle'), '- Acme')).toBe('Statistics - Acme') expect(adminDocumentTitle('Statystyki', '')).toBe('Statystyki') }) }) @@ -93,14 +93,14 @@ describe('favicon check', () => { }) test('warnings read in both admin languages with the size filled in', () => { - expect(ipalT(tFor('en'), 'faviconTooSmall', { height: 32, width: 32 })).toContain('32×32 px') - expect(ipalT(tFor('pl'), 'faviconTooSmall', { height: 32, width: 32 })).toBe('Ikona ma 32×32 px. Google pokazuje ikony od 48×48 px; wgraj większą.') - expect(ipalT(tFor('pl'), 'faviconNotSquare', { height: 96, width: 192 })).toContain('192×96 px') + expect(iaplT(tFor('en'), 'faviconTooSmall', { height: 32, width: 32 })).toContain('32×32 px') + expect(iaplT(tFor('pl'), 'faviconTooSmall', { height: 32, width: 32 })).toBe('Ikona ma 32×32 px. Google pokazuje ikony od 48×48 px; wgraj większą.') + expect(iaplT(tFor('pl'), 'faviconNotSquare', { height: 96, width: 192 })).toContain('192×96 px') }) test('Site settings shows the check under the site icon', async () => { const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({ + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false } as never)({ collections: [ { slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }, diff --git a/test/auditPolishLiterals.test.ts b/test/auditPolishLiterals.test.ts index b3b4588..2417c52 100644 --- a/test/auditPolishLiterals.test.ts +++ b/test/auditPolishLiterals.test.ts @@ -8,7 +8,7 @@ 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') +const scripts = path.join(packageRoot, 'docs/agent/skills/iapl-audit/scripts') let dirs: string[] = [] function project(files: Record): string { @@ -137,7 +137,7 @@ describe('hardcoded Polish text: public strings are still reported', () => { }) }) -describe('ipal-audit and ipal-doctor agree', () => { +describe('iapl-audit and iapl-doctor agree', () => { const files = { 'package.json': JSON.stringify({ name: 'examplepl-web' }), 'src/collections/Pages.ts': `${HELPER}export const Pages = { slug: 'pages', fields: [ diff --git a/test/blockLibrary.test.ts b/test/blockLibrary.test.ts index 7bb0e90..2ccb146 100644 --- a/test/blockLibrary.test.ts +++ b/test/blockLibrary.test.ts @@ -277,7 +277,7 @@ describe('styling: every token utility the blocks use exists in the preset', () }) }) -describe('ipal-blocks eject', () => { +describe('iapl-blocks eject', () => { const tmp = mkdtempSync(path.join(os.tmpdir(), 'ipal-eject-')) afterAll(() => rmSync(tmp, { force: true, recursive: true })) @@ -297,7 +297,7 @@ describe('ipal-blocks eject', () => { test('every block ejects with imports that exist in the package entries', () => { const problems: string[] = [] for (const slug of LIBRARY_BLOCK_SLUGS) { - execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' }) + execFileSync('node', [path.join(root, 'bin/iapl-blocks.mjs'), 'eject', slug, '--dest', tmp], { cwd: tmp, stdio: 'pipe' }) const dir = path.join(tmp, slug[0].toUpperCase() + slug.slice(1)) for (const file of readdirSync(dir)) { const src = readFileSync(path.join(dir, file), 'utf8') @@ -318,7 +318,7 @@ describe('ipal-blocks eject', () => { }) test('an existing file is never overwritten', () => { - const out = execFileSync('node', [path.join(root, 'bin/ipal-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' }) + const out = execFileSync('node', [path.join(root, 'bin/iapl-blocks.mjs'), 'eject', 'faq', '--dest', tmp], { cwd: tmp, encoding: 'utf8', stdio: 'pipe' }) expect(out).not.toMatch(/^write /m) }) }) diff --git a/test/blockLibraryPayload.test.ts b/test/blockLibraryPayload.test.ts index b65c4c7..8dc0884 100644 --- a/test/blockLibraryPayload.test.ts +++ b/test/blockLibraryPayload.test.ts @@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js' import { createSeeder } from '../src/exports/seed.js' import { pageTemplates, systemPageRefs } from '../src/exports/templates.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -54,7 +54,7 @@ describe('block library in Payload', () => { editor: lexicalEditor(), localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] }, plugins: [ - ipalKit({ + iapl({ content: { collections: [{ slug: 'posts' }] }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, diff --git a/test/construction.test.ts b/test/construction.test.ts index 98e9d79..f976045 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' import { createPageRoute } from '../src/modules/frontend/pageRoute.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -45,7 +45,7 @@ describe('under construction — Site Settings → createPageRoute', () => { ], db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })], secret: 'construction-test-secret', telemetry: false, }) diff --git a/test/cookieApproval.test.ts b/test/cookieApproval.test.ts index 6ed2d0a..42cb433 100644 --- a/test/cookieApproval.test.ts +++ b/test/cookieApproval.test.ts @@ -18,7 +18,7 @@ import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConse import { approveCookies, buildCookieApprovalEndpoints, loadCookieApproval } from '../src/modules/consent/scanner/approval.js' import { nextChange, runCookieScan } from '../src/modules/consent/scanner/scan.js' import { sameCookie } from '../src/modules/consent/scanner/sync.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -53,7 +53,7 @@ beforeAll(async () => { ], db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, stats: true, twoFactor: false })], secret: 'cookie-approval-test-secret', telemetry: false, }), @@ -180,7 +180,7 @@ describe('cookie approval against a real Payload', () => { describe('cookie approval — optional', () => { const config = (cookieScanner: unknown) => - ipalKit({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config) + iapl({ cookieScanner: cookieScanner as never, i18n, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config) test('on by default: the view, its endpoint and the dashboard reminder', async () => { const c = await config(true) diff --git a/test/cookieCrawlIntegration.test.ts b/test/cookieCrawlIntegration.test.ts index ae2121e..89b23c9 100644 --- a/test/cookieCrawlIntegration.test.ts +++ b/test/cookieCrawlIntegration.test.ts @@ -20,7 +20,7 @@ import { crawlSite } from '../services/cookie-crawler/crawl.mjs' import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js' import { buildCookieCrawlEndpoints } from '../src/modules/consent/scanner/crawl/endpoints.js' import { COOKIE_SCAN_LABELS } from '../src/modules/consent/scanner/labels.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -66,7 +66,7 @@ beforeAll(async () => { db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, cookieScanner: { crawl: crawlOptions(), declarations }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, diff --git a/test/cookieCrawler.test.ts b/test/cookieCrawler.test.ts index aba3782..c1a0674 100644 --- a/test/cookieCrawler.test.ts +++ b/test/cookieCrawler.test.ts @@ -183,8 +183,8 @@ describe('crawl — site side', () => { test('config: options, then env, then Payload serverURL; short tokens are not a token', () => { const payload = { config: { serverURL: 'https://acme.pl/' } } as unknown as BasePayload - vi.stubEnv('IPAL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/') - vi.stubEnv('IPAL_COOKIE_SCAN_TOKEN', 'short') + vi.stubEnv('IAPL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/') + vi.stubEnv('IAPL_COOKIE_SCAN_TOKEN', 'short') const c = resolveCrawlConfig({ maxPages: 500 }, payload) expect(c).toMatchObject({ maxPages: 100, serviceUrl: 'https://crawler.intecion.net', siteUrl: 'https://acme.pl', token: null }) expect(resolveCrawlConfig({ token: TOKEN, trackerHosts: (d) => [...d, 'chat.example'] }, payload).trackerHosts).toContain('chat.example') diff --git a/test/cookieScanner.test.ts b/test/cookieScanner.test.ts index 0e8b31b..fcaa4bd 100644 --- a/test/cookieScanner.test.ts +++ b/test/cookieScanner.test.ts @@ -10,7 +10,7 @@ import { cookieNameMatches, DEFAULT_COOKIE_INTEGRATIONS } from '../src/modules/c import { COOKIE_SCAN_LABELS, labelFor, labelRecord, mergeCookieScanLabels } from '../src/modules/consent/scanner/labels.js' import { mergeCookieReview, suggestionFor, textFor } from '../src/modules/consent/scanner/merge.js' import { collectCookieFindings, parseCookieNames } from '../src/modules/consent/scanner/scan.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' vi.mock('server-only', () => ({})) @@ -187,7 +187,7 @@ describe('cookie scanner — labels and config', () => { }) const run = async (cookieScanner?: unknown) => - ipalKit({ + iapl({ cookieScanner: cookieScanner as never, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false, diff --git a/test/cookieScannerIntegration.test.ts b/test/cookieScannerIntegration.test.ts index 61d548d..1b84ba6 100644 --- a/test/cookieScannerIntegration.test.ts +++ b/test/cookieScannerIntegration.test.ts @@ -13,7 +13,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { buildCookieScanEndpoints } from '../src/modules/consent/scanner/endpoint.js' import { runCookieScan } from '../src/modules/consent/scanner/scan.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -54,7 +54,7 @@ beforeAll(async () => { db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, cookieScanner: { declarations }, i18n: { diff --git a/test/dashboardAlerts.test.ts b/test/dashboardAlerts.test.ts index 2bf97b8..db5c51a 100644 --- a/test/dashboardAlerts.test.ts +++ b/test/dashboardAlerts.test.ts @@ -10,7 +10,7 @@ import { describe, expect, test } from 'vitest' import { CookieCrawlAlert } from '../src/modules/consent/scanner/crawl/CookieCrawlAlert.js' import { IntegrationAlerts } from '../src/modules/integrations/IntegrationAlerts.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const ERROR_TEXT = 'SMTP-ERROR-DETAIL: 535 authentication failed for mailer@example.com' const payloadWith = (twoFactor: boolean) => ({ @@ -91,10 +91,10 @@ describe('CookieCrawlAlert', () => { }) }) -describe('ipalKit({ dashboardAlerts })', () => { +describe('iapl({ dashboardAlerts })', () => { const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const propsOf = async (options: Record) => { - const config = await ipalKit({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never) + const config = await iapl({ cookieScanner: { crawl: true }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x' } as never) return JSON.stringify(config.admin?.components?.beforeDashboard) } diff --git a/test/designTokens.test.ts b/test/designTokens.test.ts index ba4e9f2..d3425c4 100644 --- a/test/designTokens.test.ts +++ b/test/designTokens.test.ts @@ -12,9 +12,9 @@ import { defineTokens, FLUID_SCALE, fluidClamp, - IPAL_BREAKPOINTS, - IPAL_TOKENS, - ipalVar, + IAPL_BREAKPOINTS, + IAPL_TOKENS, + iaplVar, parseColor, resolveColors, tokensToCss, @@ -164,21 +164,21 @@ describe('defineTokens / tokensToCss', () => { }) describe('names', () => { - test('IPAL_TOKENS and ipalVar give var() strings', () => { - expect(IPAL_TOKENS.primary).toBe('var(--ipal-primary)') - expect(IPAL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)') - expect(IPAL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)') - expect(ipalVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)') - expect(IPAL_BREAKPOINTS.md).toBe(48) + test('IAPL_TOKENS and iaplVar give var() strings', () => { + expect(IAPL_TOKENS.primary).toBe('var(--ipal-primary)') + expect(IAPL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)') + expect(IAPL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)') + expect(iaplVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)') + expect(IAPL_BREAKPOINTS.md).toBe(48) }) }) -describe('ipal-tokens CLI', () => { +describe('iapl-tokens CLI', () => { let dir: string let lines: string[] const log = (line: string) => lines.push(line) beforeEach(() => { - dir = mkdtempSync(path.join(tmpdir(), 'ipal-tokens-')) + dir = mkdtempSync(path.join(tmpdir(), 'iapl-tokens-')) lines = [] }) afterEach(() => rmSync(dir, { force: true, recursive: true })) diff --git a/test/docsConsistency.test.ts b/test/docsConsistency.test.ts index 43cf4cd..54ce7da 100644 --- a/test/docsConsistency.test.ts +++ b/test/docsConsistency.test.ts @@ -122,15 +122,15 @@ describe('docs ↔ code', () => { test('every top-level plugin option is documented', () => { const src = read('src/types.ts') - const body = src.slice(src.indexOf('export type IpalOptions = {')) + const body = src.slice(src.indexOf('export type IaplOptions = {')) const keys = [...body.matchAll(/^ {2}(\w+)\??:/gm)].map((m) => m[1]) expect(keys.length).toBeGreaterThan(10) const all = docs.map(read).join('\n') expect(keys.filter((key) => !new RegExp(`\\b${key}\\b`).test(all))).toEqual([]) }) - test('every IPAL_* env var named in the docs is read by the code', () => { - // The plugin, or a script/template shipped in the skills (e.g. IPAL_SEED_ALLOW_PROD_UPDATE). + test('every IAPL_* env var named in the docs is read by the code', () => { + // The plugin, or a script/template shipped in the skills (e.g. IAPL_SEED_ALLOW_PROD_UPDATE). const shipped = docs.filter((f) => f.startsWith('docs/agent/skills/') && /\.(?:mjs|ts|tsx)$/.test(f)) const code = [...srcFiles(), ...shipped].map(read).join('\n') const named = new Set([...docs, 'README.md'].flatMap((f) => [...read(f).matchAll(/\bIPAL_[A-Z0-9_]+/g)].map((m) => m[0]))) @@ -185,7 +185,7 @@ describe('docs ↔ code', () => { expect([...contentHelperNames()].filter((name) => !new RegExp(`\\b${name}\\b`).test(page))).toEqual([]) }) - test('install commands never tell projects to add packages ipal-kit already depends on', () => { + test('install commands never tell projects to add packages IAPL already depends on', () => { const own = Object.keys(JSON.parse(read('package.json')).dependencies) const offending: string[] = [] for (const file of ['README.md', 'docs/dev/PROGRAMISTA.md']) { @@ -230,7 +230,7 @@ describe('docs are in English', () => { }) /** - * The agent guide (AGENT.md + the ipal-* skills copied into projects) is all an agent in a + * The agent guide (AGENT.md + the iapl-* skills copied into projects) is all an agent in a * consumer project reads. Every export, option and env var must be findable there, or the * agent re-implements what the plugin already does. */ @@ -254,13 +254,13 @@ describe('agent guide covers the whole plugin', () => { return [...body.matchAll(/^\s+(\w+)\??:/gm)].map((m) => m[1]) } const keys = [ - ...typeKeys('src/types.ts', 'IpalOptions'), + ...typeKeys('src/types.ts', 'IaplOptions'), ...typeKeys('src/modules/access/types.ts', 'AccessOption'), ...typeKeys('src/modules/content/types.ts', 'ContentCollectionOption'), ...typeKeys('src/modules/content/types.ts', 'ContentOption'), ...typeKeys('src/modules/consent/scanner/types.ts', 'CookieScannerOptions'), ...typeKeys('src/modules/consent/scanner/types.ts', 'CookieCrawlOptions'), - ...typeKeys('src/modules/env/ipalEnvRules.ts', 'IpalEnvFeatures'), + ...typeKeys('src/modules/env/iaplEnvRules.ts', 'IaplEnvFeatures'), ...typeKeys('src/modules/forms/types.ts', 'FormsOption'), ...typeKeys('src/modules/i18n/types.ts', 'I18nConfig'), ...typeKeys('src/modules/i18n/types.ts', 'LocaleDefinition'), @@ -285,16 +285,16 @@ describe('agent guide covers the whole plugin', () => { test('the working rules reach every skill that builds the site', () => { const agent = read('docs/agent/AGENT.md') - for (const heading of ['## Ask before you build', '## ipal-kit first', '## Code rules']) {expect(agent).toContain(heading)} - const skills = ['ipal-setup', 'ipal-site', 'ipal-block', 'ipal-collection', 'ipal-form'] + for (const heading of ['## Ask before you build', '## IAPL first', '## Code rules']) {expect(agent).toContain(heading)} + const skills = ['iapl-setup', 'iapl-site', 'iapl-block', 'iapl-collection', 'iapl-form'] const missing = skills.filter((name) => { const text = read(`docs/agent/skills/${name}/SKILL.md`) - return !text.includes('ipal-kit first') || !text.includes('Code rules') || !text.includes('ipal-plugin-gap') + return !text.includes('IAPL first') || !text.includes('Code rules') || !text.includes('iapl-plugin-gap') }) expect(missing).toEqual([]) // Both entry skills start with the architecture questions and wait for the answers. - expect(read('docs/agent/skills/ipal-setup/SKILL.md')).toContain('## 0. Architecture questions') - expect(read('docs/agent/skills/ipal-site/SKILL.md')).toContain('Architecture questions') + expect(read('docs/agent/skills/iapl-setup/SKILL.md')).toContain('## 0. Architecture questions') + expect(read('docs/agent/skills/iapl-site/SKILL.md')).toContain('Architecture questions') }) test('every @/lib/content helper', () => { diff --git a/test/doctor.test.ts b/test/doctor.test.ts index 855bb73..07f0651 100644 --- a/test/doctor.test.ts +++ b/test/doctor.test.ts @@ -21,7 +21,7 @@ let dirs: string[] = [] /** A project folder from a { path: content } map; package.json objects are serialised. */ function project(files: Record): string { - const root = mkdtempSync(path.join(tmpdir(), 'ipal-doctor-')) + const root = mkdtempSync(path.join(tmpdir(), 'iapl-doctor-')) dirs.push(root) for (const [rel, content] of Object.entries(files)) { const file = path.join(root, rel) @@ -154,18 +154,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = const run = async (config: string, only: string[], deepStatus?: object) => rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {})) - test('access-missing: ipalKit without `access` means every account is an admin', async () => { - expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning']) + test('access-missing: iapl without `access` means every account is an admin', async () => { + expect(await run("plugins: [iapl({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning']) // a collection's own access rules are not the plugin option - expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning']) - for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) { + expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [iapl({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning']) + for (const ok of ["iapl({ access: { authCollection: 'users' }, i18n })", "iapl({ i18n, access: { defaultRole: 'editor' } })", 'iapl({ access: {}, i18n })', 'iapl({ access: accessOptions, i18n })', '// no plugin here']) { expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []]) } }) test('turnstile-degraded: a warning, an error after a day', async () => { const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString() - const cfg = "ipalKit({ access: { authCollection: 'users' } })" + const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error']) expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning']) @@ -180,7 +180,7 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = }) test('turnstile-env-key: the secret still comes from the environment', async () => { - const cfg = "ipalKit({ access: { authCollection: 'users' } })" + const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning']) expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([]) expect(await run(cfg, ['turnstile-env-key'])).toEqual([]) @@ -189,14 +189,14 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = test('csrf-empty: without serverURL and csrf Payload takes the login cookie from any origin', async () => { // the word is spelled in two parts: test/testConfig.test.ts refuses test files that name Payload's config builder const build = (body: string) => `export default ${'build'}${'Config'}(${body})` - expect(await run(build("{ plugins: [ipalKit({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning']) + expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'])).toEqual(['csrf-empty:warning']) expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([]) expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([]) expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([]) }) test('open-signup: an auth collection anyone can register in is said, as info', async () => { - const cfg = "ipalKit({ access: { authCollection: 'users' } })" + const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['open-signup'], { openSignUp: ['customers', 'members'] })).toEqual(['open-signup:info', 'open-signup:info']) expect(await run(cfg, ['open-signup'], { openSignUp: [] })).toEqual([]) expect(await run(cfg, ['open-signup'], { openSignUp: null })).toEqual([]) @@ -204,7 +204,7 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () = }) test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => { - const cfg = "ipalKit({ access: { authCollection: 'users' } })" + const cfg = "iapl({ access: { authCollection: 'users' } })" expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error']) expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:read', 'agents:unlock'] })).toEqual(expect.arrayContaining(['staff-accounts-open:warning', 'staff-accounts-open:error'])) expect(await run(cfg, ['staff-own-roles'], { staffOnOwnRoles: ['crew'] })).toEqual(['staff-own-roles:warning']) @@ -237,7 +237,7 @@ describe('helpers', () => { expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' }) }) test('readAuditSkips maps keys to the reason', () => { - const skips = readAuditSkips('- ipal-audit-skip: mcp, twofactor — client decision 2026-10-01\n') + const skips = readAuditSkips('- iapl-audit-skip: mcp, twofactor — client decision 2026-10-01\n') expect(skips.get('mcp')).toBe('client decision 2026-10-01') expect(skips.get('twofactor')).toBe('client decision 2026-10-01') }) @@ -250,7 +250,7 @@ describe('helpers', () => { expect(globToRegExp('src/*.ts').test('src/a/b.ts')).toBe(false) }) test('parseToolOutput reads the [LEVEL] title (n) — rule blocks of audit.sh and seo-check', () => { - const lines = parseToolOutput('ipal-audit\n\n[ERROR] hex colors in classes (2) — §6.11 tokens\n src/a.tsx:1: bg-[#fff]\n src/b.tsx:2: x\n[INFO] note — fine\n') + const lines = parseToolOutput('iapl-audit\n\n[ERROR] hex colors in classes (2) — §6.11 tokens\n src/a.tsx:1: bg-[#fff]\n src/b.tsx:2: x\n[INFO] note — fine\n') expect(lines).toEqual([ { items: ['src/a.tsx:1: bg-[#fff]', 'src/b.tsx:2: x'], level: 'error', rule: '§6.11 tokens', title: 'hex colors in classes' }, { items: [], level: 'info', rule: 'fine', title: 'note' }, @@ -263,7 +263,7 @@ describe('helpers', () => { }) }) -describe('ipal-audit through the doctor', () => { +describe('iapl-audit through the doctor', () => { const site = (contentTs: string) => project({ ...base(), 'src/lib/content.ts': contentTs, 'src/payload.config.ts': "import { payloadTotp } from '@clocklimited/payload-2fa'\n" }) const aiBots = async (root: string) => (await doctor(root, ['audit'])).findings.filter((f) => f.rule === 'audit:robots-blocks-ai-bots') @@ -350,10 +350,10 @@ describe('versions', () => { describe('db-name', () => { const env = (dev: string, example = dev) => ({ ...base(), '.env': `DATABASE_URI=mongodb://127.0.0.1:27017/${dev}\n`, '.env.example': `DATABASE_URI=mongodb://USER:PASS@HOST:PORT/${example}?authSource=admin\n` }) test('_dev passes', async () => { - expect(rules(await doctor(project({ ...env('examplepl_dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name']))).toEqual([]) + expect(rules(await doctor(project({ ...env('examplepl_dev'), 'iapl-doctor.json': { domain: 'example.pl' } }), ['db-name']))).toEqual([]) }) test('a local .env on _prod is an error, another name too', async () => { - const report = await doctor(project({ ...env('examplepl_prod', 'dev'), 'ipal-doctor.json': { domain: 'example.pl' } }), ['db-name']) + const report = await doctor(project({ ...env('examplepl_prod', 'dev'), 'iapl-doctor.json': { domain: 'example.pl' } }), ['db-name']) expect(report.findings.map((f) => f.message)).toEqual([ '.env points at the production database examplepl_prod — a local run or seed writes to production', '.env.example: database "dev", expected examplepl_dev', @@ -413,7 +413,7 @@ describe('layout, blocks, seeds, agents', () => { expect(report.findings[0].message).toContain('src/proxy.ts') }) test('layout.allow extends the src/ allow list; an audit skip drops its file', async () => { - const root = project({ ...base(), 'AGENTS.md': '## Project decisions\n- ipal-audit-skip: mcp — client decision\n', 'src/scripts/x.ts': '' }) + const root = project({ ...base(), 'AGENTS.md': '## Project decisions\n- iapl-audit-skip: mcp — client decision\n', 'src/scripts/x.ts': '' }) const report = await doctor(root, ['layout-required', 'layout-extra'], { config: { layout: { allow: ['scripts'] } } }) expect(report.findings.map((f) => f.rule)).toEqual(['layout-required']) expect(report.findings[0].message).not.toContain('api/mcp') @@ -459,7 +459,7 @@ describe('layout, blocks, seeds, agents', () => { test('seeds: helper, no deletes, no fresh script, guard on; after launch a record list', async () => { const files = { ...base(), - 'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts', 'seed:fresh': 'payload run src/seed/old.ts', 'seed:full': 'IPAL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }), + 'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts', 'seed:fresh': 'payload run src/seed/old.ts', 'seed:full': 'IAPL_SEED_ALLOW_FULL=1 payload run src/seed/index.ts' } }), 'src/seed/index.ts': "import { pages } from './pages'\nconst seed = createSeeder(payload)", 'src/seed/old.ts': 'await payload.delete({ collection: "pages" })', 'src/seed/pages.ts': 'export const pages = []', @@ -467,19 +467,19 @@ describe('layout, blocks, seeds, agents', () => { expect(rules(await doctor(project(files), ['seed-named']))).toEqual([ 'seed-named:error', // seed:fresh name 'seed-named:error', // old.ts deletes - 'seed-named:error', // IPAL_SEED_ALLOW_FULL=1 in seed:full + 'seed-named:error', // IAPL_SEED_ALLOW_FULL=1 in seed:full 'seed-named:warning', // old.ts without the helper (errors sort first) ]) const launched = await doctor(project({ ...files, 'package.json': pkgJson({ scripts: { seed: 'payload run src/seed/index.ts' } }) }), ['seed-named'], { config: { launched: true } }) expect(launched.findings.map((f) => f.message)).toEqual(['script "seed" has no record list — after launch every run needs SEED_ONLY']) }) test('AGENTS.md needs a non-empty "Project decisions" and the pointer for the installed version', async () => { - const pointer = '\n## ipal-kit 1.14.6 — agent guide\n' + const pointer = '\n## IAPL 1.14.6 — agent guide\n' expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `# x\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:error']) expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual(['agents-md:warning']) expect(rules(await doctor(project({ ...base(), 'AGENTS.md': `## Project decisions\n- pl only\n${pointer}`, 'CLAUDE.md': '@AGENTS.md\n' }), ['agents-md']))).toEqual([]) }) - test('planSkills: missing, stale and retired ipal-* folders', () => { + test('planSkills: missing, stale and retired iapl-* folders', () => { const source = project({ 'ipal-a/SKILL.md': 'a', 'ipal-b/SKILL.md': 'b' }) const dest = project({ 'ipal-b/SKILL.md': 'old', 'ipal-old/SKILL.md': 'x', 'mine/SKILL.md': 'own' }) expect(planSkills({ dest, source })).toEqual({ missing: ['ipal-a'], retired: ['ipal-old'], stale: ['ipal-b'] }) @@ -538,7 +538,7 @@ describe('security and deep status', () => { const payload = { config: { admin: { user: 'users' }, collections: [] }, count: vi.fn() } const call = (auth?: string) => endpoint.handler({ headers: new Headers(auth ? { authorization: auth, 'x-forwarded-for': '1.2.3.4' } : {}), payload } as never) as Promise expect((await call()).status).toBe(404) - vi.stubEnv('IPAL_DOCTOR_TOKEN', 'x'.repeat(40)) + vi.stubEnv('IAPL_DOCTOR_TOKEN', 'x'.repeat(40)) expect((await call('Bearer wrong')).status).toBe(401) const ok = await call(`Bearer ${'x'.repeat(40)}`) expect(ok.status).toBe(200) @@ -546,7 +546,7 @@ describe('security and deep status', () => { }) }) -describe('silencing (ipal-doctor.json)', () => { +describe('silencing (iapl-doctor.json)', () => { const noAgents = () => project(base()) test('off with a reason silences (kept in the report); without a reason it is ignored and reported', async () => { const silenced = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'demo' } } } }) @@ -555,11 +555,11 @@ describe('silencing (ipal-doctor.json)', () => { const noReason = await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true } } } }) expect(rules(noReason)).toEqual(['doctor-config:error', 'agents-md:error']) }) - test('severity override, expired until, files filter, ipal-audit-skip', async () => { + test('severity override, expired until, files filter, iapl-audit-skip', async () => { expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { reason: 'r', severity: 'info' } } } }))).toEqual(['agents-md:info']) expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { off: true, reason: 'r', until: '2026-10-01' } } } }))).toEqual(['agents-md:error', 'doctor-config:warning']) expect(rules(await doctor(noAgents(), ['agents-md'], { config: { rules: { 'agents-md': { files: ['src/**'], off: true, reason: 'r' } } } }))).toEqual(['agents-md:error']) - const skip = project({ ...base(), 'AGENTS.md': '- ipal-audit-skip: twofactor — the client signs in with SSO\n', 'src/payload.config.ts': '' }) + const skip = project({ ...base(), 'AGENTS.md': '- iapl-audit-skip: twofactor — the client signs in with SSO\n', 'src/payload.config.ts': '' }) expect((await doctor(skip, ['2fa'])).findings[0]).toMatchObject({ reason: 'the client signs in with SSO', silenced: true }) }) }) @@ -595,7 +595,7 @@ describe('live (--url)', () => { }) describe('CLI', () => { - const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n\n## ipal-kit 1.14.6 — agent guide\n', 'CLAUDE.md': '@AGENTS.md\n' }) + const clean = () => project({ ...base(), 'AGENTS.md': '## Project decisions\n- x\n\n## IAPL 1.14.6 — agent guide\n', 'CLAUDE.md': '@AGENTS.md\n' }) const cli = async (args: string[], cwd: string) => { const out: string[] = [] const code = await runDoctorCli(args, { cwd, log: (l) => out.push(l), packageRoot }) @@ -613,7 +613,7 @@ describe('CLI', () => { expect((await cli([info, '--offline', '--only', 'versions'], info)).code).toBe(0) expect((await cli([info, '--offline', '--only', 'versions', '--strict'], info)).code).toBe(1) expect((await cli([project({ 'x.txt': '' })], packageRoot)).code).toBe(2) - const bad = project({ ...base(), 'ipal-doctor.json': '{ nope' }) + const bad = project({ ...base(), 'iapl-doctor.json': '{ nope' }) expect((await cli([bad, '--offline', '--only', 'versions'], bad)).code).toBe(2) }) test('--json is schema 1 with a summary; the human report lists fix and docs', async () => { @@ -644,13 +644,13 @@ describe('CLI', () => { }) describe('the reference site', () => { - test('reference/ipal-doctor.json silences only with reasons', () => { - const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/ipal-doctor.json'), 'utf8')) as DoctorConfig + test('reference/iapl-doctor.json silences only with reasons', () => { + const config = JSON.parse(readFileSync(path.join(packageRoot, 'reference/iapl-doctor.json'), 'utf8')) as DoctorConfig for (const setting of Object.values(config.rules ?? {})) {expect(setting.reason?.trim()).toBeTruthy()} }) }) -describe('ipal-doctor: first-seen dates', () => { +describe('iapl-doctor: first-seen dates', () => { test('are written only outside CI, and never with --json or --sites', () => { expect(shouldWriteSeen({}, {})).toBe(true) expect(shouldWriteSeen({}, { CI: 'true' })).toBe(false) diff --git a/test/drafts.test.ts b/test/drafts.test.ts index e769d69..caa03ee 100644 --- a/test/drafts.test.ts +++ b/test/drafts.test.ts @@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest' import { resolveRoute } from '../src/modules/content/resolveRoute.js' import { buildNoindexField } from '../src/modules/seo/buildNoindexField.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' let payload: Payload @@ -33,7 +33,7 @@ beforeAll(async () => { db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, diff --git a/test/env.test.ts b/test/env.test.ts index 51d162b..34656f7 100644 --- a/test/env.test.ts +++ b/test/env.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { assertEnv } from '../src/modules/env/assertEnv.js' import { checkDatabaseName, databaseNameFromUri, databaseNamesFor } from '../src/modules/env/databaseName.js' -import { ipalEnvRules } from '../src/modules/env/ipalEnvRules.js' +import { iaplEnvRules } from '../src/modules/env/iaplEnvRules.js' const base = { DATABASE_URI: 'mongodb://db/x', NEXT_PUBLIC_SERVER_URL: 'http://localhost:3000', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' } const r2 = { @@ -13,15 +13,15 @@ const r2 = { R2_SECRET_ACCESS_KEY: 's', } -function check(env: Record, storage: NonNullable[0]>['storage'] = true) { +function check(env: Record, storage: NonNullable[0]>['storage'] = true) { vi.unstubAllEnvs() for (const [k, v] of Object.entries(env)) {vi.stubEnv(k, v)} - return () => assertEnv(ipalEnvRules({ storage }), { env }) + return () => assertEnv(iaplEnvRules({ storage }), { env }) } afterEach(() => vi.unstubAllEnvs()) -describe('ipalEnvRules({ storage })', () => { +describe('iaplEnvRules({ storage })', () => { test('production: every R2_* is required', () => { expect(check({ ...base, NODE_ENV: 'production' })).toThrow(/R2_BUCKET is required/) expect(check({ ...base, ...r2, NODE_ENV: 'production' })).not.toThrow() @@ -75,17 +75,17 @@ describe('database naming rule', () => { expect(checkDatabaseName({ databaseUri: 'postgres://db/payload' })).toBeNull() }) - test('ipalEnvRules({ databaseName }) only warns — assertEnv still passes', () => { + test('iaplEnvRules({ databaseName }) only warns — assertEnv still passes', () => { const warn = vi.fn() const env = { DATABASE_URI: 'mongodb://mongo/payload', NEXT_PUBLIC_SERVER_URL: 'https://intecion.com', PAYLOAD_SECRET: 's' } - expect(() => assertEnv(ipalEnvRules({ databaseName: { domain: 'intecion.com', warn } }), { env })).not.toThrow() + expect(() => assertEnv(iaplEnvRules({ databaseName: { domain: 'intecion.com', warn } }), { env })).not.toThrow() expect(warn).toHaveBeenCalledWith(expect.stringMatching(/DATABASE_URI: database "payload"[\s\S]*intecioncom_prod/)) warn.mockClear() - assertEnv(ipalEnvRules({ databaseName: { domain: 'www.intecion.com', warn } }), { env: { ...env, DATABASE_URI: 'mongodb://mongo/intecioncom_dev' } }) + assertEnv(iaplEnvRules({ databaseName: { domain: 'www.intecion.com', warn } }), { env: { ...env, DATABASE_URI: 'mongodb://mongo/intecioncom_dev' } }) expect(warn).not.toHaveBeenCalled() // true: the domain comes from NEXT_PUBLIC_SERVER_URL in process.env vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://architektimprez.pl') - assertEnv(ipalEnvRules({ databaseName: { warn } }), { env: { ...env, DATABASE_URI: 'postgres://db/architektimprez_prod' } }) + assertEnv(iaplEnvRules({ databaseName: { warn } }), { env: { ...env, DATABASE_URI: 'postgres://db/architektimprez_prod' } }) expect(warn).toHaveBeenCalledWith(expect.stringMatching(/expected "architektimprezpl_prod"/)) vi.unstubAllEnvs() }) @@ -97,20 +97,20 @@ describe('PAYLOAD_SECRET minimum length', () => { test('a short secret fails in production', () => { vi.stubEnv('NODE_ENV', 'production') - expect(() => assertEnv(ipalEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/) - expect(() => assertEnv(ipalEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow() + expect(() => assertEnv(iaplEnvRules(), { env })).toThrow(/PAYLOAD_SECRET must be at least 32 characters in production \(got 12\)/) + expect(() => assertEnv(iaplEnvRules(), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(32) } })).not.toThrow() }) test('a short secret passes outside production', () => { vi.stubEnv('NODE_ENV', 'development') - expect(() => assertEnv(ipalEnvRules(), { env })).not.toThrow() + expect(() => assertEnv(iaplEnvRules(), { env })).not.toThrow() }) test('secretMinLength: 0 turns the check off; a custom minimum is used', () => { vi.stubEnv('NODE_ENV', 'production') - expect(() => assertEnv(ipalEnvRules({ secretMinLength: 0 }), { env })).not.toThrow() - expect(() => assertEnv(ipalEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/) - expect(() => assertEnv(ipalEnvRules({ secretMinLength: 8 }), { env })).not.toThrow() - expect(() => assertEnv(ipalEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/) + expect(() => assertEnv(iaplEnvRules({ secretMinLength: 0 }), { env })).not.toThrow() + expect(() => assertEnv(iaplEnvRules({ secretMinLength: 64 }), { env: { ...env, PAYLOAD_SECRET: 'x'.repeat(40) } })).toThrow(/at least 64 characters/) + expect(() => assertEnv(iaplEnvRules({ secretMinLength: 8 }), { env })).not.toThrow() + expect(() => assertEnv(iaplEnvRules({ secretVar: 'MY_SECRET' }), { env: { ...env, MY_SECRET: 'short' } })).toThrow(/MY_SECRET must be at least 32/) }) }) diff --git a/test/externalSkills.test.ts b/test/externalSkills.test.ts index e787c63..12bba5c 100644 --- a/test/externalSkills.test.ts +++ b/test/externalSkills.test.ts @@ -1,6 +1,6 @@ /** * Third-party agent skills vendored into the package (docs/agent/external) and installed by - * `ipal-skills --external`. They are pinned, text-only and carry their licence; the installer + * `iapl-skills --external`. They are pinned, text-only and carry their licence; the installer * downloads nothing and leaves the project's own skill folders alone. */ import { execFileSync } from 'node:child_process' @@ -47,7 +47,7 @@ describe('vendored external skills', () => { }) test('the installer downloads nothing', () => { - const bin = read(path.join(root, 'bin/ipal-skills.mjs')) + const bin = read(path.join(root, 'bin/iapl-skills.mjs')) expect(bin).not.toMatch(/https?:\/\/|\bfetch\(|child_process|execFile|spawn/) }) @@ -80,12 +80,12 @@ describe('vendored external skills', () => { }) }) -describe('ipal-skills --external', () => { +describe('iapl-skills --external', () => { const work = mkdtempSync(path.join(tmpdir(), 'ipal-ext-test-')) afterAll(() => rmSync(work, { force: true, recursive: true })) const skillsDir = path.join(work, '.agents/skills') const run = (...args: string[]) => - execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', ...args], { cwd: work, encoding: 'utf8' }) + execFileSync('node', [path.join(root, 'bin/iapl-skills.mjs'), '--no-pointer', ...args], { cwd: work, encoding: 'utf8' }) const names = () => readdirSync(skillsDir).sort() test('adds ext-* only on request and leaves the project\'s own folders alone', () => { @@ -103,7 +103,7 @@ describe('ipal-skills --external', () => { expect(read(path.join(skillsDir, 'ext-mine/SKILL.md'))).toBe('own ext') }) - test('removes only retired ext-* folders that ipal-kit installed', () => { + test('removes only retired ext-* folders that IAPL installed', () => { const retired = path.join(skillsDir, 'ext-retired') mkdirSync(retired) cpSync(path.join(extDir, manifest.skills[0].name, 'SOURCE.md'), path.join(retired, 'SOURCE.md')) @@ -115,7 +115,7 @@ describe('ipal-skills --external', () => { test('an unknown name stops the run before anything is copied', () => { const empty = mkdtempSync(path.join(work, 'empty-')) expect(() => - execFileSync('node', [path.join(root, 'bin/ipal-skills.mjs'), '--no-pointer', '--external', 'ext-nope'], { cwd: empty, stdio: 'pipe' }), + execFileSync('node', [path.join(root, 'bin/iapl-skills.mjs'), '--no-pointer', '--external', 'ext-nope'], { cwd: empty, stdio: 'pipe' }), ).toThrow() expect(readdirSync(empty)).toEqual([]) }) diff --git a/test/fillEmptyLocales.test.ts b/test/fillEmptyLocales.test.ts index e547007..b0ab298 100644 --- a/test/fillEmptyLocales.test.ts +++ b/test/fillEmptyLocales.test.ts @@ -16,7 +16,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js' import { suggestionFor } from '../src/modules/consent/scanner/merge.js' import { addToCookieList } from '../src/modules/consent/scanner/sync.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -48,7 +48,7 @@ beforeAll(async () => { ], db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n, twoFactor: false })], secret: 'fill-locales-test-secret', telemetry: false, }), @@ -106,7 +106,7 @@ describe('fill empty locales — cookie review', () => { describe('options', () => { const build = (extra: Record) => - ipalKit({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config) + iapl({ i18n, twoFactor: false, ...extra } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }] } as unknown as Config) const global = (c: Config, slug: string) => c.globals!.find((g) => g.slug === slug)! const tabs = (g: GlobalConfig) => (g.fields.find((f) => f.type === 'tabs') as { tabs: Tab[] } & Field).tabs diff --git a/test/formAttachments.test.ts b/test/formAttachments.test.ts index 0915fe1..7ab472e 100644 --- a/test/formAttachments.test.ts +++ b/test/formAttachments.test.ts @@ -22,7 +22,7 @@ import type { FormFileScanInput } from '../src/modules/forms/attachments/config. import { getFormAttachments } from '../src/modules/forms/attachments/config.js' import { formSubmitState, handleFormSubmit } from '../src/modules/forms/attachments/submitHandler.js' import { submitForm } from '../src/modules/forms/submitForm.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -131,7 +131,7 @@ beforeAll(async () => { editor: lexicalEditor(), email: recordingMail, plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: { attachments: { @@ -499,7 +499,7 @@ describe('5 · nothing is stored, nothing can be downloaded', () => { collections: [{ slug: 'users', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }], db: sqliteAdapter({ client: { url: 'file::memory:' } }), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, twoFactor: false })], secret: 'x', }) const forms = plain.collections.find((c) => c.slug === 'forms')! @@ -725,7 +725,7 @@ describe('options a project can set', () => { }, }), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: { attachments: { diff --git a/test/graphqlSchema.test.ts b/test/graphqlSchema.test.ts index 6acac5e..b0da817 100644 --- a/test/graphqlSchema.test.ts +++ b/test/graphqlSchema.test.ts @@ -11,7 +11,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -78,7 +78,7 @@ const fullConfig = () => buildTestConfig({ ...project(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, consentLog: true, content: { collections: [{ slug: 'posts' }] }, diff --git a/test/helpers.ts b/test/helpers.ts index 8caf8a8..48b0844 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -14,7 +14,7 @@ export const buildTestConfig = (config: Config) => buildConfig({ ...config, typescript: { ...config.typescript, autoGenerate: false } }) /** - * The parts of @clocklimited/payload-2fa that ipalKit checks for after the injected factory ran + * The parts of @clocklimited/payload-2fa that iapl checks for after the injected factory ran * (missingTotpParts): the two fields and the `totp` strategy on the target collection. * A fake 2FA factory in a test wraps its config in this. */ diff --git a/test/indexNow.test.ts b/test/indexNow.test.ts index 9841e72..5a64746 100644 --- a/test/indexNow.test.ts +++ b/test/indexNow.test.ts @@ -75,8 +75,8 @@ describe('IndexNow hook', () => { expect(fetchSpy).not.toHaveBeenCalled() }) - test('staging copy (IPAL_NOINDEX) sends nothing even in production', async () => { - vi.stubEnv('IPAL_NOINDEX', '1') + test('staging copy (IAPL_NOINDEX) sends nothing even in production', async () => { + vi.stubEnv('IAPL_NOINDEX', '1') await run({ _status: 'published' }) expect(fetchSpy).not.toHaveBeenCalled() }) diff --git a/test/integration.test.ts b/test/integration.test.ts index a006e8d..f73eb60 100644 --- a/test/integration.test.ts +++ b/test/integration.test.ts @@ -17,7 +17,7 @@ import { getConsentTexts, getCookieTable } from '../src/modules/consent/getConse import { submitForm } from '../src/modules/forms/submitForm.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' import { createPageRoute } from '../src/modules/frontend/pageRoute.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -44,7 +44,7 @@ beforeAll(async () => { db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, consentLog: true, forms: {}, diff --git a/test/m1Turnstile.test.ts b/test/m1Turnstile.test.ts index b2daa7a..3607dab 100644 --- a/test/m1Turnstile.test.ts +++ b/test/m1Turnstile.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { passTurnstile, resolveTurnstileOnConfigError, TURNSTILE_ON_CONFIG_ERROR_DEFAULT } from '../src/modules/forms/submitForm.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' vi.mock('server-only', () => ({})) @@ -97,10 +97,10 @@ describe('forms.turnstileOnConfigError', () => { expect(fetchMock).not.toHaveBeenCalled() }) - test('ipalKit carries the option to where the gate reads it', async () => { + test('iapl carries the option to where the gate reads it', async () => { const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } const build = async (forms: Record) => - ((await ipalKit({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError + ((await iapl({ forms, i18n, twoFactor: false } as never)({ collections: [], secret: 'x' } as never)).custom as { ipal?: { forms?: { turnstileOnConfigError?: unknown } } }).ipal?.forms?.turnstileOnConfigError expect(await build({})).toBeUndefined() expect(await build({ turnstileOnConfigError: 'reject' })).toBe('reject') expect(await build({ turnstileOnConfigError: { files: 'allow' } })).toEqual({ files: 'allow' }) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 012c954..d62d1fa 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test, vi } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { @@ -21,9 +21,9 @@ const base = (): Config => secret: 'test', }) as unknown as Config -describe('ipalKit — config transform', () => { +describe('iapl — config transform', () => { test('adds globals, endpoint, localization and roles', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(base()) expect(config.globals?.map((g) => g.slug)).toEqual( expect.arrayContaining(['site-settings', 'site-integrations']), @@ -36,18 +36,18 @@ describe('ipalKit — config transform', () => { }) test('enforces 2FA unless explicitly disabled', async () => { - await expect(ipalKit({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/) - await expect(ipalKit({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow( + await expect(iapl({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/) + await expect(iapl({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow( /no 2FA plugin was injected/, ) const totp = vi.fn((o: { collection: string }) => (c: Config) => withTotpParts(c, o.collection)) - await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base()) + await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base()) expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } })) }) test('enabled: false keeps the schema (collections, globals) but adds no endpoints, onInit or admin components', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base()) + const config = await iapl({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base()) expect(config.globals?.map((g) => g.slug)).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications'])) expect(config.collections?.map((c) => c.slug)).toEqual(expect.arrayContaining(['users', 'consent-records', 'stats-visits'])) expect(config.endpoints ?? []).toEqual([]) @@ -56,18 +56,18 @@ describe('ipalKit — config transform', () => { }) test('forms.consentFieldName reaches submitForm through config.custom.ipal', async () => { - const config = await ipalKit({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base()) + const config = await iapl({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base()) expect((config.custom as { ipal?: { consentFieldName?: string } }).ipal?.consentFieldName).toBe('zgoda') }) test('invalid i18n fails fast', () => { - expect(() => ipalKit({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow() + expect(() => iapl({ i18n: { defaultLocale: 'de', locales: i18n.locales }, twoFactor: false })).toThrow() }) }) -describe('ipalKit — auth collection', () => { +describe('iapl — auth collection', () => { test('injects a users auth collection when the project has none, with roles', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x', } as unknown as Config) @@ -78,7 +78,7 @@ describe('ipalKit — auth collection', () => { test("keeps the project's own users collection", async () => { const own = { slug: 'users', auth: true, fields: [{ name: 'fullName', type: 'text' }] } - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [own], secret: 'x', } as unknown as Config) @@ -108,17 +108,17 @@ describe('options that keep features reachable and overridable', () => { }) as unknown as Config test('seo.uploadsCollection: the meta image relates to the given upload collection (default media)', async () => { - const custom = await ipalKit({ i18n, seo: { collections: ['pages'], uploadsCollection: 'images' }, twoFactor: false })(withPages()) + const custom = await iapl({ i18n, seo: { collections: ['pages'], uploadsCollection: 'images' }, twoFactor: false })(withPages()) const meta = findField(custom.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')! expect(findField(meta.fields as unknown[], 'image')?.relationTo).toBe('images') - const plain = await ipalKit({ i18n, seo: { collections: ['pages'] }, twoFactor: false })(withPages()) + const plain = await iapl({ i18n, seo: { collections: ['pages'] }, twoFactor: false })(withPages()) const metaDefault = findField(plain.collections!.find((c) => c.slug === 'pages')!.fields, 'meta')! expect(findField(metaDefault.fields as unknown[], 'image')?.relationTo).toBe('media') }) test('without `access` (no roles field) admin and editor features stay reachable for logged-in users', async () => { - const config = await ipalKit({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base()) + const config = await iapl({ consentLog: true, forms: {}, i18n, stats: true, twoFactor: false })(base()) const users = config.collections!.find((c) => c.slug === 'users')! // `admin.user` is what Payload's sanitize fills in: the panel's login collection = the staff collection. const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never @@ -135,7 +135,7 @@ describe('options that keep features reachable and overridable', () => { }) test('with `access` the roles still decide', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, stats: true, twoFactor: false })(base()) const users = config.collections!.find((c) => c.slug === 'users')! const req = (user: unknown) => ({ payload: { collections: { users: { config: users } }, config: { admin: { user: 'users' } } }, user }) as never const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: { req: unknown }) => unknown @@ -154,12 +154,12 @@ describe('gap fixes: searchSettings, collection overrides', () => { } test('searchSettings: false removes the Search engines tab without `seo`', async () => { - expect(tabsOf(await ipalKit({ i18n, twoFactor: false })(base()))).toContain('Search engines') - expect(tabsOf(await ipalKit({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search engines') + expect(tabsOf(await iapl({ i18n, twoFactor: false })(base()))).toContain('Search engines') + expect(tabsOf(await iapl({ i18n, searchSettings: false, twoFactor: false })(base()))).not.toContain('Search engines') }) test('searchSettings: a function shapes the fields; the top-level option wins over seo.searchSettings', async () => { - const config = await ipalKit({ + const config = await iapl({ i18n, searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name === 'llmsIntro'), seo: { collections: [], searchSettings: false }, @@ -171,12 +171,12 @@ describe('gap fixes: searchSettings, collection overrides', () => { )! expect(tab.fields.map((f) => f.name)).toEqual(['llmsIntro']) // the older seo.searchSettings still works alone - expect(tabsOf(await ipalKit({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search engines') + expect(tabsOf(await iapl({ i18n, seo: { collections: [], searchSettings: false }, twoFactor: false })(base()))).not.toContain('Search engines') }) test('consentLog / stats collectionOverrides: an object merges access, a function takes over', async () => { const dpoOnly = ({ req }: { req: { user?: { email?: string } } }) => req.user?.email === 'dpo@acme.pl' - const config = await ipalKit({ + const config = await iapl({ consentLog: { collectionOverrides: { access: { read: dpoOnly as never }, admin: { group: 'Privacy' } } }, i18n, stats: { collectionOverrides: (c) => ({ ...c, labels: { plural: 'Visits', singular: 'Visit' } }) }, diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index 12d8477..d67f9ad 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -34,8 +34,8 @@ describe('clientIp', () => { expect(clientIp(r, { header: 'x-client-ip' })).toBe('') }) - test('IPAL_IP_HEADER env pins the header', () => { - vi.stubEnv('IPAL_IP_HEADER', 'x-forwarded-for') + test('IAPL_IP_HEADER env pins the header', () => { + vi.stubEnv('IAPL_IP_HEADER', 'x-forwarded-for') expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-forwarded-for': '6.6.6.6, 4.4.4.4' }))).toBe('4.4.4.4') }) @@ -107,20 +107,20 @@ describe('consumeRateLimit', () => { }) }) -describe('IPAL_IP_HEADER', () => { +describe('IAPL_IP_HEADER', () => { afterEach(() => { vi.unstubAllEnvs() vi.restoreAllMocks() }) - test('ipalEnvRules({ ipHeader }) requires it in production only', async () => { + test('iaplEnvRules({ ipHeader }) requires it in production only', async () => { const { assertEnv } = await import('../src/modules/env/assertEnv.js') - const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js') + const { iaplEnvRules } = await import('../src/modules/env/iaplEnvRules.js') const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' } vi.stubEnv('NODE_ENV', 'production') - expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/) - expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow() + expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).toThrow(/IAPL_IP_HEADER/) + expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: { ...base, IAPL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow() vi.stubEnv('NODE_ENV', 'development') - expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).not.toThrow() + expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).not.toThrow() }) }) diff --git a/test/revalidateGlobals.test.ts b/test/revalidateGlobals.test.ts index 7f46200..76c7fc8 100644 --- a/test/revalidateGlobals.test.ts +++ b/test/revalidateGlobals.test.ts @@ -3,7 +3,7 @@ import type { Config, GlobalConfig } from 'payload' import { afterEach, describe, expect, test, vi } from 'vitest' import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const const run = (g: GlobalConfig | undefined, context: object = {}) => @@ -12,10 +12,10 @@ const run = (g: GlobalConfig | undefined, context: object = {}) => describe('globals revalidate the site layout on save', () => { afterEach(() => vi.unstubAllEnvs()) - test('ipalKit({ revalidatePath }) wires every plugin global', async () => { + test('iapl({ revalidatePath }) wires every plugin global', async () => { vi.stubEnv('NEXT_RUNTIME', 'nodejs') const revalidatePath = vi.fn() - const config = await ipalKit({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) + const config = await iapl({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) for (const slug of ['site-settings', 'site-integrations', 'cookie-settings', 'notifications']) { revalidatePath.mockClear() run(config.globals?.find((g) => g.slug === slug)) diff --git a/test/safeBack.test.ts b/test/safeBack.test.ts index f29bae2..694e0b3 100644 --- a/test/safeBack.test.ts +++ b/test/safeBack.test.ts @@ -14,7 +14,7 @@ import type { I18nConfig } from '../src/modules/i18n/types.js' import { findImportMapFile, missingImportMapEntries } from '../src/modules/security/totp/importMapCheck.js' import { changedViewKeys, safeAdminBack, wrapTotpViews } from '../src/modules/security/totp/safeBack.js' import { SafeTotpView } from '../src/modules/security/totp/SafeTotpView.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } @@ -146,9 +146,9 @@ describe('wrapTotpViews', () => { describe.each([ ['3.0.0-beta.7', payloadTotpBeta7], ['3.0.0-beta.1', payloadTotpBeta1 as unknown as typeof payloadTotpBeta7], -])('ipalKit with the real 2FA package %s', (_version, payloadTotp) => { +])('iapl with the real 2FA package %s', (_version, payloadTotp) => { const build = (twoFactor: false | Record, extra: Partial = {}, options: Record = {}) => - ipalKit({ + iapl({ access: { authCollection: 'users' }, i18n, twoFactor: twoFactor === false ? false : ({ issuer: 'Example', plugin: payloadTotp, ...twoFactor } as never), @@ -172,13 +172,13 @@ describe.each([ expect(component(config, 'SetupTOTPBackslash')?.path).toBe('@intecion/ipal-kit/admin#SafeTotpView') }) - test('the package registered by the project too, before ipalKit: still guarded', async () => { + test('the package registered by the project too, before iapl: still guarded', async () => { const first = payloadTotp({ collection: 'users', totp: { issuer: 'E' } } as never)({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'x' } as never) expect(raw(first).length).toBe(4) expect(raw(await build({}, first as never))).toEqual([]) }) - test('ipalKit run over its own output (a config reused): still guarded', async () => { + test('iapl run over its own output (a config reused): still guarded', async () => { const once = await build({}) const twice = await build({}, { admin: once.admin } as never) expect(raw(twice)).toEqual([]) @@ -187,7 +187,7 @@ describe.each([ test('the same incoming config object built twice', async () => { const incoming = { admin: { components: { views: {} } }, collections: [], secret: 'x' } as unknown as Config - const plugin = () => ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming) + const plugin = () => iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotp } as never })(incoming) expect(raw(await plugin())).toEqual([]) expect(raw(await plugin())).toEqual([]) }) @@ -221,7 +221,7 @@ describe.each([ 'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPSetup': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPSetup' }, 'ipal-totp-view:@clocklimited/payload-2fa/rsc#TOTPVerify': { type: 'component', path: '@clocklimited/payload-2fa/rsc#TOTPVerify' }, }) - // the tab title ipal-kit gives the screens is still there + // the tab title IAPL gives the screens is still there expect((config.admin?.components?.views as Record).VerifyTOTP.meta?.title).toBeTruthy() }) @@ -306,13 +306,13 @@ describe('SafeTotpView', () => { }) }) -// "Setup required" (requireSetup), the back-link check (safeBack) and ipal-kit's own check (guard) are separate +// "Setup required" (requireSetup), the back-link check (safeBack) and IAPL's own check (guard) are separate // switches: each combination builds, and each part is on exactly when its own switch says so. describe('requireSetup x safeBack x guard', () => { const combos = [undefined, false].flatMap((requireSetup) => [undefined, false].flatMap((safeBack) => [undefined, false].map((guard) => ({ guard, requireSetup, safeBack })))) test.each(combos)('requireSetup: $requireSetup, safeBack: $safeBack, guard: $guard', async (options) => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...options } as never })({ collections: [], secret: 'x' } as unknown as Config) const views = Object.values(config.admin?.components?.views ?? {}) as { Component: { path?: string } | string; path: string }[] const totpViews = views.filter((v) => /(?:setup|verify)-totp$/.test(v.path)) expect(totpViews).toHaveLength(4) @@ -320,13 +320,13 @@ describe('requireSetup x safeBack x guard', () => { const wrapped = totpViews.filter((v) => typeof v.Component === 'object' && v.Component.path === '@intecion/ipal-kit/admin#SafeTotpView').length expect(wrapped).toBe(options.safeBack === false ? 0 : 4) - // setup required needs ipal-kit's own check; with either off there is no status field, hook or notice + // setup required needs IAPL's own check; with either off there is no status field, hook or notice const setupOn = options.requireSetup !== false && options.guard !== false const users = config.collections?.find((c) => c.slug === 'users') // the data field whenever 2FA is on (the schema does not follow the switches); the panel's status field with the mode expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom'))).toBe(true) expect(Boolean(users?.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus'))).toBe(setupOn) - // the administrator's reset (a lost phone) comes with ipal-kit's own check, also when setup is not required + // the administrator's reset (a lost phone) comes with IAPL's own check, also when setup is not required expect(Boolean(config.endpoints?.some((e) => e.path === '/ipal/two-factor/reset'))).toBe(options.guard !== false) const provider = JSON.stringify(config.admin?.components?.providers ?? []) expect(provider.includes('"requireSetup":true')).toBe(setupOn) @@ -339,12 +339,12 @@ describe('requireSetup x safeBack x guard', () => { describe('requireSetup.setupNotice', () => { const providers = async (requireSetup?: Record) => - JSON.stringify((await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? []) + JSON.stringify((await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup } as never })({ collections: [], secret: 'x' } as unknown as Config)).admin?.components?.providers ?? []) test('on by default; false removes the notice, not the lock', async () => { expect(await providers()).toContain('"requireSetup":true') expect(await providers({ setupNotice: false })).not.toContain('"requireSetup":true') - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, requireSetup: { setupNotice: false } } as never })({ collections: [], secret: 'x' } as unknown as Config) expect((config.custom as { ipal: { twoFactor: { requireSetup: boolean } } }).ipal.twoFactor.requireSetup).toBe(true) }) }) @@ -357,7 +357,7 @@ describe('a 2FA factory that hands back the same view objects on every call', () const factory = (o: { collection: string }) => (c: Config) => withTotpParts({ ...c, admin: { ...c.admin, components: { ...c.admin?.components, views: { ...c.admin?.components?.views, ...views } } } } as Config, o.collection) const build = (incoming: Partial = {}) => - ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config) + iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: factory as never } })({ collections: [], secret: 'x', ...incoming } as unknown as Config) const paths = (config: Config) => Object.values(config.admin?.components?.views ?? {}).map((v) => (v as { Component: { path: string } }).Component.path) test('is guarded when registered once, twice, and over a config that already holds those objects', async () => { @@ -455,11 +455,11 @@ describe('the stale import-map check', () => { } }) - test('in production ipalKit marks the redirect provider when the map lacks the wrapper; not otherwise', async () => { + test('in production iapl marks the redirect provider when the map lacks the wrapper; not otherwise', async () => { const stale = await project('src/app/(payload)/admin', 'export const importMap = { "@intecion/ipal-kit/admin#TotpRedirectProvider": X }') const current = await project('src/app/(payload)/admin', `export const importMap = { "${ENTRY}": Y }`) const flagged = async (baseDir: string, twoFactor: Record = {}) => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({ + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, ...twoFactor } as never })({ admin: { importMap: { baseDir } }, collections: [], secret: 'x', @@ -502,10 +502,10 @@ describe('the stale import-map check', () => { } }) - test('only ipal-kit\'s own redirect provider gets the flag, not a project\'s provider', async () => { + test('only IAPL\'s own redirect provider gets the flag, not a project\'s provider', async () => { const stale = await project('src/app/(payload)/admin', 'export const importMap = {}') const providers = async (provider?: unknown) => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({ + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'E', plugin: payloadTotpBeta7, provider } as never })({ admin: { importMap: { baseDir: stale } }, collections: [], secret: 'x', diff --git a/test/secondFactorGuard.test.ts b/test/secondFactorGuard.test.ts index 7281b40..d30c0ff 100644 --- a/test/secondFactorGuard.test.ts +++ b/test/secondFactorGuard.test.ts @@ -1,6 +1,6 @@ /** * The rules behind test/securityHttp.test.ts, one by one: who is staff (userMeetsRole), when the second - * factor counts as passed, and what ipalKit does with a 2FA plugin it does not recognise. + * factor counts as passed, and what iapl does with a 2FA plugin it does not recognise. */ import type { Access, Config } from 'payload' @@ -23,7 +23,7 @@ import { } from '../src/modules/security/totp/secondFactor.js' import { buildTwoFactorResetEndpoint, resolveRequireSetup, strictExempt } from '../src/modules/security/totp/setupRequired.js' import { buildVerifyLimit, clearVerifyLimits, verifyLimitKey } from '../src/modules/security/totp/verifyLimit.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } @@ -47,7 +47,7 @@ const twoAuth = (): Config => describe('userMeetsRole: who is staff', () => { test('with roles: the role decides; an account of another auth collection never passes', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth()) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(twoAuth()) const payload = payloadOf(config) expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true) expect(userMeetsRole({ payload, user: { collection: 'users', roles: ['user'] } }, 'editor')).toBe(false) @@ -61,7 +61,7 @@ describe('userMeetsRole: who is staff', () => { }) test('without `access`: every account of the panel collection passes, other auth collections do not', async () => { - const config = await ipalKit({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) + const config = await iapl({ i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) const payload = payloadOf(config) expect(staffCollectionSlugs(payload)).toEqual(['users']) expect(userMeetsRole({ payload, user: { collection: 'users' } }, 'admin')).toBe(true) @@ -69,7 +69,7 @@ describe('userMeetsRole: who is staff', () => { }) test('access.staffCollections names more staff collections, on purpose', async () => { - const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth()) + const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: false })(twoAuth()) const payload = payloadOf(config) expect(staffCollectionSlugs(payload)).toEqual(['users', 'partners']) expect(userMeetsRole({ payload, user: { collection: 'partners' } }, 'admin')).toBe(true) // no roles field there: all equal @@ -77,8 +77,8 @@ describe('userMeetsRole: who is staff', () => { expect(userMeetsRole({ payload, user: { collection: 'customers' } }, 'admin')).toBe(false) }) - test('without a payload: the staff collections of the config ipalKit built last; only a held role counts', async () => { - await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) + test('without a payload: the staff collections of the config iapl built last; only a held role counts', async () => { + await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ ...twoAuth(), admin: { user: 'users' } } as Config) expect(userMeetsRole({ user: { collection: 'users' } }, 'user')).toBe(false) expect(userMeetsRole({ user: { collection: 'users', roles: ['admin'] } }, 'admin')).toBe(true) expect(userMeetsRole({ user: { collection: 'customers', roles: ['admin'] } }, 'admin')).toBe(false) @@ -190,12 +190,12 @@ describe('secondFactorPassed', () => { }) }) -describe('ipalKit and the 2FA plugin', () => { +describe('iapl and the 2FA plugin', () => { const passwordOnly = { id: 1, _strategy: 'local-jwt', collection: 'users', hasTotp: true, roles: ['admin'] } const verified = { ...passwordOnly, _strategy: 'totp' } test('every collection and global in the config is guarded, whenever it was added', async () => { - const config = await ipalKit({ + const config = await iapl({ access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, forms: {}, i18n, stats: true, twoFactor: { issuer: 'A', plugin: fakeTotp as never }, })({ collections: [{ slug: 'pages', fields: [] }], globals: [{ slug: 'own', fields: [] }], secret: 'x' } as unknown as Config) @@ -258,15 +258,15 @@ describe('ipalKit and the 2FA plugin', () => { test('a 2FA plugin without the parts the guard relies on stops the start', async () => { const unknown = () => (c: Config) => c const run = (guard?: false) => - ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config) + iapl({ i18n, twoFactor: { issuer: 'A', plugin: unknown as never, ...(guard === false ? { guard } : {}) } })({ collections: [], secret: 'x' } as unknown as Config) await expect(run()).rejects.toThrow(/did not add the `totpSecret` field, the `hasTotp` field, the `totp` auth strategy/) // twoFactor.guard: false = the package alone, as before const config = await run(false) expect((config.custom as { ipal?: { twoFactor?: unknown } } | undefined)?.ipal?.twoFactor).toBeUndefined() }) - test('per-entity opt-out: the package key and ipal-kit\'s key, operation by operation', async () => { - const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ + test('per-entity opt-out: the package key and IAPL\'s key, operation by operation', async () => { + const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ collections: [ { slug: 'a', custom: { totp: { disableAccessWrapper: { read: true } } }, fields: [] }, { slug: 'b', custom: { ipal: { secondFactor: false } }, fields: [] }, @@ -288,7 +288,7 @@ describe('ipalKit and the 2FA plugin', () => { const g = config.globals!.find((x) => x.slug === 'g')!.access expect(call(g, 'read')).toBe(true) expect(call(g, 'update')).toBe(false) - // ipal-kit's key reaches the package in its own key, so the package leaves the operation alone too + // IAPL's key reaches the package in its own key, so the package leaves the operation alone too expect((config.globals!.find((x) => x.slug === 'g')!.custom as { totp: unknown }).totp).toEqual({ disableAccessWrapper: { read: true } }) }) @@ -338,9 +338,9 @@ describe('ipalKit and the 2FA plugin', () => { return last } clearVerifyLimits() - expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429) + expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never } })(base()), 6)).toBe(429) clearVerifyLimits() - expect(await call(await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200) + expect(await call(await iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoint as never, verifyLimit: false } })(base()), 8)).toBe(200) }) // M1 (R3-2): the count is also kept in the database, so a restart or a second instance does not reset it. @@ -475,7 +475,7 @@ describe('ipalKit and the 2FA plugin', () => { ...withTotpParts(c, o.collection), endpoints: [...(c.endpoints ?? []), ...['/verify-totp', '/setup-totp', '/remove-totp'].map((path) => ({ handler, method: 'post' as const, path }))], }) - const build = (twoFactor: Record = {}) => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config) + const build = (twoFactor: Record = {}) => iapl({ i18n, twoFactor: { issuer: 'A', plugin: withEndpoints as never, ...twoFactor } as never })({ collections: [], endpoints: [], secret: 'x' } as unknown as Config) const call = async (config: Config, path: string, headers: Record, user: Record) => (await config.endpoints!.find((e) => e.path === path)!.handler({ headers: new Headers(headers), i18n: undefined, payload: { config, logger: { warn } }, url: 'https://site.example/api' + path, user: { id: 5, collection: 'users', ...user } } as never)).status const elsewhere = { host: 'site.example', origin: 'https://blog.site.example' } @@ -507,7 +507,7 @@ describe('ipalKit and the 2FA plugin', () => { }) test('staff collections outside the 2FA collection are named in a warning at start', async () => { - const config = await ipalKit({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ + const config = await iapl({ access: { authCollection: 'users', staffCollections: ['partners'] }, i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })({ ...twoAuth(), admin: { user: 'users' }, } as Config) @@ -528,7 +528,7 @@ describe('ipalKit and the 2FA plugin', () => { test('setup required: on by default, with the field, the hook, the reset endpoint and the notices; every part can be changed', async () => { const base = () => ({ collections: [], secret: 'x' }) as unknown as Config - const on = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base()) + const on = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never } })(base()) const guard = (c: Config) => (c.custom as { ipal: { twoFactor: Record } }).ipal.twoFactor expect(guard(on)).toMatchObject({ collection: 'users', requireSetup: true, setupWindowMs: 72 * 3_600_000 }) const users = on.collections!.find((c) => c.slug === 'users')! @@ -537,10 +537,10 @@ describe('ipalKit and the 2FA plugin', () => { expect(on.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) expect(JSON.stringify(on.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert') - const custom = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base()) + const custom = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: 24 } } })(base()) expect(guard(custom).setupWindowMs).toBe(24 * 3_600_000) - const off = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base()) + const off = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: false } })(base()) expect(guard(off)).toMatchObject({ requireSetup: false }) // the data field stays whenever 2FA is on: the schema must not depend on the switch (SQL would drop the column) const offUsers = off.collections!.find((c) => c.slug === 'users')! @@ -548,7 +548,7 @@ describe('ipalKit and the 2FA plugin', () => { expect(offUsers.fields.some((f) => 'name' in f && f.name === 'totpSetupStatus')).toBe(false) expect(offUsers.hooks?.beforeChange?.length ?? 0).toBe(0) // no stamping while the mode is off expect(JSON.stringify(off.admin?.components?.beforeDashboard ?? [])).not.toContain('TwoFactorAlert') - const guardOff = await ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base()) + const guardOff = await iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never } })(base()) expect(guardOff.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(true) // each part of the mode has its own switch @@ -559,28 +559,28 @@ describe('ipalKit and the 2FA plugin', () => { }) // fakeTotp registers no provider, so the setup notice is checked with the real package in test/safeBack.test.ts expect(has(on)).toMatchObject({ dashboard: true, status: true }) - const noDash = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base()) + const noDash = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { dashboardNotice: false } } })(base()) expect(has(noDash)).toMatchObject({ dashboard: false, status: true }) - const noStatus = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base()) + const noStatus = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { statusField: false } } })(base()) expect(has(noStatus)).toMatchObject({ dashboard: true, status: false }) expect(guard(noStatus)).toMatchObject({ requireSetup: true }) // the lock itself is unchanged expect(off.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(true) // an admin can still reset a lost phone // 2FA off: nothing of this exists - const none = await ipalKit({ i18n, twoFactor: false })(base()) + const none = await iapl({ i18n, twoFactor: false })(base()) expect(none.endpoints!.some((e) => e.path === '/ipal/two-factor/reset')).toBe(false) expect(none.collections!.find((c) => c.slug === 'users')!.fields.some((f) => 'name' in f && f.name === 'totpSetupFrom')).toBe(false) }) test.each([['24'], [-1], [Number.NaN], [Number.POSITIVE_INFINITY], [true], [null]])('requireSetup.windowHours %s stops the start (a typo must not mean "no limit")', async (windowHours) => { - await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/) - // also when ipal-kit's own check is off: a wrong value is never silently accepted - await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/) + await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours must be a number/) + // also when IAPL's own check is off: a wrong value is never silently accepted + await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { guard: false, issuer: 'A', plugin: fakeTotp as never, requireSetup: { windowHours: windowHours as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/windowHours/) expect(() => resolveRequireSetup({ windowHours: windowHours as never })).toThrow(/windowHours/) }) test('requireSetup: null is the default, like leaving it out', async () => { - const config = await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config) + const config = await iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: null as never } })({ collections: [], secret: 'x' } as unknown as Config) expect((config.custom as { ipal: { twoFactor: Record } }).ipal.twoFactor).toMatchObject({ requireSetup: true, setupWindowMs: 72 * 3_600_000 }) expect(JSON.stringify(config.admin?.components?.beforeDashboard)).toContain('TwoFactorAlert') expect(resolveRequireSetup(null as never)).toEqual({ requireSetup: true, setupWindowMs: 72 * 3_600_000 }) @@ -599,7 +599,7 @@ describe('ipalKit and the 2FA plugin', () => { test('an async function stops the start', async () => { expect(() => resolveRequireSetup({ exempt: (async () => false) as never })).toThrow(/must not be async/) - await expect(Promise.resolve().then(() => ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/) + await expect(Promise.resolve().then(() => iapl({ i18n, twoFactor: { issuer: 'A', plugin: fakeTotp as never, requireSetup: { exempt: (async () => true) as never } } })({ collections: [], secret: 'x' } as unknown as Config))).rejects.toThrow(/must not be async/) expect(() => resolveRequireSetup({ exempt: 'yes' as never })).toThrow(/must be a function/) }) @@ -740,7 +740,7 @@ describe('ipalKit and the 2FA plugin', () => { }) test('twoFactor: false — no guard, a password is enough (as documented)', async () => { - const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config) const payload = payloadOf(config) const read = config.globals!.find((g) => g.slug === 'site-integrations')!.access!.read as (a: unknown) => unknown expect(read({ req: { payload, user: { collection: 'users', roles: ['admin'] } } })).toBe(true) diff --git a/test/securityHttp.test.ts b/test/securityHttp.test.ts index dd52613..a72530c 100644 --- a/test/securityHttp.test.ts +++ b/test/securityHttp.test.ts @@ -13,7 +13,7 @@ import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { numericIds, testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' @@ -25,7 +25,7 @@ vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHe const TOTP_SECRET = 'JBSWY3DPEHPK3PXP' const PASSWORD = 'a-long-test-password-1' -/** A plugin the project lists AFTER ipalKit: its collection did not exist when ipalKit ran. */ +/** A plugin the project lists AFTER iapl: its collection did not exist when iapl ran. */ const latePlugin: Plugin = (config: Config) => ({ ...config, collections: [ @@ -47,7 +47,7 @@ const projectCollections: CollectionConfig[] = [ auth: true, fields: [{ name: 'roles', type: 'select', hasMany: true, options: ['user', 'editor', 'admin'], saveToJWT: true }], }, - // The 2FA package's own per-entity opt-out, and ipal-kit's. + // The 2FA package's own per-entity opt-out, and IAPL's. { slug: 'open-notes', access: { read: ({ req }) => Boolean(req.user), update: ({ req }) => Boolean(req.user) }, @@ -100,7 +100,7 @@ const makeConfig = () => db: testDatabase('sechttp'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, consentLog: true, cookieScanner: { crawl: true }, @@ -378,7 +378,7 @@ describe('per-entity opt-out from the second factor', () => { expect((await api('/open-notes', sessions.anonymous)).status).toBe(403) // its own rule still applies }) - test("ipal-kit's key: custom.ipal.secondFactor", async () => { + test("IAPL's key: custom.ipal.secondFactor", async () => { expect((await api('/open-tasks', sessions.passwordOnly)).status).toBe(200) expect((await api('/open-tasks', sessions.passwordOnly, { body: '{}', method: 'POST' })).status).toBe(403) }) diff --git a/test/securityHttpBeta1.test.ts b/test/securityHttpBeta1.test.ts index 44e4076..4b42e4b 100644 --- a/test/securityHttpBeta1.test.ts +++ b/test/securityHttpBeta1.test.ts @@ -12,7 +12,7 @@ import { getPayload } from 'payload' import { payloadTotp } from 'payload-2fa-beta1' import { afterAll, beforeAll, expect, test, vi } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' @@ -40,7 +40,7 @@ beforeAll(async () => { db: testDatabase('sechttp_b1'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, diff --git a/test/securityHttpFirstAdmin.test.ts b/test/securityHttpFirstAdmin.test.ts index 71a4828..2266e03 100644 --- a/test/securityHttpFirstAdmin.test.ts +++ b/test/securityHttpFirstAdmin.test.ts @@ -12,7 +12,7 @@ import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, expect, test, vi } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js' @@ -31,7 +31,7 @@ beforeAll(async () => { db: testDatabase('sechttp_first'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, diff --git a/test/securityHttpTokens.test.ts b/test/securityHttpTokens.test.ts index cd00bfa..b525165 100644 --- a/test/securityHttpTokens.test.ts +++ b/test/securityHttpTokens.test.ts @@ -11,7 +11,7 @@ import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, expect, test, vi } from 'vitest' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' @@ -25,7 +25,7 @@ let server: TestServer let payload: Payload beforeAll(async () => { - process.env.IPAL_DOCTOR_TOKEN = DOCTOR_TOKEN + process.env.IAPL_DOCTOR_TOKEN = DOCTOR_TOKEN const config = buildTestConfig({ collections: [ // The project's own staff collection, with API keys. @@ -35,7 +35,7 @@ beforeAll(async () => { db: testDatabase('sechttp_tok'), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, @@ -54,7 +54,7 @@ beforeAll(async () => { }, 120_000) afterAll(async () => { - delete process.env.IPAL_DOCTOR_TOKEN + delete process.env.IAPL_DOCTOR_TOKEN await server?.close() await payload?.destroy?.() }) diff --git a/test/seed.test.ts b/test/seed.test.ts index b1ac821..0f303ea 100644 --- a/test/seed.test.ts +++ b/test/seed.test.ts @@ -8,7 +8,7 @@ import { getPayload } from 'payload' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' import { createSeeder, editedSinceSeed, isLocalDatabase, seedHash } from '../src/exports/seed.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -126,7 +126,7 @@ describe('createSeeder', () => { }, ], localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] }, - plugins: [ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })], + plugins: [iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }, indexNow: true, pages: { slug: 'pages' }, twoFactor: false })], secret: 'seed-test-secret', telemetry: false, }) @@ -271,12 +271,12 @@ describe('createSeeder', () => { expect(((await payload.findGlobal({ slug: 'look' as never })) as { mode: string }).mode).toBe('dark') }) - test('production guard: update refused on production or a non-local database unless IPAL_SEED_ALLOW_PROD_UPDATE=1', () => { + test('production guard: update refused on production or a non-local database unless IAPL_SEED_ALLOW_PROD_UPDATE=1', () => { vi.stubEnv('NODE_ENV', 'production') const only = ['pages:kontakt'] expect(() => seeder({ only, update: true })).toThrow(/update refused: NODE_ENV=production[\s\S]*Back up the database/) expect(() => seeder({ only })).not.toThrow() // create-only of listed records is always allowed - vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1') expect(seeder({ only, update: true }).update).toBe(true) expect(lines.join('\n')).toMatch(/Did you back it up/) @@ -285,7 +285,7 @@ describe('createSeeder', () => { expect(() => seeder({ only, update: true })).toThrow(/update refused: the database is not local/) expect(() => seeder({ guard: { localHosts: ['db'] }, update: true })).not.toThrow() expect(() => seeder({ guard: false, update: true })).not.toThrow() - vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1') expect(() => seeder({ force: true, only, update: true })).toThrow(/force refused/) }) @@ -300,7 +300,7 @@ describe('createSeeder', () => { vi.stubEnv('DATABASE_URI', 'postgres://u:p@db:5432/app') expect(() => seeder()).toThrow(/full seed refused: the database is not local/) expect(() => seeder({ guard: { allowFull: true } })).not.toThrow() - vi.stubEnv('IPAL_SEED_ALLOW_FULL', '1') + vi.stubEnv('IAPL_SEED_ALLOW_FULL', '1') expect(() => seeder()).not.toThrow() expect(() => seeder({ guard: false })).not.toThrow() }) @@ -335,7 +335,7 @@ describe('createSeeder', () => { test('seed writes skip IndexNow; a normal save still pings', async () => { const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 202 })) vi.stubEnv('NODE_ENV', 'production') - vi.stubEnv('IPAL_SEED_ALLOW_PROD_UPDATE', '1') + vi.stubEnv('IAPL_SEED_ALLOW_PROD_UPDATE', '1') vi.stubEnv('NEXT_PUBLIC_SERVER_URL', 'https://acme.pl') vi.stubEnv('INDEXNOW_KEY', 'k123') diff --git a/test/seedLocalizedArrays.test.ts b/test/seedLocalizedArrays.test.ts index 1a660e0..9506535 100644 --- a/test/seedLocalizedArrays.test.ts +++ b/test/seedLocalizedArrays.test.ts @@ -9,7 +9,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { createSeeder } from '../src/exports/seed.js' import { localize } from '../src/modules/seed/values.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -89,7 +89,7 @@ describe('createSeeder: whole localized arrays keep every language', () => { ], localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] }, plugins: [ - ipalKit({ + iapl({ forms: {}, i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) }, pages: { slug: 'pages' }, diff --git a/test/seedRequiredRefs.test.ts b/test/seedRequiredRefs.test.ts index a07c559..1c28300 100644 --- a/test/seedRequiredRefs.test.ts +++ b/test/seedRequiredRefs.test.ts @@ -11,7 +11,7 @@ import type { SeedResult } from '../src/exports/seed.js' import { createSeeder } from '../src/exports/seed.js' import { buildLinksField, buildSectionHeaderField } from '../src/index.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -64,7 +64,7 @@ describe('createSeeder: required fields with references', () => { editor: lexicalEditor(), localization: { defaultLocale: 'pl', fallback: true, locales: [...LOCALES] }, plugins: [ - ipalKit({ + iapl({ forms: {}, i18n: { defaultLocale: 'pl', locales: LOCALES.map((code) => ({ code, label: code.toUpperCase() })) }, pages: { slug: 'pages' }, diff --git a/test/seo.test.ts b/test/seo.test.ts index 99e9d12..b6b30d5 100644 --- a/test/seo.test.ts +++ b/test/seo.test.ts @@ -241,10 +241,10 @@ describe('buildUploadSecurityHeaders', () => { }) }) -describe('site-wide noindex (IPAL_NOINDEX) and Markdown headers', () => { +describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => { test('staging blocks crawling everywhere', async () => { const { vi } = await import('vitest') - vi.stubEnv('IPAL_NOINDEX', '1') + vi.stubEnv('IAPL_NOINDEX', '1') try { expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } }) expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow') diff --git a/test/seoIntegration.test.ts b/test/seoIntegration.test.ts index d2618ca..0943b83 100644 --- a/test/seoIntegration.test.ts +++ b/test/seoIntegration.test.ts @@ -8,7 +8,7 @@ import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' vi.mock('server-only', () => ({})) @@ -42,7 +42,7 @@ describe('SEO outputs against a real database', () => { ], db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })], secret: 'seo-integration-test-secret', telemetry: false, }) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts index 7501844..9f282c4 100644 --- a/test/seoSearch.test.ts +++ b/test/seoSearch.test.ts @@ -14,7 +14,7 @@ import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js' import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js' import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js' import { collectSiteIndex } from '../src/modules/seo/siteIndex.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const config: I18nConfig = { defaultLocale: 'pl', @@ -122,8 +122,8 @@ describe('AI crawlers (robots)', () => { expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] }) }) - test('IPAL_NOINDEX still wins over every exception', () => { - vi.stubEnv('IPAL_NOINDEX', '1') + test('IAPL_NOINDEX still wins over every exception', () => { + vi.stubEnv('IAPL_NOINDEX', '1') const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' }) expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' }) }) @@ -333,16 +333,16 @@ describe('plugin: Search engines tab', () => { } test('on by default, off with seo.searchSettings: false', async () => { - const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base()) + const on = await iapl({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base()) expect(tabs(on)).toContain('Search engines') - const off = await ipalKit({ + const off = await iapl({ access: { authCollection: 'users' }, i18n: config, seo: { collections: [], searchSettings: false }, twoFactor: false, })(base()) expect(tabs(off)).not.toContain('Search engines') - const custom = await ipalKit({ + const custom = await iapl({ access: { authCollection: 'users' }, i18n: config, seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') }, diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts index a314c04..b221905 100644 --- a/test/settingsDepth.test.ts +++ b/test/settingsDepth.test.ts @@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest' import { resolveRoute } from '../src/modules/content/resolveRoute.js' import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' let payload: Payload @@ -34,7 +34,7 @@ beforeAll(async () => { db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }), editor: lexicalEditor(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, diff --git a/test/setupColumnMissing.test.ts b/test/setupColumnMissing.test.ts index 77c2ad5..0b4e775 100644 --- a/test/setupColumnMissing.test.ts +++ b/test/setupColumnMissing.test.ts @@ -14,7 +14,7 @@ import { getPayload } from 'payload' import { afterAll, beforeAll, expect, test, vi } from 'vitest' import { backfillSetupFrom } from '../src/modules/security/totp/setupRequired.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' @@ -31,7 +31,7 @@ beforeAll(async () => { collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], db: testDatabase('setupcol'), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })], + plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })], secret: 'integration-test-secret-0123456789', telemetry: false, }) diff --git a/test/starter.test.ts b/test/starter.test.ts index a2c1f69..61c0fd2 100644 --- a/test/starter.test.ts +++ b/test/starter.test.ts @@ -123,13 +123,13 @@ describe('starter: answers', () => { expect(validateAnswers(a)).toHaveLength(3) }) - it('refuses single-language and English-default sites with a pointer to ipal-setup', () => { + it('refuses single-language and English-default sites with a pointer to iapl-setup', () => { const single = validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] })) expect(single).toHaveLength(1) - expect(single[0]).toMatch(/single-language site is not supported by `ipal-kit create` yet .*ipal-setup/) + expect(single[0]).toMatch(/single-language site is not supported by `iapl create` yet .*iapl-setup/) const english = validateAnswers(answers((x) => { x.languages.default = 'en' })) expect(english).toHaveLength(1) - expect(english[0]).toMatch(/default language other than "pl" \(here "en"\).*ipal-setup/) + expect(english[0]).toMatch(/default language other than "pl" \(here "en"\).*iapl-setup/) expect(validateAnswers(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }, { code: 'de', label: 'Deutsch' }] }))[0]).toMatch(/without "en"/) expect(validateAnswers(answers((x) => { x.languages.locales.push({ code: 'de', label: 'Deutsch' }) }))).toEqual([]) }) @@ -141,7 +141,7 @@ describe('starter: answers', () => { writeFileSync(file, JSON.stringify(answers((x) => { x.languages.locales = [{ code: 'pl', label: 'Polski' }] }))) try { expect(await runCreateCli(['acme-test.pl', '--answers', file, '--dir', dir, '--no-install', '--no-git'], (line) => lines.push(line))).toBe(1) - expect(lines.join('\n')).toMatch(/nothing was written[\s\S]*single-language site[\s\S]*ipal-setup/) + expect(lines.join('\n')).toMatch(/nothing was written[\s\S]*single-language site[\s\S]*iapl-setup/) expect(existsSync(dir)).toBe(false) } finally { rmSync(file, { force: true }) @@ -175,7 +175,7 @@ describe('starter: generated files', () => { 'snapshots:', '', " '@intecion/ipal-kit@file:..(abc)':", ' dependencies:', ' next: 16.4.3', '', ' next@16.4.3: {}', '', ].join('\n') const out = lockfileWithoutPlugin(lock) - expect(out).not.toContain('ipal-kit') + expect(out).not.toContain('IAPL') expect(out).not.toContain('dependenciesMeta') expect(out).toContain(" next@16.4.3:\n resolution: {integrity: x}") expect(out).toContain(' next@16.4.3: {}') @@ -231,8 +231,8 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start expect(files['src/seed/base.ts']).toContain("email: 'biuro@acme-test.pl'") expect(files['pnpm-lock.yaml']).not.toContain('@intecion/ipal-kit') const traced = renderSite(bundle, answers(), { ...ctx, source: { bundleSha256: 'abc', commit: 'def' } }) - expect(JSON.parse(traced['.ipal/starter.json'] ?? '')).toMatchObject({ ipalKit: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } }) - const doctor = JSON.parse(files['ipal-doctor.json'] ?? '') as { rules: Record } + expect(JSON.parse(traced['.iapl/starter.json'] ?? '')).toMatchObject({ iapl: '1.15.0', source: { bundleSha256: 'abc', commit: 'def' } }) + const doctor = JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: Record } expect(Object.keys(doctor.rules).sort()).toEqual(['audit:collections-present', 'csp', 'i18n-literals']) expect((JSON.parse(files['package.json'] ?? '') as { packageManager?: string }).packageManager).toMatch(/^pnpm@\d/) }) @@ -252,8 +252,8 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start expect(files['src/blocks/configs.ts']).not.toContain('entryList') expect(files['src/instrumentation.ts']).toContain('storage: false,') expect(files['src/lib/content.ts']).not.toMatch(/buildLocalBusinessJsonLd|getPayload/) - expect(files['AGENTS.md']).toContain('ipal-audit-skip: twofactor, r2') - expect(Object.keys((JSON.parse(files['ipal-doctor.json'] ?? '') as { rules: object }).rules).sort()).toEqual(['2fa', 'csp', 'i18n-literals']) + expect(files['AGENTS.md']).toContain('iapl-audit-skip: twofactor, r2') + expect(Object.keys((JSON.parse(files['iapl-doctor.json'] ?? '') as { rules: object }).rules).sort()).toEqual(['2fa', 'csp', 'i18n-literals']) expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl') }) }) diff --git a/test/stats.test.ts b/test/stats.test.ts index bb7b74e..f7d57b2 100644 --- a/test/stats.test.ts +++ b/test/stats.test.ts @@ -9,7 +9,7 @@ import { serializeConsent } from '../src/modules/consent/storage.js' import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js' import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath } from '../src/modules/stats/parse.js' import { lastDays, summarize } from '../src/modules/stats/summarize.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36' const VID = 'a'.repeat(32) @@ -178,13 +178,13 @@ describe('stats — plugin wiring', () => { const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } test('off by default', async () => { - const config = await ipalKit({ i18n, twoFactor: false })(base()) + const config = await iapl({ i18n, twoFactor: false })(base()) expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(false) expect(config.endpoints?.some((e) => e.path === '/ipal/hit')).toBe(false) }) test('stats: true adds the collection, endpoint, view, nav link and dashboard card', async () => { - const config = await ipalKit({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base()) + const config = await iapl({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base()) expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(true) expect(config.endpoints?.some((e) => e.path === '/ipal/hit' && e.method === 'post')).toBe(true) const components = config.admin?.components @@ -194,7 +194,7 @@ describe('stats — plugin wiring', () => { }) test('dashboard: false leaves the dashboard alone', async () => { - const config = await ipalKit({ i18n, stats: { dashboard: false }, twoFactor: false })(base()) + const config = await iapl({ i18n, stats: { dashboard: false }, twoFactor: false })(base()) expect(JSON.stringify(config.admin?.components?.beforeDashboard)).not.toContain('StatsWidget') }) }) diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index d8e0c1f..56d4f1b 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -135,7 +135,7 @@ describe('submitForm — other gates', () => { }) }) - test('ipalKit forms.consentFieldName (payload.config.custom) names the consent field', async () => { + test('iapl forms.consentFieldName (payload.config.custom) names the consent field', async () => { const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'zgoda', blockType: 'checkbox' }] } } }) Object.assign(payload, { config: { custom: { ipal: { consentFieldName: 'zgoda' } } } }) expect(await submitForm({ data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).toEqual({ diff --git a/test/themeStorage.test.ts b/test/themeStorage.test.ts index 77ac677..28da64a 100644 --- a/test/themeStorage.test.ts +++ b/test/themeStorage.test.ts @@ -19,7 +19,7 @@ import { themeConfigFrom, themeScript, } from '../src/modules/theme/theme.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' function fakeStorage(initial: Record = {}) { const data = new Map(Object.entries(initial)) @@ -82,7 +82,7 @@ describe('theme storage key', () => { }) test('the plugin option reaches getSiteShell through config.custom; themeConfigFrom carries it', async () => { - const config = await ipalKit({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, theme: { storageKey: 'acme-theme' }, twoFactor: false })({ + const config = await iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, theme: { storageKey: 'acme-theme' }, twoFactor: false })({ collections: [{ slug: 'users', auth: true, fields: [] }], } as unknown as Config) expect((config.custom as { ipal: { themeStorageKey: string } }).ipal.themeStorageKey).toBe('acme-theme') diff --git a/test/totpRedirect.test.ts b/test/totpRedirect.test.ts index 1ae0dbd..5549f62 100644 --- a/test/totpRedirect.test.ts +++ b/test/totpRedirect.test.ts @@ -3,7 +3,7 @@ import type { Config } from 'payload' import { payloadTotp } from '@clocklimited/payload-2fa' import { describe, expect, it } from 'vitest' -import { ipalKit } from '../src/index.js' +import { iapl } from '../src/index.js' import { totpRedirectTarget } from '../src/modules/security/totp/totpRedirect.js' const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } @@ -64,9 +64,9 @@ describe('2FA setup redirect (fresh admin, forceSetup)', () => { describe('twoFactor.provider', () => { const run = (provider?: unknown) => - ipalKit({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base()) + iapl({ i18n, twoFactor: { issuer: 'Test', plugin: payloadTotp, ...(provider === undefined ? {} : { provider }) } } as never)(base()) - it("replaces the package's header-based provider with ipal-kit's by default", async () => { + it("replaces the package's header-based provider with IAPL's by default", async () => { const config = await run() expect(providerPaths(config)).toContain('@intecion/ipal-kit/admin#TotpRedirectProvider') expect(providerPaths(config)).not.toContain('@clocklimited/payload-2fa/rsc#TOTPProvider') diff --git a/test/totpTextsAndCookieButton.test.ts b/test/totpTextsAndCookieButton.test.ts index 1c82ba8..6d80840 100644 --- a/test/totpTextsAndCookieButton.test.ts +++ b/test/totpTextsAndCookieButton.test.ts @@ -4,7 +4,7 @@ import { describe, expect, test } from 'vitest' import { bottomOverlap } from '../src/modules/consent/CookieButton.js' import { TOTP_TEXTS } from '../src/modules/security/totp/totpTexts.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { withTotpParts } from './helpers.js' const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } @@ -39,8 +39,8 @@ const base = (translations?: Record): Config => type Translations = Record; verify: { title: string } } }> describe('2FA texts', () => { - test('ipal-kit texts go over the package, the project over both; screens get a tab title', async () => { - const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp } } as never)( + test('IAPL texts go over the package, the project over both; screens get a tab title', async () => { + const config = await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp } } as never)( base({ en: { totpPlugin: { verify: { title: 'Project check' } } } }), ) const t = config.i18n!.translations as Translations @@ -53,7 +53,7 @@ describe('2FA texts', () => { }) test("texts: false keeps the package's", async () => { - const config = await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp, texts: false } } as never)(base()) + const config = await iapl({ i18n, twoFactor: { issuer: 'Acme', plugin: fakeTotp, texts: false } } as never)(base()) expect((config.i18n!.translations as Translations).pl.totpPlugin.verify.title).toBe('Weryfikacja') }) diff --git a/test/twoFactor.test.ts b/test/twoFactor.test.ts index 45a91ff..f2fc114 100644 --- a/test/twoFactor.test.ts +++ b/test/twoFactor.test.ts @@ -7,7 +7,7 @@ import { describe, expect, test } from 'vitest' import type { I18nConfig } from '../src/modules/i18n/types.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } @@ -21,8 +21,8 @@ describe('@clocklimited/payload-2fa with the real plugin', () => { expect(payloadSeenFrom(twoFactorEntry)).toBe(payloadSeenFrom(import.meta.url)) }) - test('ipalKit wraps the auth collection with TOTP: secret field, strategy and setup view', async () => { - const config = await ipalKit({ + test('iapl wraps the auth collection with TOTP: secret field, strategy and setup view', async () => { + const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'Example', plugin: payloadTotp }, diff --git a/test/writeOnlySecrets.test.ts b/test/writeOnlySecrets.test.ts index 752a67b..854eef9 100644 --- a/test/writeOnlySecrets.test.ts +++ b/test/writeOnlySecrets.test.ts @@ -14,7 +14,7 @@ import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js' import { keepSecretBeforeValidate, maskSecretAfterRead, SECRET_CLEAR, SECRET_MASK, writeOnlySecret, writeOnlySecrets } from '../src/modules/secrets/writeOnly.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' @@ -39,7 +39,7 @@ beforeAll(async () => { collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }], db: testDatabase('secrets'), editor: lexicalEditor(), - plugins: [ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], + plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: false })], secret: 'integration-test-secret-0123456789', telemetry: false, }) @@ -193,7 +193,7 @@ describe('the building blocks', () => { const hooked = (fields: unknown) => JSON.stringify(fields, (_k, v) => (typeof v === 'function' ? v.name : v)).includes('maskSecretAfterRead') expect(hooked(buildSiteIntegrations().fields)).toBe(true) expect(hooked(buildSiteIntegrations({ writeOnlySecrets: false }).fields)).toBe(false) - const off = await ipalKit({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never) + const off = await iapl({ i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, secrets: { writeOnly: false }, twoFactor: false })({ collections: [], secret: 'x' } as never) expect(hooked(off.globals!.find((g) => g.slug === 'site-integrations')!.fields)).toBe(false) }) }) diff --git a/test/writeOnlySecretsBound.test.ts b/test/writeOnlySecretsBound.test.ts index d583a96..af3bcae 100644 --- a/test/writeOnlySecretsBound.test.ts +++ b/test/writeOnlySecretsBound.test.ts @@ -16,7 +16,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vit import { buildSiteIntegrations } from '../src/globals/SiteIntegrations/index.js' import { mailAdapter } from '../src/modules/email/mailAdapter.js' import { buildKeepSecret, keepSecretBeforeValidate, maskSecretsOnRestore, maskWriteOnlySecrets, SECRET_CLEAR, SECRET_MASK, writeOnlySecret } from '../src/modules/secrets/writeOnly.js' -import { ipalKit } from '../src/plugin.js' +import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' @@ -76,7 +76,7 @@ beforeAll(async () => { editor: lexicalEditor(), email: mailAdapter(), plugins: [ - ipalKit({ + iapl({ access: { authCollection: 'users' }, forms: {}, // a project that turns versions on for the global