Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ packages/player/ @missing-elements/h5p-offline-player — the published
utils.ts its helpers — play and settle, waitForEvent with a filter, inject,
the fixture's message and button — which a test uses rather than retyping
tests/fixtures/src/ the source of the generated .h5p archives
tests/package-types.ts the published declarations as a caller on `nodenext` sees them, checked by
tsconfig.consumer.json (see *Types for the plain-JS packages*)
public/ generated, not in git: the runtime's dist/ as frame-assets/, and the test fixtures
NOTICE.md zip.js's notice, and where the runtime went; shipped with the package

Expand Down Expand Up @@ -145,12 +147,17 @@ packages/normalize/ @missing-elements/h5p-normalize — the package rewrit
bin/h5p-normalize.mjs the command
lib/ normalize.mjs (the policy), mp4-faststart.mjs (the remux), zip-writer.mjs,
crc32.mjs, format.mjs, fingerprint.mjs (the player's `indexFingerprint` for Node)
tests/ node tests; tests/helpers/mp4.ts builds structurally honest mp4s
tests/ node tests; tests/helpers/mp4.ts builds structurally honest mp4s;
package-types.ts the package by its name as a TypeScript caller sees it
types/ generated, not in git: the declarations, from the JSDoc (`pnpm types`;
see *Types for the plain-JS packages*)

packages/verify/ @missing-elements/h5p-verify — plays a package headless and reports whether it works
bin/h5p-verify.mjs the command
lib/verify.mjs the static server, the browser run and the report; lib/page.html the page it drives
tests/ node tests that run the real thing against the demo's committed content
tests/ node tests that run the real thing against the demo's committed content;
package-types.ts as for the normalizer
types/ generated, not in git: the declarations, `VerifyReport` among them

packages/cmi5/ @missing-elements/h5p-cmi5 — cmi5 for the element, published as a library
src/index.ts startCmi5(player): the launch, the outcome, terminate; its pure parts
Expand All @@ -174,7 +181,9 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st
page, the headers for five kinds of host and NOTICE.txt
bin/h5p-embed.mjs the command
tests/ build.test.ts, no browser; site.test.ts, a written site on 127.0.0.1
framed by a page on localhost, as deployed
framed by a page on localhost, as deployed; package-types.ts as for the
normalizer
types/ generated, not in git: the declarations of both entries

apps/demo/ the demo app: the dev server for the whole repository, and the hosted site
index.html the hosted player page
Expand Down Expand Up @@ -1702,6 +1711,41 @@ The tests need the player built (`pnpm build`); the package's `test` script does
The repository's own sweep does click through content and read its statements (next section),
for packages it makes; the verifier, which is handed a stranger's, still does not.

## Types for the plain-JS packages

The normalizer, the verifier and the embed package are JavaScript with JSDoc, and since #60 their
documented API ships with declarations generated from it: `tsconfig.json` checks `lib/` (and
`site/embed.js`) with `checkJs`, `tsconfig.types.json` emits the entries' declarations into
`types/` with `stripInternal`, and each `exports` entry names them under `types`. `pnpm types`
writes them, deleting the folder first, since `tsc` never removes a declaration whose source
went; `typecheck` and `prepack` both run it. Three things learned writing them, with TypeScript 7:

- **A top-level `@typedef` is always exported**, and `@internal` on one does not strip it. Worse,
its comment counts among the leading comments of the next declaration, which `stripInternal`
then drops: an `@internal` typedef above a public function took the function out of the
declarations and left the typedef in. A type only the code needs is written inline, derived
(`ReturnType<typeof headerRules>`), or declared inside the function that uses it, where it is
local. `@internal` goes on functions and classes only: the helpers each entry exports for its
tests (`contentChanges`, `parseOrigin`, `orderEntries` and the rest).
- **`tests/package-types.ts` imports the package by its own name**, so it resolves through the
`types` condition. Without `types/`, TypeScript falls back to the JavaScript through `default`
and finds the internal helper, so the file's `@ts-expect-error` on that import fails: the check
cannot pass on anything but the published declarations.
- **The player's relative imports name their file, `./shared/protocol.js`**, as cmi5's do.
`tsc` copies a specifier into the declarations as written, and `node16`/`nodenext` resolution
follows only one that names its file, so up to 1.1.0 what came through `types/`'s own imports —
`PlayerErrorDetail['code']`, `missingLibraries`, `ReadyDetail['source']` — was `any` to such a
caller with `skipLibCheck`, and an error without it; under `bundler` everything was typed.
Found on 2026-10-21 installing the packed tarballs into a fresh project, and fixed in #65.
Vite and esbuild take `.js` to the `.ts` beside it, so the bundles are the same code (only the
minifier's names moved, since it picks them by the source's character frequency).
`tests/package-types.ts` is the player's check, compiled by `tsconfig.consumer.json` on
`nodenext` with `skipLibCheck` off — `skipDefaultLibCheck` on, since the DOM and WebWorker libs
clash when checked together — and kept out of `tsconfig.test.json`, where the source's
`H5PPlayerElement` would meet the declarations' one. `sync-h5p-assets` writes the `.js` into
the generated `pack-index.ts` too. The player's bundler resolution says nothing about a new
import without one: the check catches it only where the public types reach it.

## The content-type sweep

`pnpm sweep` (`apps/demo/scripts/sweep-content-types.mjs`) plays every runnable library in the
Expand Down
9 changes: 5 additions & 4 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ What is covered of the pack itself: the `pack` export, `parts/` with its `index.
[README](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed#readme)
lists them: what a snippet, or a page that reads `report`, is built on.
- **`buildSite()`**, the command as a function, and **`startEmbed()`**, the page as one, with
their options; and `resizer.js`, which speaks H5P's own resizer protocol.
their options and their types; and `resizer.js`, which speaks H5P's own resizer protocol.

A written site is a folder of copies and changes only when it is written again: upgrading is
running the new version of the command and deploying the folder.
Expand All @@ -102,14 +102,15 @@ with the specification is a conformance fix.

### The normalizer, `@missing-elements/h5p-normalize`

The command's options, and `normalizeArchive()`, `formatBytes()` and `archiveFingerprint()`. The
content of a package it rewrites never changes. How it lays out the zip may change in a minor, as
The command's options, and `normalizeArchive()`, `formatBytes()` and `archiveFingerprint()`, with
their types. The content of a package it rewrites never changes. How it lays out the zip may change in a minor, as
long as the player streams the result at least as well.

### The verifier, `@missing-elements/h5p-verify`

The command's options, its exit codes — 0 plays, 1 does not, 2 could not run — `report.json`, to
which fields may be added, and `verifyPackage()` and `summarize()`. The verifier is a step in other
which fields may be added, and `verifyPackage()` and `summarize()`, with their types: `VerifyReport`
is `report.json`'s shape, and gains fields the same way. The verifier is a step in other
people's pipelines, so a check that turns a pass into a fail comes in a minor, never a patch; a new
warning can come in any release.

Expand Down
1 change: 1 addition & 0 deletions packages/embed/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export, which `libraries=pack` then plays from) or `packBase` (the folder of a c
`@missing-elements/h5p-runtime` export, for a bundled element) and `askInOwnFrame` (default
`true`; `false` plays a package from another origin as it is when a same-origin page frames it).
`librariesPack`, the URL of a whole `libraries.h5p`, still works, as a bundle that only fills gaps.
Both entries ship with TypeScript declarations.

```js
import '@missing-elements/h5p-offline-player'
Expand Down
78 changes: 68 additions & 10 deletions packages/embed/lib/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ const PAGE_FILES = ['embed.js', 'embed.css', 'main.js', 'resizer.js']
/** The player's files, by the names the element looks for beside itself. */
const PLAYER_FILES = ['h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js']

/** Where an installed package's file is, or a message that says which one is missing. */
/**
* Where an installed package's file is, or a message that says which one is missing.
* @param {string} specifier
* @param {string} hint
*/
function installed(specifier, hint) {
try {
return require.resolve(specifier)
Expand All @@ -39,6 +43,9 @@ function installed(specifier, hint) {
* CSP host is, letters, digits and hyphens between dots: the URL parser takes `*`, `;` and `"` in
* a host, and a wildcard would allow what the page then refuses, by exact origin, on every load,
* while a quote would end the policy in the files that quote it (#58).
* @internal
* @param {string} value
* @returns {string}
*/
export function parseOrigin(value) {
let url
Expand All @@ -65,6 +72,7 @@ const PACK_CDN_ORIGIN = 'https://cdn.jsdelivr.net'
* A `libraries` value for addresses that name none, checked against the site it goes into: the
* tokens the page understands (`pack`, `none`, https URLs), and with a host list, nothing
* the page would then refuse on every load. Returns the value normalised to single spaces.
* @internal
*
* @param {string | null | undefined} value
* @param {object} [site]
Expand Down Expand Up @@ -103,7 +111,12 @@ export function parseDefaultLibraries(value, { packages = null, libraries = true
return tokens.join(' ')
}

/** Origins given as a list, or as one string separated by commas or whitespace. */
/**
* Origins given as a list, or as one string separated by commas or whitespace.
* @internal
* @param {string[] | string | null | undefined} values
* @returns {string[] | null}
*/
export function parseOrigins(values) {
if (values == null) return null
const list = (Array.isArray(values) ? values : [values]).flatMap((value) => String(value).split(/[\s,]+/)).filter(Boolean)
Expand All @@ -117,6 +130,7 @@ export function parseOrigins(values) {
* it — and names who may frame the page; without it any site may.
*/
/**
* @internal
* @param {object} [options]
* @param {string[] | null} [options.packages]
* @param {string[] | null} [options.ancestors]
Expand All @@ -140,7 +154,11 @@ export function contentSecurityPolicy({ packages = null, ancestors = null, meta
return directives.join('; ')
}

/** Header rules, one set for every host format: the policy everywhere, and the caching that matters. */
/**
* Header rules, one set for every host format: the policy everywhere, and the caching that matters.
* @param {string} csp
* @returns {{ path: string, headers: Record<string, string> }[]}
*/
function headerRules(csp) {
const revalidate = 'public, max-age=3600, stale-while-revalidate=86400'
// Asked again on every load, a 304 when nothing changed. The runtime's files keep their names
Expand All @@ -167,13 +185,20 @@ function headerRules(csp) {
]
}

/** Netlify's and Cloudflare Pages' `_headers`. */
/**
* Netlify's and Cloudflare Pages' `_headers`.
* @param {ReturnType<typeof headerRules>} rules
*/
function netlifyHeaders(rules) {
return rules.map(({ path, headers }) => `${path}\n${Object.entries(headers).map(([key, value]) => ` ${key}: ${value}`).join('\n')}`).join('\n') + '\n'
}

/** Vercel's `vercel.json`, for deploying the folder as a project of its own. */
/**
* Vercel's `vercel.json`, for deploying the folder as a project of its own.
* @param {ReturnType<typeof headerRules>} rules
*/
function vercelConfig(rules) {
/** @param {string} path */
const source = (path) => (path === '/*' ? '/(.*)' : path.replace(/\*$/, '(.*)'))
return JSON.stringify(
{ headers: rules.map(({ path, headers }) => ({ source: source(path), headers: Object.entries(headers).map(([key, value]) => ({ key, value })) })) },
Expand All @@ -190,13 +215,19 @@ function vercelConfig(rules) {
* in every format, which is safe because the policy carries only single quotes.
*/

/** The rule for every path, and the ones for a single path or prefix. */
/**
* The rule for every path, and the ones for a single path or prefix.
* @param {ReturnType<typeof headerRules>} rules
*/
function splitRules(rules) {
const all = rules.find((rule) => rule.path === '/*')
const all = /** @type {ReturnType<typeof headerRules>[number]} */ (rules.find((rule) => rule.path === '/*'))
return { all, specific: rules.filter((rule) => rule !== all) }
}

/** Caddy's `Caddyfile`: a site block to run as it is, or to paste into one. */
/**
* Caddy's `Caddyfile`: a site block to run as it is, or to paste into one.
* @param {ReturnType<typeof headerRules>} rules
*/
function caddyfile(rules) {
const { all, specific } = splitRules(rules)
const lines = [
Expand All @@ -216,10 +247,13 @@ function caddyfile(rules) {
* nginx: a file to `include` inside the `server` block that serves the folder. nginx's
* `add_header` in a `location` replaces every `add_header` inherited from the server level
* rather than adding to it, so each location repeats the headers that apply everywhere.
* @param {ReturnType<typeof headerRules>} rules
*/
function nginxConf(rules) {
const { all, specific } = splitRules(rules)
/** @param {[string, string]} entry */
const header = ([key, value]) => `add_header ${key} "${value}" always;`
/** @param {string} path */
const matcher = (path) => (path.endsWith('/*') ? `^~ ${path.slice(0, -1)}` : `= ${path}`)
const lines = [
'# Written by h5p-embed. Include this file inside the server block that serves the folder:',
Expand All @@ -235,10 +269,15 @@ function nginxConf(rules) {
return lines.join('\n') + '\n'
}

/** Apache's `.htaccess`, for a folder under a vhost that allows it. */
/**
* Apache's `.htaccess`, for a folder under a vhost that allows it.
* @param {ReturnType<typeof headerRules>} rules
*/
function htaccess(rules) {
const { all, specific } = splitRules(rules)
/** @param {[string, string]} entry */
const header = ([key, value]) => `Header always set ${key} "${value}"`
/** @param {ReturnType<typeof headerRules>[number]} rule */
const block = ({ path, headers }) => {
const body = Object.entries(headers).map((entry) => `\t${header(entry)}`).join('\n')
// <Files> matches a name in any directory; a prefix needs the request URI, with no anchor at
Expand All @@ -256,6 +295,7 @@ function htaccess(rules) {
return lines.join('\n') + '\n'
}

/** @param {{ version: string, libraries: boolean }} site */
function notice({ version, libraries }) {
return `This folder is the H5P embed page, written by @missing-elements/h5p-embed.

Expand Down Expand Up @@ -283,7 +323,10 @@ https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed
`
}

/** Whether a directory exists and has anything in it. A path that is a file is an error. */
/**
* Whether a directory exists and has anything in it. A path that is a file is an error.
* @param {string} dir
*/
async function occupied(dir) {
let info
try {
Expand All @@ -295,6 +338,19 @@ async function occupied(dir) {
return (await readdir(dir)).length > 0
}

/**
* What `buildSite` wrote, for a summary.
* @typedef {object} BuiltSite
* @property {string} out the folder, as an absolute path
* @property {string} version the player's version, as its `dist/VERSION` says
* @property {string} csp the policy the headers carry
* @property {boolean} libraries whether the site carries the library pack's parts
* @property {string[] | null} packages the origins packages may come from; `null` for any
* @property {string[] | null} ancestors the origins that may frame the page; `null` for any
* @property {string | null} defaultLibraries the `libraries` value for addresses that name none
* @property {number} size the folder's size in bytes
*/

/**
* Writes the site into `out`. Refuses a folder that already has files in it unless `force`, and
* even then only replaces the files it writes, so pointing it at the wrong folder costs nothing
Expand All @@ -307,6 +363,7 @@ async function occupied(dir) {
* @param {string[] | string | null} [options.ancestors] the only origins that may frame the page
* @param {string | null} [options.defaultLibraries] the `libraries` value for addresses that name none
* @param {boolean} [options.force]
* @returns {Promise<BuiltSite>}
*/
export async function buildSite({ out, libraries = true, packages = null, ancestors = null, defaultLibraries = null, force = false }) {
if (!out) throw new EmbedError('No output folder given.')
Expand Down Expand Up @@ -372,6 +429,7 @@ export async function buildSite({ out, libraries = true, packages = null, ancest
/**
* The folder's size in bytes, for the summary. Paths from a recursive `readdir` rather than
* `Dirent.parentPath`, which Node 20 has only from 20.12.
* @param {string} dir
*/
async function sizeOf(dir) {
let total = 0
Expand Down
20 changes: 14 additions & 6 deletions packages/embed/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,23 @@
"h5p-embed": "./bin/h5p-embed.mjs"
},
"exports": {
".": "./lib/build.mjs",
"./embed.js": "./site/embed.js",
".": {
"types": "./types/lib/build.d.mts",
"default": "./lib/build.mjs"
},
"./embed.js": {
"types": "./types/site/embed.d.ts",
"default": "./site/embed.js"
},
"./embed.css": "./site/embed.css",
"./resizer.js": "./site/resizer.js",
"./package.json": "./package.json"
},
"files": [
"bin",
"lib",
"site"
"site",
"types"
],
"keywords": [
"h5p",
Expand All @@ -44,9 +51,10 @@
],
"scripts": {
"test": "pnpm --filter @missing-elements/h5p-offline-player build && vitest run",
"typecheck": "tsc -p tsconfig.json",
"prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"",
"prepublishOnly": "node -e \"if (!/^pnpm\\//.test(process.env.npm_config_user_agent || '')) { console.error('Publish with pnpm publish: npm would ship the workspace:^ dependency ranges as they are, and the package would not install.'); process.exit(1) }\" && pnpm typecheck && pnpm test"
"typecheck": "pnpm types && tsc -p tsconfig.json",
"prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types",
"prepublishOnly": "node -e \"if (!/^pnpm\\//.test(process.env.npm_config_user_agent || '')) { console.error('Publish with pnpm publish: npm would ship the workspace:^ dependency ranges as they are, and the package would not install.'); process.exit(1) }\" && pnpm typecheck && pnpm test",
"types": "node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json"
},
"dependencies": {
"@missing-elements/h5p-libraries": "workspace:^",
Expand Down
Loading
Loading