From 53901933f644a4b0788ea59cd270fda5a57e7c38 Mon Sep 17 00:00:00 2001 From: snapetech <71525329+snapetech@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:32:59 +0000 Subject: [PATCH 01/55] test: harden theme package boundary and document readiness --- docs/interface-themes/authoring.md | 3 +- .../interface-themes/implementation-status.md | 120 ++++++------------ server/routes/interfaceThemes.test.ts | 21 +-- server/utils/interfaceThemePackage.test.ts | 18 ++- 4 files changed, 69 insertions(+), 93 deletions(-) diff --git a/docs/interface-themes/authoring.md b/docs/interface-themes/authoring.md index 259147703c..e879d51e43 100644 --- a/docs/interface-themes/authoring.md +++ b/docs/interface-themes/authoring.md @@ -131,7 +131,8 @@ and again before serving their stylesheets. The installer accepts one JSON unknown format/API versions are rejected. The install catalog accepts at most 16 custom themes and 4 MiB of custom theme CSS total. - Only installed packages are listed or served. The selected package's CSS is - fetched from the same-origin API; unselected theme packages are not loaded. + fetched from the same-origin API with `nosniff` and same-origin resource + policy headers; unselected theme packages are not loaded. Install themes only from authors you trust. Scoped CSS cannot access account data through an application API, but a theme can still change or hide interface diff --git a/docs/interface-themes/implementation-status.md b/docs/interface-themes/implementation-status.md index 012c17d9ae..4b2c9d6f66 100644 --- a/docs/interface-themes/implementation-status.md +++ b/docs/interface-themes/implementation-status.md @@ -1,92 +1,46 @@ -# SeerrOrig / SeerrNGJ Rebuild Status +# SeerrOrig / SeerrNGJ Theme System Status -This is the working status record for the two-interface rebuild. Update it in -the same commit as each implementation slice. A source change is not visual -acceptance: rendered review stays unverified until the application has been -captured at matching viewports and states. +Updated 2026-10-28 from the GitHub `main` checkout plus the local verification pass. The theme package architecture is implemented and present on `main`. This record distinguishes code and automated checks from acceptance gates that still require live services or a rendered browser. -## Implementation basis +## Product and engine decision -- Rebuild base: `snapetech-org/seerrng` `main`, commit - `4f5541aa5d83cb95e2cbd214ebda72d025d5daf6`. -- Exact original UI reference: Seerr `v3.5.1`, commit - `564bfb08b54caa374bddaf820abfd226e5e69151`. -- Engine/backend decision: keep the SeerrNG engine, APIs, provider integrations, - database, and current dependency contracts. Upstream v3.5.1 is the visual and - interaction reference for SeerrOrig, not a backend rollback target. +- Keep the SeerrNG engine, APIs, provider integrations, database, permission checks, migrations, and dependency contracts. +- Use Seerr `v3.5.1`, commit `564bfb08b54caa374bddaf820abfd226e5e69151`, as SeerrOrig's visual and interaction reference; do not roll the backend back to upstream Seerr. +- SeerrNGJ preserves John's grouped navigation and blue/silver presentation. Both interfaces use the same feature components and route/API semantics. -## Rebuilt in this slice +## CSS ownership and runtime -- Added the account-level `interfaceTheme` preference with the stable values - `seerrOrig` and `seerrNGJ`; the default is `seerrOrig`. -- Added an own-profile API write route and SQLite/PostgreSQL migrations. - Accounts with the explicit legacy `john-redesign` preset migrate to NGJ; - other accounts use the new Orig default. -- Added a theme selector separate from the existing palette and advanced-color - controls. `_document` starts on SeerrOrig before hydration; the authenticated - account profile is restored as soon as user settings load. -- Added three independently owned stylesheets in - `src/styles/interfaceThemes/`. Each has its own navigation, poster, detail, - card, form, table, and surface rules. -- Expanded theme coverage to current video and cross-media detail roles, - acquisition cards, issue/blocklist summaries, service settings, and data - tables. The route components retain their existing behavior and contracts. -- Extracted theme-specific navigation presentation into a tested helper: - SeerrOrig flattens and orders the original core links while retaining current - visibility filtering; SeerrNGJ keeps the grouped SeerrNG navigation. -- Expanded the side-by-side static comparison harness with discovery, an - audiobook detail, a request action, and service administration examples. It - loads the same profile stylesheets used by the application. -- Added the initial route-family feature map and this implementation record. +- `src/styles/globals.css` supplies reset/Tailwind foundations, shared interaction behavior, palette infrastructure, and structural component styles. It no longer supplies the built-in theme values for the package-owned geometry, spacing, poster sizing, compact cards, detail rows, controls, or menu surfaces. +- `src/styles/interfaceThemes/shared.css` maps shared semantic roles to the `--interface-*` tokens. The theme packages own those token values and add scoped selectors for page, navigation, discovery, card, detail, settings, table, and responsive layouts. +- `themes/seerrOrig/` and `themes/seerrNGJ/` each contain a manifest and a complete scoped stylesheet. SeerrOrig uses compact 150px posters, flatter upstream-order navigation, tighter slate surfaces, and a centered-to-row detail flow. SeerrNGJ uses 169.2px posters, grouped navigation, framed navy/blue surfaces, and denser split layouts. The source CSS and comparison fixture are checked for distinct computed geometry and route arrangements. +- `_document` supplies SeerrOrig before hydration. The theme provider fetches the selected stylesheet from the same-origin API and activates it after it loads and the account preference saves. Only the selected package stylesheet is active. +- Theme selection remains independent of the color palette and advanced color controls. CSS can restyle and rearrange existing elements; markup, React, actions, routes, and permissions remain application-owned. -## Verification status +## Custom authoring and distribution -- CSS coverage now reaches the shared contracts used by the listed route - families; render acceptance is still needed to catch route-specific markup, - responsive, and state regressions. -- Focused theme-provider tests, server/client type checks, translation checks, - and lint have passed. The navigation presentation tests pass (2/2), client - typecheck passes, and the changed navigation files pass Prettier. A SQLite - migration execution test covers Orig defaults, the explicit John migration, - idempotency, and rollback. -- The four-worker full Node run reported 3,754 passed, 5 skipped, and 2 failed - out of 3,761. The provider deadline assertion missed its 6-second bound by - 51ms under suite load; it passes when isolated. The settings route test file - was killed during that run; it passes in isolation (93/93). A two-worker full - rerun was stopped before it produced a final summary, so a clean full-suite - result remains open. -- PostgreSQL migration execution has not yet been performed. This workspace - has no PostgreSQL client/server, container runtime, or configured database - URL; repository CI uses a private, manually dispatched runner for - database-backed checks. -- The full repository formatting check failed before formatting the changed - sidebar file. All changed files now pass the focused Prettier check; the full - repository check remains pending. -- The comparison page is a static fixture using the production profile - stylesheets. Live route screenshots, keyboard/touch review, and matching - viewport comparisons have not been completed; UI acceptance is - **unverified**. -- A theme audit caught and corrected the poster-size inversion: SeerrOrig now - uses the upstream 150px catalog track and SeerrNGJ uses the SeerrNG 169.2px - track. Both profile grids read their width from the profile token, and the - comparison page has been regenerated from those production stylesheets. - `node --test src/styles/interfaceThemeProfiles.test.mjs` passes 3/3, including - checks that the embedded CSS matches source and that the two computed layouts - differ. Changed-file Prettier and `git diff --check` also pass. -- A serial full Node-suite rerun did not produce a final TAP summary after its - execution session was lost during the `User persistence` tests. It is not a - clean suite result; the existing full-suite gate remains open. +- A package is a directory with `manifest.json` and `theme.css`; the distributable `.seerrtheme` file is JSON data and is never extracted as an archive. +- `docs/interface-themes/authoring.md`, `manifest.schema.json`, and `template/` document the API version, theme-scoped selectors, supported layout tokens, package workflow, and release checksums. +- The `interface-theme` CLI validates, packs, installs, replaces, and uninstalls custom themes. Installations are staged before swapping into app data; replacement is explicit; built-ins cannot be overwritten or removed; restart rescans the catalog. +- The validator checks manifest fields and versions, CSS syntax and scope, CSS escapes and external-resource functions, at-rules and keyframe namespaces, and package/file/count/nesting limits. Custom CSS is revalidated before serving. The same-origin stylesheet response uses `nosniff` and `Cross-Origin-Resource-Policy: same-origin`. +- Packages contain CSS only. JavaScript, HTML, fonts, images, and external resources are not part of API v1. Scoped CSS can still hide controls, so the authoring guide tells users to inspect third-party source. -## Next gates +## Verification completed -1. Complete a clean full Node suite run with a concurrency setting that fits - the available memory; retain the exact pass, skip, and fail counts. -2. Execute the PostgreSQL migration path against a disposable PostgreSQL - database. -3. Render both themes in the running app at matching desktop and phone - viewports. Review Home, video and cross-media detail, request flow, and admin - routes with loading, empty, and populated states. -4. Finish the route-level interaction and responsive review recorded in - `feature-map.md`, then update the mockup and status from verified renders. -5. Keep each implementation slice committed and pushed to the draft PR; do not - merge it. +- Theme CSS contract tests: **148 passed, 0 failed**, covering package-owned tokens, source/preview CSS equality, distinct computed layouts, navigation, card spacing, detail rows, controls, and global/shared ownership. +- Theme package, registry, API, provider, and navigation tests: **24 passed, 0 failed** in the focused server/client test run. +- Server and client TypeScript checks passed with repository-pinned pnpm 10.24.0. +- Server build passed and emitted the built-in theme packages and CLI. +- Next.js production build passed, including static generation of 140 pages. +- Changed-file ESLint, Oxlint, Prettier, and `git diff --check` passed. The full repository lint/format scripts were not used as substitutes for these targeted checks. +- `node bin/check-refreshed-ui-style.js` passed across 486 components. +- CLI integration passed in a temporary app-data directory: validate, pack, install, explicit replace, and uninstall. +- A regression test now checks that CSS comments cannot split external-resource function names to evade validation. +- `theme-comparison.html` embeds the production shared CSS and both theme package stylesheets; JSDOM verifies the embedded CSS matches source and resolves different poster, filter, detail, settings, navigation, and token values. + +## Remaining readiness gates + +1. **Full Node suite:** no clean final result yet. The latest two-worker run stopped producing output after roughly 34 minutes and was interrupted without a final TAP summary; captured output had no failure lines, which is not a pass. An earlier four-worker run reported 3,754 passed, 5 skipped, and 2 failed out of 3,761 (a provider deadline missed by 51ms under load and the settings-route worker being killed). Both affected groups passed in isolation, but the suite needs a complete stable run. +2. **PostgreSQL migrations:** the execution test is gated by `SEERR_MIGRATION_TEST_POSTGRES_URL`. This workspace has no PostgreSQL client/server, container runtime, or configured test URL, so live PostgreSQL execution remains unverified. SQLite migration tests do not replace it. +3. **Rendered acceptance:** live route screenshots and keyboard/touch/responsive review remain unverified. The static comparison is a source-backed fixture, not a live application review. The feature map covers route families as an audit plan; it does not claim all 149 page routes and states were rendered. + +The per-theme CSS architecture and authoring workflow are implemented. The change is **not fully release-ready** until the full suite, PostgreSQL execution, and rendered acceptance gates above are closed. diff --git a/server/routes/interfaceThemes.test.ts b/server/routes/interfaceThemes.test.ts index 2f723d1d80..6e64109bc4 100644 --- a/server/routes/interfaceThemes.test.ts +++ b/server/routes/interfaceThemes.test.ts @@ -1,7 +1,7 @@ -import assert from 'node:assert/strict'; import express from 'express'; -import request from 'supertest'; +import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; +import request from 'supertest'; import themeRoutes from './interfaceThemes'; const app = express().use('/api/v1/interface-themes', themeRoutes); @@ -24,17 +24,22 @@ describe('public interface theme package routes', () => { assert.equal(response.status, 200); assert.match(response.headers['content-type'], /^text\/css; charset=utf-8/); assert.equal(response.headers['x-content-type-options'], 'nosniff'); + assert.equal( + response.headers['cross-origin-resource-policy'], + 'same-origin' + ); assert.match(response.text, /data-interface-theme='seerrOrig'/); assert.equal( - (await request(app).get( - '/api/v1/interface-themes/%2e%2e/theme.css' - )).status, + (await request(app).get('/api/v1/interface-themes/%2e%2e/theme.css')) + .status, 404 ); assert.equal( - (await request(app).get( - '/api/v1/interface-themes/not-installed/theme.css' - )).status, + ( + await request(app).get( + '/api/v1/interface-themes/not-installed/theme.css' + ) + ).status, 404 ); }); diff --git a/server/utils/interfaceThemePackage.test.ts b/server/utils/interfaceThemePackage.test.ts index 3c190ab6d5..88d326da69 100644 --- a/server/utils/interfaceThemePackage.test.ts +++ b/server/utils/interfaceThemePackage.test.ts @@ -67,6 +67,21 @@ describe('interface theme package contract', () => { } }); + it('rejects resource functions split by CSS comments', () => { + for (const value of [ + 'u/**/rl(https://example.invalid/pixel.png)', + 'url/**/(https://example.invalid/pixel.png)', + 'image/**/-set("https://example.invalid/pixel.png" 1x)', + ]) { + assert.throws(() => + validateInterfaceThemeCss( + `[data-interface-theme='${manifest.id}'] .page { background-image: ${value}; }`, + manifest.id + ) + ); + } + }); + it('allows namespaced package keyframes and rejects unknown package fields', () => { assert.doesNotThrow(() => validateInterfaceThemeCss( @@ -75,7 +90,8 @@ describe('interface theme package contract', () => { ) ); assert.throws( - () => validateInterfaceThemeManifest({ ...manifest, script: 'install.js' }), + () => + validateInterfaceThemeManifest({ ...manifest, script: 'install.js' }), /unknown manifest field/ ); assert.throws( From 8eb4180a8d4d03d0f98ddb068843c0c3cb756451 Mon Sep 17 00:00:00 2001 From: snapetech <71525329+snapetech@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:34:52 +0000 Subject: [PATCH 02/55] docs: clarify theme CI execution gate --- docs/interface-themes/implementation-status.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/interface-themes/implementation-status.md b/docs/interface-themes/implementation-status.md index 4b2c9d6f66..7803f04590 100644 --- a/docs/interface-themes/implementation-status.md +++ b/docs/interface-themes/implementation-status.md @@ -42,5 +42,6 @@ Updated 2026-10-28 from the GitHub `main` checkout plus the local verification p 1. **Full Node suite:** no clean final result yet. The latest two-worker run stopped producing output after roughly 34 minutes and was interrupted without a final TAP summary; captured output had no failure lines, which is not a pass. An earlier four-worker run reported 3,754 passed, 5 skipped, and 2 failed out of 3,761 (a provider deadline missed by 51ms under load and the settings-route worker being killed). Both affected groups passed in isolation, but the suite needs a complete stable run. 2. **PostgreSQL migrations:** the execution test is gated by `SEERR_MIGRATION_TEST_POSTGRES_URL`. This workspace has no PostgreSQL client/server, container runtime, or configured test URL, so live PostgreSQL execution remains unverified. SQLite migration tests do not replace it. 3. **Rendered acceptance:** live route screenshots and keyboard/touch/responsive review remain unverified. The static comparison is a source-backed fixture, not a live application review. The feature map covers route families as an audit plan; it does not claim all 149 page routes and states were rendered. +4. **Repository CI:** the PR-triggered `public-fork-pr.yml` workflow is limited to public forks; GitHub returned no jobs for this same-repository branch. The project CI workflow is manual and uses a private JIT runner, so no project-wide CI result exists for this head. -The per-theme CSS architecture and authoring workflow are implemented. The change is **not fully release-ready** until the full suite, PostgreSQL execution, and rendered acceptance gates above are closed. +The per-theme CSS architecture and authoring workflow are implemented. The change is **not fully release-ready** until the full suite, PostgreSQL execution, rendered acceptance, and repository CI gates above are closed. From 09b9fc648f2e6ad1f9c8e8fb41431810c08519ee Mon Sep 17 00:00:00 2001 From: snapetech <71525329+snapetech@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:02:40 +0000 Subject: [PATCH 03/55] fix(migration): honor CI Postgres test URL --- server/migration/postgres/mediaUniqueness.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/server/migration/postgres/mediaUniqueness.test.ts b/server/migration/postgres/mediaUniqueness.test.ts index f93c9d0dc1..d35ba8b65a 100644 --- a/server/migration/postgres/mediaUniqueness.test.ts +++ b/server/migration/postgres/mediaUniqueness.test.ts @@ -7,7 +7,9 @@ import { EnforceScreenBlocklistUniqueness1782700000000 } from './1782700000000-E import { EnforceCanonicalBookIdentifierUniqueness1782800000000 } from './1782800000000-EnforceCanonicalBookIdentifierUniqueness'; import { EnforceMusicMediaUniqueness1782900000000 } from './1782900000000-EnforceMusicMediaUniqueness'; -const postgresUrl = process.env.SEERR_TEST_POSTGRES_URL; +const postgresUrl = + process.env.SEERR_MIGRATION_TEST_POSTGRES_URL ?? + process.env.SEERR_TEST_POSTGRES_URL; const postgresTest = postgresUrl ? test : test.skip; const createMigrationTables = async (queryRunner: QueryRunner) => { From cfca21e1ef1dc0450f6dfe9c5d1c5794434f2dad Mon Sep 17 00:00:00 2001 From: snapetech <71525329+snapetech@users.noreply.github.com> Date: Thu, 29 Oct 2026 00:23:25 +0000 Subject: [PATCH 04/55] fix(theme): narrow bundled manifest literals --- src/utils/interfaceThemeCatalog.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/utils/interfaceThemeCatalog.ts b/src/utils/interfaceThemeCatalog.ts index fd11d35a38..45722ed6bf 100644 --- a/src/utils/interfaceThemeCatalog.ts +++ b/src/utils/interfaceThemeCatalog.ts @@ -1,6 +1,29 @@ +import type { InterfaceThemeManifest } from '@server/utils/interfaceTheme'; import seerrNGJ from '../../themes/seerrNGJ/manifest.json'; import seerrOrig from '../../themes/seerrOrig/manifest.json'; -import type { InterfaceThemeManifest } from '@server/utils/interfaceTheme'; + +/** + * JSON module imports widen literal fields to number/string. Validate the + * literal contract here so the picker fallback agrees with the package schema. + */ +const assertBuiltInManifest: ( + manifest: typeof seerrOrig | typeof seerrNGJ +) => asserts manifest is InterfaceThemeManifest = (manifest) => { + if ( + manifest.formatVersion !== 1 || + manifest.themeApiVersion !== 1 || + (manifest.navigation !== 'flat' && manifest.navigation !== 'grouped') || + (manifest.activeNavigationIcon !== 'outline' && + manifest.activeNavigationIcon !== 'filled') + ) { + throw new Error( + 'Invalid built-in interface theme manifest: ' + manifest.id + ); + } +}; + +assertBuiltInManifest(seerrOrig); +assertBuiltInManifest(seerrNGJ); /** Built-in picker fallback; the package manifests remain the source of truth. */ export const BUILT_IN_INTERFACE_THEME_MANIFESTS: InterfaceThemeManifest[] = [ From ee7d1262691397b987790cf8cab98290bdf45d36 Mon Sep 17 00:00:00 2001 From: snapetech <71525329+snapetech@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:01:52 +0000 Subject: [PATCH 05/55] test(theme): complete package verification gates --- .github/workflows/fork-safe-validation.yml | 7 +- bin/check-current-batch-contract-lib.js | 7302 +---------------- bin/check-current-batch-contract-lib.test.mjs | 28 + bin/check-current-batch-contract.js | 3 + .../interface-themes/implementation-status.md | 63 +- scripts/check-helm-security.test.mjs | 164 +- scripts/release-notes.test.mjs | 21 +- scripts/update-interface-theme-comparison.mjs | 4 +- server/commands/interfaceTheme.ts | 23 +- server/lib/sqliteFileSecurity.test.ts | 7 +- server/routes/adult.ts | 4 +- server/routes/interfaceThemes.ts | 3 +- server/test/loopbackHttpRequest.ts | 29 + server/utils/httpServer.test.ts | 9 +- server/utils/interfaceTheme.ts | 4 +- server/utils/interfaceThemePackage.ts | 25 +- server/utils/interfaceThemeRegistry.ts | 42 +- server/utils/tls.test.ts | 13 +- .../Sidebar/navigationPresentation.test.ts | 5 +- src/context/ThemeContext.test.ts | 10 +- src/context/ThemeContext.tsx | 4 +- src/context/ThemeProvider.vitest.test.tsx | 25 +- src/styles/buttonGeometry.test.mjs | 85 +- src/styles/cardSpacing.test.mjs | 7 +- src/styles/detailRows.test.mjs | 15 +- src/styles/interfaceThemeProfiles.test.mjs | 2 +- src/styles/interfaceThemes/shared.css | 12 +- src/styles/phonePosterGrid.test.mjs | 10 +- src/styles/seasonEpisodeTree.test.mjs | 5 +- src/styles/seriesDetailsStyle.test.mjs | 16 +- themes/seerrNGJ/theme.css | 5 +- themes/seerrOrig/theme.css | 5 +- 32 files changed, 450 insertions(+), 7507 deletions(-) create mode 100644 server/test/loopbackHttpRequest.ts diff --git a/.github/workflows/fork-safe-validation.yml b/.github/workflows/fork-safe-validation.yml index 727ba26644..1067c4a8ca 100644 --- a/.github/workflows/fork-safe-validation.yml +++ b/.github/workflows/fork-safe-validation.yml @@ -15,7 +15,12 @@ jobs: github.event.pull_request.base.ref == 'main' runs-on: group: public-fork-jit - labels: [self-hosted, linux, x64, public-pr-seerrng, ng-public-run-${{ github.run_id }}] + labels: + - self-hosted + - linux + - x64 + - public-pr-seerrng + - ng-public-run-${{ github.run_id }} timeout-minutes: 30 permissions: contents: read diff --git a/bin/check-current-batch-contract-lib.js b/bin/check-current-batch-contract-lib.js index 30f01238d9..32c32cf517 100644 --- a/bin/check-current-batch-contract-lib.js +++ b/bin/check-current-batch-contract-lib.js @@ -1,7301 +1 @@ -/* eslint-disable @typescript-eslint/no-require-imports -- This validator is loaded by the repository's CommonJS contract runner. */ -const fs = require('node:fs'); -const path = require('node:path'); - -const parsedCssOwner = (stylesheet, selector, expected, media) => { - try { - const normalize = (value) => value.replace(/\s+/g, ' ').trim(); - const declarations = []; - require('postcss') - .parse(stylesheet) - .walkRules((rule) => { - if ( - !rule.selectors.some( - (item) => normalize(item) === normalize(selector) - ) - ) - return; - if ( - media && - !( - rule.parent.type === 'atrule' && - rule.parent.name === 'media' && - normalize(rule.parent.params) === media - ) - ) - return; - for (const node of rule.nodes) { - if (node.type === 'atrule' && node.name === 'apply') - throw new Error('Retired utility owner'); - if (node.type === 'decl') declarations.push(node); - } - }); - return Object.entries(expected).every(([property, value]) => { - const matches = declarations.filter((item) => item.prop === property); - const competing = - property === 'background-color' - ? ['background', 'all'] - : property.startsWith('font-') || property === 'line-height' - ? ['font', 'all'] - : property === 'border-bottom' - ? [ - 'border', - 'border-color', - 'border-width', - 'border-style', - 'all', - ] - : ['all']; - return ( - matches.length === 1 && - normalize(matches[0].value) === normalize(value) && - !declarations.some((item) => competing.includes(item.prop)) - ); - }); - } catch { - return false; - } -}; - -const parsedJsx = (source) => { - const ts = require('typescript'); - const tree = ts.createSourceFile( - 'Owner.tsx', - source, - ts.ScriptTarget.Latest, - true, - ts.ScriptKind.TSX - ); - if (tree.parseDiagnostics.length) throw new Error('Invalid JSX source'); - const elements = []; - const visit = (node) => { - if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) - elements.push(node); - ts.forEachChild(node, visit); - }; - visit(tree); - const opening = (node) => - ts.isJsxElement(node) ? node.openingElement : node; - const tag = (node) => opening(node).tagName.getText(tree); - const attr = (node, name) => - opening(node).attributes.properties.find( - (item) => ts.isJsxAttribute(item) && item.name.getText(tree) === name - )?.initializer; - const expression = (node, name) => { - const value = attr(node, name); - return value && ts.isJsxExpression(value) ? value.expression : value; - }; - const present = (node, name) => - opening(node).attributes.properties.some( - (item) => ts.isJsxAttribute(item) && item.name.getText(tree) === name - ); - const text = (node, name) => { - const value = expression(node, name); - return value && ts.isStringLiteral(value) ? value.text : undefined; - }; - const roles = (node, ...names) => - names.every((name) => - (text(node, 'className') ?? '').split(/\s+/).includes(name) - ); - const compact = (node) => node?.getText(tree).replace(/\s+/g, ''); - const within = (node, ancestor) => { - for (let current = node.parent; current; current = current.parent) - if (current === ancestor) return true; - return false; - }; - return { - ts, - tree, - elements, - tag, - attr, - expression, - present, - text, - roles, - compact, - within, - }; -}; - -// Read connected Cypress actions/assertions, not a test title or retired format -// control. One test must exercise entry, both in-dialog choices and zero writes. -const validateSeriesRequestEntryEvidence = (source) => { - try { - const { ts, tree } = parsedJsx(source); - const callsWithin = (root) => { - const calls = []; - const visit = (node) => { - if (ts.isCallExpression(node)) calls.push(node); - ts.forEachChild(node, visit); - }; - visit(root); - return calls; - }; - const chain = (node) => { - if (!node || !ts.isCallExpression(node)) return []; - if (ts.isIdentifier(node.expression)) - return [{ name: node.expression.text, args: node.arguments }]; - if (!ts.isPropertyAccessExpression(node.expression)) return []; - let owner = node.expression.expression; - while (ts.isPropertyAccessExpression(owner)) owner = owner.expression; - const prior = ts.isCallExpression(owner) - ? chain(owner) - : ts.isIdentifier(owner) && owner.text === 'cy' - ? [{ name: 'cy', args: [] }] - : []; - return prior.length - ? [...prior, { name: node.expression.name.text, args: node.arguments }] - : []; - }; - const text = (node) => - node && ts.isStringLiteral(node) ? node.text : undefined; - const has = (steps, name, first, second) => - steps.some( - (step) => - step.name === name && - (first === undefined || text(step.args[0]) === first) && - (second === undefined || text(step.args[1]) === second) - ); - const assertion = (steps, name, value) => - has(steps, 'should', name, value) || has(steps, 'and', name, value); - const label = (node, expected) => { - if (!node) return false; - if (ts.isStringLiteral(node)) return node.text === expected; - if (!ts.isRegularExpressionLiteral(node)) return false; - const match = node.text.match(/^\/(.*)\/([a-z]*)$/); - if (!match || !match[1].startsWith('^') || !match[1].endsWith('$')) - return false; - // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- the pattern is built from repository files, never from user input - const pattern = new RegExp(match[1], match[2]); - return pattern.test(expected) && !pattern.test(`${expected} Extra`); - }; - const contains = (steps, expected) => - steps.some( - (step) => - step.name === 'contains' && - text(step.args[0]) === 'button' && - label(step.args[1], expected) - ); - const tests = callsWithin(tree).filter( - (call) => - ts.isIdentifier(call.expression) && call.expression.text === 'it' - ); - return tests.some((test) => { - const body = test.arguments.find(ts.isArrowFunction)?.body; - if (!body) return false; - const calls = callsWithin(body); - const entry = calls.find((call) => { - const steps = chain(call); - return ( - steps[0]?.name === 'cy' && - contains(steps, 'Request') && - has(steps, 'filter', ':visible') && - assertion(steps, 'be.enabled') && - steps.at(-1)?.name === 'click' - ); - }); - const dialog = calls.find((call) => { - const steps = chain(call); - return ( - has(steps, 'get', '[role="dialog"]') && - assertion(steps, 'be.visible') && - steps.at(-1)?.name === 'within' - ); - }); - if (!entry || !dialog || entry.pos >= dialog.pos) return false; - const choiceCalls = callsWithin(dialog.arguments[0]?.body ?? dialog); - const choices = choiceCalls.map(chain); - const quality = (steps, expected) => - has(steps, 'get', '[role="group"][aria-label="Quality"]') && - contains(steps, expected); - const pressed = (steps) => - steps.some( - (step) => - ['should', 'and'].includes(step.name) && - text(step.args[0]) === 'have.attr' && - text(step.args[1]) === 'aria-pressed' && - text(step.args[2]) === 'true' - ); - if ( - !choices.some((steps) => quality(steps, 'HD') && pressed(steps)) || - !choices.some( - (steps) => - quality(steps, 'HD') && has(steps, 'click') && pressed(steps) - ) || - !choices.some( - (steps) => - quality(steps, '4K') && - assertion(steps, 'be.enabled') && - has(steps, 'click') - ) || - !choices.some((steps) => quality(steps, '4K') && pressed(steps)) || - !calls.some((call) => { - const steps = chain(call); - return ( - call.pos < entry.pos && - has(steps, 'get', '[data-testid=format-request-option-standard]') && - assertion(steps, 'not.exist') - ); - }) - ) - return false; - const switch4k = choiceCalls.find((call) => { - const steps = chain(call); - return quality(steps, '4K') && has(steps, 'click'); - }); - const selected4k = choiceCalls.find( - (call) => - call.pos > switch4k.pos && - quality(chain(call), '4K') && - pressed(chain(call)) - ); - if ( - !selected4k || - !choiceCalls.some( - (call) => - call.pos < switch4k.pos && - quality(chain(call), 'HD') && - pressed(chain(call)) - ) || - !choiceCalls.some( - (call) => - call.pos > selected4k.pos && - quality(chain(call), 'HD') && - has(chain(call), 'click') && - pressed(chain(call)) - ) - ) - return false; - return calls.some((call) => { - const steps = chain(call); - const expectation = steps[0]; - const counter = expectation?.args[0]; - const zero = steps.at(-1); - if ( - expectation?.name !== 'expect' || - !counter || - !ts.isIdentifier(counter) || - zero?.name !== 'eq' || - !zero.args[0] || - !ts.isNumericLiteral(zero.args[0]) || - zero.args[0].text !== '0' || - call.pos <= dialog.pos - ) - return false; - let queuedAssertion = false; - for ( - let owner = call.parent; - owner && owner !== body; - owner = owner.parent - ) { - if (ts.isCallExpression(owner) && has(chain(owner), 'then')) - queuedAssertion = true; - } - const initialized = body.statements?.some( - (statement) => - ts.isVariableStatement(statement) && - statement.declarationList.declarations.some( - (declaration) => - ts.isIdentifier(declaration.name) && - declaration.name.text === counter.text && - declaration.initializer && - ts.isNumericLiteral(declaration.initializer) && - declaration.initializer.text === '0' - ) - ); - const observed = calls.some((intercept) => { - const observer = intercept.arguments[2]; - if ( - intercept.pos >= entry.pos || - !has(chain(intercept), 'intercept', 'POST', '/api/v1/request*') || - !observer || - !ts.isArrowFunction(observer) - ) - return false; - let incremented = false; - const scan = (node) => { - if ( - (ts.isPostfixUnaryExpression(node) || - ts.isPrefixUnaryExpression(node)) && - node.operator === ts.SyntaxKind.PlusPlusToken && - ts.isIdentifier(node.operand) && - node.operand.text === counter.text - ) - incremented = true; - if ( - ts.isBinaryExpression(node) && - node.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken && - ts.isIdentifier(node.left) && - node.left.text === counter.text && - ts.isNumericLiteral(node.right) && - node.right.text === '1' - ) - incremented = true; - ts.forEachChild(node, scan); - }; - scan(observer.body); - return incremented; - }); - return initialized && observed && queuedAssertion; - }); - }); - } catch { - return false; - } -}; - -const validateRequestFolders = (source, stylesheet, aspect) => { - try { - const { elements, roles, text, expression, compact, within } = - parsedJsx(source); - const table = elements.find( - (node) => - roles(node, 'card-table') && - text(node, 'data-table-layout') === 'request-folders' - ); - if (!table) return false; - const header = elements.find( - (node) => - within(node, table) && text(node, 'data-table-part') === 'header' - ); - const rows = elements.find( - (node) => within(node, table) && text(node, 'data-table-part') === 'rows' - ); - if (!header || !rows || within(header, rows)) return false; - const base = ".card-table[data-table-layout='request-folders']"; - if (aspect === 'scroll') - return ( - roles(rows, 'scrollable-card') && - compact(expression(rows, 'data-scrollable')) === - '(serverData?.rootFolders.length??0)>5' && - parsedCssOwner(stylesheet, `${base} [data-scrollable='true']`, { - 'max-height': '8.5rem', - 'overflow-y': 'auto', - }) - ); - if (aspect === 'border') - return parsedCssOwner(stylesheet, `${base} [data-table-part='header']`, { - 'border-bottom': - 'var(--detail-divider-width) solid rgb(var(--theme-control-border) / 0.72)', - }); - return ( - parsedCssOwner(stylesheet, base, { - width: 'fit-content', - 'max-width': '100%', - '--card-table-columns': 'minmax(0, max-content) max-content', - }) && - ['header', 'rows', 'choice-row'].every((part) => - parsedCssOwner(stylesheet, `${base} [data-table-part='${part}']`, { - display: 'grid', - 'grid-column': '1 / -1', - 'grid-template-columns': 'subgrid', - }) - ) - ); - } catch { - return false; - } -}; - -const validateRequestMediaArtwork = ( - source, - artworkSource, - stylesheet, - aspect -) => { - try { - const request = parsedJsx(source); - const shell = request.elements.find( - (node) => - request.tag(node) === 'article' && - request.roles( - node, - 'media-detail-card', - 'app-card-main', - 'card-layout', - 'refreshed-card-surface' - ) - ); - if (!shell) return false; - const artwork = request.elements.find( - (node) => - request.tag(node) === 'MediaDetailArtwork' && - request.within(node, shell) - ); - const content = request.elements.find( - (node) => - request.text(node, 'data-card-part') === 'content' && - request.within(node, shell) - ); - if ( - !artwork || - !content || - request.compact(request.expression(artwork, 'src')) !== 'artwork' || - request.compact(request.expression(artwork, 'type')) !== 'artworkType' - ) - return false; - const shared = parsedJsx(artworkSource); - const layer = shared.elements.find((node) => - shared.roles(node, 'media-detail-artwork-layer') - ); - if (!layer) return false; - if (aspect === 'clip') - return ( - parsedCssOwner(stylesheet, '.media-detail-card', { - position: 'relative', - overflow: 'hidden', - }) && - parsedCssOwner(stylesheet, '.media-detail-artwork-layer', { - position: 'absolute', - inset: '0', - overflow: 'hidden', - }) - ); - if (aspect === 'crop') - return ( - shared.elements.some( - (node) => - shared.tag(node) === 'CachedImage' && - shared.within(node, layer) && - shared.roles(node, 'media-detail-artwork-image') && - shared.present(node, 'fill') - ) && - parsedCssOwner(stylesheet, '.media-detail-artwork-image', { - 'object-fit': 'cover', - }) && - parsedCssOwner( - stylesheet, - '.media-detail-artwork-layer .media-detail-artwork-image', - { 'object-position': 'var(--card-artwork-position)' } - ) && - parsedCssOwner(stylesheet, '.card-layout', { - '--card-artwork-position': 'top', - }) - ); - return ( - shared.elements.some( - (node) => - shared.roles(node, 'refreshed-artwork-scrim') && - shared.within(node, layer) - ) && - parsedCssOwner(stylesheet, '.refreshed-artwork-scrim', { - position: 'absolute', - inset: '0', - 'background-color': 'rgb(var(--theme-artwork-scrim) / 0.46)', - }) - ); - } catch { - return false; - } -}; - -const validateTvRequestCanvas = (source, stylesheet, inset) => { - try { - const jsx = parsedJsx(source); - const modal = jsx.elements.find( - (node) => - jsx.tag(node) === 'Modal' && - (jsx.text(node, 'dialogClass') ?? '') - .split(/\s+/) - .includes('request-modal-site-surface') - ); - const shell = jsx.elements.find( - (node) => - jsx.tag(node) === 'RequestMediaCard' && modal && jsx.within(node, modal) - ); - if (!modal || !shell) return false; - return inset - ? jsx.elements.some( - (node) => - jsx.within(node, shell) && - jsx.roles( - node, - 'app-card-inset', - 'refreshed-inset-surface', - 'detail-summary-card' - ) - ) - : parsedCssOwner( - stylesheet, - '.request-modal-site-surface', - { 'max-width': '64rem' }, - '(min-width: 640px)' - ); - } catch { - return false; - } -}; - -const validateTreeEligibility = (source, aspect) => { - try { - const jsx = parsedJsx(source); - const { ts, tree, elements, text, tag, expression, compact } = jsx; - const declarations = new Map(); - const scan = (node) => { - if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) - declarations.set(node.name.text, node.initializer); - ts.forEachChild(node, scan); - }; - scan(tree); - const fallback = declarations.get('isTreeEpisodeSelectable'); - if ( - !fallback || - !ts.isArrowFunction(fallback) || - compact(fallback.body) !== 'episode.selectable??episode.available' - ) - return false; - if (aspect === 'row') { - const row = elements.find( - (node) => - tag(node) === 'button' && - text(node, 'data-tree-part') === 'episode-selection' - ); - return ( - row && - compact(expression(row, 'disabled')) === - 'disabled||!isTreeEpisodeSelectable(episode)' - ); - } - if (aspect === 'guard') { - const toggle = declarations.get('toggleEpisode'); - return ( - toggle && - ts.isArrowFunction(toggle) && - ts.isBlock(toggle.body) && - toggle.body.statements.some( - (node) => - ts.isIfStatement(node) && - compact(node.expression) === '!isTreeEpisodeSelectable(episode)' && - ts.isReturnStatement(node.thenStatement) && - !node.thenStatement.expression - ) - ); - } - if (aspect === 'all') { - const control = elements.find( - (node) => - tag(node) === 'SelectionCircle' && - compact(expression(node, 'onClick')) === 'toggleAll' - ); - return ( - control && - compact(expression(control, 'disabled')) === - 'disabled||availableIds.size===0' - ); - } - return ['seasonSelection', 'toggleSeasonSelection', 'availableIds'].every( - (name) => { - const owner = declarations.get(name); - let filtered = false; - const visit = (node) => { - if ( - ts.isCallExpression(node) && - ts.isPropertyAccessExpression(node.expression) && - node.expression.name.text === 'filter' && - node.arguments.length === 1 && - ts.isIdentifier(node.arguments[0]) && - node.arguments[0].text === 'isTreeEpisodeSelectable' - ) - filtered = true; - ts.forEachChild(node, visit); - }; - if (owner) visit(owner); - return filtered; - } - ); - } catch { - return false; - } -}; - -const isProviderSelectionIndicator = (source, stylesheet) => { - try { - const jsx = parsedJsx(source); - const button = jsx.elements.find((node) => jsx.tag(node) === 'button'); - if ( - !button || - !jsx.roles(button, 'provider-container') || - jsx.compact(jsx.expression(button, 'aria-pressed')) !== 'isActive' || - jsx.compact(jsx.expression(button, 'data-selected')) !== 'isActive' || - jsx.compact(jsx.expression(button, 'onClick')) !== - '()=>toggleProvider(provider.id)' || - jsx.compact(jsx.expression(button, 'aria-label')) !== 'provider.name' - ) - return false; - const logo = jsx.elements.find( - (node) => - jsx.text(node, 'data-provider-region') === 'logo' && - jsx.within(node, button) - ); - const check = jsx.elements.find( - (node) => - jsx.text(node, 'data-provider-region') === 'check' && - jsx.within(node, button) - ); - if ( - !logo || - !check || - jsx.tag(check) !== 'div' || - !jsx.elements.some( - (node) => jsx.tag(node) === 'CachedImage' && jsx.within(node, logo) - ) - ) - return false; - const conditional = check.parent?.parent; - if ( - !conditional || - !jsx.ts.isBinaryExpression(conditional) || - conditional.operatorToken.kind !== - jsx.ts.SyntaxKind.AmpersandAmpersandToken || - jsx.compact(conditional.left) !== 'isActive' - ) - return false; - const icons = jsx.elements.filter( - (node) => jsx.tag(node) === 'CheckCircleIcon' && jsx.within(node, button) - ); - return ( - icons.length === 1 && - jsx.within(icons[0], check) && - parsedCssOwner( - stylesheet, - ".provider-container > [data-provider-region='check']", - { 'pointer-events': 'none', position: 'absolute' } - ) && - parsedCssOwner( - stylesheet, - ".provider-container [data-provider-region='logo'] img", - { 'object-fit': 'contain' } - ) - ); - } catch { - return false; - } -}; - -// Inspect the actual section descriptors/children instead of retired heading or -// Tailwind strings. A declaration elsewhere must not mask a missing panel. -const readPinnedFilterSections = (source) => { - const ts = require('typescript'); - const tree = ts.createSourceFile( - 'FilterConsumer.tsx', - source, - ts.ScriptTarget.Latest, - true, - ts.ScriptKind.TSX - ); - if (tree.parseDiagnostics.length) throw new Error('Invalid filter consumer'); - const unwrap = (node) => { - while ( - node && - (ts.isParenthesizedExpression(node) || ts.isJsxExpression(node)) - ) - node = node.expression; - return node; - }; - const attribute = (node, name) => - node.attributes.properties.find( - (item) => ts.isJsxAttribute(item) && item.name.getText(tree) === name - )?.initializer; - const property = (node, name) => - node.properties.find( - (item) => - ts.isPropertyAssignment(item) && - item.name.getText(tree).replace(/['"]/g, '') === name - )?.initializer; - const sections = new Map(); - const add = (name, children, label) => { - name = unwrap(name); - if ( - !name || - !ts.isStringLiteral(name) || - sections.has(name.text) || - !unwrap(label) || - !children - ) - throw new Error('Missing or duplicate pinned filter section'); - let rendered = false; - const visit = (node) => { - if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) { - const opening = ts.isJsxElement(node) ? node.openingElement : node; - if (opening.tagName.getText(tree) !== 'PinnedFilterSection') - rendered = true; - } - ts.forEachChild(node, visit); - }; - visit(children); - if (!rendered) throw new Error('Missing pinned filter content'); - sections.set(name.text, { children: unwrap(children), tree }); - }; - const visit = (node) => { - if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) { - const opening = ts.isJsxElement(node) ? node.openingElement : node; - const tag = opening.tagName.getText(tree); - if (tag === 'PinnedFilterSectionGroup') { - if (!unwrap(attribute(opening, 'mediaType'))) - throw new Error('Missing pin context'); - const entries = unwrap(attribute(opening, 'sections')); - if (!entries || !ts.isArrayLiteralExpression(entries)) - throw new Error('Unresolved filter section descriptors'); - for (const entry of entries.elements) { - if (!ts.isObjectLiteralExpression(entry)) - throw new Error('Unresolved filter section descriptor'); - add( - property(entry, 'section'), - property(entry, 'children'), - property(entry, 'label') - ); - } - } else if (tag === 'PinnedFilterSection') { - if (!ts.isJsxElement(node) || !unwrap(attribute(opening, 'mediaType'))) - throw new Error('Missing pin context or panel'); - add(attribute(opening, 'section'), node, attribute(opening, 'label')); - } - } - ts.forEachChild(node, visit); - }; - visit(tree); - return sections; -}; - -const validatePinnedFilterSections = (source, required) => { - try { - const sections = readPinnedFilterSections(source); - return required.every((name) => sections.has(name)); - } catch { - return false; - } -}; - -const validateNativeFilterGeometry = (stylesheet) => { - try { - const css = require('postcss').parse(stylesheet); - const owners = new Map([ - [ - '.app-filter-segment-focus', - new Map([ - ['display', 'flex'], - ['height', '100%'], - ['align-items', 'center'], - ['padding-inline', 'var(--button-padding-x)'], - ['column-gap', 'var(--button-content-gap)'], - ]), - ], - [ - '.app-filter-search-control', - new Map([ - ['max-width', '100%'], - ['flex', 'none'], - ['align-self', 'center'], - ]), - ], - [ - '.app-filter-row', - new Map([ - ['display', 'flex'], - ['flex-wrap', 'wrap'], - ['align-items', 'center'], - ['gap', '5px'], - ]), - ], - [ - '.app-pinned-filter-section', - new Map([ - ['margin-top', '0'], - ['margin-bottom', '20px'], - ]), - ], - ['.app-pinned-filter-panel', new Map([['margin-top', '12px']])], - ]); - for (const [selector, expected] of owners) { - const declarations = []; - css.walkRules((rule) => { - if (!rule.selectors.includes(selector)) return; - for (const node of rule.nodes) { - if (node.type === 'atrule' && node.name === 'apply') - throw new Error('Utility-owned filter geometry'); - if (node.type === 'decl') declarations.push(node); - } - }); - for (const [property, value] of expected) { - const values = declarations.filter((node) => node.prop === property); - if (values.length !== 1 || values[0].value !== value) - throw new Error('Missing or competing shared filter geometry'); - } - const competing = - selector === '.app-filter-segment-focus' - ? ['padding', 'padding-left', 'padding-right', 'gap', 'all'] - : selector === '.app-filter-search-control' || - selector === '.app-filter-row' - ? ['all'] - : ['margin', 'all']; - if (declarations.some((node) => competing.includes(node.prop))) - throw new Error('Competing shorthand geometry'); - } - css.walkRules((rule) => { - if (rule.selectors.includes('.app-filter-button > button')) - rule.walkDecls((decl) => { - if (/^(padding|gap|column-gap)(-|$)/.test(decl.prop)) - throw new Error('Retired descendant spacing owner'); - }); - }); - return true; - } catch { - return false; - } -}; - -const validateMusicFilterLayout = (source) => { - try { - const ts = require('typescript'); - const { children, tree } = readPinnedFilterSections(source).get('filters'); - if (!ts.isJsxElement(children)) return false; - const row = children.openingElement.attributes.properties.find( - (item) => - ts.isJsxAttribute(item) && item.name.getText(tree) === 'className' - )?.initializer; - if ( - !row || - !ts.isStringLiteral(row) || - !row.text.split(/\s+/).includes('app-filter-row') - ) - return false; - const controls = []; - const visit = (node) => { - if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) { - const opening = ts.isJsxElement(node) ? node.openingElement : node; - const tag = opening.tagName.getText(tree); - if ( - [ - 'FilterResetButton', - 'CardTextVisibilityToggle', - 'AvailabilityQualityControl', - 'MusicArtistFilter', - 'form', - 'CompactSelect', - 'MusicReleaseTypeSelect', - ].includes(tag) - ) { - const label = opening.attributes.properties.find( - (item) => - ts.isJsxAttribute(item) && item.name.getText(tree) === 'label' - )?.initializer; - const expression = - label && ts.isJsxExpression(label) ? label.expression : undefined; - const message = - expression && - ts.isCallExpression(expression) && - expression.expression.getText(tree) === 'intl.formatMessage' - ? expression.arguments[0] - : undefined; - const key = - message && - ts.isPropertyAccessExpression(message) && - ts.isIdentifier(message.expression) && - message.expression.text === 'messages' - ? message.name.text - : undefined; - controls.push(tag === 'CompactSelect' ? `${tag}:${key}` : tag); - } - } - ts.forEachChild(node, visit); - }; - visit(children); - const expected = [ - 'FilterResetButton', - 'CardTextVisibilityToggle', - 'AvailabilityQualityControl', - 'MusicArtistFilter', - 'form', - 'CompactSelect:releaseYear', - 'MusicReleaseTypeSelect', - 'CompactSelect:genres', - ]; - return ( - controls.length === expected.length && - controls.every((control, index) => control === expected[index]) - ); - } catch { - return false; - } -}; - -const validateRequestListSortDirection = (source) => { - try { - const ts = require('typescript'); - const { children, tree } = readPinnedFilterSections(source).get('sortBy'); - const matches = []; - const visit = (node) => { - if ( - ts.isJsxElement(node) && - node.openingElement.tagName.getText(tree) === 'button' - ) { - const attr = (name) => - node.openingElement.attributes.properties.find( - (item) => - ts.isJsxAttribute(item) && item.name.getText(tree) === name - )?.initializer; - let direction = false; - const inspect = (item) => { - if ( - ts.isCallExpression(item) && - item.expression.getText(tree) === 'setCurrentSortDirection' - ) - direction = true; - ts.forEachChild(item, inspect); - }; - if (attr('onClick')) inspect(attr('onClick')); - if (direction) { - const className = attr('className'); - const expression = - className && ts.isJsxExpression(className) - ? className.expression - : undefined; - matches.push( - Boolean( - expression && - ts.isCallExpression(expression) && - expression.expression.getText(tree) === - 'getFilterToggleButtonClass' && - expression.arguments.length === 1 && - expression.arguments[0].kind === ts.SyntaxKind.FalseKeyword && - attr('aria-label') && - node.parent && - ts.isJsxElement(node.parent) && - node.parent.openingElement.tagName.getText(tree) === 'Tooltip' - ) - ); - } - } - ts.forEachChild(node, visit); - }; - visit(children); - return matches.length === 1 && matches[0]; - } catch { - return false; - } -}; - -const compactRequestGeometryReason = - 'loaded and loading compact Request cards must share CSS geometry without fixed loaded height'; -const validateCompactRequestGeometry = (source, stylesheet) => { - const ts = require('typescript'); - const postcss = require('postcss'); - const tree = ts.createSourceFile( - 'RequestCard.tsx', - source, - ts.ScriptTarget.Latest, - true, - ts.ScriptKind.TSX - ); - const roots = []; - const attr = (node, name) => - node.attributes.properties.find( - (item) => ts.isJsxAttribute(item) && item.name.getText(tree) === name - ); - const text = (node) => { - if (ts.isJsxExpression(node)) return text(node.expression); - if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) - return node.text; - if (ts.isTemplateExpression(node)) - return ( - node.head.text + - node.templateSpans - .map((span) => text(span.expression) + span.literal.text) - .join('') - ); - if ( - ts.isConditionalExpression(node) && - ts.isIdentifier(node.condition) && - node.condition.text === 'compact' - ) - return text(node.whenTrue); - throw new Error('Unresolved compact root classes'); - }; - try { - const visit = (node) => { - if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) { - const className = attr(node, 'className'); - if (className?.initializer) { - let tokens; - try { - tokens = text(className.initializer).split(/\s+/).filter(Boolean); - } catch { - tokens = []; - } - const loaded = - attr(node, 'data-testid')?.initializer?.text === 'request-card'; - const placeholder = tokens.includes('request-card-placeholder'); - if (loaded || placeholder) - roots.push({ node, tokens, loaded, placeholder }); - } - } - ts.forEachChild(node, visit); - }; - const scanComponents = (node) => { - if ( - ts.isVariableDeclaration(node) && - ts.isIdentifier(node.name) && - ['RequestCard', 'RequestCardPlaceholder'].includes(node.name.text) && - node.initializer && - ts.isArrowFunction(node.initializer) - ) { - visit(node.initializer.body); - } else { - ts.forEachChild(node, scanComponents); - } - }; - scanComponents(tree); - if ( - !roots.some((root) => root.loaded) || - !roots.some((root) => root.placeholder) - ) - return false; - for (const root of roots) { - if (!root.tokens.includes('request-card-compact-layout')) return false; - if ( - root.tokens.some((token) => - /^(?:[a-z]+:)*!?(?:w-72|w-96|h-\[9\.5rem\]|min-h-0)$/.test(token) - ) - ) - return false; - const style = attr(root.node, 'style'); - if (style?.initializer) { - let geometry = false; - const inspect = (node) => { - if ( - ts.isPropertyAssignment(node) && - /^(?:width|height|minWidth|minHeight|maxWidth|maxHeight)$/.test( - node.name.getText(tree).replace(/['"]/g, '') - ) - ) - geometry = true; - ts.forEachChild(node, inspect); - }; - inspect(style.initializer); - if (geometry) return false; - } - } - const css = postcss.parse(stylesheet); - const declarations = (selector, property) => { - const values = []; - css.walkRules((rule) => { - if (rule.selectors.includes(selector)) - rule.walkDecls(property, (decl) => values.push(decl.value)); - }); - return values; - }; - const exactly = (selector, property, value) => { - const values = declarations(selector, property); - return values.length === 1 && values[0] === value; - }; - return ( - exactly( - '.request-card-compact-layout', - 'width', - 'var(--request-card-compact-width)' - ) && - exactly( - '.request-card-compact-layout', - 'min-height', - 'var(--request-card-compact-height)' - ) && - exactly( - '.request-card-placeholder', - 'height', - 'var(--request-card-compact-height)' - ) && - ['height', 'max-height', 'overflow'].every( - (property) => - declarations('.request-card-compact-layout', property).length === 0 - ) && - ['width', 'min-width', 'max-width', 'min-height', 'max-height'].every( - (property) => - declarations('.request-card-placeholder', property).length === 0 - ) - ); - } catch { - return false; - } -}; - -const readRepositoryFiles = (root, fileNames) => - Object.fromEntries( - fileNames.map((fileName) => [ - fileName, - fs.readFileSync(path.join(root, fileName), 'utf8'), - ]) - ); - -const validateCurrentBatchContract = (files) => { - const errors = []; - const requireFile = (fileName) => { - if (!(fileName in files)) { - errors.push(`Missing contract input: ${fileName}`); - return ''; - } - return files[fileName]; - }; - const requireText = (fileName, text, reason) => { - if (!requireFile(fileName).includes(text)) { - errors.push(`${fileName}: ${reason}`); - } - }; - const rejectText = (fileName, text, reason) => { - if (requireFile(fileName).includes(text)) { - errors.push(`${fileName}: ${reason}`); - } - }; - // Shared roles can belong to comma-separated selector groups. Check the - // owning declaration block, not an unrelated occurrence elsewhere in CSS. - let cssBlocks; - const requireCssRule = (selector, declarations, reason) => { - if (!cssBlocks) { - const source = requireFile('src/styles/globals.css').replace( - /\/\*[\s\S]*?\*\//g, - '' - ); - cssBlocks = [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)]; - } - const normalize = (value) => - value - .replace(/\s+/g, ' ') - .replace(/\(\s+/g, '(') - .replace(/\s+\)/g, ')') - .trim(); - const matches = cssBlocks.filter(([, selectors]) => - selectors - .split(',') - .some((value) => normalize(value) === normalize(selector)) - ); - if ( - !declarations.every((text) => - matches.some(([, , body]) => normalize(body).includes(normalize(text))) - ) - ) { - errors.push(`src/styles/globals.css: ${reason}`); - } - }; - const requireCount = (fileName, text, expected, reason) => { - const source = requireFile(fileName); - const actual = source.split(text).length - 1; - if (actual !== expected) { - errors.push( - `${fileName}: ${reason} (expected ${expected}, found ${actual})` - ); - } - }; - const requireDistinctSectionHeadings = ( - fileName, - sectionStart, - sectionEnd, - headingTokens, - reason - ) => { - const source = requireFile(fileName); - const sections = []; - let offset = 0; - while (true) { - const start = source.indexOf(sectionStart, offset); - if (start < 0) break; - const contentStart = start + sectionStart.length; - const end = source.indexOf(sectionEnd, contentStart); - if (end < 0) break; - sections.push(source.slice(contentStart, end)); - offset = end + sectionEnd.length; - } - - const headingSections = headingTokens.map((heading) => - sections.findIndex((section) => section.includes(heading)) - ); - if ( - headingSections.some((section) => section < 0) || - new Set(headingSections).size !== headingTokens.length - ) { - errors.push(`${fileName}: ${reason}`); - } - }; - const requireHeadingScopedText = ( - fileName, - headingTokens, - requiredTokens, - reason - ) => { - const source = requireFile(fileName); - const headings = headingTokens.map((heading) => ({ - heading, - position: source.indexOf(heading), - })); - if (headings.some(({ position }) => position < 0)) { - errors.push(`${fileName}: ${reason}`); - return; - } - - for (const { position } of headings) { - const nextHeadingPosition = headings - .map(({ position: candidate }) => candidate) - .filter((candidate) => candidate > position) - .sort((left, right) => left - right)[0]; - const group = source.slice(position, nextHeadingPosition); - if (requiredTokens.some((token) => !group.includes(token))) { - errors.push(`${fileName}: ${reason}`); - return; - } - } - }; - const requireOrder = (fileName, tokens, reason) => { - const source = requireFile(fileName); - let previous = -1; - for (const token of tokens) { - const position = source.indexOf(token, previous + 1); - if (position < 0 || position < previous) { - errors.push(`${fileName}: ${reason}`); - return; - } - previous = position; - } - }; - - const ledger = 'docs/maintainers/current-batch-acceptance-ledger.md'; - requireText( - ledger, - 'Task-capture rule: a message prefixed with `task:`, `feature:`, `bug:`, or', - 'must preserve the tagged-prompt capture rule' - ); - requireText( - ledger, - 'Completed work belongs in Git history and release notes, not', - 'must remain an outstanding-work-only ledger' - ); - requireText( - ledger, - '## Hardcover-enriched Book search', - 'must retain the future Hardcover Book-search integration' - ); - requireText( - '.dockerignore', - '.npmrc', - 'the Docker context must exclude the root npm credential file' - ); - rejectText( - '.dockerignore', - '!/.npmrc', - 'the Docker context must not re-include host package-manager configuration' - ); - requireText( - 'Dockerfile', - 'pnpm --config.engine-strict=true install --prod --frozen-lockfile', - 'production dependency installation must keep strict engine checks without copying .npmrc' - ); - requireText( - 'Dockerfile', - 'pnpm --config.engine-strict=true install --frozen-lockfile', - 'build dependency installation must keep strict engine checks without copying .npmrc' - ); - rejectText( - 'Dockerfile', - '.npmrc', - 'the Dockerfile must not copy host package-manager configuration' - ); - requireText( - '.dockerignore', - 'docs/*', - 'the Docker context must exclude development-only documentation' - ); - requireText( - 'scripts/check-container-security.test.mjs', - 'the production build does not require development-only contracts', - 'the container security test must verify production builds exclude development-only contracts' - ); - requireText( - ledger, - "Sonarr's generic Series rating is never used or", - 'must preserve the evidence-based Series IMDb decision' - ); - requireText( - ledger, - '## Music artist page refresh', - 'must keep the music artist refresh deferred' - ); - requireText( - ledger, - '## Pinned Cast, Crew, Artists, and Tags disclosures', - 'must retain the pinned media-detail disclosure feature' - ); - requireText( - ledger, - '## Series collections and franchise groups', - 'must retain the future Series collections feature' - ); - requireText( - ledger, - '## Deferred requested-Movie View Request refresh', - 'must retain the tagged View Request refresh as a deferred feature' - ); - requireText( - ledger, - '## Deferred media-detail action-row redesign', - 'must retain the tagged action-row redesign as a deferred feature' - ); - requireText( - ledger, - '## Collection request-page refresh and cross-media collections', - 'must retain the future cross-media Collection request work' - ); - requireText( - ledger, - '## Deferred refresh of pages not yet redesigned', - 'must retain the deferred-page refresh inventory' - ); - requireText( - ledger, - '## Keith-requested feature', - 'must retain the pending Keith feature intake' - ); - requireText( - ledger, - '## New v3.21.2 corrections', - 'must retain the pending v3.21.2 correction intake' - ); - requireText( - ledger, - '### Poster overlay alignment', - 'must retain the poster overlay alignment task' - ); - requireText( - ledger, - '### Poster overlay shadows', - 'must retain the poster overlay shadow task' - ); - requireText( - ledger, - '### Main-menu cleanup', - 'must retain the main-menu cleanup task' - ); - const navigationModel = 'src/components/Layout/Sidebar/navigation.tsx'; - requireCount( - navigationModel, - "href: '/discover/audiobooks'", - 1, - 'primary navigation must contain exactly one Audiobooks entry' - ); - requireCount( - navigationModel, - "href: '/requests'", - 1, - 'primary navigation must retain exactly one main Requests entry' - ); - rejectText( - navigationModel, - "href: '/requests/status'", - 'primary navigation must not contain the removed Request Status entry' - ); - for (const navigationConsumer of [ - 'src/components/Layout/Sidebar/index.tsx', - 'src/components/Layout/MobileMenu/index.tsx', - ]) { - requireText( - navigationConsumer, - "from '@app/components/Layout/Sidebar/navigation'", - 'desktop and mobile menus must render the same shared navigation model' - ); - } - requireText( - navigationModel, - "users: 'User List',", - 'the shared desktop and mobile main-menu label must read User List' - ); - rejectText( - navigationModel, - "users: 'Users',", - 'the main-menu label must not revert to Users' - ); - requireText( - 'src/styles/globals.css', - 'background-color: transparent !important;', - 'compact discovery selectors must override the white third-party control surface' - ); - for (const [fileName, tokens] of [ - ['src/components/Discover/FilterPanel/index.tsx', ['sortBy: undefined,']], - [ - 'src/components/Discover/DiscoverBooks/index.tsx', - ['sortBy !== defaultSortBy', 'sortBy: undefined,'], - ], - [ - 'src/components/Discover/DiscoverMusic/index.tsx', - ["sortBy !== 'ranked'", 'sortBy: undefined,'], - ], - [ - 'src/components/Blocklist/index.tsx', - ["setSort('date');", "setSortDirection('desc');"], - ], - [ - 'src/components/IssueList/index.tsx', - ["setSort('added');", "setDirection('desc');"], - ], - [ - 'src/components/Requests/index.tsx', - ["setSort('added');", "setSortDirection('desc');"], - ], - [ - 'src/components/Search/index.tsx', - ['query: { query: query || undefined }'], - ], - ]) { - for (const token of tokens) { - requireText( - fileName, - token, - 'Clear Filters must restore the default sort order on every filtered page' - ); - } - } - rejectText( - ledger, - '## Keith v3.20.2 upstream integration', - 'must not list completed release integration work' - ); - rejectText( - ledger, - '## Final visual-correction batch before laptop preview', - 'must not list completed visual-correction work' - ); - requireText( - 'docs/maintainers/ui-style-standard.md', - 'Filter section controls sit above the section they control, with shared spacing and wrapping.', - 'the style standard must govern filter section placement and wrapping' - ); - requireText( - 'docs/maintainers/ui-style-standard.md', - 'Keep media/context/state filters distinct.', - 'the style standard must distinguish media, context, and state filter roles' - ); - requireText( - 'docs/maintainers/ui-style-standard.md', - 'Clearing must clear both pending/debounced and active state', - 'the style standard must govern truthful filter reset behavior' - ); - requireText( - 'docs/maintainers/ui-style-standard.md', - 'UI actions and count/status displays must reflect real eligibility and permissions.', - 'the style standard must preserve truthful status and action eligibility' - ); - requireText( - 'docs/maintainers/ui-style-standard.md', - 'Status badges are classified by role and interaction', - 'the style standard must distinguish status presentation from actionable controls' - ); - requireText( - 'docs/maintainers/site-visual-audit-2026-09-11.md', - 'every rendered claim in this document is\nhistorical evidence from the laptop r3 image created at 2026-09-12 04:18:02 MDT', - 'the historical visual audit must not claim current render evidence for post-r3 source' - ); - - requireOrder( - 'src/components/Requests/index.tsx', - [ - "key: 'all'", - "key: 'completed'", - "key: 'incomplete'", - "key: 'active'", - "key: 'attention'", - "key: 'unavailable'", - "key: 'failed'", - ], - 'Request Status task summaries must retain the approved single-row order' - ); - for (const fileName of [ - 'src/components/RequestModal/MovieRequestModal.tsx', - 'src/components/RequestModal/MusicRequestModal.tsx', - 'src/components/RequestModal/BookRequestModal.tsx', - ]) { - requireOrder( - fileName, - ['{intl.formatMessage(messages.approval)}:', ' void onClickHideItemBtn()}', - 'poster/title cards must not mutate the Blocklist before confirmation' - ); - - const visibleTerminologyFiles = Object.keys(files).filter( - (fileName) => - (fileName.startsWith('src/components/') || - fileName === 'src/i18n/globalMessages.ts' || - fileName === 'src/i18n/locale/en.json') && - fileName !== 'src/components/RequestModal/AdvancedRequester/index.tsx' - ); - for (const fileName of visibleTerminologyFiles) { - const sourceWithoutServiceNames = requireFile(fileName).replaceAll( - 'Bookshelf-Ebook', - '' - ); - if (/\bEbooks?\b/.test(sourceWithoutServiceNames)) { - errors.push( - `${fileName}: user-visible Ebook terminology must be Book; configured service names are the only exception` - ); - } - } - requireText( - 'src/i18n/globalMessages.ts', - "ebookAndAudiobook: 'Book + Audiobook'", - 'shared format labels must use Book terminology' - ); - requireText( - 'src/components/Search/index.tsx', - "ebooks: 'Books'", - 'Search must label the ebook-format filter as Books' - ); - requireOrder( - 'src/components/Search/index.tsx', - [ - 'intl.formatMessage(messages.mediaFilters)', - '{visibleSearchCategories.map', - 'intl.formatMessage(messages.filter)', - 'Status:', - 'association detail cards must not repeat a separate Status heading or value' - ); - requireText( - 'src/components/Association/AssociationDetailCard.tsx', - 'onSelect?: () => void;', - 'the shared association detail card must expose one navigation-close callback' - ); - requireCount( - 'src/components/Association/AssociationDetailCard.tsx', - 'onClick={onSelect}', - 2, - 'both the association poster and title links must invoke the shared navigation-close callback' - ); - requireCount( - 'src/components/Association/AssociationPopover.tsx', - 'onSelect={onSelect}', - 2, - 'every Associations popup result group must pass through the navigation-close callback' - ); - requireText( - 'src/components/Association/AssociationBadge.tsx', - 'onSelect={() => setIsOpen(false)}', - 'selecting an Associations popup result must close the popup as navigation begins' - ); - requireText( - 'src/components/CollectionDetails/CollectionAssociationsButton.tsx', - 'onSelect={() => setShow(false)}', - 'collection association links must close their popup as navigation begins' - ); - requireText( - 'src/components/Association/AssociationWall.tsx', - '', - ], - 'pending bell and processing timer badges must explain their meaning in tooltips' - ); - requireText( - 'src/components/Common/StatusBadgeMini/index.tsx', - ': `poster-control ${tone}`', - 'poster quality states must match the rounded media-type badge silhouette' - ); - requireCssRule( - '.poster-control.poster-control-processing', - [ - 'border-color: color-mix(in srgb, var(--palette-blue) 90%, transparent);', - 'var(--poster-control-background-opacity)', - ], - 'processing timer badges must preserve the shared poster opacity and blue palette' - ); - requireCssRule( - '.poster-control.poster-control-pending', - [ - 'border-color: color-mix(in srgb, var(--palette-yellow) 90%, transparent);', - 'var(--poster-control-background-opacity)', - ], - 'pending bell badges must preserve the shared poster opacity and yellow palette' - ); - requireCssRule( - '.poster-control.poster-control-available', - [ - 'border-color: color-mix(in srgb, var(--palette-green) 90%, transparent);', - 'var(--poster-control-background-opacity)', - ], - 'available quality badges must use the shared poster opacity and green palette' - ); - rejectText( - 'src/components/Common/StatusBadgeMini/index.tsx', - 'bg-green-700/70', - 'poster availability badges must not restore the former opaque surface' - ); - for (const [fileName, token, description] of [ - [ - 'src/components/Common/MediaTypeBadge/index.tsx', - "card: 'poster-control media-type-badge-card'", - 'media-type poster badges must consume the shared poster-control surface', - ], - [ - 'src/components/Common/BookFormatBadge/index.tsx', - "card: 'poster-control poster-control-book-format media-type-badge-width'", - 'book-format poster badges must consume the shared poster-control surface', - ], - [ - 'src/components/Common/Badge/index.tsx', - 'bg-indigo-500/35', - 'shared badges must use the shared button resting transparency', - ], - ]) { - requireText(fileName, token, description); - } - requireOrder( - 'src/components/Common/StatusBadgeMini/index.tsx', - [ - 'data-testid="poster-quality-status-badge"', - '{quality}', - '