diff --git a/.agents/plans/eject-prototype-migration.md b/.agents/plans/eject-prototype-migration.md deleted file mode 100644 index 33686ffeef..0000000000 --- a/.agents/plans/eject-prototype-migration.md +++ /dev/null @@ -1,35 +0,0 @@ -# Eject prototype migration - -Prototype reference: PR #1696 at `compiler-prototype` (`b44e532c796d69832190c1ca9aa8886e04be960c`). - -This table is the temporary path-level ledger for moving the prototype into focused stacked PRs. Paths are restored or recreated intentionally; the prototype commit stack is not cherry-picked. - -| Prototype path or area | Destination | Issue | First-pass disposition | -| --- | --- | --- | --- | -| `packages/compiler/src/{compile,config,diagnostics,load-config,parse,project,transform}.ts` | PR 1: `eject/01-compiler-foundation` | #1957 | Reuse and adapt as the generic compiler API. | -| `packages/compiler/src/transforms/**` | PR 1: `eject/01-compiler-foundation` | #1957 | Reuse import rewriting and generic cleanup transforms with focused tests. | -| `packages/compiler/src/jsx/**` | PR 1: `eject/01-compiler-foundation` | #1957 | Reuse generic TypeScript-JSX matchers/transforms; keep free of Video.js component semantics. | -| `packages/compiler/src/bundlers/**` | PR 1: `eject/01-compiler-foundation` | #1957 | Reuse the generic Vite adapter and tests. | -| `packages/compiler/{package.json,tsconfig.json,tsdown.config.ts,vitest.config.ts}` plus root workspace references | PR 1: `eject/01-compiler-foundation` | #1957 | Recreate minimal private-package wiring; remove the prototype `vjs` bin and defer style/Tailwind entry points. | -| `packages/compiler/src/cli.ts` and `src/tests/cli.test.ts` | Deferred to public CLI integration | #1974, #1975 | Do not migrate into the compiler foundation; `@videojs/cli` owns `vjs`. | -| `packages/compiler/src/styles/**` | PR 5 target/style output | #1963, #1964 | Defer semantic style analysis until component style ownership is established. | -| `packages/compiler/src/tailwind/**` | PR 5 target/style output | #1962 | Defer Tailwind generation from the generic foundation boundary. | -| `packages/core/src/jsx-runtime.ts`, `jsx-dev-runtime.ts`, `components.config.js`, `scripts/generate-components.ts`, and `src/core/ui/**/*-component.ts` | PR 2: `eject/02-canonical-source` | #1953 | Reuse constrained JSX, manifest generation, compound-part typing, `Slot`, and `Text` after reconciling against current Core. | -| `internal/decisions/constrained-jsx-boundaries.md` | PR 2: `eject/02-canonical-source` | #1953 | Restore only if source and tests still support every recorded decision. | -| `packages/skins/src/default/video.skin.tsx` and `packages/skins/src/index.ts` | PR 3/5 canonical ownership and core Skin source | #1955, #1967, #1968, #1969 | Split the monolith into installable domain components and Skin composition; do not restore as one final artifact. Stage authored source under isolated `packages/skins/canonical/` while current packaged assets remain the runtime baseline. | -| `packages/skins/package.json`, `tsconfig.json`, `tsdown.config.ts` | PR 3: `eject/03-canonical-skins` | #1953, #1955 | Add only canonical authoring dependencies and validation; keep the existing `src` build and exports unchanged. | -| `packages/skins/src/**/{css,tailwind}/**` and prototype `packages/skins/__old__/**` | PR 5/6 style source and output | #1964, #1965, #1962, #1963 | Use as migration evidence; do not restore parked or generated layouts wholesale. | -| Future `packages/skins/artifacts.ts` plus dependency analysis/output model | PR 4: `eject/04-artifact-graph` | #1958, #1959 | Implement after the canonical workspace boundary is reviewed; keep it out of the canonical-source PR. | -| `packages/react/skins.compiler.config.ts` | PR 5 React output | #1960 | Reuse target-specific transforms after canonical component boundaries settle. | -| `packages/react/src/presets/video/__generated__/**` | Later generated package/parity PR | #1972, #1973 | Regenerate from the production graph; never copy prototype output as authored source. | -| Prototype HTML Skin/template edits | PR 5 HTML output | #1961 | Use as parity evidence; create idiomatic light-DOM output with exact registrations rather than restoring flattened generated files. | -| `packages/icons/components.config.js`, `scripts/build.ts`, generated icon families, and manifest/export changes | Focused icon contract before icon-bearing source | #1956 | Reconcile with current icon sources without importing private cross-package build scripts; publish stable exports before source-owned output depends on them. | -| Registry adapter/catalog (not implemented as a clean prototype boundary) | PR 6 registry and parity | #1966, #1970, #1971 | Implement outside compiler core from the artifact graph. | -| Existing `apps/e2e/tests/visual/*-skin.spec.ts` and current ejected-Skin fixtures | Later parity PR | #1972, #1973 | Extend the existing harness; do not create a second parity system. | - -## Stack guardrails - -- PR 1 contains no Video.js component names, canonical Skin source, shadcn registry types, public `vjs` binary, Tailwind/CSS generation, or large generated output changes. -- PR 2 contains constrained JSX/manifests only, with no Skin workspace ownership, artifact graph, registry files, or target output. -- PR 3 adds isolated canonical Skin ownership without moving or replacing the current packaged `packages/skins/src` assets. -- Do not begin `eject/04-artifact-graph` until the canonical workspace boundary is reviewed. diff --git a/.claude/plans/moq-engine-implementation.md b/.agents/plans/moq-engine-implementation.md similarity index 100% rename from .claude/plans/moq-engine-implementation.md rename to .agents/plans/moq-engine-implementation.md diff --git a/.agents/skills/configure-vite-plus/SKILL.md b/.agents/skills/configure-vite-plus/SKILL.md new file mode 100644 index 0000000000..0a768f1711 --- /dev/null +++ b/.agents/skills/configure-vite-plus/SKILL.md @@ -0,0 +1,47 @@ +--- +name: configure-vite-plus +description: Configure Vite+. Use for tasks, cache, migration, or CI. +--- + +# Configure Vite+ workflows + +Inspect the installed `vite-plus` version, root and owning-package manifests and `vite.config.ts` files, `build/pack.ts`, relevant CI workflows, and the command's current clean-run behavior before editing. Use `pnpm exec vp --help` and installed types when they differ from online documentation. + +Read [references/official-guide.md](references/official-guide.md) only for the sections that match the work: task graphs, cache diagnosis, GitHub Actions cache, Pack, or migration. + +## Workflow + +1. Classify each operation: `vp build` for applications, `vp pack` for libraries, and `vp run` for orchestration and caching. Invoke a script or configured task as `vp run `; bare `vp ` selects a built-in command. +2. Preserve build boundaries. Keep historically separate packaging workflows in separate Vite+ configs unless they are genuinely variants of one build. A named `pack` array supports `vp pack --filter ` within one workflow; a nested `vite.config.ts` supports an independent workflow via `vp -C pack`. +3. Define ordering in `run.tasks`, not in serial shell pipelines. Every configured task needs `command` and cannot duplicate a same-named `package.json` script. Use `{ task: 'build', from: ['dependencies', 'devDependencies'] }` for declared direct workspace edges and `package#task` for synthetic edges such as generated CDN assets. `-r` selects workspace tasks; it does not replace missing task dependencies. +4. Let the graph expose independent work to Vite+'s scheduler. Do not lower concurrency to repair missing edges. Reserve `--parallel`, which ignores dependencies, for independent persistent tasks such as development servers. +5. Keep root scripts as thin selectors. Put package-specific commands, inputs, outputs, environment, and dependencies in the owning package's config. +6. Prove local cache stability before configuring cross-run cache. Only `vp run` uses Vite Task caching. Run the exact task twice and require the second run to hit. Prefer automatic tracking, then add `input`, `output`, `env`, or `untrackedEnv` only from observed misses. Avoid generators that rewrite unchanged inputs. +7. In GitHub Actions, install first, restore `node_modules/.vite/task-cache`, run the same `vp run` tasks used locally, and save only after success. Keep source and lockfile hashes out of the Actions cache key because Vite Task fingerprints task inputs. + +## Repository gotchas + +- Reuse packaging defaults from `build/pack.ts`; keep package entries, platform, and exceptional plugins local. +- Top-level Vite `resolve.alias` and Pack's `pack.alias` serve different consumers. Do not assume one configures the other; share alias constants when both commands need identical mappings and test both paths. +- Vite+ loads a package config before it can schedule that package's dependencies. Config-time imports from private workspace packages must be available without relying on their built output. +- `vp pack` uses file-system cache tracking rather than `vp build`'s cooperative Vite metadata. Diagnose its observed reads and writes before adding manual globs. + +## Example + +Input: The sandbox build consumes normal workspace packages and generated HTML CDN files. + +Output: A configured build task with declared workspace and generated-artifact dependencies. + +```ts +build: { + command: 'vp build', + dependsOn: [ + { task: 'build', from: ['dependencies', 'devDependencies'] }, + '@videojs/html#build:cdn', + ], +} +``` + +## Validation + +Run the narrow target from a clean output state, inspect `vp run -v` ordering, and run it immediately again to verify cache hits and restored outputs. Then run the affected package tests/build, `pnpm typecheck` when types or configs changed, and `pnpm check:workspace`. For CI changes, verify restore occurs after install, save uses the restore step's primary key, and logs show both an Actions cache restore and Vite Task cache hits. diff --git a/.agents/skills/configure-vite-plus/references/official-guide.md b/.agents/skills/configure-vite-plus/references/official-guide.md new file mode 100644 index 0000000000..52999cb2d5 --- /dev/null +++ b/.agents/skills/configure-vite-plus/references/official-guide.md @@ -0,0 +1,32 @@ +# Official Vite+ reading map + +Use the smallest relevant section. The repository's installed version, CLI help, and types remain the executable source of truth when the evolving documentation differs. + +## Run task definitions and workspace ordering + +Read the [Run guide](https://viteplus.dev/guide/run) and [Run configuration](https://viteplus.dev/config/run) before adding or changing tasks. Read the [monorepo guide](https://viteplus.dev/guide/monorepo) when package selection or workspace topology changes. + +Verify these details against the installed version: + +- A task name may be defined in `vite.config.ts` or `package.json`, not both. +- `package#task` names an exact cross-package edge. The object `dependsOn` form expands a task over the declaring package's chosen dependency fields. +- Recursive and transitive selection derive ordering from normal workspace `dependencies`; selection flags do not infer exceptional artifact relationships. +- Normal execution preserves dependency ordering and runs independent work concurrently. `--parallel` deliberately ignores task dependencies. + +## Local caching and unstable tracking + +Read [Task Caching](https://viteplus.dev/guide/cache), [Automatic Data Tracking](https://viteplus.dev/guide/automatic-data-tracking), and the `input`, `output`, `env`, and `untrackedEnv` sections of [Run configuration](https://viteplus.dev/config/run). + +Start with automatic tracking. Add `{ auto: true }` plus exclusions when a generated output was incorrectly observed as an input. Use workspace-based pattern objects for files outside the task's package. Replace automatic inputs with explicit globs only when the complete input set is known. Remember that only `vp build` currently supplies cooperative Vite metadata; other commands rely on file-system observations unless configured manually. + +## GitHub Actions cache + +Read the experimental [GitHub Actions cache guide](https://viteplus.dev/guide/github-actions-cache) before changing a workflow. + +The documented order is install, restore, `vp run` tasks, then save on success. The cache directory is `node_modules/.vite/task-cache`. Use an immutable primary key containing OS, architecture, run ID, and attempt, with an OS/architecture restore prefix. Do not add source hashes to the Actions key. Confirm an immediate local second run hits before expecting a restored CI cache to hit, and measure whether transfer overhead is worthwhile. + +## Pack and migrations + +Read [Pack](https://viteplus.dev/guide/pack) and [Pack configuration](https://viteplus.dev/config/pack) before changing a library build. Consult the linked tsdown documentation for Pack-only options. Read [Migrate to Vite+](https://viteplus.dev/guide/migrate) and [Migration Rules](https://viteplus.dev/guide/migrate-rules) when replacing another tool rather than maintaining the resulting setup. + +`vp pack` reads its tsdown settings from the active `vite.config.ts` `pack` block. Use a `name` plus `--filter` for related configs loaded together. Use the global `-C ` option when a deliberately separate config lives in its own directory. diff --git a/.agents/skills/create-html-component/SKILL.md b/.agents/skills/create-html-component/SKILL.md index 9293788806..b6fe89541c 100644 --- a/.agents/skills/create-html-component/SKILL.md +++ b/.agents/skills/create-html-component/SKILL.md @@ -11,14 +11,14 @@ Read the relevant core contract, nearest HTML element and tests, definition entr 1. Classify the request as a reusable primitive or app/skin composition before defining its contract. Then define the state owner, semantics, APIs, optional parts, styling contract, and opt-outs. 2. Put runtime-neutral state and actions in `packages/core/src/core/ui/`; put reusable DOM interaction in `packages/core/src/dom/ui/`; keep the element an adapter. -3. Match the nearest `MediaElement` or `MediaButtonElement` pattern. Send properties down and semantic events up; use controllers or context only across a real ownership boundary. +3. Match the nearest `UIElement` or `MediaButtonElement` pattern. Send properties down and semantic events up; use controllers or context only across a real ownership boundary. 4. Let `ReactiveElement` own rendered DOM updates: derive changes from reactive properties and controller state, then apply them through its update lifecycle. Avoid out-of-band mutations so scheduling, `updateComplete`, tests, and integrations remain authoritative. 5. Add markup for semantics, focus, content, or parts consumers must place, omit, or replace. Leave purely visual structure to skins, CSS, or pseudo-elements. If the API starts coordinating independent behavior, extract another element or controller instead of adding modes and options. 6. Expose discrete state through mapped `data-*` attributes and dynamic layout values through stable CSS custom properties. Define each token's owner, units, and fallback. Treat descendant selectors, `:has()`, and other complex selectors introduced by composition as a likely sign that the primitive boundary or styling hooks need improvement. 7. Keep the element class free of registration side effects. Register it with `safeDefine` under `packages/html/src/define/ui/`, update `HTMLElementTagNameMap`, and preserve narrow import and `sideEffects` boundaries. 8. Clean up subscriptions, observers, listeners, locks, and async work across disconnect and destroy. Add focused core and HTML tests; verify interaction in a browser when semantics, focus, or pointer behavior changes. -Check `packages/html/package.json` and `packages/html/tsdown.config.ts` when adding an entrypoint or registration module. Run the narrow package tests and build; build changed exported types before repository typechecking. +Check `packages/html/package.json` and `packages/html/vite.config.ts` when adding an entrypoint or registration module. Run the narrow package tests and build; build changed exported types before repository typechecking. ## Example diff --git a/.agents/skills/create-react-component/SKILL.md b/.agents/skills/create-react-component/SKILL.md index 4496b6f8f7..fab7785a21 100644 --- a/.agents/skills/create-react-component/SKILL.md +++ b/.agents/skills/create-react-component/SKILL.md @@ -16,9 +16,9 @@ Read the relevant core contract, nearest React component and tests, public expor 5. Add a compound part only for a semantic, focusable, placeable, omittable, or replaceable node. Keep context values narrow and scoped to the owning root; do not mirror derived state through effects. If the API starts coordinating independent behavior, extract another component or hook instead of adding modes and options. 6. Expose discrete state through mapped `data-*` attributes and dynamic layout values through stable CSS custom properties. Leave visual defaults to skins and CSS. Treat descendant selectors, `:has()`, and other complex selectors introduced by composition as a likely sign that the primitive boundary or styling hooks need improvement. 7. Preserve the default semantic element while allowing deliberate replacement through `render`. Ensure omitted parts and unsupported features do not leave hidden behavior or required markup behind. -8. Export compound APIs as tree-shakeable ESM namespaces with `export * as Name from './index.parts'`; keep parts as direct re-exports and do not assemble a runtime namespace object. Avoid pulling optional dependencies into unrelated imports. Add focused tests for rendered behavior, ref/prop composition, context boundaries, and customization. +8. Export compound APIs as tree-shakeable ESM namespaces with `export * as Name from './index.parts'`; keep parts as direct re-exports and do not assemble a runtime namespace object. When a compound specializes another compound, re-export unchanged base parts under the specialized namespace and create a specialized part only when its behavior or defaults differ. Avoid pulling optional dependencies into unrelated imports. Add focused tests for rendered behavior, ref/prop composition, context boundaries, and customization. -Use `packages/react/src/ui/create-media-button.tsx`, `packages/react/src/utils/use-render.tsx`, and `packages/react/src/ui/slider/index.parts.ts` as implementation anchors. Check `packages/react/package.json` and `packages/react/tsdown.config.ts` when the public or bundle boundary changes. +Use `packages/react/src/ui/create-media-button.tsx`, `packages/react/src/utils/use-render.tsx`, and `packages/react/src/ui/slider/index.parts.ts` as implementation anchors. Check `packages/react/package.json` and `packages/react/vite.config.ts` when the public or bundle boundary changes. ## Example diff --git a/.agents/skills/create-rolldown-plugin/SKILL.md b/.agents/skills/create-rolldown-plugin/SKILL.md new file mode 100644 index 0000000000..d95f6ee3ee --- /dev/null +++ b/.agents/skills/create-rolldown-plugin/SKILL.md @@ -0,0 +1,34 @@ +--- +name: create-rolldown-plugin +description: Create Rolldown plugins. Use for hooks. +--- + +# Rolldown plugin implementation + +Inspect the installed Rolldown version, relevant package config and exports, neighboring plugins, and host-level tests before choosing hooks. Prefer a Rolldown plugin when the behavior is about modules or build output rather than Vite configuration, HTML, the dev server, or HMR. + +## Workflow + +1. Define the host contract first: selected modules, source shape entering and leaving each hook, virtual IDs, graph information required, output ownership, watch inputs, and whether the plugin is safe in ordinary application builds or only a dedicated build. Use `transform` for source-module semantics and `renderChunk` only when the edit depends on final generated chunks or output options. +2. Let Rolldown own resolution, traversal, ordering, caching, watching, and output. Use `this.resolve`, normal graph entries, `this.addWatchFile`, and `this.emitFile`; do not invoke another compiler plugin directly or start a nested build to simulate the host graph. +3. Use host-native object hook filters for `resolveId`, `load`, and `transform`. Keep a matching handler guard only when compatibility with hosts lacking the filter is intentional and tested. Normalize query-bearing IDs without dropping parameters that distinguish transformed module identities. +4. Keep virtual modules private unless consumers genuinely import them. Prefix internal IDs with `\0`, resolve them explicitly, return the correct `moduleType`, and add every non-imported source dependency as a watch file. +5. Keep mutable state per plugin instance and reset build-derived state in `buildStart`. Prefer module `meta` for JSON-serializable information that must survive later transforms or host caching; namespace it and explicitly merge updates within that namespace because hook results merge `meta` only one level deep. Read graph-wide information no earlier than `buildEnd` unless the hook contract guarantees completeness. +6. Extend existing input rather than replacing it. Use `packages/vjsc/src/plugins/input.ts` in VJSC. Remember that an `options()` result does not deep-merge `input`, while an emitted chunk follows chunk naming unless `fileName` is forced. +7. Emit generated output with `this.emitFile`. Do not write staging source. Never delete unrelated chunks or assets; complete bundle replacement is valid only for an explicitly asset-only build with tests proving the boundary. +8. When `transform` or `renderChunk` consumes host-provided `magicString`, explicitly enable `experimental.nativeMagicString: true` in the owning Rolldown input config. In tsdown, configure it under `inputOptions.experimental`. Return the native object rather than stringifying it so Rolldown can compose maps, enable output `sourcemap` when consumers need emitted maps, and fail clearly if a repository-owned host violates this contract. Reserve JavaScript fallbacks for intentional compatibility adapters. +9. Test through real Rolldown builds. Cover existing entries, virtual resolution and module type, filters, query identities, static/dynamic/type-only dependencies, graph timing, watched inputs, rebuild state, output names/content, and path or name collisions. + +Read [references/api-and-host-contracts.md](references/api-and-host-contracts.md) when the plugin uses virtual entries, graph inspection, editable source capture, inter-plugin communication, declarations, or output replacement. + +Use `packages/vjsc/src/plugins/vjsc.ts` as the transform-pipeline anchor, `packages/vjsc/src/plugins/component-schema.ts` for virtual package entries and declaration-aware hosts, and `packages/vjsc/src/plugins/shadcn.ts` for a dedicated asset build. + +## Validation + +Run the narrow plugin tests, the owning package build, host-consumer tests, `pnpm typecheck`, and `pnpm check:workspace`. If the plugin claims Vite compatibility, exercise the same contract through both Rolldown and Vite rather than relying on structural types alone. + +## Example + +Input: “Create a build plugin that publishes transformed component metadata as JSON.” + +Output: One Rolldown plugin that loads components through the host graph, retains namespaced metadata, assembles complete graph data at the proper hook, watches discovery inputs, emits JSON assets, preserves unrelated output, and has direct Rolldown plus host-compatibility tests. diff --git a/.agents/skills/create-rolldown-plugin/references/api-and-host-contracts.md b/.agents/skills/create-rolldown-plugin/references/api-and-host-contracts.md new file mode 100644 index 0000000000..d445d11234 --- /dev/null +++ b/.agents/skills/create-rolldown-plugin/references/api-and-host-contracts.md @@ -0,0 +1,56 @@ +# Rolldown API and host contracts + +Read this reference only for graph-sensitive, virtual-module, inter-plugin, declaration, or output-producing plugins. + +## Current sources + +- Installed types are authoritative for the repository version: `node_modules/rolldown/dist/index.d.mts` and its referenced declarations. +- Official overview: +- Hook filters: +- Source transformations: +- Inter-plugin communication: +- Plugin interface: +- Plugin context and graph/output methods: +- Module types: +- Native MagicString: + +Recheck both installed types and official documentation when the dependency changes. Rolldown is evolving quickly, and a documented current behavior may not exist in the pinned runtime. + +## Hook and graph rules + +- `options` receives and may return the whole input-options object. Spreading the object preserves top-level properties, but assigning `input` replaces that property. Normalize `string | string[] | Record` deliberately and reject named-entry collisions. +- `buildStart` sees normalized options after all `options` hooks. It is the right place to reset state, discover build inputs, register watches, and emit additional graph entries. +- `resolveId`, `load`, and `transform` participate in the host graph. Return `null` to defer. When recursively resolving from `resolveId`, pass relevant resolve options and `skipSelf: true`. +- Prefer native hook filters. String ID filters are globs; regular expressions are tested against normalized separators. Composable `@rolldown/pluginutils` filters are Rolldown-only unless the target Vite version explicitly supports them. +- Returning `moduleType` lets the host route TS, TSX, CSS, JSON, and other source correctly. A module-type change does not restart the earlier transform chain, so type-changing plugins belong early. +- `ModuleInfo` becomes progressively complete. Use `moduleParsed` or `buildEnd` for resolved dependencies and `buildEnd` for final `isEntry`, importers, and graph ownership. +- `importedIds` and `dynamicallyImportedIds` represent runtime graph edges. Type-only imports are erased before the runtime graph and require analysis of retained editable source followed by `this.resolve` for identity. Resolution alone does not guarantee the target was loaded. +- Module `meta` is the stable handoff for source or annotations needed after later transforms. Namespace it, such as `meta.vjsc`, and do not replace the entire metadata object. + +## Inter-plugin communication + +- Pass context for a manual `this.resolve` call through `custom`, keyed by the receiving plugin's name. Prefer this to encoding plugin-only state in proxy IDs or query strings. +- Module `meta` must be JSON-serializable because Rolldown may persist it in the watch cache. Results from `resolveId`, `load`, and `transform` are shallow-merged: a later value replaces an earlier value under the same top-level key. Read the current namespace and merge its nested fields explicitly when several hooks or plugins contribute to it. +- Use a plugin object's `api` property for direct coordination that does not belong to resolution or module metadata. Discover the provider from normalized `plugins` in `buildStart`, fail clearly when a required provider is absent, and keep the dependency optional when the consumer can operate independently. +- Module `description` and plugin `meta` are descriptive tooling metadata, not communication state. Add a human-readable description for opaque virtual modules; package metadata is useful when a published package exposes several plugins. + +## Repository-proven constraints + +- In the pinned Rolldown 1.2.x hosts, a build-start `this.load({ resolveDependencies: true })` did not reliably populate an otherwise unreachable graph. Use a real configured or emitted entry and prove traversal in both direct Rolldown and Vite tests before depending on it. +- Explicitly enable `experimental.nativeMagicString: true` in repository-owned Rolldown input configs that run MagicString transforms; tsdown places Rolldown input options under `inputOptions`. Do not rely on an observed default from the pinned runtime. +- An emitted chunk without `fileName` follows `output.chunkFileNames`, not `entryFileNames`. Add a named input when package exports require entry naming; emit a chunk when graph inclusion matters and chunk naming is acceptable. +- Treat a full query-bearing resolved ID as module identity. Keep the physical filename separately. Stripping queries cross-wires multiple transformations of the same source file. +- Capture editable transformed source before runtime JSX lowering. Later `ModuleInfo.code` is host-dependent; namespaced transform metadata is the portable handoff. +- Discovery globs need watches for both matched files and a containing directory so add/remove events rebuild. Watch each additional source at the hook that consumes it. +- Mutable maps belong to one plugin instance and one build lifecycle. Clear them on rebuild. Do not reuse a stateful instance across concurrent builds unless state is partitioned explicitly. +- tsdown declaration generation runs through a separate declaration program and may not discover a Rolldown-only virtual TypeScript entry. Keep declaration-entry wiring in an explicit tsdown adapter and verify the exact exported `.d.ts` path. + +## Output ownership + +- Prefer `transform` when an edit belongs to one source module, needs its Oxc AST or module type, or should participate in module-level caching and graph analysis. Prefer `renderChunk` when an edit depends on final chunk code, filename, format, or the rendered chunk graph. Do not use `generateBundle` for code transforms: it runs after hashes and source-map assets are produced. +- With native MagicString enabled, `renderChunk` receives a lazy `magicString` through its fourth metadata argument. Return that object directly after editing it. Repository-owned hosts should fail clearly if it is missing; only intentional compatibility adapters should retain a JavaScript fallback. +- If a `renderChunk` edit changes imports or exports, update the corresponding mutable chunk metadata. When native MagicString is unavailable by design, return a generated map; use `map: null` only for edits that do not move code and `{ mappings: '' }` only when meaningful mappings cannot be produced. +- Emit arbitrary content as assets. Use `originalFileName` for file-backed assets when useful so Rolldown can connect watching and metadata. +- `emitFile({ type: 'chunk', id })` creates an entry through the normal graph and may split or deduplicate chunks. +- If a private trigger creates helper chunks, track ownership precisely. Removing every JavaScript chunk is only safe for a dedicated asset-only build; otherwise preserve application entries and assets. +- Validate output paths after normalization, reject traversal and collisions, and test final emitted content rather than merely checking asset names. diff --git a/.agents/skills/create-vite-plugin/SKILL.md b/.agents/skills/create-vite-plugin/SKILL.md new file mode 100644 index 0000000000..b4933d796f --- /dev/null +++ b/.agents/skills/create-vite-plugin/SKILL.md @@ -0,0 +1,34 @@ +--- +name: create-vite-plugin +description: Create Vite plugins. Use for hooks. +--- + +# Vite plugin implementation + +Inspect the installed Vite and Rolldown versions, application config, neighboring plugins, and serve/build tests before implementing. Vite 8's `Plugin` extends Rolldown's `Plugin`; keep generic resolution, loading, transforms, graph work, and output in a Rolldown plugin and add a Vite layer only for Vite-specific behavior. + +## Workflow + +1. Classify the requirement. Use a Rolldown plugin directly for host-generic module/build behavior. Use a Vite plugin for `config`, environments, `configureServer`, HTML, HMR, preview, or behavior that intentionally differs between serve and build. +2. Decide activation explicitly. Use `apply: 'serve'` or `apply: 'build'` when only one command is valid. A generic build-only Rolldown plugin may instead live in `build.rolldownOptions.plugins`; do not initialize asset generation or destructive output logic during dev. +3. Enable `build.rolldownOptions.experimental.nativeMagicString: true` in repository-owned Vite builds and set `build.sourcemap: true` when production maps should be emitted. This affects Vite's production Rolldown build but does not add Rolldown AST or MagicString metadata to Vite transform hooks; use the VJSC Vite adapter for transforms that need it. +4. Use `enforce` only for a real Vite tier requirement. Prefer per-hook `order` for a specific Rolldown hook. Prove ordering with behavior tests rather than depending on array position. +5. Use `config` to return a partial Vite config that may be deeply merged. Do not attempt to inject plugins from that hook. Read final values in `configResolved`; keep environment-specific state out of global app hooks. +6. Treat resolve/load/transform hooks as per-environment. Use Vite's environment APIs or separate plugin instances when builds may run concurrently. Worker plugins must be created by `worker.plugins` and receive fresh instances. +7. Normalize paths before Vite-specific ID comparisons. For cross-host VJSC code, reuse package `src/utils` module-ID and path helpers instead of importing Vite utilities into the generic plugin. +8. Remember that aliases affect module resolution, not authored import text retained in generated source or JSON. Resolve dependencies through the host, then perform only the packaging rewrite required by the output format. +9. Test serve and build separately. Cover activation, resolved config, virtual modules, transform order, SSR/environment flags when relevant, HMR invalidation, HTML output, existing application entries, and emitted assets. + +Read [references/api-and-host-contracts.md](references/api-and-host-contracts.md) when choosing between a raw Rolldown plugin, `build.rolldownOptions.plugins`, a top-level Vite plugin, or an environment-aware plugin. + +Use `packages/vjsc/src/vite/index.ts` as the thin-adapter example, `packages/vjsc/src/plugins/tests` for direct Rolldown coverage, and `packages/skins/vjsc/tests/vite.test.ts` as the Vite host test anchor. + +## Validation + +Run focused programmatic Vite serve/build tests, the underlying Rolldown tests when shared, the owning package build, `pnpm typecheck`, and `pnpm check:workspace`. Avoid E2E coverage unless the requested behavior genuinely crosses the browser boundary. + +## Example + +Input: “Make this source transform available in Vite and rebuild when its config changes.” + +Output: A host-generic Rolldown transform reused by a thin Vite entry, Vite-only watch/config handling where needed, explicit serve/build activation, and tests proving identical transformed source through direct Rolldown and Vite. diff --git a/.agents/skills/create-vite-plugin/references/api-and-host-contracts.md b/.agents/skills/create-vite-plugin/references/api-and-host-contracts.md new file mode 100644 index 0000000000..095522ec59 --- /dev/null +++ b/.agents/skills/create-vite-plugin/references/api-and-host-contracts.md @@ -0,0 +1,62 @@ +# Vite API and host contracts + +Read this reference only when a plugin needs Vite lifecycle, environments, dev behavior, or build integration choices. + +## Current sources + +- Installed types are authoritative for the repository version: `node_modules/vite/dist/node/index.d.ts`. +- Official plugin API: +- Build and `build.rolldownOptions`: +- Production customization: +- Worker plugin lifecycle: +- Rolldown native MagicString: + +Recheck installed types alongside the documentation after Vite or Rolldown upgrades. Environment APIs and compatibility details continue to evolve. + +## Rolldown or Vite? + +Vite 8 declares `interface Plugin extends Rolldown.Plugin`. A raw Rolldown plugin is therefore the default for: + +- resolution, loading, and source transforms; +- module types, hook filters, module metadata, and graph inspection; +- build entries, chunks, assets, and watch files; +- behavior that should work in tsdown or direct Rolldown too. + +Use Vite's extended interface for: + +- root config and resolved config; +- command or mode selection; +- environment selection and environment-local state; +- dev or preview middleware; +- HTML transformation; +- HMR behavior. + +A build-only Rolldown plugin under `build.rolldownOptions.plugins` behaves like a Vite plugin with build-only, post-tier activation. Put it there when it should not participate in dev. Put it in top-level `plugins` when it must also transform served modules or needs Vite fields. + +Enable `build.rolldownOptions.experimental.nativeMagicString: true` for repository-owned Vite builds and `build.sourcemap: true` when final map files are required. In the pinned Vite 8.2.x host, transform hook options expose Vite fields but do not forward Rolldown's `ast` or `magicString`, whether a plugin is top-level or under `build.rolldownOptions.plugins`. The option still enables native MagicString in production output hooks such as `renderChunk`; it does not replace `packages/vjsc/src/vite/oxc.ts` for VJSC transforms in serve or build. + +## Ordering and lifecycle + +- `enforce: 'pre' | 'post'` moves the entire plugin into a Vite tier around core plugins. Rolldown object hooks can additionally set `order` for one hook. Use the narrowest ordering mechanism. +- `apply` gates by `serve` or `build`; a predicate can inspect raw config and command environment. `configResolved` sees the final config and is the better read-only source for later hooks. +- During dev, `options` and `buildStart` run when the plugin container starts, while `resolveId`, `load`, and `transform` run for requested modules. Output-generation hooks are build concerns. +- Vite resolve/load/transform hooks receive environment-specific extensions such as SSR context. Do not assume a single client graph when SSR, RSC, workers, or app builds are possible. +- App-level plugins and environment plugins have different lifecycles. Do not share mutable module maps across concurrent environments unless they are partitioned. Prefer fresh plugin instances; `worker.plugins` explicitly requires a factory for parallel worker builds. + +## Config and IDs + +- A Vite `config` hook may mutate config or return a deeply merged partial config, except that adding `plugins` there has no effect because plugins were already resolved. +- Rolldown's `options` hook has different semantics: returning an object manipulates/replaces input options, and assigning nested `input` replaces existing input. Do not transfer Vite config-merge assumptions to it. +- Vite normalizes resolved paths to POSIX separators. Use Vite's `normalizePath` only inside Vite-specific code. Cross-host plugins should own consistent module-ID parsing and normalization. +- Dev importers may reflect Vite's unbundled HTML request model and are not always equivalent to production importers. Pass hook options through when delegating to `this.resolve` and test both commands. +- Vite aliases select resolved modules but do not rewrite import strings preserved as editable source. Generated registries and source packages need an explicit, narrow import-packaging policy. + +## Testing matrix + +- Direct Rolldown test for the generic contract. +- Programmatic Vite build test for plugin ordering, source lowering, graph metadata, application entry preservation, and assets. +- Programmatic dev-server test when `apply: 'serve'`, middleware, HTML, module graph, or HMR is involved. +- Worker or multi-environment test only when the plugin claims that support. +- An assertion that build-only generation does not initialize during dev. + +Structural type compatibility is not enough. Tests should prove the source stage being captured, complete dependency identities, query propagation, and final emitted output under the actual pinned host. diff --git a/.agents/skills/document-spf-feature/SKILL.md b/.agents/skills/document-spf-feature/SKILL.md index 9162f8ec34..94aa7ff8e9 100644 --- a/.agents/skills/document-spf-feature/SKILL.md +++ b/.agents/skills/document-spf-feature/SKILL.md @@ -1,6 +1,6 @@ --- name: document-spf-feature -description: Create or update an SPF feature record only when the user explicitly requests it. Use for capability scope, status, evidence, constraints, or relationships under internal/design/spf/features. +description: Document an SPF feature record. Use when the user explicitly requests capability scope, relationships, status, constraints, or evidence. --- # Document an SPF feature diff --git a/.agents/skills/document-spf-use-case/SKILL.md b/.agents/skills/document-spf-use-case/SKILL.md index 540b28996f..433b0c61a2 100644 --- a/.agents/skills/document-spf-use-case/SKILL.md +++ b/.agents/skills/document-spf-use-case/SKILL.md @@ -1,6 +1,6 @@ --- name: document-spf-use-case -description: Create or update an SPF use-case record only when the user explicitly requests it. Use for delivery scenarios, variants, constituent features, status, constraints, or verification under internal/design/spf/use-cases. +description: Document an SPF use-case record. Use when the user explicitly requests delivery scenarios, variants, relationships, status, or verification. --- # Document an SPF use case diff --git a/.agents/skills/implement-ui-transition/SKILL.md b/.agents/skills/implement-ui-transition/SKILL.md index bd99b5a5d2..03d3b25389 100644 --- a/.agents/skills/implement-ui-transition/SKILL.md +++ b/.agents/skills/implement-ui-transition/SKILL.md @@ -1,6 +1,6 @@ --- name: implement-ui-transition -description: Implement or change Video.js UI transition and rendered-presence behavior. Use for open or close animation lifecycles, starting or ending data attributes, exit retention, cancellation, rapid reopen, or HTML and React parity. +description: Implement UI transitions and rendered presence. Use for lifecycle, cancellation, rapid reopen, or HTML/React parity. --- # UI transition implementation diff --git a/.agents/skills/maintain-vjsc-skin-gaps/SKILL.md b/.agents/skills/maintain-vjsc-skin-gaps/SKILL.md new file mode 100644 index 0000000000..0bc1e766be --- /dev/null +++ b/.agents/skills/maintain-vjsc-skin-gaps/SKILL.md @@ -0,0 +1,44 @@ +--- +name: maintain-vjsc-skin-gaps +description: Maintain VJSC parity gaps. Use when changing legacy skins under packages/skins/src. +--- + +# Track VJSC skin parity + +Keep `packages/skins/vjsc/gaps.md` synchronized with observable changes to the legacy skins. + +## Triggers + +- Changing behavior, markup, selectors, data attributes, tokens, responsive rules, motion, or styles under `packages/skins/src`. +- Fixing a legacy skin issue whose equivalent VJSC output may need the same fix. + +Do not use this workflow for VJSC-only work, documentation-only edits, or generated-output changes that do not alter legacy skin behavior. + +## Workflow + +1. Describe the observable legacy behavior being added or changed and identify the affected Default or Minimal skin. +2. Inspect the equivalent VJSC component, style rule, and generated HTML and React output. Similar names or classes are not evidence of parity. +3. If the same change implements VJSC parity, verify all affected targets and CSS or Tailwind outputs, then remove any obsolete gap. +4. Otherwise, add or update one entry in `packages/skins/vjsc/gaps.md` with `Source`, `Gap`, `Affected`, and `Recommendation` fields. Use the PR or commit when known; otherwise cite the changed legacy paths. +5. Avoid duplicates. Describe user-visible behavior rather than copying a raw diff, and remove the entry only after implementation and verification. + +## Example + +Input: A legacy skin change adds RTL control ordering without the equivalent VJSC rules. + +Output: Add or update this entry in `packages/skins/vjsc/gaps.md`: + +```md +## RTL control layout + +- Source: `caf179b83` / #2281 +- Gap: VJSC menus are directional, but control regions do not preserve legacy control order under `dir="rtl"`. +- Affected: Default and Minimal; HTML and React; CSS and Tailwind. +- Recommendation: Add directional layout rules and VJSC matrix coverage. +``` + +## Validation + +- Run the narrowest affected skin tests and refresh generated VJSC snapshots when output changes. +- Run `pnpm -F @videojs/skins test` for cross-target skin changes. +- Run `git diff --check`. diff --git a/.agents/skills/migrate-css-to-tailwind/references/migration.md b/.agents/skills/migrate-css-to-tailwind/references/migration.md index 7b46e7cd4e..b154f06809 100644 --- a/.agents/skills/migrate-css-to-tailwind/references/migration.md +++ b/.agents/skills/migrate-css-to-tailwind/references/migration.md @@ -36,15 +36,19 @@ Legacy **`tailwind.config.js`** theme spreads are not the primary path here—ex - `border-radius: 8px` → prefer `rounded-lg` (or a theme radius key) if equivalent/acceptable - `font-size`, `spacing`, `colors`, `shadow`, `z-index`, `radius` should map to **`@theme` or default v4 scales** when acceptable -### 3. Use Tailwind's `--spacing` scale +### 3. Keep Tailwind and skin spacing distinct -Tailwind v4 spacing utilities are based on the `--spacing` variable. Translate spacing calculations directly to native utilities: +Tailwind v4 spacing utilities are based on its `--spacing` variable. Translate site spacing calculations directly to native utilities: - `padding: calc(var(--spacing) * 2)` → `p-2` - `margin-inline: calc(var(--spacing) * 3)` → `mx-3` - `gap: var(--spacing)` → `gap-1` -Use built-in responsive or named container variants (`md:`, `@md:`, `@md/media-root:`) for media-query behavior. If a scoped design needs to scale all spacing, overriding `--spacing` at that scope is valid because native utilities inherit it. Ignore `--scale-unit` and `--size`; resolve font and icon sizes to rem values. +Use built-in responsive or named container variants (`md:`, `@md:`, `@md/media-root:`) for media-query behavior. + +In `packages/skins/src`, treat the skin container as a Tailwind theme boundary. Calculate the skin-owned `--media-spacing` from `--media-scale-unit` and `--media-scale`, then set `--spacing: var(--media-spacing)` on the container so native utilities respond to skin scaling without depending on the host's Tailwind configuration. The VJSC stylesheet performs the equivalent mapping at its isolated `@theme inline` boundary. + +Ignore legacy `--scale-unit` and `--size`; use the current `--media-*` tokens or resolve site font and icon sizes to rem values. For arbitrary values, Tailwind v4 also provides the build-time `--spacing(N)` function. Use it for literal spacing multipliers that do not map cleanly to a native utility: @@ -52,7 +56,7 @@ For arbitrary values, Tailwind v4 also provides the build-time `--spacing(N)` fu - `[--max-width:calc(var(--spacing)*44)]` → `[--max-width:--spacing(44)]` - `[bottom:calc(100% + var(--spacing) * 4.8)]` → `[bottom:calc(100%+--spacing(4.8))]` -`rounded-(--spacing(7))` is not the equivalent syntax: the parenthesized form is for a custom-property utility and would look for `var(--spacing(7))`. Keep `calc(var(--spacing) * var(...))` when the multiplier is runtime-derived because `--spacing()` only replaces literal values. +`rounded-(--spacing(7))` is not the equivalent syntax: the parenthesized form is for a custom-property utility and would look for `var(--spacing(7))`. Keep `calc(var(--spacing) * var(...))`, or `calc(var(--media-spacing) * var(...))` in skins, when the multiplier is runtime-derived because `--spacing()` only replaces literal values. ### 4. Handle site one-offs without arbitrary-value classes diff --git a/.agents/skills/review-html-component/SKILL.md b/.agents/skills/review-html-component/SKILL.md index c9b2a31429..14df895465 100644 --- a/.agents/skills/review-html-component/SKILL.md +++ b/.agents/skills/review-html-component/SKILL.md @@ -1,6 +1,6 @@ --- name: review-html-component -description: Review Video.js custom-element UI components without editing code. Use for HTML data flow, element boundaries, markup, styling APIs, transitions, rendered presence, opt-outs, registration, lifecycle, or bundle impact. +description: Review custom-element UI without editing code. Use for data flow, markup, styling, transitions, registration, or bundles. --- # HTML component review @@ -15,7 +15,7 @@ Read the implementation, core and DOM contracts, rendered semantics, tests, defi 6. Inspect registration and tree-shaking boundaries. Element classes should not self-register; `define/ui` modules should register narrowly through `safeDefine`; `package.json` and build entries must mark only real side effects. 7. Check connection, disconnection, destruction, upgrade behavior, transition presence and races, cleanup, accessibility, and platform tests. Verify interaction in a browser when focus, keyboard, pointer, timing, or rendered structure matters. -Use `packages/html/src/ui/play-button/`, `packages/html/src/ui/slider/`, `packages/html/src/define/ui/`, `packages/html/package.json`, and `packages/html/tsdown.config.ts` as comparison anchors. +Use `packages/html/src/ui/play-button/`, `packages/html/src/ui/slider/`, `packages/html/src/define/ui/`, `packages/html/package.json`, and `packages/html/vite.config.ts` as comparison anchors. Report findings by severity with the location, affected consumer, evidence, and smallest viable improvement. Separate correctness and contract gaps from optional trade-offs. diff --git a/.agents/skills/review-react-component/SKILL.md b/.agents/skills/review-react-component/SKILL.md index cafcbeec27..91ad1f8732 100644 --- a/.agents/skills/review-react-component/SKILL.md +++ b/.agents/skills/review-react-component/SKILL.md @@ -1,6 +1,6 @@ --- name: review-react-component -description: Review Video.js React UI components without editing code. Use for React data flow, component boundaries, compound APIs, render customization, styling APIs, transitions, rendered presence, opt-outs, exports, or bundle impact. +description: Review React UI without editing code. Use for data flow, APIs, customization, styling, transitions, or bundles. --- # React component review @@ -15,7 +15,7 @@ Read the implementation, core and DOM contracts, rendered semantics, tests, expo 6. Inspect imports, dependencies, re-exports, client boundaries, and production tree shaking. Compound APIs should use `export * as Name from './index.parts'` with direct part re-exports, not a runtime namespace object. Optional parts or integrations should not force unrelated code into a consumer bundle. 7. Check transition presence and races, cleanup, SSR behavior, accessibility, and tests for state flow, nested roots, prop/ref composition, rendered output, and customization. -Use `packages/react/src/ui/create-media-button.tsx`, `packages/react/src/utils/use-render.tsx`, `packages/react/src/ui/play-button/`, `packages/react/src/ui/slider/`, `packages/react/package.json`, and `packages/react/tsdown.config.ts` as comparison anchors. +Use `packages/react/src/ui/create-media-button.tsx`, `packages/react/src/utils/use-render.tsx`, `packages/react/src/ui/play-button/`, `packages/react/src/ui/slider/`, `packages/react/package.json`, and `packages/react/vite.config.ts` as comparison anchors. Report findings by severity with the location, affected consumer, evidence, and smallest viable improvement. Separate correctness and contract gaps from optional trade-offs. diff --git a/.agents/skills/transform-rolldown-code/SKILL.md b/.agents/skills/transform-rolldown-code/SKILL.md new file mode 100644 index 0000000000..af0021b734 --- /dev/null +++ b/.agents/skills/transform-rolldown-code/SKILL.md @@ -0,0 +1,95 @@ +--- +name: transform-rolldown-code +description: Transform code. Use for Rolldown. +--- + +# Rolldown code transforms + +Use the incoming Oxc AST for analysis and its paired MagicString for source edits. + +## Workflow + +1. Narrow modules with a native transform hook filter. Use a cheap `code.includes(...)` guard before accessing `meta.ast` so parsing stays lazy. +2. Access `meta.ast` only when syntax analysis is required. It is a read-only Oxc `Program` parsed according to `meta.moduleType` and supports JavaScript, JSX, TypeScript, and TSX syntax. +3. Use AST `start` and `end` offsets with `meta.magicString.overwrite`, `remove`, `appendLeft`, or related edits. Both values describe the same incoming `code` string. +4. Return the edited MagicString as `{ code: magicString }`. Edits are ignored when the hook does not return it. Return `null` when nothing changed. +5. Keep using offsets from the original hook input. The AST does not update after MagicString edits. Analyze generated syntax in a later transform pass or plugin when necessary. +6. Keep module-oriented edits in `transform`. Use `renderChunk` only when the replacement depends on final generated code, chunk filenames, output format, or the rendered chunk graph; never move ordinary AST transforms there. + +Treat `meta.ast` as read-only. Mutating its nodes does not change output because Rolldown does not print the modified JavaScript AST. + +The Oxc AST is syntactic. It includes TS and TSX nodes but has no TypeScript `Program`, `TypeChecker`, resolved symbols, inferred types, or cross-file semantics. + +For true AST-to-AST transforms, use an appropriate parser, transformer, and code generator, then return generated code with a source map. Every source-changing transform should provide a map unless it intentionally documents a `sourceMap: false` option; returning native MagicString provides one automatically. Use `map: null` only when the edit does not move code. + +Treat `meta.ast` and `meta.magicString` as a required contract in repository-owned Rolldown builds and fail clearly when either is unexpectedly unavailable. Only synthesize or guard the metadata in an intentional compatibility adapter, such as the Vite adapter. + +## Host setup + +Explicitly enable Rolldown's native implementation in every repository-owned input config that runs these transforms: + +```ts +experimental: { + nativeMagicString: true, +} +``` + +For tsdown, put the same option under `inputOptions.experimental`. Keep returning the native object directly so Rolldown can generate and compose source maps off the main thread. Enable output `sourcemap: true` when the build should emit map files. See the [native MagicString guide](https://rolldown.rs/in-depth/native-magic-string) and [source transformation guide](https://rolldown.rs/apis/plugin-api/transformations). + +Vite does not forward Rolldown's `ast` or `magicString` transform metadata in the pinned version, even when its build enables native MagicString. Continue to adapt these transforms through `packages/vjsc/src/vite/oxc.ts` for Vite serve and build. + +## Pattern + +```ts +import { walk } from 'oxc-walker'; + +export const plugin = { + name: 'example-transform', + + transform(code, id, meta) { + if (!code.includes('$compile')) return null; + + const ast = meta.ast; + const magicString = meta.magicString; + if (!ast || !magicString) { + throw new Error('example-transform requires Rolldown AST metadata and native MagicString.'); + } + + let changed = false; + + walk(ast, { + enter(node) { + if ( + node.type === 'CallExpression' && + node.callee.type === 'Identifier' && + node.callee.name === '$compile' + ) { + magicString.overwrite(node.callee.start, node.callee.end, 'compile'); + changed = true; + } + }, + }); + + return changed ? { code: magicString } : null; + }, +}; +``` + +Think of the hook as: + +```text +incoming code + -> Oxc AST: find and understand syntax + -> MagicString: edit source using AST ranges + -> return edited code +``` + +## Validation + +Run the transform through a real Rolldown build with native MagicString explicitly enabled. Assert changed and unchanged modules, relevant JS/JSX/TS/TSX forms, source maps when consumers need them, and a clear failure when required metadata is unavailable. + +## Example + +Input: "Rename `$compile()` calls without changing matching strings or comments." + +Output: A filtered transform that finds call expressions through `meta.ast`, overwrites the callee ranges through `meta.magicString`, returns the edited value, and passes a real Rolldown build test. diff --git a/.agents/skills/write-api-reference/references/builder-conventions.md b/.agents/skills/write-api-reference/references/builder-conventions.md index 7874473240..498ec7f2b2 100644 --- a/.agents/skills/write-api-reference/references/builder-conventions.md +++ b/.agents/skills/write-api-reference/references/builder-conventions.md @@ -2,16 +2,24 @@ Naming and file placement conventions required by the api-docs-builder at `site/scripts/api-docs-builder/`. +The builder parses authored TypeScript and TSX with Oxc. Its cached project resolver follows relative and +workspace-package imports, re-exports, interface inheritance, aliases, and the generic substitutions used by +the documented API patterns; it does not invoke the TypeScript compiler. + ## File Locations | File | Path | Purpose | |------|------|---------| -| Core | `packages/core/src/core/ui/{name}/{name}-core.ts` | Props, State, defaultProps | -| Data attrs | `packages/core/src/core/ui/{name}/{name}-data-attrs.ts` | Data attribute definitions | -| CSS vars | `packages/core/src/core/ui/{name}/{name}-css-vars.ts` | CSS custom property definitions (optional) | +| Core | `packages/core/src/core/ui/{name}/core.ts` | Props, State, defaultProps | +| Data attrs | `packages/core/src/core/ui/{name}/data.ts` | Data attribute definitions | +| CSS vars | `packages/core/src/core/ui/{name}/vars.ts` | CSS custom property definitions (optional) | | HTML element | `packages/html/src/ui/{name}/{name}-element.ts` | Custom element with `static tagName` | | React parts | `packages/react/src/ui/{name}/index.parts.ts` | Multi-part detection (optional) | +Qualified core helpers retain the qualifier, such as `segments-core.ts`. Additional part-scoped data attribute +files use `{qualifier}-data.ts`, such as `item-data.ts`, and export the full component-qualified name +(`MenuItemDataAttrs`). + ## Naming Requirements The builder derives PascalCase from kebab-case using `kebabCase` from es-toolkit. All interfaces and exports must follow this pattern: diff --git a/.agents/skills/write-api-reference/references/demo-patterns.md b/.agents/skills/write-api-reference/references/demo-patterns.md index 63db1ab383..e1c830f489 100644 --- a/.agents/skills/write-api-reference/references/demo-patterns.md +++ b/.agents/skills/write-api-reference/references/demo-patterns.md @@ -105,12 +105,14 @@ The `.astro` wrapper is required because only Astro ` + + diff --git a/apps/e2e/apps/vite/src/late-element-registration.ts b/apps/e2e/apps/vite/src/late-element-registration.ts new file mode 100644 index 0000000000..5388979ce4 --- /dev/null +++ b/apps/e2e/apps/vite/src/late-element-registration.ts @@ -0,0 +1,45 @@ +import { ReactiveElement } from '@videojs/html'; + +interface LateReactiveElement extends ReactiveElement { + label: string; + connectedLabel: string | undefined; + renderedLabel: string | undefined; + updateCount: number; +} + +declare global { + interface Window { + lateRegistrationComplete: Promise; + } +} + +const element = document.querySelector('late-reactive-element'); +if (!element) throw new Error('Late reactive element was not found'); + +element.label = 'pre-upgrade'; + +class TestElement extends ReactiveElement { + static override properties = { + label: { type: String }, + }; + + label = 'default'; + connectedLabel: string | undefined; + renderedLabel: string | undefined; + updateCount = 0; + + override connectedCallback(): void { + super.connectedCallback(); + this.connectedLabel = this.label; + } + + protected override update(): void { + this.renderedLabel = this.label; + this.updateCount++; + } +} + +customElements.define('late-reactive-element', TestElement); + +element.label = 'newer'; +window.lateRegistrationComplete = element.updateComplete.then(() => element); diff --git a/apps/e2e/apps/vite/vite.config.ts b/apps/e2e/apps/vite/vite.config.ts index ff89b7db1e..0146a12c46 100644 --- a/apps/e2e/apps/vite/vite.config.ts +++ b/apps/e2e/apps/vite/vite.config.ts @@ -2,25 +2,34 @@ import { existsSync, readdirSync, statSync } from 'node:fs'; import { resolve } from 'node:path'; import react from '@vitejs/plugin-react'; -import { defineConfig } from 'vite'; +import { defineConfig } from 'vite-plus'; +import { vjscPlugin } from 'vjsc/vite'; + +import { configureSkinModule } from '../../../../packages/skins/vjsc/config.ts'; + +const packageDir = import.meta.dirname; function getPageEntries(): Record { const entries: Record = {}; // Hand-written pages in src/ (ejected, captions, etc.) - const srcDir = resolve(__dirname, 'src'); + const srcDir = resolve(packageDir, 'src'); + for (const entry of readdirSync(srcDir)) { const file = resolve(srcDir, entry); + if (entry.endsWith('.html') && entry !== 'index.html' && statSync(file).isFile()) { entries[entry.replace('.html', '')] = file; } } // Generated pages in src/pages/ - const pagesDir = resolve(__dirname, 'src/pages'); + const pagesDir = resolve(packageDir, 'src/pages'); + if (existsSync(pagesDir)) { for (const entry of readdirSync(pagesDir)) { const file = resolve(pagesDir, entry); + if (entry.endsWith('.html') && statSync(file).isFile()) { entries[`pages/${entry.replace('.html', '')}`] = file; } @@ -36,12 +45,9 @@ export default defineConfig({ define: { __DEV__: 'true', }, - plugins: [react()], + plugins: [vjscPlugin({ configure: configureSkinModule }), react({ jsxImportSource: 'react' })], resolve: { - alias: { - '@': resolve(__dirname, '../../../../packages/react/src'), - }, - dedupe: ['react', 'react-dom'], + dedupe: ['@videojs/html', '@videojs/react', 'react', 'react-dom', 'vjsc'], }, optimizeDeps: { exclude: [ @@ -52,14 +58,20 @@ export default defineConfig({ '@videojs/spf', '@videojs/store', '@videojs/utils', + 'vjsc', + 'vjsc/styles', ], }, build: { - outDir: resolve(__dirname, 'dist'), + outDir: resolve(packageDir, 'dist'), emptyOutDir: true, - rollupOptions: { + sourcemap: true, + rolldownOptions: { + experimental: { + nativeMagicString: true, + }, input: { - main: resolve(__dirname, 'src/index.html'), + main: resolve(packageDir, 'src/index.html'), ...getPageEntries(), }, }, diff --git a/apps/e2e/fixtures/media.ts b/apps/e2e/fixtures/media.ts index b2ebaacc23..e9dc196d01 100644 --- a/apps/e2e/fixtures/media.ts +++ b/apps/e2e/fixtures/media.ts @@ -37,6 +37,20 @@ export const VIDEO_PAGES = [ media: 'dash-video', resource: 'dash', }, + { + name: 'HTML Shaka Video HLS', + path: '/pages/html-shaka-video-hls.html', + framework: 'html', + media: 'shaka-video', + resource: 'hlsTs', + }, + { + name: 'HTML Shaka Video DASH', + path: '/pages/html-shaka-video-dash.html', + framework: 'html', + media: 'shaka-video', + resource: 'dash', + }, { name: 'HTML Native HLS Video', path: '/pages/html-native-hls-video.html', @@ -66,6 +80,13 @@ export const VIDEO_PAGES = [ media: 'hlsjs-video', resource: 'hlsTs', }, + { + name: 'React Shaka Video HLS', + path: '/pages/react-shaka-video-hls.html', + framework: 'react', + media: 'shaka-video', + resource: 'hlsTs', + }, ] as const satisfies readonly PageEntry[]; export const AUDIO_PAGES = [ diff --git a/apps/e2e/fixtures/presentation.ts b/apps/e2e/fixtures/presentation.ts new file mode 100644 index 0000000000..1772769f84 --- /dev/null +++ b/apps/e2e/fixtures/presentation.ts @@ -0,0 +1,73 @@ +import type { Page } from '@playwright/test'; + +export async function mockPresentation(page: Page): Promise { + await page.addInitScript(() => { + let fullscreenElement: Element | null = null; + let pipElement: Element | null = null; + + Object.defineProperties(document, { + fullscreenElement: { configurable: true, get: () => fullscreenElement }, + fullscreenEnabled: { configurable: true, get: () => true }, + pictureInPictureElement: { configurable: true, get: () => pipElement }, + pictureInPictureEnabled: { configurable: true, get: () => true }, + }); + + Object.defineProperty(HTMLElement.prototype, 'requestFullscreen', { + configurable: true, + value: async function requestFullscreen(this: HTMLElement) { + fullscreenElement = this; + document.dispatchEvent(new Event('fullscreenchange')); + }, + }); + + Object.defineProperty(document, 'exitFullscreen', { + configurable: true, + value: async () => { + fullscreenElement = null; + document.dispatchEvent(new Event('fullscreenchange')); + }, + }); + + Object.defineProperty(HTMLVideoElement.prototype, 'requestPictureInPicture', { + configurable: true, + value: async function requestPictureInPicture(this: HTMLVideoElement) { + pipElement = this; + this.dispatchEvent(new Event('enterpictureinpicture')); + return {}; + }, + }); + + Object.defineProperties(HTMLVideoElement.prototype, { + webkitPresentationMode: { + configurable: true, + get: function webkitPresentationMode(this: HTMLVideoElement) { + return pipElement === this ? 'picture-in-picture' : 'inline'; + }, + }, + webkitSetPresentationMode: { + configurable: true, + value: function webkitSetPresentationMode(this: HTMLVideoElement, mode: string) { + const wasPip = pipElement === this; + + pipElement = mode === 'picture-in-picture' ? this : null; + + if (!wasPip && pipElement === this) { + this.dispatchEvent(new Event('enterpictureinpicture')); + } else if (wasPip && pipElement !== this) { + this.dispatchEvent(new Event('leavepictureinpicture')); + } + }, + }, + }); + + Object.defineProperty(document, 'exitPictureInPicture', { + configurable: true, + value: async () => { + const video = pipElement; + + pipElement = null; + video?.dispatchEvent(new Event('leavepictureinpicture')); + }, + }); + }); +} diff --git a/apps/e2e/fixtures/resources.ts b/apps/e2e/fixtures/resources.ts index 4df61ab73b..c008c40e50 100644 --- a/apps/e2e/fixtures/resources.ts +++ b/apps/e2e/fixtures/resources.ts @@ -17,6 +17,34 @@ export const MEDIA = { poster: 'https://image.mux.com/lhnU49l1VGi3zrTAZhDm9LUUxSjpaPW9BL4jY25Kwo4/thumbnail.jpg', storyboard: 'https://image.mux.com/lhnU49l1VGi3zrTAZhDm9LUUxSjpaPW9BL4jY25Kwo4/storyboard.vtt', }, + /** + * HLS/CMAF with a 4K ladder — rungs from 640x360 up to 3838x2160, so a screen emulated below the top rung has + * something smaller to cap to. Video-only. + * + * The off-by-two widths are the source's near-square pixel aspect ratio rather than a typo, which is why the cap + * compares pixel areas instead of matching `1920x1080`-style tiers. + */ + hls4k: { + url: 'https://stream.mux.com/SfAaZ9InpM8FMfky7DkNBuTpxEDqU8Jchpa49urOWcs.m3u8', + }, + /** + * HLS/CMAF carrying **no video renditions at all** — the one failure shape with no per-rendition cause behind it, + * since nothing resolves and so nothing reports. A video-only composition can never play it. + */ + hlsAudioOnly: { + url: 'https://stream.mux.com/2NEjLyf6ETnskbfAtbM00Vdzb97B00OKUUQcRD6LZpBRw.m3u8', + }, + /** + * DRM-protected HLS, deliberately left unlicensed: the video renditions carry `EXT-X-KEY` for all three key systems + * and no license path is supplied, so an engine with no EME pipeline reports the source as protected. Here to be + * refused, not played. + * + * The playback token is signed to `exp: 2147483647` (January 2038), so this doesn't rot out from under CI. Same asset + * the sandbox offers as `hls-drm-unlicensed`. + */ + hlsDrm: { + url: 'https://stream.mux.com/FefhWnSMzDqz5z9yxssihdRx8dV6srhYJ8301uQBhRak.m3u8?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IndGcXlSYlRjZDZSaEJkMDJ3Wnd6YTAwR0htNnFVOUlQZTFJS1kwMHgzMDE2dUhBIn0.eyJzdWIiOiJGZWZoV25TTXpEcXo1ejl5eHNzaWhkUng4ZFY2c3JoWUo4MzAxdVFCaFJhayIsImF1ZCI6InYiLCJleHAiOjIxNDc0ODM2NDd9.jXIpJZPB7diM5M6jMVRQ6dELY5YnONzC8jJClm7CT1nm-q25F5PiCvHcdLGqerjN1V_7T9cjhSX02p1i0UiABaKX2Wa4HCf6H6ZSKbY3MiCiRJHnfZzr_cVHCuBRXJlMzXesK_VzgP4kVrVi9-Sj8fGaeQmt4mB0sgtGGM7LpGV1IJdv_9aWnqQpQK7IeWi9ivNwa9Vw-PeppfOFdyQbqYJScIAY-_k6fzGaQucONyIolFGJZuBcan3nDRvCUpSFi0vPO87jf5Zbp6kn-HeARmUTYDPBLoeVSjttxYhoeDQYtNeqbuJ3Tj6S1_9TsE_SNSNZm3lxHoJCz5Wp_YcusQ', + }, /** DASH (Big Buck Bunny 30fps via Akamai). */ dash: { url: 'https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd', @@ -24,8 +52,8 @@ export const MEDIA = { } as const; /** - * Caption files the Vite app serves from `apps/vite/src/public`. Real requests - * over HTTP, unlike a `data:text/vtt` URL, which WebKit treats differently. + * Caption files the Vite app serves from `apps/vite/src/public`. Real requests over HTTP, unlike a `data:text/vtt` URL, + * which WebKit treats differently. */ export const CAPTIONS = { /** One cue spanning 0–30s. */ diff --git a/apps/e2e/fixtures/selectors.ts b/apps/e2e/fixtures/selectors.ts index 12a5d8462d..e13811802e 100644 --- a/apps/e2e/fixtures/selectors.ts +++ b/apps/e2e/fixtures/selectors.ts @@ -1,16 +1,16 @@ /** * Cross-renderer selectors that work for both HTML (Web Components) and React. * - * HTML uses custom element tags: `media-play-button`, `media-time-slider`, etc. - * React uses standard elements with CSS classes: `button.media-button--play`, etc. + * HTML uses custom element tags: `media-play-button`, `media-time-slider`, etc. React uses standard elements with CSS + * classes: `button.media-button--play`, etc. * - * Both renderers apply the **same data attributes** for state (`data-paused`, - * `data-muted`, etc.), which is what tests assert against. + * Both renderers apply the **same data attributes** for state (`data-paused`, `data-muted`, etc.), which is what tests + * assert against. * * Each selector uses a CSS `,` (or) to match either renderer. */ -/** Toolbar: HTML wraps controls in ``, React in `
`. */ +/** Toolbar: HTML renders ``, React renders `
`. */ function withinControls(selector: string): string { return `media-controls ${selector}, .media-controls ${selector}`; } @@ -40,7 +40,7 @@ export const SELECTORS = { container: '.media-default-skin, .media-minimal-skin', // Controls bar - controls: 'media-controls, .media-controls', + controls: 'media-controls-content, .media-controls', // Buttons playButton: 'media-play-button, .media-button--play', @@ -49,6 +49,8 @@ export const SELECTORS = { muteButton: 'media-mute-button, .media-button--mute', fullscreenButton: 'media-fullscreen-button, .media-button--fullscreen', pipButton: 'media-pip-button, .media-button--pip', + castButton: 'media-cast-button, .media-button--cast', + airPlayButton: 'media-airplay-button, .media-button--airplay', captionsButton: 'media-captions-button, .media-button--captions', playbackRateButton: [ withinControls('media-playback-rate-button'), @@ -82,16 +84,17 @@ export const SELECTORS = { '[data-type="duration"].media-time', '[data-type="remaining"].media-time', ].join(', '), + timeToggle: 'media-time[toggle], time.media-time[role="button"]', poster: 'media-poster, img[data-loaded]', bufferingIndicator: 'media-buffering-indicator, .media-buffering-indicator', thumbnail: 'media-slider-thumbnail, .media-thumbnail__image', tooltip: 'media-tooltip, .media-tooltip', popover: 'media-popover, .media-popover', - errorDialog: 'media-error-dialog, .media-error', + errorDialog: 'media-error-dialog, .media-dialog__popup', // Media element — matches all renderer custom elements and native media - media: 'video, audio, hlsjs-video, hls-video, native-hls-video, dash-video, mux-video, mux-audio', + media: 'video, audio, hlsjs-video, hls-video, native-hls-video, dash-video, shaka-video, mux-video, mux-audio', } as const; /** Data attributes used for player state (same across both renderers). */ diff --git a/apps/e2e/package.json b/apps/e2e/package.json index 12de7d596a..845e8969b2 100644 --- a/apps/e2e/package.json +++ b/apps/e2e/package.json @@ -15,6 +15,7 @@ "test:ui": "playwright test --ui", "test:update": "playwright test --update-snapshots", "test:chromium": "playwright test --project=vite-chromium", + "test:a11y": "playwright test tests/accessibility.spec.ts --project=vite-chromium", "test:webkit": "playwright test --project=vite-webkit", "test:vite": "playwright test --project=vite-chromium", "test:sandbox": "playwright test --project=sandbox-chromium", @@ -22,6 +23,7 @@ "report": "playwright show-report" }, "devDependencies": { + "@axe-core/playwright": "^4.13.0", "@playwright/test": "^1.52.0", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", @@ -36,6 +38,8 @@ "@vitejs/plugin-react": "^6.0.4", "react": "^19.2.8", "react-dom": "^19.2.8", - "vite": "^8.1.5" + "vite": "^8.2.2", + "vite-plus": "catalog:", + "vjsc": "workspace:*" } } diff --git a/apps/e2e/page-objects/player.ts b/apps/e2e/page-objects/player.ts index f2eb247d22..cb21cda6bb 100644 --- a/apps/e2e/page-objects/player.ts +++ b/apps/e2e/page-objects/player.ts @@ -1,15 +1,15 @@ import { expect, type Locator, type Page } from '@playwright/test'; + import { DATA_ATTRS, SELECTORS } from '../fixtures/selectors'; /** * Page Object Model for the Video.js player. * - * Uses cross-renderer selectors that work for both: - * - HTML (Web Components): custom element tags like `media-play-button` - * - React: standard elements with CSS classes like `.media-button--play` + * Uses cross-renderer selectors that work for both: - HTML (Web Components): custom element tags like + * `media-play-button` - React: standard elements with CSS classes like `.media-button--play` * - * Both renderers share the same data attributes for state, so all - * assertions against `data-paused`, `data-muted`, etc. are portable. + * Both renderers share the same data attributes for state, so all assertions against `data-paused`, `data-muted`, etc. + * are portable. * * Playwright auto-pierces Shadow DOM for HTML custom elements. */ @@ -38,6 +38,10 @@ export class PlayerPage { return this.page.locator(SELECTORS.timeSlider).first(); } + get timeSliderThumb(): Locator { + return this.timeSlider.getByRole('slider'); + } + get muteButton(): Locator { return this.page.locator(SELECTORS.muteButton).first(); } @@ -46,6 +50,10 @@ export class PlayerPage { return this.page.locator(SELECTORS.volumeSlider).first(); } + get volumeSliderThumb(): Locator { + return this.volumeSlider.getByRole('slider'); + } + get fullscreenButton(): Locator { return this.page.locator(SELECTORS.fullscreenButton).first(); } @@ -54,6 +62,14 @@ export class PlayerPage { return this.page.locator(SELECTORS.pipButton).first(); } + get castButton(): Locator { + return this.page.locator(SELECTORS.castButton).first(); + } + + get airPlayButton(): Locator { + return this.page.locator(SELECTORS.airPlayButton).first(); + } + get captionsButton(): Locator { return this.page.locator(SELECTORS.captionsButton).first(); } @@ -99,6 +115,10 @@ export class PlayerPage { return this.page.locator(SELECTORS.duration).first(); } + get timeToggle(): Locator { + return this.page.locator(SELECTORS.timeToggle).first(); + } + get thumbnail(): Locator { return this.page.locator(SELECTORS.thumbnail).first(); } @@ -157,6 +177,7 @@ export class PlayerPage { (selector) => { const media = document.querySelector(selector) as HTMLMediaElement | null; const actual = (media?.querySelector?.('video') as HTMLMediaElement) ?? media; + return actual && actual.readyState >= 1; }, SELECTORS.media, @@ -170,6 +191,7 @@ export class PlayerPage { await this.page.evaluate((selector) => { const media = document.querySelector(selector) as HTMLMediaElement | null; const actual = (media?.querySelector?.('video') as HTMLMediaElement) ?? media; + if (actual) actual.muted = true; }, SELECTORS.media); } @@ -186,6 +208,7 @@ export class PlayerPage { await this.page.evaluate(async (selector) => { const media = document.querySelector(selector) as HTMLMediaElement | null; const actual = (media?.querySelector?.('video') as HTMLMediaElement) ?? media; + await actual?.play(); }, SELECTORS.media); await expect(this.playButton).not.toHaveAttribute(DATA_ATTRS.paused, { timeout: 5_000 }); @@ -220,6 +243,7 @@ export class PlayerPage { return this.page.evaluate((selector) => { const media = document.querySelector(selector) as HTMLMediaElement | null; const actual = (media?.querySelector?.('video') as HTMLMediaElement) ?? media; + return actual?.playbackRate ?? 1; }, SELECTORS.media); } @@ -233,6 +257,7 @@ export class PlayerPage { (selector) => { const media = document.querySelector(selector) as HTMLMediaElement | null; const actual = (media?.querySelector?.('video') as HTMLMediaElement) ?? media; + return actual && actual.readyState >= 1 && actual.duration > 0 && Number.isFinite(actual.duration); }, SELECTORS.media, @@ -244,6 +269,7 @@ export class PlayerPage { const x = box.x + box.width * (percent / 100); const y = box.y + box.height / 2; + await this.page.mouse.click(x, y); // Wait for the seek to complete @@ -257,12 +283,13 @@ export class PlayerPage { const x = box.x + box.width * (percent / 100); const y = box.y + box.height / 2; + await this.page.mouse.move(x, y); } /** - * Opens the playback rate menu and selects the first option that differs from the current rate. - * Skins expose rate via a menu (not cycle-on-trigger). + * Opens the playback rate menu and selects the first option that differs from the current rate. Skins expose rate via + * a menu (not cycle-on-trigger). */ async selectAlternativePlaybackRate(): Promise { const initialRate = await this.getPlaybackRate(); @@ -278,6 +305,7 @@ export class PlayerPage { const option = this.page .locator(usesSettingsMenu ? SELECTORS.activeMenuUncheckedOptions : SELECTORS.playbackRateUncheckedOptions) .first(); + await expect(option).toBeVisible({ timeout: 5_000 }); // Menu popovers can intercept pointer events on nested radio items. await option.dispatchEvent('click'); @@ -288,6 +316,7 @@ export class PlayerPage { /** Signal pointer activity to show controls and reset the idle timer. */ async showControls(): Promise { await this.playerRoot.dispatchEvent('pointermove', { pointerType: 'mouse' }); + if ((await this.videoPlayer.count()) > 0) { await expect(this.controls).toHaveAttribute(DATA_ATTRS.visible, ''); } diff --git a/apps/e2e/playwright.config.ts b/apps/e2e/playwright.config.ts index 993b4df136..b453ea9a18 100644 --- a/apps/e2e/playwright.config.ts +++ b/apps/e2e/playwright.config.ts @@ -2,6 +2,7 @@ import { defineConfig, devices } from '@playwright/test'; const CI = !!process.env.CI; const SANDBOX_SPEC = /sandbox-(?:.*i18n|skin-styling)\.spec\.ts/; +const VJSC_SKIN_SPEC = /vjsc-skin-styling\.spec\.ts/; const VALUE_OPTIONS = new Set([ '-c', '-g', @@ -34,19 +35,25 @@ const selectedProjects = args.flatMap((arg, index) => { if (arg === '--project' || arg === '-p') { return args[index + 1] ? [args[index + 1]] : []; } + return arg.startsWith('--project=') ? [arg.slice('--project='.length)] : []; }); + const testFilters = args.filter((arg, index) => !arg.startsWith('-') && !VALUE_OPTIONS.has(args[index - 1] ?? '')); const selectedViteProject = selectedProjects.some((name) => name.startsWith('vite-')); const selectedSandboxProject = selectedProjects.some((name) => name.startsWith('sandbox-')); +const selectedVjscProject = selectedProjects.some((name) => name.startsWith('vjsc-')); const selectedSandboxSpec = testFilters.some((arg) => SANDBOX_SPEC.test(arg)); +const selectedVjscSpec = testFilters.some((arg) => VJSC_SKIN_SPEC.test(arg)); const unfilteredRun = selectedProjects.length === 0 && testFilters.length === 0; + const shouldStartViteServer = selectedViteProject || unfilteredRun || - (selectedProjects.length === 0 && testFilters.some((arg) => !SANDBOX_SPEC.test(arg))); + (selectedProjects.length === 0 && testFilters.some((arg) => !SANDBOX_SPEC.test(arg) && !VJSC_SKIN_SPEC.test(arg))); const shouldStartSandboxServer = !process.env.SANDBOX_URL && (selectedSandboxProject || selectedSandboxSpec || unfilteredRun); +const shouldStartVjscServer = selectedVjscProject || selectedVjscSpec || unfilteredRun; export default defineConfig({ testDir: './tests', @@ -80,21 +87,21 @@ export default defineConfig({ // --- Chromium --- { name: 'vite-chromium', - testIgnore: SANDBOX_SPEC, + testIgnore: [SANDBOX_SPEC, VJSC_SKIN_SPEC], use: { ...devices['Desktop Chrome'], baseURL: 'http://localhost:5180' }, }, // --- WebKit --- { name: 'vite-webkit', - testIgnore: SANDBOX_SPEC, + testIgnore: [SANDBOX_SPEC, VJSC_SKIN_SPEC], use: { ...devices['Desktop Safari'], baseURL: 'http://localhost:5180' }, }, // --- Firefox --- { name: 'vite-firefox', - testIgnore: SANDBOX_SPEC, + testIgnore: [SANDBOX_SPEC, VJSC_SKIN_SPEC], use: { ...devices['Desktop Firefox'], baseURL: 'http://localhost:5180' }, }, @@ -104,6 +111,12 @@ export default defineConfig({ use: { ...devices['Desktop Chrome'] }, }, + { + name: 'vjsc-chromium', + testMatch: VJSC_SKIN_SPEC, + use: { ...devices['Desktop Chrome'], baseURL: 'http://localhost:5190' }, + }, + // --- Future: Next.js --- // { // name: 'next-chromium', @@ -133,7 +146,7 @@ export default defineConfig({ ? [ { command: - 'pnpm --dir ../.. build:cdn && node_modules/.bin/tsx scripts/setup.ts && node_modules/.bin/vite --host --port 5299', + 'pnpm --dir ../.. build:cdn && pnpm exec tsx scripts/setup.ts && pnpm exec vp dev --host --port 5299', cwd: '../sandbox', port: 5299, reuseExistingServer: !CI, @@ -141,6 +154,17 @@ export default defineConfig({ }, ] : []), + ...(shouldStartVjscServer + ? [ + { + command: 'pnpm exec vp -C dev dev --host --port 5190 --strictPort', + cwd: '../../packages/skins', + port: 5190, + reuseExistingServer: !CI, + timeout: 120_000, + }, + ] + : []), // --- Future: Next.js --- // { diff --git a/apps/e2e/scripts/generate-pages.ts b/apps/e2e/scripts/generate-pages.ts index 5ab81943fd..fd60f356b1 100644 --- a/apps/e2e/scripts/generate-pages.ts +++ b/apps/e2e/scripts/generate-pages.ts @@ -1,9 +1,9 @@ /** * Generates Vite test pages from PageEntry definitions. * - * Reads the media type configs and page arrays, then writes .ts/.tsx + .html - * files to `apps/vite/src/pages/`. Special pages (ejected skins, captions) are - * hand-written and not generated. + * Reads the media type configs and page arrays, then writes .ts/.tsx + .html files to `apps/vite/src/pages/`, which is + * gitignored — every page there comes from this script, including the special ones (ejected skins, captions, background + * video), which take their own templates rather than the player shell. * * Run: `pnpm --dir apps/e2e generate-pages` */ @@ -83,6 +83,14 @@ const MEDIA_TYPES: Record = { hasPoster: false, isAudio: false, }, + 'shaka-video': { + element: 'shaka-video', + imports: ['@videojs/html/media/shaka-video'], + attrs: 'playsinline', + hasStoryboard: false, + hasPoster: true, + isAudio: false, + }, audio: { element: 'audio', imports: [], @@ -99,13 +107,29 @@ const MEDIA_TYPES: Record = { hasPoster: false, isAudio: true, }, + // Rendered by the `background` category templates rather than the player ones: + // this element has no controls to hang on a skin. The entry exists because + // every page looks its media type up here. + 'hls-background-video': { + element: 'hls-background-video', + imports: ['@videojs/html/media/hls-background-video'], + attrs: '', + hasStoryboard: false, + hasPoster: false, + isAudio: false, + }, }; // React component names for media elements const REACT_MEDIA: Record = { video: { component: 'Video', importPath: '@videojs/react/video' }, 'hlsjs-video': { component: 'HlsJsVideo', importPath: '@videojs/react/media/hlsjs-video' }, + 'shaka-video': { component: 'ShakaVideo', importPath: '@videojs/react/media/shaka-video' }, audio: { component: 'Audio', importPath: '@videojs/react/audio' }, + 'hls-background-video': { + component: 'HlsBackgroundVideo', + importPath: '@videojs/react/media/hls-background-video', + }, }; // CDN import paths (override standard imports) @@ -124,7 +148,7 @@ interface PageDef { framework: 'html' | 'react'; media: string; resource: string; - category?: 'cdn' | 'ejected-html' | 'ejected-react' | 'captions' | 'source-html' | 'source-react'; + category?: 'cdn' | 'ejected-html' | 'ejected-react' | 'captions' | 'background' | 'source-html' | 'source-react'; } // --------------------------------------------------------------------------- @@ -147,6 +171,10 @@ function htmlShell(title: string, scriptSrc: string): string { `; } +function resourceHasPoster(resource: string): boolean { + return resource === 'mp4' || resource === 'hlsTs' || resource === 'hlsFmp4'; +} + function htmlVideoPage(config: MediaTypeConfig, resource: string, imports: string[]): string { const allImports = [...imports, `import { MEDIA } from '../resources';`].join('\n'); @@ -154,9 +182,10 @@ function htmlVideoPage(config: MediaTypeConfig, resource: string, imports: strin ? `\n ` : ''; - const poster = config.hasPoster - ? `\n Video poster` - : ''; + const poster = + config.hasPoster && resourceHasPoster(resource) + ? `\n Video poster` + : ''; const attrs = config.attrs ? ` ${config.attrs}` : ''; @@ -204,7 +233,7 @@ function reactVideoPage(media: string, resource: string, config: MediaTypeConfig ? `import { Video, VideoPlayer, VideoSkin } from '@videojs/react/video';` : `import { ${reactMedia.component} } from '${reactMedia.importPath}';\nimport { VideoPlayer, VideoSkin } from '@videojs/react/video';`; - const posterProp = config.hasPoster ? ` poster={MEDIA.${resource}.poster}` : ''; + const posterProp = config.hasPoster && resourceHasPoster(resource) ? ` poster={MEDIA.${resource}.poster}` : ''; const storyboardTrack = config.hasStoryboard ? `\n ` : ''; @@ -216,8 +245,8 @@ import { MEDIA } from '../resources'; function App() { return ( - - + + <${reactMedia.component} src={MEDIA.${resource}.url} playsInline crossOrigin="anonymous">${storyboardTrack} @@ -258,9 +287,75 @@ createRoot(document.getElementById('root')!).render(); } // --------------------------------------------------------------------------- -// Special page templates (captions, ejected skins) +// Special page templates (captions, ejected skins, background video) // --------------------------------------------------------------------------- +/** + * The SPF background-video Media, alone rather than inside a player: the composition subscribes to no store features + * and has no controls, so a skin would only add moving parts to what the spec is measuring. + * + * `?src=` picks the source, so one page serves every shape `spf-background-video.spec.ts` drives — playable, MPEG-TS, + * encrypted, audio-only — and a test can compare two of them without a page each. Assigned as a property rather than + * interpolated into markup, since the DRM source carries a signed-URL query string. + */ +function backgroundVideoPage(config: MediaTypeConfig, resource: string): string { + return `${config.imports.map((imp) => `import '${imp}';`).join('\n')} +import { MEDIA } from '../resources'; + +const src = new URLSearchParams(window.location.search).get('src') ?? MEDIA.${resource}.url; + +const media = document.createElement('${config.element}') as HTMLElement & { src: string }; +media.src = src; +// Viewport units rather than percentages: the shared page shell's #root has no +// height of its own, and a background video that lays out at zero is one an +// engine may treat as offscreen. +media.style.width = '100vw'; +media.style.height = '100vh'; + +document.getElementById('root')!.append(media); +`; +} + +/** + * The React counterpart, and the only place `onError` can be observed: the component hands out no reference to its + * Media, so what a consumer sees is whatever React's own event plumbing delivers. Failures are counted onto `window` + * rather than rendered — the assertion is that the prop fired at all, since the condition behind it isn't reachable + * from here by design. + */ +function reactBackgroundVideoPage(media: string, resource: string): string { + const reactMedia = REACT_MEDIA[media]; + if (!reactMedia) throw new Error(`No React component mapping for media type: ${media}`); + + return `import { ${reactMedia.component} } from '${reactMedia.importPath}'; +import { createRoot } from 'react-dom/client'; +import { MEDIA } from '../resources'; + +declare global { + interface Window { + __backgroundVideoErrors: number; + } +} + +window.__backgroundVideoErrors = 0; + +const src = new URLSearchParams(window.location.search).get('src') ?? MEDIA.${resource}.url; + +function App() { + return ( + <${reactMedia.component} + src={src} + style={{ width: '100vw', height: '100vh' }} + onError={() => { + window.__backgroundVideoErrors += 1; + }} + /> + ); +} + +createRoot(document.getElementById('root')!).render(); +`; +} + function captionsPage(resource: string): string { const captionVtt = 'WEBVTT\\n\\n00:00:00.000 --> 00:00:30.000\\nThis is a test caption'; @@ -310,7 +405,7 @@ const style = document.createElement('style'); style.textContent = skin.css; document.head.appendChild(style); -const playerMatch = skin.html.match(/[\\s\\S]*<\\/video-player>/); +const playerMatch = skin.html.match(/]*>[\\s\\S]*<\\/video-player>/); if (!playerMatch) { throw new Error('Could not find in ejected HTML output.'); @@ -332,7 +427,7 @@ video.innerHTML = \` - - Video poster - - -\`; +const skin = String( + DefaultVideoSkin({ + 'data-source-skin': '', + poster: MEDIA.${resource}.poster, + style: 'display: block; max-width: 800px; aspect-ratio: 16/9', + }) +).replace( + '', + \`\` +); + +document.getElementById('root')!.innerHTML = \`\${skin}\`; `; } function sourceReactPage(resource: string): string { - const generatedRoot = '../../../../../../packages/react/src/__generated__/skins/default-video'; + const source = '../../../../../../packages/skins/vjsc/skins/default-video/skin.tsx'; - return `import { createPlayer } from '@/player/create-player'; -import { Video } from '@/media/video'; -import { videoFeatures } from '@videojs/core/dom'; -import type { CSSProperties } from 'react'; + return `import { createPlayer } from '@videojs/react'; +import { Video, videoFeatures } from '@videojs/react/video'; import { createRoot } from 'react-dom/client'; -import { DefaultVideoSkin } from '${generatedRoot}/skin'; -import '${generatedRoot}/styles/styles.css'; +import { DefaultVideoSkin } from '${source}?style=css&target=react&skin=default-video'; import { MEDIA } from '../resources'; const { Player } = createPlayer({ features: videoFeatures }); function App() { return ( - + @@ -445,7 +521,41 @@ const PAGES: PageDef[] = [ media: 'hls-video', resource: 'hlsTs', }, + // The SPF background-video composition, driven by `spf-background-video.spec.ts` + // alone: `?src=` swaps the source per test, so these carry a playable default + // and stay out of `fixtures/media.ts`'s page arrays — the parameterized + // playback suites all assume a player with controls. + { + name: 'HTML HLS Background Video', + path: 'html-hls-background-video', + framework: 'html', + media: 'hls-background-video', + resource: 'hlsFmp4', + category: 'background', + }, + { + name: 'React HLS Background Video', + path: 'react-hls-background-video', + framework: 'react', + media: 'hls-background-video', + resource: 'hlsFmp4', + category: 'background', + }, { name: 'HTML DASH Video', path: 'html-dash-video', framework: 'html', media: 'dash-video', resource: 'dash' }, + { + name: 'HTML Shaka Video HLS', + path: 'html-shaka-video-hls', + framework: 'html', + media: 'shaka-video', + resource: 'hlsTs', + }, + { + name: 'HTML Shaka Video DASH', + path: 'html-shaka-video-dash', + framework: 'html', + media: 'shaka-video', + resource: 'dash', + }, { name: 'HTML Native HLS Video', path: 'html-native-hls-video', @@ -462,6 +572,13 @@ const PAGES: PageDef[] = [ // React Video { name: 'React Video MP4', path: 'react-video-mp4', framework: 'react', media: 'video', resource: 'mp4' }, { name: 'React Video HLS', path: 'react-video-hls', framework: 'react', media: 'hlsjs-video', resource: 'hlsTs' }, + { + name: 'React Shaka Video HLS', + path: 'react-shaka-video-hls', + framework: 'react', + media: 'shaka-video', + resource: 'hlsTs', + }, // React Audio { name: 'React Audio MP4', path: 'react-audio-mp4', framework: 'react', media: 'audio', resource: 'mp4' }, @@ -532,6 +649,7 @@ function getImports(page: PageDef, config: MediaTypeConfig): string[] { if (page.category === 'cdn') { const cdnImports = CDN_IMPORTS[page.media]; if (!cdnImports) throw new Error(`No CDN imports for media type: ${page.media}`); + return cdnImports.map((i) => `import '${i}';`); } @@ -554,7 +672,12 @@ function generatePage(page: PageDef): { ts: string; html: string; ext: string } let ts: string; // Special category pages - if (page.category === 'captions') { + if (page.category === 'background') { + ts = + page.framework === 'react' + ? reactBackgroundVideoPage(page.media, page.resource) + : backgroundVideoPage(config, page.resource); + } else if (page.category === 'captions') { ts = captionsPage(page.resource); } else if (page.category === 'ejected-html') { ts = ejectedHtmlPage(page.resource); @@ -568,6 +691,7 @@ function generatePage(page: PageDef): { ts: string; html: string; ext: string } ts = config.isAudio ? reactAudioPage(page.media, page.resource) : reactVideoPage(page.media, page.resource, config); } else { const imports = getImports(page, config); + ts = config.isAudio ? htmlAudioPage(config, page.resource, imports) : htmlVideoPage(config, page.resource, imports); } @@ -578,10 +702,12 @@ function generatePage(page: PageDef): { ts: string; html: string; ext: string } function generateIndexHtml(pages: PageDef[]): string { const noCategory = (p: PageDef) => !p.category; + const htmlVideo = pages.filter((p) => p.framework === 'html' && !MEDIA_TYPES[p.media]?.isAudio && noCategory(p)); const htmlAudio = pages.filter((p) => p.framework === 'html' && MEDIA_TYPES[p.media]?.isAudio && noCategory(p)); const reactVideo = pages.filter((p) => p.framework === 'react' && !MEDIA_TYPES[p.media]?.isAudio && noCategory(p)); const reactAudio = pages.filter((p) => p.framework === 'react' && MEDIA_TYPES[p.media]?.isAudio && noCategory(p)); + const cdn = pages.filter((p) => p.category === 'cdn'); const ejected = pages.filter((p) => p.category?.startsWith('ejected')); const captions = pages.filter((p) => p.category === 'captions'); @@ -650,6 +776,7 @@ for (const page of PAGES) { // Generate index.html in src/ (not pages/) const srcDir = resolve(OUT_DIR, '..'); + writeFileSync(resolve(srcDir, 'index.html'), generateIndexHtml(PAGES)); console.log(`[generate-pages] Generated ${count} pages + index.html`); diff --git a/apps/e2e/scripts/sync-ejected-skins.ts b/apps/e2e/scripts/sync-ejected-skins.ts index 3a6d2ebc80..e3d963bcf3 100644 --- a/apps/e2e/scripts/sync-ejected-skins.ts +++ b/apps/e2e/scripts/sync-ejected-skins.ts @@ -1,6 +1,6 @@ /** - * Syncs the generated ejected skin source from the docs site build - * into the e2e test app so the ejected React test uses real output. + * Syncs the generated ejected skin source from the docs site build into the e2e test app so the ejected React test uses + * real output. * * Run after `pnpm -F site ejected-skins` and before e2e tests. */ diff --git a/apps/e2e/tests/accessibility.spec.ts b/apps/e2e/tests/accessibility.spec.ts new file mode 100644 index 0000000000..b4e15e5807 --- /dev/null +++ b/apps/e2e/tests/accessibility.spec.ts @@ -0,0 +1,84 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, type Page, type TestInfo, test } from '@playwright/test'; + +import { PlayerPage } from '../page-objects/player'; + +const WCAG_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22a', 'wcag22aa']; + +const PLAYER_PAGES = [ + { name: 'HTML video', path: '/pages/html-video-mp4.html' }, + { name: 'React video', path: '/pages/react-video-mp4.html' }, + { name: 'HTML audio', path: '/pages/html-audio-mp4.html' }, + { name: 'React audio', path: '/pages/react-audio-mp4.html' }, +] as const; + +const VIDEO_PAGES = PLAYER_PAGES.filter(({ name }) => name.endsWith('video')); + +async function checkAccessibility(page: Page, testInfo: TestInfo, state: string): Promise { + const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); + + await testInfo.attach(`axe-${state}`, { + body: JSON.stringify(results, null, 2), + contentType: 'application/json', + }); + + const violations = results.violations.map(({ id, impact, help, nodes }) => ({ + id, + impact, + help, + targets: nodes.map(({ target }) => target), + })); + + expect(violations, `${state} has automatically detectable accessibility violations`).toEqual([]); + + const brokenControls = await page.locator('[aria-controls]').evaluateAll((elements) => + elements.flatMap((element) => { + const root = element.getRootNode() as Document | ShadowRoot; + + return (element.getAttribute('aria-controls') ?? '') + .split(/\s+/) + .filter(Boolean) + .filter((id) => !root.getElementById(id)) + .map((id) => ({ id, element: element.outerHTML })); + }) + ); + + expect(brokenControls, `${state} has unresolved aria-controls references`).toEqual([]); +} + +test.describe('Accessibility', () => { + for (const entry of PLAYER_PAGES) { + test(`${entry.name} initial state`, async ({ page }, testInfo) => { + const player = new PlayerPage(page); + + await page.goto(entry.path); + await player.waitForMediaReady(); + + await checkAccessibility(page, testInfo, `${entry.name}-initial`); + }); + } + + for (const entry of VIDEO_PAGES) { + test(`${entry.name} settings menu`, async ({ page }, testInfo) => { + const player = new PlayerPage(page); + + await page.goto(entry.path); + await player.waitForMediaReady(); + await player.showControls(); + await player.settingsButton.click(); + await expect(player.settingsSpeedItem).toBeVisible(); + + await checkAccessibility(page, testInfo, `${entry.name}-settings`); + }); + + test(`${entry.name} playback rate menu`, async ({ page }, testInfo) => { + const player = new PlayerPage(page); + + await page.goto(entry.path); + await player.waitForMediaReady(); + await player.openPlaybackRateSettings(); + + await checkAccessibility(page, testInfo, `${entry.name}-playback-rate`); + }); + } +}); diff --git a/apps/e2e/tests/audio-controls.spec.ts b/apps/e2e/tests/audio-controls.spec.ts index d677f47d7c..56a8922c1e 100644 --- a/apps/e2e/tests/audio-controls.spec.ts +++ b/apps/e2e/tests/audio-controls.spec.ts @@ -1,4 +1,5 @@ import { expect, test } from '@playwright/test'; + import { AUDIO_PAGES, type PageEntry } from '../fixtures/media'; import { DATA_ATTRS, SELECTORS } from '../fixtures/selectors'; import { PlayerPage } from '../page-objects/player'; @@ -51,6 +52,7 @@ for (const { name, path, skipBrowsers } of AUDIO_PAGES as readonly PageEntry[]) return page.evaluate((selector) => { const el = document.querySelector(selector); const media = (el?.querySelector?.('video') as HTMLMediaElement) ?? (el as HTMLMediaElement); + return media?.currentTime ?? 0; }, SELECTORS.media); }, diff --git a/apps/e2e/tests/captions.spec.ts b/apps/e2e/tests/captions.spec.ts index 9dd67e73ef..5f703c4939 100644 --- a/apps/e2e/tests/captions.spec.ts +++ b/apps/e2e/tests/captions.spec.ts @@ -1,4 +1,5 @@ import { expect, type Page, test } from '@playwright/test'; + import { CAPTIONS, MEDIA } from '../fixtures/resources'; import { DATA_ATTRS, SELECTORS } from '../fixtures/selectors'; import { PlayerPage } from '../page-objects/player'; @@ -25,6 +26,7 @@ test.describe('Captions', () => { if (!video) return; const track = document.createElement('track'); + track.kind = 'subtitles'; track.label = 'English'; track.srclang = 'en'; @@ -36,6 +38,7 @@ test.describe('Captions', () => { await player.openCaptionsSettings(); const options = page.locator(SELECTORS.activeMenuOptions); + await expect(options).toHaveCount(2, { timeout: 5_000 }); }); @@ -45,6 +48,7 @@ test.describe('Captions', () => { if (!video) return; const track = document.createElement('track'); + track.kind = 'subtitles'; track.label = 'English'; track.srclang = 'en'; @@ -61,20 +65,18 @@ test.describe('Captions', () => { }); /** - * hls.js resets every text track on the media element when it attaches, detaches, - * or loads a source, so a `` that loaded before the source was known used - * to end up selected but empty — the browser never parses a loaded track again. + * Hls.js resets every text track on the media element when it attaches, detaches, or loads a source, so a `` + * that loaded before the source was known used to end up selected but empty — the browser never parses a loaded track + * again. * - * Losing cues is the part no one can undo, so that is what these assert. Which - * track is selected afterwards is the browser's call: loading a source re-runs - * automatic text-track selection, and WebKit turns off caption tracks it did not - * pick itself. `withPreservedTextTracks` unit tests cover the mode it restores. + * Losing cues is the part no one can undo, so that is what these assert. Which track is selected afterwards is the + * browser's call: loading a source re-runs automatic text-track selection, and WebKit turns off caption tracks it did + * not pick itself. `withPreservedTextTracks` unit tests cover the mode it restores. */ test.describe('Captions sideloaded before an hls.js source', () => { /** - * Cues on the sideloaded track, read from the element the page author sees. - * A disabled track reports no cues at all, so read them through a mode that - * exposes them and put the track back the way it was found. + * Cues on the sideloaded track, read from the element the page author sees. A disabled track reports no cues at all, + * so read them through a mode that exposes them and put the track back the way it was found. */ const englishCues = (page: Page) => { return page.evaluate(() => { @@ -83,8 +85,11 @@ test.describe('Captions sideloaded before an hls.js source', () => { if (!track) return -1; const { mode } = track; + if (mode === 'disabled') track.mode = 'hidden'; + const cues = track.cues?.length ?? 0; + if (mode === 'disabled') track.mode = mode; return cues; @@ -92,12 +97,10 @@ test.describe('Captions sideloaded before an hls.js source', () => { }; /** - * Selects the track from the page rather than leaning on its `default` - * attribute. The element clones `` children into its inner `