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
17 changes: 15 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,11 @@ element, and the element acts. That relay is why `frame-document.ts` has a `mess
owner's rule: the interface and the content in one language. A select for the language, on the
player page and in the app, was built the same day and closed unmerged (#53, #54) for the same
reason: it could only make the two differ. `lang` is the fallback, and so is the embed page's
`&lang=`. `german.h5p` and `english.h5p`, `basic.h5p` naming its language, are the fixtures. That one
`&lang=`. `german.h5p` and `english.h5p`, `basic.h5p` naming its language, are the fixtures, and
`german-late-manifest.h5p` a host without `Range` whose `h5p.json` arrives after the worker
opened its reader: the frame route reads the language off the record, so `refresh` saves the
manifest there once a merged snapshot brings it in, which until #57 it did not, and such a
package booted early in the element's language, untitled and unlicensed. That one
file has every language and the aliases; the boot script picks one by RFC 4647 lookup through
the aliases (`src/l10n.ts` in the runtime — `de-AT` gets `de`, `nb` Norwegian) and lays it over
the core's own English, `getLocalization()` at the vendored commit (`vendor/h5p-core/strings.json`,
Expand Down Expand Up @@ -1282,10 +1286,19 @@ element, and the element acts. That relay is why `frame-document.ts` has a `mess
with `getRegistration` on every load instead of trusting its cached one; without that, the
routes fall through to the origin, and a dev server or SPA host answers an unknown path with
its own `index.html` — the frame then renders the host page inside itself, with no error
anywhere. The chunk store is emptied, which needs nothing: a cold package is the normal case.
anywhere. The registration found must be the one the element holds: another player on the page,
or another tab, may have registered again first, and the one held has no worker once its last
client has gone, so every load failed with `no-worker` until a reload (#57). The chunk store is
emptied, which needs nothing: a cold package is the normal case.
- **The element waits for *its own* registration to reach `activated`**, not for
`navigator.serviceWorker.ready` — that tracks the page's controller and may never resolve for a
nested scope.
- **`navigator.serviceWorker` is read through `serviceWorkers()`, never directly by the element.**
In a frame sandboxed without `allow-same-origin` the property is there and Chromium and WebKit
throw a `SecurityError` on reading it (Firefox returns the container, whose `register` then
fails). Read in `connectedCallback`, the throw stopped the element before its load began: no
`error`, so the embed page never offered to open the package in its own tab (#57). Now it is
`no-worker`.
- **The first load after an upgrade is brought to the element's version before the frame
boots.** Registering again with an unchanged script URL returns the existing registration
without fetching the script — measured in Chromium on 2026-10-04 — so that load booted against
Expand Down
2 changes: 1 addition & 1 deletion docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
|---|---|---|
| `error: no-cors` | Package host sends no CORS headers | Ask the user to download the file and use `file` |
| `error: network`, "is an http: URL and this page is served over https:" | `src` or `libraries` is `http://` on an `https://` page | Use the `https://` URL. `http://localhost` works as is |
| `error: no-worker` | Page on `http://`, in-app browser without Service Workers, or `sw` cross-origin | Use `https://`; show "Open in Safari / Chrome"; serve `h5p-sw.js` from your origin |
| `error: no-worker` | Page on `http://`, in-app browser without Service Workers, `sw` cross-origin, or a frame sandboxed without `allow-same-origin` | Use `https://`; show "Open in Safari / Chrome"; serve `h5p-sw.js` from your origin; add `allow-same-origin` to the frame's `sandbox`, or drop the attribute |
| Worker or runtime files 404 after build | Bundler does not analyse `new URL(…, import.meta.url)` (esbuild), or the `runtime` property is not set | Set `player.runtime`; or serve both packages' `dist/` and set `sw` + `assets-base` |
| Worker blocked by CSP | `sw` points at another origin | Keep the worker same-origin |
| Console: creating a worker from `blob:` violates `worker-src` | The page refuses `blob:` workers; the element falls back to `h5p-jobs.js` | Set `jobs` to that file to skip the attempt. If `error: no-worker` follows, `h5p-jobs.js` is missing or not same-origin |
Expand Down
15 changes: 15 additions & 0 deletions packages/player/scripts/build-fixtures.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,21 @@ for (const [name, language] of [
])
}

// 1d. The German package with its `h5p.json` behind a megabyte of media, as `boardgame.h5p` has
// it at entry 200: on a host without Range the worker opens its reader at the first progress
// report, before the manifest has arrived, and the frame still has to boot in German (#57).
// More media after it, so the frame boots while the download is still under way.
built.push([
'german-late-manifest.h5p',
await writeArchive('german-late-manifest.h5p', async (writer) => {
const manifest = JSON.parse(await readFile(resolve(sourceDir, 'h5p.json'), 'utf8'))
await addBaseFiles(writer, { skip: ['h5p.json'] })
await writer.add('content/media/before.bin', new Uint8ArrayReader(randomBytes(1024 * 1024)), { level: 0 })
await writer.add('h5p.json', new TextReader(JSON.stringify({ ...manifest, language: 'de', defaultLanguage: 'de' })))
await writer.add('content/media/after.bin', new Uint8ArrayReader(randomBytes(4 * 1024 * 1024)), { level: 0 })
})
])

// 2. A large deflated entry: the Jobs worker inflates it into chunks and the virtual server
// serves the prefix that exists as a shorter 206.
built.push([
Expand Down
1 change: 1 addition & 0 deletions packages/player/scripts/lib/fixture-names.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const GENERATED_FIXTURES = [
'basic.h5p',
'german.h5p',
'english.h5p',
'german-late-manifest.h5p',
'finished.h5p',
'large-deflated.h5p',
'large-stored.h5p',
Expand Down
42 changes: 30 additions & 12 deletions packages/player/src/h5p-offline-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ export class H5PPlayerElement extends HTMLElement {
window.addEventListener('message', this.onWindowMessage)
window.addEventListener('pagehide', this.onPageHidden)
document.addEventListener('visibilitychange', this.onPageHidden)
navigator.serviceWorker?.addEventListener('message', this.onServiceWorkerMessage)
serviceWorkers()?.addEventListener('message', this.onServiceWorkerMessage)
if (this.src || this.currentFile) void this.startLoad()
}

Expand All @@ -559,7 +559,7 @@ export class H5PPlayerElement extends HTMLElement {
window.removeEventListener('pagehide', this.onPageHidden)
document.removeEventListener('visibilitychange', this.onPageHidden)
window.removeEventListener('resize', this.onWindowResize)
navigator.serviceWorker?.removeEventListener('message', this.onServiceWorkerMessage)
serviceWorkers()?.removeEventListener('message', this.onServiceWorkerMessage)
this.abortLoad()
this.jobs?.terminate()
this.jobs = null
Expand Down Expand Up @@ -1398,14 +1398,15 @@ export class H5PPlayerElement extends HTMLElement {
this.registration = null
}

if (!('serviceWorker' in navigator)) {
const container = serviceWorkers()
if (!container) {
throw new PlayerError(
'no-worker',
'This browser has no Service Worker support, or the page is not on https/localhost'
'This browser has no Service Worker support, the page is not on https/localhost, or it is in a frame sandboxed without allow-same-origin'
)
}

const mounted = await this.findMountedRoutes()
const mounted = await this.findMountedRoutes(container)
if (mounted) {
this.routes = mounted.routes
this.registration = mounted.registration
Expand All @@ -1423,7 +1424,7 @@ export class H5PPlayerElement extends HTMLElement {

let registration: ServiceWorkerRegistration
try {
registration = await navigator.serviceWorker.register(resolved.href, { scope })
registration = await container.register(resolved.href, { scope })
} catch (error) {
throw new PlayerError('no-worker', `Could not register ${resolved.href}`, { cause: error })
}
Expand All @@ -1439,13 +1440,13 @@ export class H5PPlayerElement extends HTMLElement {
}

/** A host that enforces one worker mounts our handlers in theirs; those routes answer `_ping`. */
private async findMountedRoutes(): Promise<
private async findMountedRoutes(container: ServiceWorkerContainer): Promise<
{ routes: Routes; registration: ServiceWorkerRegistration } | null
> {
if (!navigator.serviceWorker.controller) return null
if (!container.controller) return null

try {
const registration = await navigator.serviceWorker.ready
const registration = await container.ready
const routes = routesFor(registration.scope)
const response = await fetch(routes.ping, { cache: 'no-store' })
if (!response.ok) return null
Expand Down Expand Up @@ -2053,11 +2054,28 @@ function createNonce(): string {
return randomHex(16)
}

/** False once a registration has been torn down, which clearing site data does silently. */
/**
* The page's Service Worker container, or `null` where it has none. Not `'serviceWorker' in
* navigator`: in a frame sandboxed without `allow-same-origin` the property is there, and Chromium
* and WebKit throw a `SecurityError` on reading it (#57).
*/
function serviceWorkers(): ServiceWorkerContainer | null {
try {
return navigator.serviceWorker ?? null
} catch {
return null
}
}

/**
* False once a registration has been torn down, which clearing site data does silently. Another
* registration at the scope does not count: another player on the page, or another tab, may have
* registered again first, and the one this element holds has no worker once its clients are gone.
*/
async function stillRegistered(registration: ServiceWorkerRegistration): Promise<boolean> {
try {
const current = await navigator.serviceWorker.getRegistration(registration.scope)
return current?.active != null
const current = await serviceWorkers()?.getRegistration(registration.scope)
return current === registration && current.active != null
} catch {
// A registration that cannot be asked about is as good as gone: the load registers again.
return false
Expand Down
11 changes: 10 additions & 1 deletion packages/player/src/sw/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,16 @@ class VirtualServer {
}

const snapshot = await store.getForwardIndex()
if (snapshot) await reader.absorb(snapshot)
if (!snapshot) return reader
const manifest = reader.manifest
await reader.absorb(snapshot)
// `h5p.json` has just arrived. The reader was opened before it, at the first progress report,
// so its title, metadata and language reach the record here or not until the download is
// whole — after the frame has booted early without them, in the element's language (#57).
if (reader.manifest !== manifest) {
const record = await db.getPackage(load.pkgId)
if (record) await this.rememberManifest(record, reader)
}
return reader
}

Expand Down
18 changes: 18 additions & 0 deletions packages/player/tests/browser/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,24 @@ describe('reporting failures', () => {
expect(detail.code).toBe('bad-archive')
})

it('reports a frame sandboxed without allow-same-origin as having no worker', async () => {
// There `'serviceWorker' in navigator` holds, and Chromium and WebKit throw on reading it. The
// element used to throw in `connectedCallback` and never report anything (#57).
Object.defineProperty(navigator, 'serviceWorker', {
configurable: true,
get() {
throw new DOMException('Service worker is disabled because the context is sandboxed', 'SecurityError')
}
})
try {
const { detail } = await failureFor(FIXTURES.basic)
expect(detail.code).toBe('no-worker')
expect(detail.message).toContain('sandboxed without allow-same-origin')
} finally {
delete (navigator as { serviceWorker?: unknown }).serviceWorker
}
})

it('reports a URL that does not exist', async () => {
const { detail } = await failureFor(FIXTURES.missing)
expect(detail.code).toBe('network')
Expand Down
29 changes: 27 additions & 2 deletions packages/player/tests/browser/l10n.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type H5PPlayerElement } from '../../src/h5p-offline-player'
import { type H5PPlayerElement, type PlayerProgressDetail } from '../../src/h5p-offline-player'
import { afterEach, describe, expect, it } from 'vitest'
import '../../src/h5p-offline-player'
import { FIXTURES, createPlayer, frameDocument, frameWindow, play, waitForSettled } from './utils'
import { FIXTURES, createPlayer, frameDocument, frameWindow, play, settle, waitForSettled } from './utils'

/**
* The core's own strings in the content's language, the one its `h5p.json` names, and in the
Expand All @@ -21,6 +21,8 @@ interface Core {
}

const core = (player: H5PPlayerElement) => (frameWindow(player) as unknown as Core).H5P
const integration = (player: H5PPlayerElement) =>
(frameWindow(player) as unknown as { H5PIntegration: { contents: Record<string, { metadata?: { license?: string } }> } }).H5PIntegration
const strings = (player: H5PPlayerElement) =>
[...frameDocument(player).querySelectorAll('script[src]')].map((script) => script.getAttribute('src') ?? '').filter((src) => src.includes('l10n.js'))
const l10nJs = new URL('/frame-assets/l10n.js', location.href).href
Expand Down Expand Up @@ -52,6 +54,29 @@ describe('the core’s strings', () => {
expect(core(early).t('fullscreen')).toBe('Vollbild')
})

it('are in the package’s language from a host without Range whose h5p.json arrives late', async () => {
// The worker opens its reader at the first progress report, here before `h5p.json` has
// arrived, and the frame boots from a later one while the media still arrives (#57). The
// record had none of the manifest then, so the frame took the element's language.
document.documentElement.setAttribute('lang', 'en')
let downloaded = 0
const { player, result } = await settle('/no-range/german-late-manifest.h5p?throttle=1000000', {}, (each) => {
each.addEventListener('progress', (event: Event) => {
const { phase, fraction } = (event as unknown as CustomEvent<PlayerProgressDetail>).detail
if (phase === 'download' && fraction !== null) downloaded = fraction
})
})
expect(result).toEqual({ ok: true })
expect(downloaded).toBeLessThan(1)

expect(frameDocument(player).documentElement.lang).toBe('de')
expect(core(player).t('fullscreen')).toBe('Vollbild')
// The rest of the manifest, which arrived with it: the title, and the licence behind the
// copyright dialog.
expect(frameDocument(player).title).toBe('Offline player test')
expect(Object.values(integration(player).contents)[0].metadata?.license).toBe('CC BY')
})

it('are English, and the frame says so, when nothing declares a language', async () => {
document.documentElement.removeAttribute('lang')
const player = await play(FIXTURES.basic)
Expand Down
29 changes: 28 additions & 1 deletion packages/player/tests/browser/recovery.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest'
import '../../src/h5p-offline-player'
import type { H5PPlayerElement } from '../../src/h5p-offline-player'
import { DB_NAME } from '../../src/shared/constants'
import { FIXTURES, frameDocument, messageOf, play } from './utils'
import { FIXTURES, frameDocument, messageOf, play, waitFor, waitForSettled } from './utils'

/**
* Surviving the storage going away underneath the player.
Expand Down Expand Up @@ -49,4 +50,30 @@ describe('recovering from cleared storage', () => {
'Served from the archive, never extracted to disk.'
)
})

it('registers again when another player has taken the scope since', async () => {
// Site data cleared, then another player on the page, or another tab, registering first: the
// scope has a live registration again, but not the one this element holds (#57).
const first = await play(FIXTURES.basic)
const old = (await navigator.serviceWorker.getRegistration(first.scope!))!
// Emptied first, so that no client holds the registration and unregistering tears it down
// as clearing site data does. Unregistered under a client, Chromium revives the same
// registration for the next `register`, which is not the state this is about.
first.removeAttribute('src')
await old.unregister()
await waitFor(() => old.active === null)

const second = document.createElement('h5p-player') as H5PPlayerElement
second.style.height = '400px'
document.body.append(second)
const played = waitForSettled(second)
second.setAttribute('src', FIXTURES.german)
expect(await played).toEqual({ ok: true })
expect(await navigator.serviceWorker.getRegistration(first.scope!)).not.toBe(old)

const settled = waitForSettled(first)
first.setAttribute('src', FIXTURES.basic)
expect(await settled).toEqual({ ok: true })
expect(messageOf(first)).toBe('Served from the archive, never extracted to disk.')
})
})
7 changes: 4 additions & 3 deletions packages/runtime/src/frame-boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,9 @@ interface BootConfig {
/** What the host asked for; the same shape as `FrameOptions` in shared/protocol.ts. */
options?: FrameOptions
/**
* The element's language, which H5P's own strings follow, when the worker named `l10n.js`. Not
* the document's `lang`: that is the content's, as H5P writes it.
* The frame's language, which H5P's own strings follow, when the worker named `l10n.js`: the
* content's, as `h5p.json` names it, or the element's for a package that names none. The same
* tag as the document's `lang`.
*/
language?: string
/**
Expand Down Expand Up @@ -216,7 +217,7 @@ var flag = function (value: boolean | undefined, otherwise: boolean) {
return typeof value === 'boolean' ? value : otherwise;
};

// The core's own strings in the element's language, when this package has them: the worker names
// The core's own strings in the frame's language, when this package has them: the worker names
// `l10n.js` ahead of this script for any language but English, and the strings for the language
// the configuration names are picked from it. They are laid over the core's English key by key,
// so a string a language lacks stays English, and before the core's ready handler builds the
Expand Down
5 changes: 3 additions & 2 deletions packages/runtime/src/l10n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
* Which of this package's translations of the core's strings a frame gets. `dist/l10n.js` leaves
* every language on `window.H5PRuntimeL10n`, with the aliases `scripts/build-l10n.mjs` derived;
* the boot script picks one for the frame document's `lang`, which the player's worker writes
* from the element's language. The player knows no list of languages: what is here, and which
* tag gets which, is this package's alone, so a language added is a release of this package only.
* from the content's language, or the element's for a package that names none. The player knows
* no list of languages: what is here, and which tag gets which, is this package's alone, so a
* language added is a release of this package only.
*/

/**
Expand Down
Loading