From 35a686a9ef2e6d37176d62028ea0d911e9374c11 Mon Sep 17 00:00:00 2001
From: Aleksandr Shevchuk
Date: Tue, 3 Nov 2026 15:27:56 +0200
Subject: [PATCH 1/3] feat(embed): an H5P-to-SCORM page in the browser, the
same zip as --scorm (#122)
The people who need a SCORM package do not run npx, and their route, H5P
through Lumi, has had Lumi's export broken since April. A page on every
written site, and on the demo at /demo/scorm.html, now builds the zip the
command writes from a picked or dropped .h5p, in the browser, with nothing
uploaded.
lib/scorm.mjs is split as #108 split h5p-author's build: scorm-core.mjs
reads the package, plans its parts, lays out the entries and writes them,
and imports no Node; scorm.mjs is the Node side, unchanged for callers;
scorm-browser.mjs, ./scorm/browser, builds in a page from the site's own
copies, each part checked against the index's SHA-256, and returns a Blob.
scripts/build.mjs bundles the page's script with zip.js and the player's
./plan for the written site, which has no bundler. The demo runs the same
script in the site's own design.
scorm-browser.test.ts holds the page's zip to the command's entry for
entry, in Node; scorm-page.test.ts drives the page in Chromium.
Co-Authored-By: Claude Fable 5.1
---
AGENTS.md | 61 +++-
apps/demo/demo/index.html | 6 +
apps/demo/demo/player-page.css | 5 +-
apps/demo/demo/scorm-page.js | 17 +
apps/demo/demo/scorm.html | 114 +++++++
apps/demo/scripts/lib/pages.mjs | 1 +
apps/demo/vite.config.ts | 36 +++
docs/compatibility.md | 3 +
packages/embed/README.md | 25 +-
packages/embed/lib/build.mjs | 42 ++-
packages/embed/lib/scorm-browser.mjs | 168 ++++++++++
packages/embed/lib/scorm-core.mjs | 344 +++++++++++++++++++++
packages/embed/lib/scorm.mjs | 249 ++-------------
packages/embed/lib/shared.mjs | 14 +
packages/embed/package.json | 20 +-
packages/embed/scripts/build.mjs | 44 +++
packages/embed/site/scorm-main.js | 11 +
packages/embed/site/scorm-page.css | 65 ++++
packages/embed/site/scorm-page.js | 105 +++++++
packages/embed/site/scorm.html | 66 ++++
packages/embed/tests/build.test.ts | 8 +-
packages/embed/tests/helpers/host.ts | 47 +++
packages/embed/tests/helpers/zip.ts | 39 +++
packages/embed/tests/package-types.ts | 11 +-
packages/embed/tests/scorm-browser.test.ts | 128 ++++++++
packages/embed/tests/scorm-page.test.ts | 96 ++++++
packages/embed/tests/scorm.test.ts | 40 +--
packages/embed/tsconfig.json | 2 +-
packages/embed/tsconfig.types.json | 2 +-
pnpm-lock.yaml | 3 +
30 files changed, 1491 insertions(+), 281 deletions(-)
create mode 100644 apps/demo/demo/scorm-page.js
create mode 100644 apps/demo/demo/scorm.html
create mode 100644 packages/embed/lib/scorm-browser.mjs
create mode 100644 packages/embed/lib/scorm-core.mjs
create mode 100644 packages/embed/lib/shared.mjs
create mode 100644 packages/embed/scripts/build.mjs
create mode 100644 packages/embed/site/scorm-main.js
create mode 100644 packages/embed/site/scorm-page.css
create mode 100644 packages/embed/site/scorm-page.js
create mode 100644 packages/embed/site/scorm.html
create mode 100644 packages/embed/tests/helpers/host.ts
create mode 100644 packages/embed/tests/helpers/zip.ts
create mode 100644 packages/embed/tests/scorm-browser.test.ts
create mode 100644 packages/embed/tests/scorm-page.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 53786948..a095e2a4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -248,23 +248,36 @@ packages/embed/ @missing-elements/h5p-embed — the embed page as a st
site/ the page: index.html (its CSP a placeholder the writer fills), main.js,
embed.js (startEmbed, also what the demo's /embed runs), embed.css,
resizer.js (the page-side half of the resizer protocol, served at the
- folder's root, and at /resizer.js on the demo)
+ folder's root, and at /resizer.js on the demo); and the SCORM page:
+ scorm.html, scorm-main.js, scorm-page.js (startScormPage, also what the
+ demo's /demo/scorm.html runs) and scorm-page.css (#122)
lib/build.mjs buildSite(): copies the page, the player's dist/, the runtime's dist/ as
frame-assets/ and the library pack; writes config.js, the policy into the
page, the headers for five kinds of host and NOTICE.txt
lib/scorm.mjs buildScorm(), `--scorm`: one .h5p, the player, the runtime and the parts of the
pack it needs as a SCORM 1.2 zip, planned with the player's `./plan`; refused for
a library neither the package nor the pack carries
+ lib/scorm-core.mjs what the SCORM zip is wherever it is written, and no Node import: the
+ package read and its parts planned, the entries laid out, the zip written
+ into a zip.js writer; lib/scorm-browser.mjs, `./scorm/browser`,
+ buildScormInPage(): the same zip in a page, from a File, the files
+ fetched from the site and the zip a Blob; lib/shared.mjs, EmbedError and
+ the player's file names, for the modules that import no Node (#122)
scorm/ the SCORM package's launch page (index.html, its title, language and
build filled in by the writer) and scorm.js, its bridge to the LMS's API
bin/h5p-embed.mjs the command
- scripts/ check-published.mjs, the publish guard for the player it pins exactly (#109)
- and the normalizer's `./crc32` (#108)
+ scripts/ build.mjs, dist/scorm-page.js: the SCORM page's script bundled with zip.js
+ and the player's `./plan` for a written site, which has no bundler
+ (#122); check-published.mjs, the publish guard for the player it pins
+ exactly (#109) and the normalizer's `./crc32` (#108)
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; scorm.test.ts, the zip in Node
and the launch page under a stand-in for an LMS's player page in
- Chromium; package-types.ts as for the normalizer
- types/ generated, not in git: the declarations of the three entries
+ Chromium; scorm-browser.test.ts, the page's builder run in Node against
+ the command's zip, entry for entry; scorm-page.test.ts, the page itself
+ in Chromium; helpers/, the static host and the quiz helpers those share;
+ package-types.ts as for the normalizer
+ types/ generated, not in git: the declarations of the five entries
packages/vscode/ h5p-preview, "H5P Preview by Missing Elements" — the VS Code extension, a .vsix
for the Visual Studio Marketplace and Open VSX, not on npm (see *The VS Code
@@ -297,7 +310,9 @@ apps/demo/ the demo app: the dev server for the whole repository,
demo/ demo/index.html is the examples index, demo/setup.html the setup page for
integrators, demo/compare.html how it compares with h5p.com, the H5P
plugins, Lumi and h5p-standalone, demo/normalize.html why deflated media cannot stream and how
- the normalizer fixes it (prose and a CSS-only diagram, no script), the rest
+ the normalizer fixes it (prose and a CSS-only diagram, no script),
+ demo/scorm.html the H5P-to-SCORM page, the embed package's run with the
+ demo's own copies (demo/scorm-page.js, #122), the rest
the individual embedding demos, all sharing demo/player-page.css;
demo/cmi5.html with demo/cmi5-page.js is a cmi5 assignable unit around
the element, on @missing-elements/h5p-cmi5, and demo/cmi5-course.zip the
@@ -2574,6 +2589,36 @@ one row each; an LMS added here gets a row there.
its success unknown. The pack, its parts, the demo packages (the normalizer's) and h5p-author's
quiz have no stored entry with a descriptor, so nothing else needed the change.
+- **The same zip is built in a page, with nothing uploaded** (#122, 2026-11-03). The people who
+ need a SCORM package, designers and teachers with Canvas, Moodle or Blackboard, do not run `npx`:
+ their route, H5P → Lumi → SCORM, which UBC, UFL, ISU, the University of Alberta and others
+ publish guides for, has had Lumi's export broken since April 2026, and no converter ran in the
+ browser. So `scorm.mjs` was split as #108 split h5p-author's build. `scorm-core.mjs` reads the
+ package, plans the parts, lays out the entries and writes them, and imports no Node; `scorm.mjs`
+ is the Node side, the files from the installed packages and the zip to a path, its API unchanged;
+ `scorm-browser.mjs`, `./scorm/browser`, is the page's, `buildScormInPage()`: the package a
+ `File`, the player's files, the runtime and the pack fetched from the site the page is on (`base`,
+ `pack` or `packBase`, or `assets` for a page that bundles the launch page, the bridge, the
+ stylesheet and the licence list), each part checked against the index's SHA-256 since it came
+ over the network, and the zip a `Blob`. The runtime's files are named by a list,
+ `RUNTIME_FILES`, plus the fonts from its `MANIFEST.json`, since a folder on a server cannot be
+ listed; `scorm-browser.test.ts` runs the builder in Node, which has `fetch`, `File` and
+ `crypto.subtle`, against a written site and holds its zip to the command's entry for entry, so a
+ file the runtime adds shows up there. `site/scorm-page.js` is the page's script,
+ `startScormPage()`, which reads `#file`, `#status`, `#download` and `#notice`, and a `#state`
+ badge where the page has one; the written site loads it as `scripts/build.mjs` bundles it with
+ zip.js and the player's `./plan` (`dist/scorm-page.js`, zip.js's licence in its header, since the
+ site has no bundler), from `scorm.html`, with the launch page and the bridge copied beside it as
+ `scorm-launch.html` and `scorm.js` and the player's and the pack's versions in `config.js`. The
+ demo reuses the source at `/demo/scorm.html` in the site's own design: the pack's parts as Vite
+ emits them, the four files as `?raw` strings, the player's version from a `define`, and the
+ player's built files from the site root, which a dev middleware serves from the player's `dist/`
+ (`playerDistPlugin`). Decided with the owner that day: SCORM 1.2 only, H5P's result rule kept,
+ the tested LMSs the supported ones. Canvas, the audience's LMS, runs its SCORM on Rustici's
+ SCORM Cloud by all accounts and cannot be tested here, since Canvas Free-for-Teacher has no SCORM
+ upload. `scorm-page.test.ts` drives the page in Chromium: a chosen file, the download, which is
+ the command's zip and plays unpacked, a refusal, and the next file after it.
+
`tests/scorm.test.ts` checks the zip, the parts it carries, its stored entries' local headers and
its refusals in Node. In Chromium it plays the unpacked zip under a page that holds the API and
frames the launch page, as Moodle's player does. It covers:
@@ -2755,6 +2800,7 @@ Three artefacts, built three different ways, because they are consumed three dif
| `dist/h5p-sw-mount.js` | esbuild, ESM | For hosts that enforce one worker per origin |
| `dist/h5p-jobs.js` | esbuild, IIFE | The Jobs worker as a file, for a page whose CSP refuses a `blob:` worker |
| `dist/h5p-plan.js` | esbuild, ESM, not minified | The player's library rules, `./plan`, for the packages that write what it plays; the build fails if zip.js gets in |
+| `packages/embed/dist/scorm-page.js` | esbuild, ESM | The SCORM page's script for a written site, which has no bundler: zip.js and the player's `./plan` inside, zip.js's licence in its header |
| `packages/runtime/dist/` | `packages/runtime/scripts/build.mjs` | The H5P core from `vendor/h5p-core/`, its scripts joined and minified under a licence header, its stylesheets rebuilt to stand alone, and the boot script; a package of its own, GPL |
| `apps/demo/dist-demo/` | `apps/demo/scripts/build-demo.mjs` | The hosted demo: the pages, and `dist/`'s layout at the site root |
@@ -3608,7 +3654,8 @@ deliberate additions to it, not drift:
- A VS Code extension. The design has the player on websites; the extension plays a package in
the editor, from a server on the author's own computer.
- A SCORM package. The design emits results and stores none; `h5p-embed --scorm` puts one package
- in an LMS, which records its score, result, time and the learner's place.
+ in an LMS, which records its score, result, time and the learner's place; since #122 a page on
+ the written site, and on the demo, builds the same zip in the browser.
- The libraries are warmed into the cache before the frame boots on a `Range` host. The design
reads every entry on demand; on a high-latency host that made the boot a matter of minutes.
- A library source that cannot be reached falls back to a bundle downloaded whole from the same
diff --git a/apps/demo/demo/index.html b/apps/demo/demo/index.html
index ce55c6f2..6b8b7a1c 100644
--- a/apps/demo/demo/index.html
+++ b/apps/demo/demo/index.html
@@ -96,6 +96,12 @@
More ways to host it
The player as an assignable unit: launched by an LMS, statements to its LRS, completion by the mastery score. The package stays on this site.
+
+ Add the zip to a course as a SCORM activity. The LMS records the score out of 100, whether
+ the content was passed or failed, or completed when it does not say, the time spent, and
+ the learner's place, so the next launch continues where they left off. Content that reports
+ no result of its own, an Accordion or a Virtual Tour, stays incomplete. The package plays
+ with its own code on the LMS's origin, as every SCORM package does.
+
+
+
+
Checked in
Add the zip as
Change from the defaults
+
+
+
Moodle 4.5
a SCORM package activity
nothing; keep the maximum grade at 100
+
ILIAS 11
a SCORM learning module
turn Learning Progress on
+
OpenOLAT 21.1
a "SCORM 1.2" course element
the pass mark; in a learning path, the completion criterion
+
Chamilo 3.0
an imported learning path
publish the learning path
+
SCORM Cloud
a course
nothing
+
Frappe LMS
a SCORM chapter
nothing; the content needs a pass mark
+
+
+
+ Another LMS that takes SCORM 1.2 may work as well; these are the ones checked, as a learner
+ in Chrome. The LMS has to be served over https, since the player needs its Service Worker.
+ SCORM 1.2 keeps 4,096 characters of saved state, enough for a quiz; a larger state is not
+ saved.
+
+
+
What goes in the zip
+
+ The package, the player and the H5P runtime, and a launch page that reports to the LMS. A
+ package exported without its libraries, as h5p.com and h5p.org export, gets the ones it
+ needs from this site's copy of the library pack, and only those: a quiz with formulas takes
+ eleven, most of it the formula renderer. One that carries its libraries, as exports from
+ Lumi and the H5P plugins of Moodle, WordPress and Drupal do, plays with its own. A package
+ that needs a library neither has is refused here, with the library named, rather than in
+ front of a learner.
+
+
+
From the command line
+
+ The same zip, from the same code, for a script or a pipeline; on Node 22 or later. A site
+ written by h5p-embed for a player domain of your own carries this page too, at
+ /scorm.html.
+
+
+
+
+
+
diff --git a/apps/demo/scripts/lib/pages.mjs b/apps/demo/scripts/lib/pages.mjs
index e5fe9e1a..4271e9a1 100644
--- a/apps/demo/scripts/lib/pages.mjs
+++ b/apps/demo/scripts/lib/pages.mjs
@@ -13,6 +13,7 @@ export const PAGES = [
{ name: 'normalize', file: 'demo/normalize.html', path: '/demo/normalize.html' },
{ name: 'xapi', file: 'demo/xapi.html', path: '/demo/xapi.html' },
{ name: 'cmi5', file: 'demo/cmi5.html', path: '/demo/cmi5.html' },
+ { name: 'scorm', file: 'demo/scorm.html', path: '/demo/scorm.html' },
{ name: 'local-file', file: 'demo/local-file.html', path: '/demo/local-file.html' },
{ name: 'two-players', file: 'demo/two-players.html', path: '/demo/two-players.html' },
{ name: 'demo-embed', file: 'demo/embed.html', path: '/demo/embed.html' }
diff --git a/apps/demo/vite.config.ts b/apps/demo/vite.config.ts
index c0d627cb..b98a0515 100644
--- a/apps/demo/vite.config.ts
+++ b/apps/demo/vite.config.ts
@@ -29,6 +29,8 @@ const rootDir = import.meta.dirname
const repositoryRoot = resolve(rootDir, '..', '..')
const playerDir = resolve(repositoryRoot, 'packages', 'player')
const ELEMENT = resolve(playerDir, 'src', 'h5p-offline-player.ts')
+// What the SCORM page's zip names as the player's version, since the pages build the element from source.
+const PLAYER_VERSION: string = JSON.parse(readFileSync(resolve(playerDir, 'package.json'), 'utf8')).version
// The cmi5 wiring from its source too, so the demo needs no build of it either.
const CMI5 = resolve(repositoryRoot, 'packages', 'cmi5', 'src', 'index.ts')
@@ -85,6 +87,35 @@ function appWorkerPlugin(): Plugin {
}
}
+/**
+ * Serves the player's built element and Jobs worker at the site root in dev, for the SCORM page,
+ * which puts them into the zip it builds and so needs the files a host deploys, not the modules
+ * the pages run from source. They are the player's `dist/`, which `pnpm build` writes; before
+ * that the page says so. The build emits `h5p-player.js` there itself and `scripts/build-demo.mjs`
+ * writes `h5p-jobs.js` beside it.
+ */
+function playerDistPlugin(): Plugin {
+ const dist = resolve(playerDir, 'dist')
+ return {
+ name: 'h5p-player-dist',
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ const path = req.url?.split('?')[0]
+ if (path !== '/h5p-player.js' && path !== '/h5p-jobs.js') return next()
+ try {
+ const source = readFileSync(resolve(dist, path.slice(1)))
+ res.setHeader('content-type', 'text/javascript; charset=utf-8')
+ res.setHeader('cache-control', 'no-store')
+ res.end(source)
+ } catch {
+ res.statusCode = 404
+ res.end(`// ${path} is not built: run pnpm build in the repository first.`)
+ }
+ })
+ }
+ }
+}
+
/**
* Serves `/resizer.js` in dev from the embed package, where the script lives; the build copies the
* same file to the site root (`scripts/build-demo.mjs`).
@@ -112,6 +143,7 @@ export default defineConfig(({ command }) => ({
devServiceWorkerPlugin(),
appWorkerPlugin(),
resizerPlugin(),
+ playerDistPlugin(),
// The demo content first, then the player's fixtures: the pages use the former, and the
// latter stay reachable for trying a fixture against the dev server.
noRangeFixturesPlugin([resolve(rootDir, 'demo', 'content'), PLAYER_FIXTURES]),
@@ -122,6 +154,10 @@ export default defineConfig(({ command }) => ({
codeBlocksPlugin()
],
+ define: {
+ __PLAYER_VERSION__: JSON.stringify(PLAYER_VERSION)
+ },
+
resolve: {
alias: [
{ find: /^@missing-elements\/h5p-offline-player$/, replacement: ELEMENT },
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 3bd95df4..175933de 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -96,6 +96,9 @@ What is covered of the pack itself: the `pack` export, `parts/` with its `index.
`cmi.core.lesson_status`, `cmi.core.session_time`, `cmi.core.exit`), and what it keeps in
`cmi.suspend_data`, which a zip written by a later version reads back unless the libraries it
carries from the pack have changed.
+- **The SCORM page**, `scorm.html` on a written site, and **`buildScormInPage()`** and
+ **`startScormPage()`**, with their options and types: the same zip as `buildScorm()`'s, built in
+ the browser.
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. A SCORM zip likewise, replaced in
diff --git a/packages/embed/README.md b/packages/embed/README.md
index 83762912..57e733e0 100644
--- a/packages/embed/README.md
+++ b/packages/embed/README.md
@@ -3,7 +3,8 @@
Writes the H5P embed page as a static site for a player domain of your own. Any site then embeds
a package with an iframe and one script line. No H5P server, no backend, no third-party service.
With `--scorm`, it writes one package as a SCORM zip instead, for an LMS such as Moodle, ILIAS,
-OpenOLAT or Chamilo to play and grade (see
+OpenOLAT or Chamilo to play and grade, and the site it writes carries a page that builds the same
+zip in the browser, for anyone with a `.h5p` and no terminal (see
[A SCORM package, for an LMS](#a-scorm-package-for-an-lms)).
Needs Node 22 or later. Write `@latest`: without it, npm on an older Node quietly installs the
@@ -159,6 +160,14 @@ complete such an activity on viewing it instead. Replacing the zip with one writ
`.h5p`, or with other libraries from the pack, starts learners over, since their saved state
belongs to what it was saved in.
+### In the browser
+
+The site `h5p-embed` writes carries the same converter as a page, `scorm.html`: a `.h5p` chosen
+or dropped on it becomes the same zip, built in the browser from the site's own copies of the
+player, the runtime and the library pack, and offered as a download. Nothing is uploaded and no
+`npx` is needed; the page says which LMSs the zip is checked in and what each needs. The demo
+site has it at [/demo/scorm.html](https://h5p-offline-player.vercel.app/demo/scorm.html).
+
### Supported LMSs
Checked at these versions, as a learner in Chrome. Other LMSs have not been tried yet.
@@ -225,6 +234,17 @@ export, which `libraries=pack` then plays from) or `packBase` (the folder of a c
`force`, and returns the zip's path, its title, size, the `libraries` it carries from the pack,
and `build`, the stamp saved state is kept against. Every entry ships with TypeScript declarations.
+`buildScormInPage` from `@missing-elements/h5p-embed/scorm/browser` is the same build in a page:
+it takes `file`, a `File` or `Blob`; `base`, the folder with the player's three files and
+`frame-assets/` (the page's own by default); `pack` or `packBase`, as `startEmbed` takes them;
+`assets`, for a page that bundles the launch page's template, its bridge, `embed.css` and the
+pack's `libraries.txt` rather than serving them beside the player as the written site does;
+`version` and `packVersion`, for the zip's notice; and `onProgress`. It returns the zip as a
+`Blob`, with its `name`, `title`, `libraries`, `build` and `size`. `startScormPage` from
+`@missing-elements/h5p-embed/scorm-page.js` is the page's script, which reads the page's
+`#file`, `#status`, `#download` and `#notice` (see `site/scorm.html`); the written site loads it
+bundled, with zip.js inside, and a page that bundles imports the source.
+
```js
import '@missing-elements/h5p-offline-player'
import { runtime } from '@missing-elements/h5p-runtime'
@@ -252,4 +272,5 @@ under the GPL-3.0, as `frame-assets/` with its `LICENSE.txt` and `NOTICE.txt`, a
`--no-libraries`, the hub's libraries under their own licences, listed in `libraries.txt`. The
folder's `NOTICE.txt` says which file is what. A SCORM zip carries the runtime the same way, the
package under its own licences, and any libraries from the pack as the folder does; its
-`NOTICE.txt` says the same.
+`NOTICE.txt` says the same. The folder's `scorm-page.js` carries zip.js, BSD-3-Clause, with its
+licence in its header, as the player's workers do.
diff --git a/packages/embed/lib/build.mjs b/packages/embed/lib/build.mjs
index e729ea0b..341fbbb6 100644
--- a/packages/embed/lib/build.mjs
+++ b/packages/embed/lib/build.mjs
@@ -2,6 +2,7 @@ import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promi
import { createRequire } from 'node:module'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { EmbedError, PLAYER_FILES } from './shared.mjs'
/**
* Writes the embed page as a static site: one folder, deployable to any static host, that a site
@@ -9,22 +10,30 @@ import { fileURLToPath } from 'node:url'
* and its workers from the player's `dist/`, the H5P runtime from its own package as
* `frame-assets/`, the library pack's parts from `@missing-elements/h5p-libraries` as
* `libraries/` — so the versions are the ones this package was published with, and nothing is
- * fetched.
+ * fetched. The SCORM page goes in beside it, with the launch page's template and bridge it
+ * builds a zip from, so a teacher on the site makes one with nothing but a browser.
*/
-export class EmbedError extends Error {}
+export { EmbedError } from './shared.mjs'
const require = createRequire(import.meta.url)
// `fileURLToPath` rather than `import.meta.dirname`, which Node 20 has only from 20.11.
const SITE = fileURLToPath(new URL('../site', import.meta.url))
+const SCORM = fileURLToPath(new URL('../scorm', import.meta.url))
+const DIST = fileURLToPath(new URL('../dist', import.meta.url))
-/** The page's own files, copied as they are; `index.html` is written, not copied. */
-const PAGE_FILES = ['embed.js', 'embed.css', 'main.js', 'resizer.js']
+/** The page's own files, copied as they are; `index.html` and `scorm.html` are written, not copied. */
+const PAGE_FILES = ['embed.js', 'embed.css', 'main.js', 'resizer.js', 'scorm-main.js', 'scorm-page.css']
/**
- * The player's files, by the names the element looks for beside itself.
- * @internal
+ * What the SCORM page builds a zip from, under the names its script fetches them by: the launch
+ * page's template and its bridge, from `scorm/`; and the page's script as `scripts/build.mjs`
+ * bundles it, since the site has no bundler and the script imports zip.js.
*/
-export const PLAYER_FILES = ['h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js']
+const SCORM_FILES = [
+ ['scorm-launch.html', join(SCORM, 'index.html')],
+ ['scorm.js', join(SCORM, 'scorm.js')],
+ ['scorm-page.js', join(DIST, 'scorm-page.js')]
+]
/**
* Where an installed package's file is, or a message that says which one is missing.
@@ -305,6 +314,10 @@ function notice({ version, libraries }) {
index.html, main.js, embed.js, embed.css, resizer.js, config.js
the embed page and the sizing script: MIT
+ scorm.html, scorm-main.js, scorm-page.js, scorm-page.css, scorm-launch.html, scorm.js
+ the SCORM page, which builds a SCORM package of a .h5p in the browser, and
+ the launch page it puts in the zip: MIT. scorm-page.js also carries zip.js,
+ BSD-3-Clause, its licence in its header.
Caddyfile, nginx.conf, .htaccess, _headers, vercel.json
the same headers for five kinds of host; use the one yours reads
h5p-player.js, h5p-sw.js, h5p-jobs.js
@@ -386,9 +399,14 @@ export async function buildSite({ out, libraries = true, packages = null, ancest
const runtime = dirname(installed('@missing-elements/h5p-runtime/dist/h5p.css', 'Run `pnpm build` in the workspace, or reinstall this package.'))
const pack = libraries ? dirname(installed('@missing-elements/h5p-libraries/parts/index.json', 'Reinstall this package, or pass --no-libraries.')) : null
const version = (await readFile(join(player, 'VERSION'), 'utf8').catch(() => 'unknown')).trim()
+ const packVersion = pack ? String(JSON.parse(await readFile(join(dirname(pack), 'package.json'), 'utf8')).version) : null
+ for (const [, file] of SCORM_FILES) {
+ if (!(await stat(file).catch(() => null))?.isFile()) throw new EmbedError(`${file} is missing. Run \`pnpm build\` in packages/embed, or reinstall this package.`)
+ }
await mkdir(target, { recursive: true })
for (const name of PAGE_FILES) await cp(join(SITE, name), join(target, name))
+ for (const [name, file] of SCORM_FILES) await cp(file, join(target, name))
for (const name of PLAYER_FILES) await cp(join(player, name), join(target, name))
await rm(join(target, 'frame-assets'), { recursive: true, force: true })
await cp(runtime, join(target, 'frame-assets'), { recursive: true })
@@ -402,11 +420,15 @@ export async function buildSite({ out, libraries = true, packages = null, ancest
await rm(join(target, 'libraries.txt'), { force: true })
}
- const html = await readFile(join(SITE, 'index.html'), 'utf8')
- await writeFile(join(target, 'index.html'), html.replace('%CSP%', contentSecurityPolicy({ packages: allowedPackages, meta: true })))
+ const metaPolicy = contentSecurityPolicy({ packages: allowedPackages, meta: true })
+ for (const page of ['index.html', 'scorm.html']) {
+ const html = await readFile(join(SITE, page), 'utf8')
+ await writeFile(join(target, page), html.replace('%CSP%', metaPolicy))
+ }
+ // The versions are for the SCORM page's notice: its zip names what it carries, as the command's does.
await writeFile(
join(target, 'config.js'),
- `// Written by h5p-embed: what main.js hands the page.\nexport default ${JSON.stringify({ libraries: Boolean(pack), packages: allowedPackages, defaultLibraries: fallbackLibraries })}\n`
+ `// Written by h5p-embed: what main.js and scorm-main.js hand their pages.\nexport default ${JSON.stringify({ libraries: Boolean(pack), packages: allowedPackages, defaultLibraries: fallbackLibraries, version, packVersion })}\n`
)
const csp = contentSecurityPolicy({ packages: allowedPackages, ancestors: allowedAncestors })
diff --git a/packages/embed/lib/scorm-browser.mjs b/packages/embed/lib/scorm-browser.mjs
new file mode 100644
index 00000000..e40f5885
--- /dev/null
+++ b/packages/embed/lib/scorm-browser.mjs
@@ -0,0 +1,168 @@
+import { BlobWriter, ZipWriter } from '@zip.js/zip.js'
+import { packLibrariesIn } from '@missing-elements/h5p-offline-player/plan'
+import { addScormEntries, buildStamp, readPackage, runtimeFiles, scormEntries, scormTitle, sha256Hex } from './scorm-core.mjs'
+import { EmbedError, PLAYER_FILES } from './shared.mjs'
+
+/**
+ * @missing-elements/h5p-embed/scorm/browser: the SCORM package built in a page, for the people
+ * who need one and do not run `npx`. The same zip `buildScorm` writes, from the same code
+ * (`scorm-core.mjs`), but the package is a `File` the page was given, the player, the runtime and
+ * the library pack come from the site the page is on, and the zip comes back as a `Blob` for a
+ * download link. Nothing is uploaded anywhere. It needs a secure context, https or localhost, for
+ * `crypto.subtle`.
+ */
+
+/**
+ * @typedef {import('@missing-elements/h5p-offline-player').LibraryPack} PackIndex
+ * the `pack` export of `@missing-elements/h5p-libraries` as a bundler emits it: the index, each
+ * library with its part's URL, as the element's `pack` property takes it
+ * @typedef {{ step: 'reading' | 'libraries' | 'writing', libraries?: number }} ScormProgress
+ * where the build is: reading the package, fetching its `libraries` parts of the pack, writing
+ * the zip
+ */
+
+/**
+ * @typedef {object} PageScormOptions
+ * @property {Blob} file the package, as picked or dropped
+ * @property {string} [name] its file name, for the zip's name, the title's fallback and the
+ * messages; a `File`'s own by default
+ * @property {string | URL} [base] the folder that holds the player's three files and
+ * `frame-assets/`, and, unless `assets` gives them, `scorm-launch.html`, `scorm.js`, `embed.css`
+ * and `libraries.txt`: this page's own folder by default
+ * @property {PackIndex | null} [pack] the library pack, as the `pack` export a bundler resolves;
+ * it wins over `packBase`
+ * @property {string | URL | null} [packBase] the folder of a copy of the pack's `parts/`, which
+ * the written site has as `libraries/`. Without either, a package that does not carry its
+ * libraries is refused
+ * @property {{ launch?: string, bridge?: string | Blob, css?: string | Blob, libraries?: string | Blob }} [assets]
+ * the launch page's template, its bridge, the stylesheet and the pack's licence list, for a page
+ * that bundles them rather than serving them beside the player
+ * @property {string} [version] the player's version, for the notice; `unknown` if not given
+ * @property {string | null} [packVersion] the pack's, the same way
+ * @property {(progress: ScormProgress) => void} [onProgress]
+ * @property {typeof fetch} [fetch]
+ */
+
+/**
+ * What `buildScormInPage` built.
+ * @typedef {object} PageScorm
+ * @property {Blob} blob the zip
+ * @property {string} name what to call it: the package's name with `.scorm.zip` in place of its extension
+ * @property {string} title the package's title, as the LMS lists it
+ * @property {string} version the player's version, as given
+ * @property {string[]} libraries the folders of the libraries the zip carries from the pack
+ * @property {string} build the build stamp, as `buildScorm` returns it
+ * @property {number} size the zip's size in bytes
+ */
+
+/**
+ * @param {typeof fetch} fetchImpl
+ * @param {string} url
+ * @param {string} what
+ */
+async function fetched(fetchImpl, url, what) {
+ let response
+ try {
+ response = await fetchImpl(url)
+ } catch (error) {
+ throw new EmbedError(`${what} could not be fetched from ${url}: ${error instanceof Error ? error.message : error}`)
+ }
+ if (!response.ok) throw new EmbedError(`${what} is not at ${url}: it answered ${response.status}.`)
+ return response
+}
+
+/**
+ * A text or a `Blob` given, as a `Blob`.
+ * @param {string | Blob} value
+ */
+const asBlob = (value) => (value instanceof Blob ? value : new Blob([value]))
+
+/**
+ * Builds the SCORM 1.2 zip of a package in a page, and returns it as a `Blob`. Refuses what
+ * `buildScorm` refuses, with the same messages, and a part of the pack whose bytes do not match
+ * the index, since they came over the network.
+ * @param {PageScormOptions} options
+ * @returns {Promise}
+ */
+export async function buildScormInPage(options) {
+ const { file, pack = null, packBase = null, assets = {}, version = 'unknown', packVersion = null, onProgress = () => {}, fetch: fetchImpl = globalThis.fetch } = options ?? {}
+ if (!(file instanceof Blob)) throw new TypeError('Give the package as a File or a Blob')
+ if (!globalThis.crypto?.subtle) {
+ throw new EmbedError('A page builds SCORM packages in a secure context only, https or localhost: it needs crypto.subtle, which a page has nowhere else.')
+ }
+ const name = options.name ?? (/** @type {{ name?: unknown }} */ (file).name)
+ if (typeof name !== 'string' || !name) throw new TypeError("Give the package's name: a Blob has none")
+ const base = new URL(options.base ?? './', globalThis.location?.href)
+ if (!base.href.endsWith('/')) base.pathname += '/'
+ /** @param {string} path */
+ const at = (path) => new URL(path, base).href
+
+ // The pack as the page can reach it, held to its shape by the player's own rule; a part's
+ // record, what the zip's index repeats, is the entry without its address.
+ /** @type {import('./scorm-core.mjs').PackPart[]} */
+ let parts = []
+ /** @type {unknown[]} */
+ let index = []
+ if (pack) {
+ index = (Array.isArray(pack.libraries) ? pack.libraries : []).map((entry) => ({ ...entry, url: new URL(entry.url, base).href }))
+ } else if (packBase) {
+ const packUrl = new URL(packBase, base)
+ if (!packUrl.href.endsWith('/')) packUrl.pathname += '/'
+ const listed = await (await fetched(fetchImpl, new URL('index.json', packUrl).href, "The library pack's index")).json()
+ index = (Array.isArray(listed?.libraries) ? listed.libraries : []).map((/** @type {any} */ entry) => (
+ entry && typeof entry === 'object' && typeof entry.folder === 'string' ? { ...entry, url: new URL(`${entry.folder}.h5p`, packUrl).href } : null
+ ))
+ }
+ const library = packLibrariesIn(index).map((entry) => {
+ const { url, ...record } = entry
+ return { ...record, url, record }
+ })
+
+ onProgress({ step: 'reading' })
+ let manifest
+ try {
+ ;({ manifest, parts } = await readPackage(file, name, library))
+ } catch (error) {
+ // Without a pack, say so, rather than that the pack lacks what the package needs.
+ if (error instanceof EmbedError && library.length === 0 && /neither it nor the library pack carries/.test(error.message)) {
+ throw new EmbedError(`${name} does not carry all its libraries, and this page has no library pack to take them from. Export the package with its libraries, as Lumi and the H5P plugins of Moodle, WordPress and Drupal do.`)
+ }
+ throw error
+ }
+ const title = scormTitle(manifest, name.replace(/\.[^.]+$/, ''))
+
+ onProgress({ step: 'libraries', libraries: parts.length })
+ /** @param {string} url @param {string} what */
+ const blob = async (url, what) => (await fetched(fetchImpl, url, what)).blob()
+ /** @param {string[]} names @param {(name: string) => string} url @param {string} what */
+ const blobs = async (names, url, what) => new Map(await Promise.all(names.map(async (item) => /** @type {[string, Blob]} */ ([item, await blob(url(item), `${what} ${item}`)]))))
+ const partBlobs = await blobs(parts.map((part) => part.folder), (folder) => /** @type {import('./scorm-core.mjs').PackPart} */ (parts.find((part) => part.folder === folder)).url, 'The library part')
+ // Checked as the player checks a part before it uses one: these bytes came over the network.
+ for (const part of parts) {
+ const bytes = await /** @type {Blob} */ (partBlobs.get(part.folder)).arrayBuffer()
+ if ((await sha256Hex(bytes)) !== part.sha256) {
+ throw new EmbedError(`The library part ${part.folder} from ${part.url} does not match the pack's index, so the zip was not written.`)
+ }
+ }
+ const runtimeManifest = await (await fetched(fetchImpl, at('frame-assets/MANIFEST.json'), "The runtime's manifest")).json()
+ const files = {
+ launch: assets.launch ?? (await (await fetched(fetchImpl, at('scorm-launch.html'), "The launch page's template")).text()),
+ bridge: assets.bridge !== undefined ? asBlob(assets.bridge) : await blob(at('scorm.js'), 'The launch page\'s script'),
+ css: assets.css !== undefined ? asBlob(assets.css) : await blob(at('embed.css'), 'The stylesheet'),
+ player: await blobs(PLAYER_FILES, at, "The player's file"),
+ runtime: await blobs(runtimeFiles(runtimeManifest), (path) => at(`frame-assets/${path}`), "The runtime's file"),
+ pkg: file,
+ parts: partBlobs,
+ librariesText: parts.length === 0 ? null : assets.libraries !== undefined ? asBlob(assets.libraries) : await blob(at('libraries.txt'), "The pack's licence list")
+ }
+
+ // The whole package in memory once, for its hash: `crypto.subtle` takes no stream.
+ const build = await buildStamp(await sha256Hex(await file.arrayBuffer()), parts)
+ const { entries, xml } = scormEntries({ manifest, source: name, title, build, version, packVersion, parts, files })
+
+ onProgress({ step: 'writing' })
+ const zip = new ZipWriter(new BlobWriter('application/zip'), { useWebWorkers: false })
+ await addScormEntries(zip, { entries, xml })
+ const out = await zip.close()
+ return { blob: out, name: `${name.replace(/\.[^.]+$/, '')}.scorm.zip`, title, version, libraries: parts.map((part) => part.folder), build, size: out.size }
+}
diff --git a/packages/embed/lib/scorm-core.mjs b/packages/embed/lib/scorm-core.mjs
new file mode 100644
index 00000000..690dc661
--- /dev/null
+++ b/packages/embed/lib/scorm-core.mjs
@@ -0,0 +1,344 @@
+import { BlobReader, TextReader, TextWriter, ZipReader } from '@zip.js/zip.js'
+import { crc32 } from '@missing-elements/h5p-normalize/crc32'
+import { dependenciesIn, indexLibraryFolders, librariesNamedIn, ownLibraries, planPack, reachableFolder, walkDependencies } from '@missing-elements/h5p-offline-player/plan'
+import { EmbedError, PLAYER_FILES } from './shared.mjs'
+
+/**
+ * What the SCORM package is, wherever it is written. The command's `buildScorm` in Node and the
+ * page's `buildScormInPage` in a browser read the package and plan its parts here, lay out the
+ * same entries and write them the same way, and differ only in where the bytes come from and
+ * where the zip goes: so a zip built in a browser is the zip the command writes, which is what
+ * the LMSs were checked with. No Node import, so the page's bundle carries this as it is.
+ */
+
+/** What the zip calls the package; the launch page plays it by this name. */
+export const PACKAGE = 'package.h5p'
+/** Where the zip keeps the library pack's parts it carries, as the embed site does. */
+export const LIBRARIES = 'libraries'
+
+/**
+ * The runtime's `dist/` as a page has to name it, since a folder on a server cannot be listed:
+ * every file but the fonts, which `MANIFEST.json` names. Node lists the folder instead, and the
+ * test of the page's build holds the two to each other, so a file the runtime adds shows up there.
+ */
+export const RUNTIME_FILES = ['frame.bundle.js', 'frame-boot.js', 'h5p.css', 'l10n.js', 'LICENSE.txt', 'NOTICE.txt', 'MANIFEST.json', 'fonts/Inter-LICENSE.txt', 'fonts/OpenSans-OFL.txt']
+
+/**
+ * The runtime's files, from its manifest: `RUNTIME_FILES` and the fonts it names.
+ * @param {unknown} manifest the runtime's `MANIFEST.json`, parsed
+ */
+export function runtimeFiles(manifest) {
+ const fonts = /** @type {{ fonts?: unknown } | null} */ (manifest)?.fonts
+ const named = (Array.isArray(fonts) ? fonts : []).flatMap((font) => (typeof font?.file === 'string' ? [`fonts/${font.file}`] : []))
+ return [...RUNTIME_FILES, ...named]
+}
+
+/**
+ * A part of the library pack as the writer takes it: its record in the index, which the zip's
+ * index repeats as `record`, and where its archive is.
+ * @typedef {import('@missing-elements/h5p-offline-player/plan').PackLibrary & { url: string, record: import('@missing-elements/h5p-offline-player/plan').PackLibrary }} PackPart
+ */
+
+/** @param {string} text */
+const escapeXml = (text) =>
+ text.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char)
+
+/** @param {string} text */
+const escapeHtml = (text) => text.replace(/[&<>"]/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[char] ?? char)
+
+/**
+ * The page's language: `h5p.json`'s `defaultLanguage` when it is a language tag, else English.
+ * @param {unknown} value
+ */
+function languageTag(value) {
+ return typeof value === 'string' && /^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(value) ? value : 'en'
+}
+
+/**
+ * The manifest, SCORM 1.2's: one organisation with one item, played by one SCO, the launch page.
+ * Every file is listed, which Moodle does not need and some LMSs do.
+ * @param {{ identifier: string, title: string, files: string[] }} manifest
+ */
+function manifestXml({ identifier, title, files }) {
+ const name = escapeXml(title)
+ return `
+
+
+ ADL SCORM
+ 1.2
+
+
+
+ ${name}
+
+ ${name}
+
+
+
+
+
+${files.map((file) => ` `).join('\n')}
+
+
+
+`
+}
+
+/** @param {{ version: string, source: string, pack: string | null }} zip `pack`, the library pack's version when the zip carries parts of it */
+function notice({ version, source, pack }) {
+ return `This is a SCORM 1.2 package written by @missing-elements/h5p-embed. It plays ${source} in an
+LMS and reports its score, its result and the time spent, and keeps the learner's place.
+
+ imsmanifest.xml the package's manifest
+ index.html, scorm.js, embed.css
+ the launch page and its bridge to the LMS: MIT
+ h5p-player.js, h5p-sw.js, h5p-jobs.js
+ @missing-elements/h5p-offline-player ${version}: MIT. The Service Worker,
+ h5p-sw.js, also carries zip.js, BSD-3-Clause, its licence in its header.
+ frame-assets/ @missing-elements/h5p-runtime, the H5P core runtime: GPL-3.0-only. Its
+ LICENSE.txt and NOTICE.txt say what it is and where its source is; keep them
+ with it.
+ ${PACKAGE} the H5P package, its content and libraries under their own licences, which its
+ h5p.json and each library's library.json name.
+${
+ pack
+ ? ` ${LIBRARIES}/ @missing-elements/h5p-libraries ${pack}, the H5P hub's libraries: those the package
+ needs and does not carry, one archive per library and index.json, each under
+ its own licence, listed in libraries.txt.
+`
+ : ''
+}
+https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed
+`
+}
+
+/**
+ * A `Blob`'s CRC-32, read as a stream.
+ * @param {Blob} blob
+ */
+async function crcOf(blob) {
+ const reader = blob.stream().getReader()
+ let crc = 0
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) return crc
+ crc = crc32(value, crc)
+ }
+}
+
+/**
+ * SHA-256 as lower-case hex, by the browser's and Node's `crypto.subtle`.
+ * @param {BufferSource} data
+ */
+export async function sha256Hex(data) {
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', data))
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')
+}
+
+/**
+ * The build stamp a learner's saved place is kept against: the package's SHA-256, or, with parts
+ * of the pack, one over its and theirs, so a zip written with other libraries starts learners
+ * over, as a refreshed package does in the player; its first 16 hex digits.
+ * @param {string} packageSha256 the package's, as hex
+ * @param {PackPart[]} parts
+ */
+export async function buildStamp(packageSha256, parts) {
+ const hashes = [packageSha256, ...parts.map((part) => part.sha256)]
+ const stamp = hashes.length === 1 ? hashes[0] : await sha256Hex(new TextEncoder().encode(hashes.join('\n')))
+ return stamp.slice(0, 16)
+}
+
+/**
+ * The package's title, as the LMS lists it: `h5p.json`'s, with the control characters XML refuses
+ * read as spaces, since a title pasted in can carry one; or the file's name.
+ * @param {unknown} manifest `h5p.json`, parsed
+ * @param {string} fallback
+ */
+export function scormTitle(manifest, fallback) {
+ const title = /** @type {{ title?: unknown } | null} */ (manifest)?.title
+ const named = typeof title === 'string' ? title.replace(/[\x00-\x1f\x7f]+/g, ' ').trim() : ''
+ return named || fallback
+}
+
+/**
+ * What the package declares and carries, and what the pack adds, read before anything is
+ * written: `h5p.json`, and the parts of the pack the zip carries, by the player's own plan.
+ * Refuses a package that needs a library neither it nor the pack has.
+ *
+ * @param {Blob} blob the package
+ * @param {string} name what to call it in a message
+ * @param {PackPart[]} pack the library pack, as the writer takes it
+ * @param {{ useWebWorkers?: boolean }} [options] zip.js's, for the reader
+ * @returns {Promise<{ manifest: any, parts: PackPart[] }>} `manifest`, `h5p.json` parsed; `parts`, sorted by folder
+ */
+export async function readPackage(blob, name, pack, { useWebWorkers = false } = {}) {
+ let reader
+ try {
+ reader = new ZipReader(new BlobReader(blob), { useWebWorkers })
+ // One unsafe name does not refuse the package, as it does not in the player, which leaves that
+ // entry out.
+ const entries = await reader.getEntries({ filenameValidation: 'tolerant' })
+ const byName = new Map(entries.filter((entry) => !entry.directory).map((entry) => [entry.filename, entry]))
+ /** @param {string} entryName */
+ const readJson = async (entryName) => {
+ const entry = byName.get(entryName)
+ if (!entry?.getData) throw new EmbedError(`${name} has no ${entryName}: it is not an H5P package.`)
+ const text = await entry.getData(new TextWriter())
+ try {
+ return JSON.parse(text)
+ } catch {
+ throw new EmbedError(`${name}: ${entryName} is not JSON.`)
+ }
+ }
+ const manifest = await readJson('h5p.json')
+ if (dependenciesIn(manifest).length === 0) {
+ throw new EmbedError(`${name}: h5p.json names no libraries, so there is nothing to play.`)
+ }
+ const params = await readJson('content/content.json')
+ /** @param {{ machineName: string, majorVersion: string | number, minorVersion: string | number }} dependency */
+ const numbered = ({ machineName, majorVersion, minorVersion }) => ({ machineName, majorVersion: Number(majorVersion), minorVersion: Number(minorVersion) })
+ const roots = [...dependenciesIn(manifest), ...librariesNamedIn(params)].map(numbered)
+ const folders = [...byName.keys()].flatMap((entryName) => {
+ const match = /^([^/]+)\/library\.json$/.exec(entryName)
+ return match ? [match[1]] : []
+ })
+ // The player's own plan, as the launch page has the element run it: gaps filled from the pack,
+ // nothing provided before, no refresh (`refresh-libraries="off"`).
+ const plan = planPack({ own: await ownLibraries(folders, (folder) => readJson(`${folder}/library.json`)), provided: [], roots, params, pack, refresh: false, fill: true })
+ const byFolder = new Map(pack.map((library) => [library.folder, library]))
+ const parts = (plan?.parts ?? []).map((part) => /** @type {PackPart} */ (byFolder.get(part.folder))).sort((a, b) => (a.folder < b.folder ? -1 : a.folder > b.folder ? 1 : 0))
+
+ // Held to its libraries as the player holds it once the parts are attached: the folders they
+ // replace withheld, and each part's `library.json` naming what its record in the index does.
+ const records = new Map(parts.map((part) => [`${part.folder}/library.json`, part.record]))
+ const withheld = new Set(plan?.superseded ?? [])
+ const names = new Set([...byName.keys()].filter((entryName) => !withheld.has(entryName.split('/')[0])))
+ for (const entryName of records.keys()) names.add(entryName)
+ const available = indexLibraryFolders(names)
+ const { missing } = await walkDependencies(
+ roots,
+ (dependency) => reachableFolder(dependency, names, available),
+ async (folder) => records.get(`${folder}/library.json`) ?? readJson(`${folder}/library.json`)
+ )
+ if (missing.length > 0) {
+ const packed = new Map(pack.map((library) => [`${library.machineName} ${library.majorVersion}`, library]))
+ const listed = missing
+ .map(({ machineName, majorVersion, minorVersion }) => {
+ const older = packed.get(`${machineName} ${Number(majorVersion)}`)
+ return `${machineName} ${majorVersion}.${minorVersion}${older ? ` (the pack has ${older.majorVersion}.${older.minorVersion})` : ''}`
+ })
+ .sort()
+ throw new EmbedError(
+ `${name} needs libraries that neither it nor the library pack carries: ${listed.join(', ')}. ` +
+ 'Export the package with its libraries, as Lumi and the H5P plugins of Moodle, WordPress and Drupal do.'
+ )
+ }
+ return { manifest, parts }
+ } catch (error) {
+ if (error instanceof EmbedError) throw error
+ throw new EmbedError(`${name} could not be read as a zip archive: ${error instanceof Error ? error.message : error}`)
+ } finally {
+ await reader?.close()
+ }
+}
+
+/**
+ * An entry of the zip: a text the writer makes, or bytes it was given.
+ * @typedef {{ name: string, text: string } | { name: string, blob: Blob }} ScormEntry
+ */
+
+/**
+ * What the zip is made of, gathered by whoever has the files: the launch page's template and
+ * the bridge and stylesheet beside it; the player's files by name; the runtime's by path under
+ * `frame-assets/`; the package; the parts of the pack by folder; and the pack's licence list,
+ * when parts are carried.
+ * @typedef {object} ScormFiles
+ * @property {string} launch the launch page's template, `scorm/index.html`
+ * @property {Blob} bridge `scorm/scorm.js`
+ * @property {Blob} css `embed.css`
+ * @property {Map} player the player's files, by name
+ * @property {Map} runtime the runtime's files, by path under `frame-assets/`
+ * @property {Blob} pkg the package
+ * @property {Map} parts the parts of the pack the zip carries, by folder
+ * @property {Blob | null} librariesText the pack's `libraries.txt`; `null` when no part is carried
+ */
+
+/**
+ * Everything the zip holds, in the order it is written, with the manifest that lists it: the
+ * launch page filled in with the content's language, the title and the build, and naming the
+ * zip's own copy of the pack when it carries one.
+ *
+ * @param {object} input
+ * @param {any} input.manifest `h5p.json`, parsed
+ * @param {string} input.source the package's file name, for the notice
+ * @param {string} input.title
+ * @param {string} input.build the build stamp
+ * @param {string} input.version the player's version, as its `dist/VERSION` says
+ * @param {string | null} input.packVersion the library pack's version; read when the zip carries parts of it
+ * @param {PackPart[]} input.parts the parts carried, sorted by folder
+ * @param {ScormFiles} input.files
+ * @returns {{ entries: ScormEntry[], xml: string }}
+ */
+export function scormEntries({ manifest, source, title, build, version, packVersion, parts, files }) {
+ const pack = parts.length > 0 ? packVersion ?? 'unknown' : null
+ const page = files.launch
+ .replace('%LANG%', languageTag(manifest.defaultLanguage))
+ // A function, so that a title's `$&` or `$'` is written as it is rather than read as a pattern.
+ .replace('%TITLE%', () => escapeHtml(title))
+ .replace('%BUILD%', build)
+ // The element plans from the zip's index what the writer planned, and plays the package's own
+ // libraries as they are.
+ .replace('%LIBRARIES%', pack ? ` libraries="pack" pack-base="./${LIBRARIES}/" refresh-libraries="off"` : '')
+ /** @param {Map} map @param {string} name @param {string} what */
+ const given = (map, name, what) => {
+ const blob = map.get(name)
+ if (!blob) throw new EmbedError(`${what} ${name} was not given.`)
+ return blob
+ }
+ /** @type {ScormEntry[]} */
+ const entries = [
+ { name: 'index.html', text: page },
+ { name: 'scorm.js', blob: files.bridge },
+ { name: 'embed.css', blob: files.css },
+ ...PLAYER_FILES.map((name) => ({ name, blob: given(files.player, name, "The player's file") })),
+ ...[...files.runtime.keys()].sort().map((name) => ({ name: `frame-assets/${name}`, blob: given(files.runtime, name, "The runtime's file") })),
+ { name: PACKAGE, blob: files.pkg }
+ ]
+ if (pack) {
+ entries.push({ name: `${LIBRARIES}/index.json`, text: `${JSON.stringify({ libraries: parts.map((part) => part.record) }, null, 2)}\n` })
+ for (const part of parts) entries.push({ name: `${LIBRARIES}/${part.folder}.h5p`, blob: given(files.parts, part.folder, 'The library part') })
+ if (!files.librariesText) throw new EmbedError("The pack's libraries.txt was not given.")
+ entries.push({ name: 'libraries.txt', blob: files.librariesText })
+ }
+ entries.push({ name: 'NOTICE.txt', text: notice({ version, source, pack }) })
+ const xml = manifestXml({ identifier: `h5p-${build}`, title, files: ['imsmanifest.xml', ...entries.map((entry) => entry.name)] })
+ return { entries, xml }
+}
+
+/**
+ * Writes the manifest and the entries into a zip.js writer, which the caller opens on a file or a
+ * `Blob` and closes.
+ * @param {import('@zip.js/zip.js').ZipWriter} zip
+ * @param {{ entries: ScormEntry[], xml: string }} content
+ */
+export async function addScormEntries(zip, { entries, xml }) {
+ await zip.add('imsmanifest.xml', new TextReader(xml))
+ for (const entry of entries) {
+ if ('text' in entry) {
+ await zip.add(entry.name, new TextReader(entry.text), { level: 6 })
+ continue
+ }
+ const { name, blob } = entry
+ // The package, the pack's parts and the fonts are compressed already, so they are stored.
+ // Written into a stream, an entry gets a data descriptor, and a Java ZipInputStream refuses
+ // a stored entry that has one: SCORM Cloud refused exactly those (#92). Passed through with
+ // its size and CRC, it gets a complete local header instead, and is still streamed, not held.
+ if (name.endsWith('.h5p') || name.endsWith('.woff2')) {
+ await zip.add(name, new BlobReader(blob), { passThrough: true, compressionMethod: 0, uncompressedSize: blob.size, crc32: await crcOf(blob) })
+ } else {
+ await zip.add(name, new BlobReader(blob), { level: 6 })
+ }
+ }
+}
diff --git a/packages/embed/lib/scorm.mjs b/packages/embed/lib/scorm.mjs
index 5486a73d..62be70ad 100644
--- a/packages/embed/lib/scorm.mjs
+++ b/packages/embed/lib/scorm.mjs
@@ -4,10 +4,10 @@ import { readdir, readFile, rename, rm, stat } from 'node:fs/promises'
import { basename, dirname, extname, join, resolve, sep } from 'node:path'
import { Writable } from 'node:stream'
import { fileURLToPath, pathToFileURL } from 'node:url'
-import { BlobReader, TextReader, TextWriter, ZipReader, ZipWriter, configure } from '@zip.js/zip.js'
-import { crc32 } from '@missing-elements/h5p-normalize/crc32'
-import { dependenciesIn, indexLibraryFolders, librariesNamedIn, ownLibraries, planPack, reachableFolder, walkDependencies } from '@missing-elements/h5p-offline-player/plan'
-import { EmbedError, PLAYER_FILES, installed } from './build.mjs'
+import { ZipWriter } from '@zip.js/zip.js'
+import { installed } from './build.mjs'
+import { addScormEntries, buildStamp, readPackage, scormEntries, scormTitle } from './scorm-core.mjs'
+import { EmbedError, PLAYER_FILES } from './shared.mjs'
/**
* Writes a SCORM 1.2 package that plays one `.h5p` in an LMS and reports its result there: the
@@ -22,24 +22,21 @@ import { EmbedError, PLAYER_FILES, installed } from './build.mjs'
* library neither has is refused here rather than in front of a learner. Checked against Moodle 4.5
* on 2026-10-28: the worker registered under `pluginfile.php`, the package was read by ranges, and
* the score reached the gradebook.
+ *
+ * What the zip is and how it is written is `scorm-core.mjs`'s, shared with the page's builder;
+ * this is the Node side: the files from the installed packages, and the zip to a path.
*/
-configure({ useWebWorkers: false })
-
const SCORM = fileURLToPath(new URL('../scorm', import.meta.url))
const SITE = fileURLToPath(new URL('../site', import.meta.url))
-/** What the zip calls the package; the launch page plays it by this name. */
-const PACKAGE = 'package.h5p'
-/** Where the zip keeps the library pack's parts it carries, as the embed site does. */
-const LIBRARIES = 'libraries'
-
/**
* The library pack's index, its `parts/index.json`, as the plan takes it: each library's record,
* which the zip's index repeats as `record`, with the part's file as `url`. A record the index got
* wrong is left out.
* @param {unknown} index
* @param {string} packDir the folder holding the index and the parts
+ * @returns {import('./scorm-core.mjs').PackPart[]}
*/
function packLibraries(index, packDir) {
const list = /** @type {{ libraries?: unknown } | null} */ (index)?.libraries
@@ -51,81 +48,6 @@ function packLibraries(index, packDir) {
})
}
-/** @param {string} text */
-const escapeXml = (text) =>
- text.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char)
-
-/** @param {string} text */
-const escapeHtml = (text) => text.replace(/[&<>"]/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[char] ?? char)
-
-/**
- * The page's language: `h5p.json`'s `defaultLanguage` when it is a language tag, else English.
- * @param {unknown} value
- */
-function languageTag(value) {
- return typeof value === 'string' && /^[a-z]{2,3}(?:-[a-z0-9]{1,8})*$/i.test(value) ? value : 'en'
-}
-
-/**
- * The manifest, SCORM 1.2's: one organisation with one item, played by one SCO, the launch page.
- * Every file is listed, which Moodle does not need and some LMSs do.
- * @param {{ identifier: string, title: string, files: string[] }} manifest
- */
-function manifestXml({ identifier, title, files }) {
- const name = escapeXml(title)
- return `
-
-
- ADL SCORM
- 1.2
-
-
-
- ${name}
-
- ${name}
-
-
-
-
-
-${files.map((file) => ` `).join('\n')}
-
-
-
-`
-}
-
-/** @param {{ version: string, source: string, pack: string | null }} zip `pack`, the library pack's version when the zip carries parts of it */
-function notice({ version, source, pack }) {
- return `This is a SCORM 1.2 package written by @missing-elements/h5p-embed. It plays ${source} in an
-LMS and reports its score, its result and the time spent, and keeps the learner's place.
-
- imsmanifest.xml the package's manifest
- index.html, scorm.js, embed.css
- the launch page and its bridge to the LMS: MIT
- h5p-player.js, h5p-sw.js, h5p-jobs.js
- @missing-elements/h5p-offline-player ${version}: MIT. The Service Worker,
- h5p-sw.js, also carries zip.js, BSD-3-Clause, its licence in its header.
- frame-assets/ @missing-elements/h5p-runtime, the H5P core runtime: GPL-3.0-only. Its
- LICENSE.txt and NOTICE.txt say what it is and where its source is; keep them
- with it.
- ${PACKAGE} the H5P package, its content and libraries under their own licences, which its
- h5p.json and each library's library.json name.
-${
- pack
- ? ` ${LIBRARIES}/ @missing-elements/h5p-libraries ${pack}, the H5P hub's libraries: those the package
- needs and does not carry, one archive per library and index.json, each under
- its own licence, listed in libraries.txt.
-`
- : ''
-}
-https://github.com/missing-elements/h5p-offline-player/tree/main/packages/embed
-`
-}
-
/**
* A file's SHA-256, read as a stream.
* @param {string} file
@@ -140,16 +62,6 @@ function sha256(file) {
})
}
-/**
- * A file's CRC-32, read as a stream.
- * @param {string} file
- */
-async function fileCrc32(file) {
- let crc = 0
- for await (const chunk of createReadStream(file)) crc = crc32(chunk, crc)
- return crc
-}
-
/**
* Every file under a folder, as zip paths relative to it, sorted.
* @param {string} dir
@@ -203,136 +115,43 @@ export async function buildScorm({ h5p, out, force = false }) {
const pack = packLibraries(JSON.parse(await readFile(join(packDir, 'index.json'), 'utf8')), packDir)
// What the package declares and carries, and what the pack adds, read before anything is written.
- /** @type {any} `h5p.json`, parsed */
- let manifest
- /** @type {typeof pack} the parts of the pack the zip carries, by folder */
- let parts
- let reader
- try {
- reader = new ZipReader(new BlobReader(await openAsBlob(source)))
- // One unsafe name does not refuse the package, as it does not in the player, which leaves that
- // entry out.
- const entries = await reader.getEntries({ filenameValidation: 'tolerant' })
- const byName = new Map(entries.filter((entry) => !entry.directory).map((entry) => [entry.filename, entry]))
- /** @param {string} name */
- const readJson = async (name) => {
- const entry = byName.get(name)
- if (!entry?.getData) throw new EmbedError(`${basename(h5p)} has no ${name}: it is not an H5P package.`)
- const text = await entry.getData(new TextWriter())
- try {
- return JSON.parse(text)
- } catch {
- throw new EmbedError(`${basename(h5p)}: ${name} is not JSON.`)
- }
- }
- manifest = await readJson('h5p.json')
- if (dependenciesIn(manifest).length === 0) {
- throw new EmbedError(`${basename(h5p)}: h5p.json names no libraries, so there is nothing to play.`)
- }
- const params = await readJson('content/content.json')
- /** @param {{ machineName: string, majorVersion: string | number, minorVersion: string | number }} dependency */
- const numbered = ({ machineName, majorVersion, minorVersion }) => ({ machineName, majorVersion: Number(majorVersion), minorVersion: Number(minorVersion) })
- const roots = [...dependenciesIn(manifest), ...librariesNamedIn(params)].map(numbered)
- const folders = [...byName.keys()].flatMap((name) => {
- const match = /^([^/]+)\/library\.json$/.exec(name)
- return match ? [match[1]] : []
- })
- // The player's own plan, as the launch page has the element run it: gaps filled from the pack,
- // nothing provided before, no refresh (`refresh-libraries="off"`).
- const plan = planPack({ own: await ownLibraries(folders, (folder) => readJson(`${folder}/library.json`)), provided: [], roots, params, pack, refresh: false, fill: true })
- const byFolder = new Map(pack.map((library) => [library.folder, library]))
- parts = (plan?.parts ?? []).map((part) => /** @type {typeof pack[number]} */ (byFolder.get(part.folder))).sort((a, b) => (a.folder < b.folder ? -1 : a.folder > b.folder ? 1 : 0))
-
- // Held to its libraries as the player holds it once the parts are attached: the folders they
- // replace withheld, and each part's `library.json` naming what its record in the index does.
- const records = new Map(parts.map((part) => [`${part.folder}/library.json`, part.record]))
- const withheld = new Set(plan?.superseded ?? [])
- const names = new Set([...byName.keys()].filter((name) => !withheld.has(name.split('/')[0])))
- for (const name of records.keys()) names.add(name)
- const available = indexLibraryFolders(names)
- const { missing } = await walkDependencies(
- roots,
- (dependency) => reachableFolder(dependency, names, available),
- async (folder) => records.get(`${folder}/library.json`) ?? readJson(`${folder}/library.json`)
- )
- if (missing.length > 0) {
- const packed = new Map(pack.map((library) => [`${library.machineName} ${library.majorVersion}`, library]))
- const listed = missing
- .map(({ machineName, majorVersion, minorVersion }) => {
- const older = packed.get(`${machineName} ${Number(majorVersion)}`)
- return `${machineName} ${majorVersion}.${minorVersion}${older ? ` (the pack has ${older.majorVersion}.${older.minorVersion})` : ''}`
- })
- .sort()
- throw new EmbedError(
- `${basename(h5p)} needs libraries that neither it nor the library pack carries: ${listed.join(', ')}. ` +
- 'Export the package with its libraries, as Lumi and the H5P plugins of Moodle, WordPress and Drupal do.'
- )
- }
- } catch (error) {
- if (error instanceof EmbedError) throw error
- throw new EmbedError(`${basename(h5p)} could not be read as a zip archive: ${error instanceof Error ? error.message : error}`)
- } finally {
- await reader?.close()
- }
-
- // Control characters, which XML refuses, read as spaces: a title pasted in can carry one.
- const named = typeof manifest.title === 'string' ? manifest.title.replace(/[\x00-\x1f\x7f]+/g, ' ').trim() : ''
- const title = named || basename(h5p, extname(h5p))
+ const { manifest, parts } = await readPackage(await openAsBlob(source), basename(h5p), pack)
+ const title = scormTitle(manifest, basename(h5p, extname(h5p)))
// The learner's saved place is kept against the libraries too, as the player keeps it against
// the revision: a zip written with others starts learners over, as a refreshed package does.
- const hashes = [await sha256(source), ...parts.map((part) => part.sha256)]
- const build = (hashes.length === 1 ? hashes[0] : createHash('sha256').update(hashes.join('\n')).digest('hex')).slice(0, 16)
+ const build = await buildStamp(await sha256(source), parts)
const player = dirname(installed('@missing-elements/h5p-offline-player/dist/h5p-player.js', 'Run `pnpm build` in the workspace, or reinstall this package.'))
const runtime = dirname(installed('@missing-elements/h5p-runtime/dist/h5p.css', 'Run `pnpm build` in the workspace, or reinstall this package.'))
const version = (await readFile(join(player, 'VERSION'), 'utf8').catch(() => 'unknown')).trim()
const packVersion = parts.length > 0 ? String(JSON.parse(await readFile(join(dirname(packDir), 'package.json'), 'utf8')).version) : null
- const page = (await readFile(join(SCORM, 'index.html'), 'utf8'))
- .replace('%LANG%', languageTag(manifest.defaultLanguage))
- // A function, so that a title's `$&` or `$'` is written as it is rather than read as a pattern.
- .replace('%TITLE%', () => escapeHtml(title))
- .replace('%BUILD%', build)
- // The element plans from the zip's index what the writer planned, and plays the package's own
- // libraries as they are.
- .replace('%LIBRARIES%', packVersion ? ` libraries="pack" pack-base="./${LIBRARIES}/" refresh-libraries="off"` : '')
- /** @type {[string, { text: string } | { file: string }][]} zip path, and what it holds */
- const files = [
- ['index.html', { text: page }],
- ['scorm.js', { file: join(SCORM, 'scorm.js') }],
- ['embed.css', { file: join(SITE, 'embed.css') }],
- ...PLAYER_FILES.map((name) => /** @type {[string, { file: string }]} */ ([name, { file: join(player, name) }])),
- ...(await filesUnder(runtime)).map((name) => /** @type {[string, { file: string }]} */ ([`frame-assets/${name}`, { file: join(runtime, name) }])),
- [PACKAGE, { file: source }]
- ]
- if (packVersion) {
- files.push([`${LIBRARIES}/index.json`, { text: `${JSON.stringify({ libraries: parts.map((part) => part.record) }, null, 2)}\n` }])
- for (const part of parts) files.push([`${LIBRARIES}/${part.folder}.h5p`, { file: join(packDir, `${part.folder}.h5p`) }])
- files.push(['libraries.txt', { file: join(dirname(packDir), 'libraries.txt') }])
- }
- files.push(['NOTICE.txt', { text: notice({ version, source: basename(h5p), pack: packVersion }) }])
- const xml = manifestXml({ identifier: `h5p-${build}`, title, files: ['imsmanifest.xml', ...files.map(([name]) => name)] })
+ /** @param {string[]} names @param {(name: string) => string} at */
+ const blobs = async (names, at) => new Map(await Promise.all(names.map(async (name) => /** @type {[string, Blob]} */ ([name, await openAsBlob(at(name))]))))
+ const { entries, xml } = scormEntries({
+ manifest,
+ source: basename(h5p),
+ title,
+ build,
+ version,
+ packVersion,
+ parts,
+ files: {
+ launch: await readFile(join(SCORM, 'index.html'), 'utf8'),
+ bridge: await openAsBlob(join(SCORM, 'scorm.js')),
+ css: await openAsBlob(join(SITE, 'embed.css')),
+ player: await blobs(PLAYER_FILES, (name) => join(player, name)),
+ runtime: await blobs(await filesUnder(runtime), (name) => join(runtime, name)),
+ pkg: await openAsBlob(source),
+ parts: await blobs(parts.map((part) => part.folder), (folder) => join(packDir, `${folder}.h5p`)),
+ librariesText: parts.length > 0 ? await openAsBlob(join(dirname(packDir), 'libraries.txt')) : null
+ }
+ })
// Written beside the target and renamed into place, so a failure leaves no half-written zip.
const partial = `${target}.${process.pid}.partial`
try {
- const zip = new ZipWriter(Writable.toWeb(createWriteStream(partial)))
- await zip.add('imsmanifest.xml', new TextReader(xml))
- for (const [name, content] of files) {
- if ('text' in content) {
- await zip.add(name, new TextReader(content.text), { level: 6 })
- continue
- }
- const blob = await openAsBlob(content.file)
- // The package, the pack's parts and the fonts are compressed already, so they are stored.
- // Written into a stream, an entry gets a data descriptor, and a Java ZipInputStream refuses
- // a stored entry that has one: SCORM Cloud refused exactly those (#92). Passed through with
- // its size and CRC, it gets a complete local header instead, and is still streamed, not held.
- if (name.endsWith('.h5p') || name.endsWith('.woff2')) {
- await zip.add(name, new BlobReader(blob), { passThrough: true, compressionMethod: 0, uncompressedSize: blob.size, crc32: await fileCrc32(content.file) })
- } else {
- await zip.add(name, new BlobReader(blob), { level: 6 })
- }
- }
+ const zip = new ZipWriter(Writable.toWeb(createWriteStream(partial)), { useWebWorkers: false })
+ await addScormEntries(zip, { entries, xml })
await zip.close()
await rename(partial, target)
} catch (error) {
diff --git a/packages/embed/lib/shared.mjs b/packages/embed/lib/shared.mjs
new file mode 100644
index 00000000..1578dc13
--- /dev/null
+++ b/packages/embed/lib/shared.mjs
@@ -0,0 +1,14 @@
+/**
+ * What every entry of the package shares and no Node import: the error the command and the
+ * functions throw, and the player's files by name. `build.mjs` re-exports the error, so a caller
+ * of `@missing-elements/h5p-embed` finds it where it did; the SCORM builder that runs in a page
+ * takes both from here, since `build.mjs` imports `node:fs`.
+ */
+
+export class EmbedError extends Error {}
+
+/**
+ * The player's files, by the names the element looks for beside itself.
+ * @internal
+ */
+export const PLAYER_FILES = ['h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js']
diff --git a/packages/embed/package.json b/packages/embed/package.json
index 36fc5d62..2fe57efd 100644
--- a/packages/embed/package.json
+++ b/packages/embed/package.json
@@ -1,7 +1,7 @@
{
"name": "@missing-elements/h5p-embed",
"version": "1.3.3",
- "description": "Self-hosted H5P embeds: writes the H5P embed page as a static site for a player domain of your own, then any site frames it with an iframe and one script line; or wraps one .h5p as a SCORM 1.2 package an LMS plays and grades. No H5P server, no third-party service; optional allowlists for package hosts and embedding sites.",
+ "description": "Self-hosted H5P embeds: writes the H5P embed page as a static site for a player domain of your own, then any site frames it with an iframe and one script line; or wraps one .h5p as a SCORM 1.2 package an LMS plays and grades, from the command or from a page in the browser. No H5P server, no third-party service; optional allowlists for package hosts and embedding sites.",
"license": "MIT",
"repository": {
"type": "git",
@@ -28,16 +28,28 @@
"types": "./types/lib/scorm.d.mts",
"default": "./lib/scorm.mjs"
},
+ "./scorm/browser": {
+ "types": "./types/lib/scorm-browser.d.mts",
+ "default": "./lib/scorm-browser.mjs"
+ },
"./embed.js": {
"types": "./types/site/embed.d.ts",
"default": "./site/embed.js"
},
"./embed.css": "./site/embed.css",
"./resizer.js": "./site/resizer.js",
+ "./scorm-page.js": {
+ "types": "./types/site/scorm-page.d.ts",
+ "default": "./site/scorm-page.js"
+ },
+ "./scorm-page.css": "./site/scorm-page.css",
+ "./scorm/index.html": "./scorm/index.html",
+ "./scorm/scorm.js": "./scorm/scorm.js",
"./package.json": "./package.json"
},
"files": [
"bin",
+ "dist",
"lib",
"scorm",
"site",
@@ -58,9 +70,10 @@
"cli"
],
"scripts": {
- "test": "pnpm --filter @missing-elements/h5p-offline-player build && vitest run",
+ "build": "node scripts/build.mjs",
+ "test": "pnpm --filter @missing-elements/h5p-offline-player build && pnpm build && vitest run",
"typecheck": "pnpm types && tsc -p tsconfig.json",
- "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types",
+ "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\" && pnpm types && pnpm build",
"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) }\" && node scripts/check-published.mjs && pnpm typecheck && pnpm test",
"types": "pnpm --filter @missing-elements/h5p-offline-player exec tsc -b && node -e \"require('node:fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json"
},
@@ -73,6 +86,7 @@
},
"devDependencies": {
"@types/node": "^26.6.5",
+ "esbuild": "^0.28.2",
"playwright": "^1.64.1",
"typescript": "^7.0.2",
"vitest": "^5.0.5"
diff --git a/packages/embed/scripts/build.mjs b/packages/embed/scripts/build.mjs
new file mode 100644
index 00000000..bb7bc1f2
--- /dev/null
+++ b/packages/embed/scripts/build.mjs
@@ -0,0 +1,44 @@
+import { readFile } from 'node:fs/promises'
+import { resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { build } from 'esbuild'
+
+/**
+ * Builds `dist/scorm-page.js`: the SCORM page's script with everything it imports — the builder,
+ * zip.js and the player's library rules — in one ES module, for the written site, which has no
+ * bundler of its own and loads it as it loads `embed.js`. A host that bundles imports
+ * `./scorm-page.js`, the source, instead. Run before the tests and before publishing; `buildSite`
+ * refuses to write a site without it.
+ */
+
+const root = fileURLToPath(new URL('..', import.meta.url))
+
+/**
+ * The notices on the one shipped file with third-party code in it: ours, and zip.js's licence in
+ * full, as the player's workers carry it, since its clause 2 asks for the notice, the conditions
+ * and the disclaimer to accompany a binary. Read from the installed package, so that it follows
+ * the version actually bundled.
+ */
+async function notices() {
+ const { version } = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'))
+ const zipJs = resolve(root, 'node_modules', '@zip.js', 'zip.js')
+ const zip = JSON.parse(await readFile(resolve(zipJs, 'package.json'), 'utf8')).version
+ const licence = (await readFile(resolve(zipJs, 'LICENSE'), 'utf8')).trim()
+ if (licence.includes('*/')) throw new Error('[build] the zip.js licence would end the comment early')
+ return (
+ `/*! @missing-elements/h5p-embed ${version}, the SCORM page. Copyright (c) 2026 missing-elements. MIT (https://github.com/missing-elements/h5p-offline-player/blob/main/LICENSE). ` +
+ `Bundles the library rules of @missing-elements/h5p-offline-player (MIT) and zip.js ${zip} (https://github.com/gildas-lormeau/zip.js):\n\n${licence}\n*/`
+ )
+}
+
+await build({
+ entryPoints: [resolve(root, 'site', 'scorm-page.js')],
+ outfile: resolve(root, 'dist', 'scorm-page.js'),
+ bundle: true,
+ platform: 'browser',
+ format: 'esm',
+ target: 'es2022',
+ minify: true,
+ legalComments: 'none',
+ banner: { js: await notices() }
+})
diff --git a/packages/embed/site/scorm-main.js b/packages/embed/site/scorm-main.js
new file mode 100644
index 00000000..efa15c14
--- /dev/null
+++ b/packages/embed/site/scorm-main.js
@@ -0,0 +1,11 @@
+/*! @missing-elements/h5p-embed. MIT. */
+// The SCORM page's entry: `config.js` is what `h5p-embed` was told when it wrote this site —
+// whether the library pack's parts are here, and which player and pack it was written with.
+import config from './config.js'
+import { startScormPage } from './scorm-page.js'
+
+startScormPage({
+ packBase: config.libraries ? new URL('./libraries/', import.meta.url).href : null,
+ version: config.version,
+ packVersion: config.packVersion
+})
diff --git a/packages/embed/site/scorm-page.css b/packages/embed/site/scorm-page.css
new file mode 100644
index 00000000..c5db057a
--- /dev/null
+++ b/packages/embed/site/scorm-page.css
@@ -0,0 +1,65 @@
+/* The SCORM page: a column of text with one file input, as plain as the embed page. It comes
+ after embed.css, which has the notice's look and no background of its own. */
+body {
+ padding: 1.5rem 1rem 3rem;
+ background: #fff;
+}
+
+main {
+ max-width: 42rem;
+ margin: 0 auto;
+}
+
+h1 {
+ margin: 0 0 0.5rem;
+ font-size: 1.6rem;
+}
+
+h2 {
+ margin: 2rem 0 0.5rem;
+ font-size: 1.15rem;
+}
+
+p {
+ margin: 0.6rem 0;
+}
+
+code {
+ font: 0.92em ui-monospace, SFMono-Regular, Menlo, monospace;
+}
+
+label[for="file"] {
+ display: block;
+ margin-bottom: 0.3rem;
+ font-weight: 600;
+}
+
+input[type="file"] {
+ font: inherit;
+}
+
+/* The line that says where the build is, then what it made, with the link to it. */
+.status {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 1rem;
+ min-height: 1.5rem;
+}
+
+.status a {
+ font-weight: 600;
+}
+
+table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.95em;
+}
+
+th,
+td {
+ padding: 0.4rem 0.6rem 0.4rem 0;
+ border-bottom: 1px solid #e2e6ec;
+ text-align: left;
+ vertical-align: top;
+}
diff --git a/packages/embed/site/scorm-page.js b/packages/embed/site/scorm-page.js
new file mode 100644
index 00000000..66cae235
--- /dev/null
+++ b/packages/embed/site/scorm-page.js
@@ -0,0 +1,105 @@
+/*! @missing-elements/h5p-embed. MIT. */
+/**
+ * The SCORM page: a `.h5p` picked or dropped becomes a SCORM 1.2 zip, built in the browser by
+ * `buildScormInPage` from this site's own copies of the player, the runtime and the library
+ * pack, with nothing uploaded anywhere. `startScormPage()` runs it; the site's `scorm-main.js`
+ * calls it with what `h5p-embed` wrote into `config.js`, and the demo's `/demo/scorm.html` with
+ * its own copies. The page holds `#file`, the input; `#status`, a line that says where the build
+ * is and then what it made; `#download`, the link to the zip, hidden until there is one; and
+ * `#notice`, for a refusal. A page with a `#state` badge, as the demo's pages have, gets the
+ * state's name in it, `idle`, `building`, `ready` or `error`, and as `data-state` on it and on
+ * the `.status` strip around `#status`, which its stylesheet colours.
+ */
+import { buildScormInPage } from '../lib/scorm-browser.mjs'
+import { EmbedError } from '../lib/shared.mjs'
+
+/**
+ * What `buildScormInPage` is given beside the file: where the player's files and the pack are,
+ * and the versions for the zip's notice.
+ * @typedef {Omit} ScormPageOptions
+ */
+
+/** @param {number} bytes */
+const megabytes = (bytes) => `${(bytes / 1_000_000).toFixed(1)} MB`
+
+/** @param {number} count */
+const libraries = (count) => `${count} ${count === 1 ? 'library' : 'libraries'}`
+
+/**
+ * @param {ScormPageOptions} [options]
+ */
+export function startScormPage(options = {}) {
+ const input = /** @type {HTMLInputElement} */ (document.querySelector('#file'))
+ const status = /** @type {HTMLElement} */ (document.querySelector('#status'))
+ const link = /** @type {HTMLAnchorElement} */ (document.querySelector('#download'))
+ const notice = /** @type {HTMLElement} */ (document.querySelector('#notice'))
+ const badge = /** @type {HTMLElement | null} */ (document.querySelector('#state'))
+ const strip = /** @type {HTMLElement | null} */ (status.closest('.status'))
+ /** @type {string | null} the last zip's address, let go of when the next one replaces it */
+ let last = null
+ let busy = false
+
+ /** @param {string} text */
+ const say = (text) => {
+ status.textContent = text
+ }
+
+ /** @param {'idle' | 'building' | 'ready' | 'error'} state */
+ const mark = (state) => {
+ for (const element of [badge, strip]) if (element) element.dataset.state = state
+ if (badge) badge.textContent = state
+ }
+
+ /** @param {File} file */
+ async function make(file) {
+ if (busy) return
+ busy = true
+ input.disabled = true
+ notice.hidden = true
+ link.hidden = true
+ if (last) URL.revokeObjectURL(last)
+ last = null
+ mark('building')
+ try {
+ const zip = await buildScormInPage({
+ ...options,
+ file,
+ onProgress: ({ step, libraries: count }) => {
+ if (step === 'reading') say(`Reading ${file.name}…`)
+ else if (step === 'libraries' && count) say(`Fetching ${libraries(count)} from the pack…`)
+ else if (step === 'writing') say('Writing the zip…')
+ }
+ })
+ last = URL.createObjectURL(zip.blob)
+ link.href = last
+ link.download = zip.name
+ link.textContent = `Download ${zip.name} (${megabytes(zip.size)})`
+ link.hidden = false
+ const carried = zip.libraries.length ? `, with ${libraries(zip.libraries.length)} from the pack` : ''
+ say(`“${zip.title}” as a SCORM 1.2 package${carried}. Build ${zip.build}.`)
+ mark('ready')
+ } catch (error) {
+ say('')
+ notice.textContent = error instanceof EmbedError ? error.message : `The zip could not be written: ${error instanceof Error ? error.message : error}`
+ notice.hidden = false
+ mark('error')
+ } finally {
+ busy = false
+ input.disabled = false
+ // So that the same file, chosen again after a change to it, counts as a change.
+ input.value = ''
+ }
+ }
+
+ input.addEventListener('change', () => {
+ const file = input.files?.[0]
+ if (file) void make(file)
+ })
+ // A file dropped anywhere on the page.
+ document.addEventListener('dragover', (event) => event.preventDefault())
+ document.addEventListener('drop', (event) => {
+ event.preventDefault()
+ const file = event.dataTransfer?.files?.[0]
+ if (file) void make(file)
+ })
+}
diff --git a/packages/embed/site/scorm.html b/packages/embed/site/scorm.html
new file mode 100644
index 00000000..0802a215
--- /dev/null
+++ b/packages/embed/site/scorm.html
@@ -0,0 +1,66 @@
+
+
+
+
+
+
+ H5P to SCORM
+
+
+
+
+
+
+
+
H5P to SCORM
+
+ Choose a .h5p file, or drop it on this page, and download it as a SCORM 1.2
+ package for your LMS. Nothing is uploaded: the package is built here, in your browser, with
+ the player this site serves.
+
+ Add the zip to a course as a SCORM activity. The LMS records the score out of 100, whether
+ the content was passed or failed, or completed when it does not say, the time spent, and
+ the learner's place, so the next launch continues where they left off. Content that reports
+ no result of its own, an Accordion or a Virtual Tour, stays incomplete.
+
+
+
+
Checked in
Add the zip as
Change from the defaults
+
+
+
Moodle 4.5
a SCORM package activity
nothing; keep the maximum grade at 100
+
ILIAS 11
a SCORM learning module
turn Learning Progress on
+
OpenOLAT 21.1
a "SCORM 1.2" course element
the pass mark; in a learning path, the completion criterion
+
Chamilo 3.0
an imported learning path
publish the learning path
+
SCORM Cloud
a course
nothing
+
Frappe LMS
a SCORM chapter
nothing; the content needs a pass mark
+
+
+
+ Another LMS that takes SCORM 1.2 may work as well; these are the ones checked. The LMS has
+ to be served over https.
+
+
+
What goes in the zip
+
+ The package, the player and the H5P runtime, and a launch page that reports to the LMS. A
+ package exported without its libraries, as h5p.com and h5p.org export, gets the ones it
+ needs from this site's copy of the library pack, and only those; one that carries its
+ libraries plays with its own. A package that needs a library neither has is refused here,
+ with the library named, rather than in front of a learner.
+
+
+
+
diff --git a/packages/embed/tests/build.test.ts b/packages/embed/tests/build.test.ts
index 27ebe9c0..33b86cdf 100644
--- a/packages/embed/tests/build.test.ts
+++ b/packages/embed/tests/build.test.ts
@@ -93,7 +93,7 @@ describe('the site', () => {
const out = join(dir, 'locked')
const site = await buildSite({ out, packages: 'https://cdn.example.org', ancestors: ['https://school.example'] })
- for (const name of ['index.html', 'main.js', 'embed.js', 'embed.css', 'resizer.js', 'config.js', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'libraries/index.json', 'libraries.txt', 'NOTICE.txt', '_headers', 'vercel.json', 'Caddyfile', 'nginx.conf', '.htaccess']) {
+ for (const name of ['index.html', 'main.js', 'embed.js', 'embed.css', 'resizer.js', 'config.js', 'scorm.html', 'scorm-main.js', 'scorm-page.js', 'scorm-page.css', 'scorm-launch.html', 'scorm.js', 'h5p-player.js', 'h5p-sw.js', 'h5p-jobs.js', 'libraries/index.json', 'libraries.txt', 'NOTICE.txt', '_headers', 'vercel.json', 'Caddyfile', 'nginx.conf', '.htaccess']) {
expect(existsSync(join(out, name)), name).toBe(true)
}
for (const name of ['frame-boot.js', 'frame.bundle.js', 'h5p.css', 'LICENSE.txt', 'NOTICE.txt']) {
@@ -116,7 +116,7 @@ describe('the site', () => {
for (const folder of ['/frame-assets/', '/libraries/']) {
expect(vercel.headers.find((rule: { source: string }) => rule.source.startsWith(folder)).headers).toEqual([{ key: 'Cache-Control', value: 'no-cache' }])
}
- expect(await readFile(join(out, 'config.js'), 'utf8')).toContain('{"libraries":true,"packages":["https://cdn.example.org"],"defaultLibraries":null}')
+ expect(await readFile(join(out, 'config.js'), 'utf8')).toContain('{"libraries":true,"packages":["https://cdn.example.org"],"defaultLibraries":null,"version":"' + site.version + '","packVersion":"')
// The three server formats say the same as the two host files, each in its own syntax.
const caddy = await readFile(join(out, 'Caddyfile'), 'utf8')
@@ -139,9 +139,9 @@ describe('the site', () => {
it('leaves the library pack out when asked, and says so to the page', async () => {
const out = join(dir, 'lean')
- await buildSite({ out, libraries: false })
+ const site = await buildSite({ out, libraries: false })
expect(existsSync(join(out, 'libraries'))).toBe(false)
- expect(await readFile(join(out, 'config.js'), 'utf8')).toContain('{"libraries":false,"packages":null,"defaultLibraries":null}')
+ expect(await readFile(join(out, 'config.js'), 'utf8')).toContain('{"libraries":false,"packages":null,"defaultLibraries":null,"version":"' + site.version + '","packVersion":null}')
expect(await readFile(join(out, 'NOTICE.txt'), 'utf8')).not.toContain('libraries/')
})
diff --git a/packages/embed/tests/helpers/host.ts b/packages/embed/tests/helpers/host.ts
new file mode 100644
index 00000000..bd55c96d
--- /dev/null
+++ b/packages/embed/tests/helpers/host.ts
@@ -0,0 +1,47 @@
+import { readFile } from 'node:fs/promises'
+import { createServer, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { extname, join, normalize } from 'node:path'
+
+const MIME: Record = {
+ '.html': 'text/html; charset=utf-8',
+ '.js': 'text/javascript; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.json': 'application/json',
+ '.woff2': 'font/woff2',
+ '.h5p': 'application/zip'
+}
+
+export type Host = { origin: string; close: () => Promise }
+
+/**
+ * A static host for `root`, as GitHub Pages serves a written site: the type and nothing else,
+ * CORS open so a package on it can be read from another origin. `extra` answers a path with a page
+ * of the test's own.
+ */
+export async function host(root: string, hostname: string, extra?: (path: string) => string | null): Promise {
+ const server: Server = createServer(async (request, response) => {
+ const path = decodeURIComponent(new URL(request.url ?? '/', 'http://x').pathname)
+ const page = extra?.(path)
+ if (page != null) {
+ response.writeHead(200, { 'Content-Type': MIME['.html'] }).end(page)
+ return
+ }
+ const file = join(root, normalize(path.endsWith('/') ? `${path}index.html` : path).replace(/^(\.\.[/\\])+/, ''))
+ try {
+ const body = await readFile(file)
+ response.writeHead(200, {
+ 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream',
+ 'Content-Length': body.length,
+ 'Access-Control-Allow-Origin': '*',
+ 'Cache-Control': 'no-store'
+ })
+ response.end(body)
+ } catch {
+ response.writeHead(404).end()
+ }
+ })
+ await new Promise((done) => server.listen(0, hostname, done))
+ const { port } = server.address() as AddressInfo
+ return { origin: `http://${hostname}:${port}`, close: () => new Promise((done) => server.close(() => done())) }
+}
diff --git a/packages/embed/tests/helpers/zip.ts b/packages/embed/tests/helpers/zip.ts
new file mode 100644
index 00000000..94cdcddb
--- /dev/null
+++ b/packages/embed/tests/helpers/zip.ts
@@ -0,0 +1,39 @@
+import { readFile, writeFile } from 'node:fs/promises'
+import { resolve } from 'node:path'
+import { BlobReader, BlobWriter, TextWriter, Uint8ArrayReader, Uint8ArrayWriter, ZipReader, ZipWriter } from '@zip.js/zip.js'
+
+/** The demo's quiz, which carries its libraries; and its export without them, with formulas in it. */
+export const quiz = resolve(import.meta.dirname, '../../../../apps/demo/demo/content/quiz.h5p')
+export const formulas = resolve(import.meta.dirname, '../../../../apps/demo/demo/content/formulas.h5p')
+
+/** A zip's entries, by name, with a way to read each as text or bytes. */
+export async function entriesOf(path: string) {
+ const reader = new ZipReader(new BlobReader(new Blob([await readFile(path)])))
+ const entries = await reader.getEntries()
+ const entry = (name: string) => {
+ const found = entries.find((candidate) => candidate.filename === name)
+ if (!found || found.directory) throw new Error(`${name} is not in ${path}`)
+ return found
+ }
+ const text = async (name: string) => entry(name).getData!(new TextWriter())
+ const bytes = async (name: string) => entry(name).getData!(new Uint8ArrayWriter())
+ return { names: entries.filter((candidate) => !candidate.directory).map((candidate) => candidate.filename), entry, text, bytes, close: () => reader.close() }
+}
+
+/** The quiz, changed: its `h5p.json` edited, and the entries `drop` names left out. */
+export async function changedQuiz(path: string, edit: (manifest: Record) => void, drop: (name: string) => boolean = () => false) {
+ const reader = new ZipReader(new BlobReader(new Blob([await readFile(quiz)])))
+ const writer = new ZipWriter(new BlobWriter('application/zip'))
+ for (const entry of await reader.getEntries()) {
+ if (entry.directory || drop(entry.filename)) continue
+ let bytes = await entry.getData!(new Uint8ArrayWriter())
+ if (entry.filename === 'h5p.json') {
+ const manifest = JSON.parse(new TextDecoder().decode(bytes))
+ edit(manifest)
+ bytes = new TextEncoder().encode(JSON.stringify(manifest))
+ }
+ await writer.add(entry.filename, new Uint8ArrayReader(bytes))
+ }
+ await reader.close()
+ await writeFile(path, new Uint8Array(await (await writer.close()).arrayBuffer()))
+}
diff --git a/packages/embed/tests/package-types.ts b/packages/embed/tests/package-types.ts
index 0e418fc7..5134f8a8 100644
--- a/packages/embed/tests/package-types.ts
+++ b/packages/embed/tests/package-types.ts
@@ -6,6 +6,8 @@
import { EmbedError, buildSite, type BuiltSite } from '@missing-elements/h5p-embed'
import { startEmbed } from '@missing-elements/h5p-embed/embed.js'
import { buildScorm, type BuiltScorm } from '@missing-elements/h5p-embed/scorm'
+import { buildScormInPage, type PageScorm } from '@missing-elements/h5p-embed/scorm/browser'
+import { startScormPage } from '@missing-elements/h5p-embed/scorm-page.js'
import { pack } from '@missing-elements/h5p-libraries'
import { runtime } from '@missing-elements/h5p-runtime'
// @ts-expect-error a helper the tests use, not part of the package's API (#60)
@@ -28,6 +30,13 @@ export async function asACallerWould(): Promise {
// @ts-expect-error the package is named `h5p`
await buildScorm({ package: 'course.h5p', out: 'course.scorm.zip' })
- void [hosts, build, fromPack, parseOrigin, new EmbedError('refused') instanceof Error]
+ // The same zip built in a page, from a picked file, with the pack as its package exports it.
+ const inPage: PageScorm = await buildScormInPage({ file: new Blob([]), name: 'course.h5p', base: 'https://player.example/', pack, version: '1.4.0', onProgress: ({ step }) => step })
+ const blob: Blob = inPage.blob
+ startScormPage({ pack, version: '1.4.0', packVersion: '1.0.1' })
+ // @ts-expect-error the package is a `file`, not a path
+ await buildScormInPage({ h5p: 'course.h5p' })
+
+ void [hosts, build, fromPack, blob, parseOrigin, new EmbedError('refused') instanceof Error]
return site.csp
}
diff --git a/packages/embed/tests/scorm-browser.test.ts b/packages/embed/tests/scorm-browser.test.ts
new file mode 100644
index 00000000..1703ab57
--- /dev/null
+++ b/packages/embed/tests/scorm-browser.test.ts
@@ -0,0 +1,128 @@
+import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { buildSite } from '../lib/build.mjs'
+import { buildScormInPage, type ScormProgress } from '../lib/scorm-browser.mjs'
+import { buildScorm } from '../lib/scorm.mjs'
+import { EmbedError } from '../lib/shared.mjs'
+import { host, type Host } from './helpers/host.js'
+import { changedQuiz, entriesOf, formulas, quiz } from './helpers/zip.js'
+
+/**
+ * The SCORM package built in a page, run here in Node, which has what the builder needs of a
+ * browser — `fetch`, `File`, `Blob`, `crypto.subtle` — against a written site served as a static
+ * host serves one. Held to the command's zip entry for entry: the two are written by one code,
+ * and this is what keeps them one. `scorm-page.test.ts` drives the page itself, in Chromium.
+ */
+
+const require = createRequire(import.meta.url)
+/** The versions the command's notice names, read as the command reads them. */
+const version = (await readFile(require.resolve('@missing-elements/h5p-offline-player/dist/VERSION'), 'utf8')).trim()
+const packVersion: string = require('@missing-elements/h5p-libraries/package.json').version
+
+let dir: string
+/** The written site, with the pack; one without it; and one serving a part with the wrong bytes. */
+let site: Host
+let lean: Host
+let tampered: Host
+
+beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'h5p-embed-page-scorm-'))
+ await buildSite({ out: join(dir, 'site') })
+ await buildSite({ out: join(dir, 'lean'), libraries: false })
+ await cp(join(dir, 'site'), join(dir, 'tampered'), { recursive: true })
+ // A part served with other bytes than the index says, as a host that cut one short would.
+ await writeFile(join(dir, 'tampered', 'libraries', 'H5P.Transition-1.0.h5p'), 'not the part')
+ site = await host(join(dir, 'site'), '127.0.0.1')
+ lean = await host(join(dir, 'lean'), '127.0.0.1')
+ tampered = await host(join(dir, 'tampered'), '127.0.0.1')
+})
+
+afterAll(async () => {
+ await Promise.all([site, lean, tampered].map((h) => h?.close()))
+ await rm(dir, { recursive: true, force: true })
+})
+
+/** The file as a page is given it. */
+const picked = async (path: string, name: string) => new File([await readFile(path)], name)
+/** Where a page on `where` finds the player's files and the pack. */
+const onSite = (where: Host) => ({ base: `${where.origin}/`, packBase: `${where.origin}/libraries/`, version, packVersion })
+
+/** Two zips held to each other: the same entries in the same order, each stored or deflated alike, with the same bytes. */
+async function expectSameZip(a: string, b: string) {
+ const left = await entriesOf(a)
+ const right = await entriesOf(b)
+ expect(left.names).toEqual(right.names)
+ for (const name of left.names) {
+ expect(left.entry(name).compressionMethod, name).toBe(right.entry(name).compressionMethod)
+ expect(Buffer.from(await left.bytes(name)).equals(await right.bytes(name)), name).toBe(true)
+ }
+ await left.close()
+ await right.close()
+}
+
+/** The page's zip, written out for the comparison. */
+async function builtInPage(path: string, name: string, where: Host, onProgress?: (progress: ScormProgress) => void) {
+ const built = await buildScormInPage({ file: await picked(path, name), ...onSite(where), onProgress })
+ const out = join(dir, `${name}.page.zip`)
+ await writeFile(out, new Uint8Array(await built.blob.arrayBuffer()))
+ return { built, out }
+}
+
+describe('built in a page', () => {
+ it("writes the command's zip, entry for entry, from a picked file that carries its libraries", async () => {
+ const { built, out } = await builtInPage(quiz, 'quiz.h5p', site)
+ const command = await buildScorm({ h5p: quiz, out: join(dir, 'quiz.cli.zip') })
+ expect(built).toMatchObject({ name: 'quiz.scorm.zip', title: command.title, build: command.build, libraries: [], version, size: command.size })
+ expect(built.blob.type).toBe('application/zip')
+ await expectSameZip(out, command.out)
+ })
+
+ it("writes the command's zip for an export without its libraries, with the parts from the site's pack", async () => {
+ const steps: ScormProgress[] = []
+ const { built, out } = await builtInPage(formulas, 'formulas.h5p', site, (progress) => steps.push(progress))
+ const command = await buildScorm({ h5p: formulas, out: join(dir, 'formulas.cli.zip') })
+ expect(built.libraries).toEqual(command.libraries)
+ expect(built.libraries.length).toBeGreaterThan(1)
+ expect(built).toMatchObject({ name: 'formulas.scorm.zip', title: command.title, build: command.build })
+ await expectSameZip(out, command.out)
+ expect(steps).toEqual([{ step: 'reading' }, { step: 'libraries', libraries: command.libraries.length }, { step: 'writing' }])
+ })
+
+ it("takes the pack as its package exports it, with the same result", async () => {
+ const index = JSON.parse(await readFile(join(dir, 'site', 'libraries', 'index.json'), 'utf8')) as { libraries: Array<{ folder: string }> }
+ const pack = { libraries: index.libraries.map((entry) => ({ ...entry, url: `${site.origin}/libraries/${entry.folder}.h5p` })) }
+ const { packBase: _unused, ...rest } = onSite(site)
+ const built = await buildScormInPage({ file: await picked(formulas, 'formulas.h5p'), ...rest, pack: pack as never })
+ const command = await buildScorm({ h5p: formulas, out: join(dir, 'formulas.pack.zip') })
+ expect(built).toMatchObject({ build: command.build, libraries: command.libraries })
+ })
+
+ it('refuses what the command refuses, in its words, and a part whose bytes are not the index\'s', async () => {
+ const unknown = join(dir, 'unknown.h5p')
+ await changedQuiz(unknown, (manifest) => {
+ manifest.preloadedDependencies.push({ machineName: 'H5P.Nowhere', majorVersion: 1, minorVersion: 0 })
+ })
+ await expect(buildScormInPage({ file: await picked(unknown, 'unknown.h5p'), ...onSite(site) })).rejects.toThrow(/unknown\.h5p needs libraries that neither it nor the library pack carries: H5P\.Nowhere 1\.0\./)
+ await expect(buildScormInPage({ file: new File(['not a zip'], 'not.h5p'), ...onSite(site) })).rejects.toThrow(/not\.h5p could not be read as a zip archive/)
+ await expect(buildScormInPage({ file: new Blob(['x']), ...onSite(site) })).rejects.toThrow(TypeError)
+
+ // The quiz needs no part, so the tampered one is never fetched; the export without its libraries does.
+ await expect(builtInPage(quiz, 'quiz.h5p', tampered)).resolves.toBeTruthy()
+ const refused = buildScormInPage({ file: await picked(formulas, 'formulas.h5p'), ...onSite(tampered) })
+ await expect(refused).rejects.toThrow(/H5P\.Transition-1\.0 from .* does not match the pack's index, so the zip was not written/)
+ await expect(refused).rejects.toBeInstanceOf(EmbedError)
+ })
+
+ it('says that the site has no pack, rather than that the pack lacks something, and names a file the site lacks', async () => {
+ const { packBase: _unused, ...withoutPack } = onSite(lean)
+ await expect(buildScormInPage({ file: await picked(formulas, 'formulas.h5p'), ...withoutPack })).rejects.toThrow(
+ /formulas\.h5p does not carry all its libraries, and this page has no library pack to take them from\./
+ )
+ // One that carries its libraries builds there as anywhere.
+ await expect(buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...withoutPack })).resolves.toMatchObject({ libraries: [] })
+ await expect(buildScormInPage({ file: await picked(quiz, 'quiz.h5p'), ...onSite(site), base: `${site.origin}/nowhere/` })).rejects.toThrow(/is not at .*\/nowhere\/.*: it answered 404\./)
+ })
+})
diff --git a/packages/embed/tests/scorm-page.test.ts b/packages/embed/tests/scorm-page.test.ts
new file mode 100644
index 00000000..a5308467
--- /dev/null
+++ b/packages/embed/tests/scorm-page.test.ts
@@ -0,0 +1,96 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { chromium, type Browser } from 'playwright'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { buildSite } from '../lib/build.mjs'
+import { buildScorm } from '../lib/scorm.mjs'
+import { host, type Host } from './helpers/host.js'
+import { changedQuiz, entriesOf, formulas, quiz } from './helpers/zip.js'
+
+/**
+ * The SCORM page of a written site, driven in Chromium as a teacher uses it: a file chosen, the
+ * zip offered and downloaded, and a refusal shown. What the zip holds is `scorm-browser.test.ts`'s
+ * to check against the command's; here it is the page's own script, bundled as the site carries
+ * it, and the download that reaches the disk.
+ */
+
+let dir: string
+let site: Host
+let browser: Browser
+
+beforeAll(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'h5p-embed-scorm-page-'))
+ await buildSite({ out: join(dir, 'site') })
+ site = await host(join(dir, 'site'), '127.0.0.1')
+ browser = await chromium.launch()
+})
+
+afterAll(async () => {
+ await browser?.close()
+ await site?.close()
+ await rm(dir, { recursive: true, force: true })
+})
+
+describe('the SCORM page', () => {
+ it("builds the command's zip from a chosen file and hands it over as a download, which plays", async () => {
+ const context = await browser.newContext()
+ const page = await context.newPage()
+ await page.goto(`${site.origin}/scorm.html`)
+ await page.setInputFiles('#file', quiz)
+ await page.locator('#download').waitFor({ state: 'visible', timeout: 60_000 })
+ expect(await page.locator('#status').textContent()).toMatch(/^“Do you know what just happened\?” as a SCORM 1\.2 package\. Build [0-9a-f]{16}\.$/)
+ expect(await page.locator('#download').textContent()).toMatch(/^Download quiz\.scorm\.zip \(\d+\.\d MB\)$/)
+ expect(await page.locator('#notice').isHidden()).toBe(true)
+
+ const [download] = await Promise.all([page.waitForEvent('download'), page.locator('#download').click()])
+ expect(download.suggestedFilename()).toBe('quiz.scorm.zip')
+ const saved = join(dir, 'quiz.page.zip')
+ await download.saveAs(saved)
+
+ // The same entries as the command's, with the same bytes; deflated by another zlib, so not
+ // necessarily the same size.
+ const command = await buildScorm({ h5p: quiz, out: join(dir, 'quiz.cli.zip') })
+ const downloaded = await entriesOf(saved)
+ const written = await entriesOf(command.out)
+ expect(downloaded.names).toEqual(written.names)
+ for (const name of downloaded.names) {
+ expect(Buffer.from(await downloaded.bytes(name)).equals(await written.bytes(name)), name).toBe(true)
+ }
+ await written.close()
+
+ // Unpacked onto the site, as an LMS unpacks it, the launch page plays the package.
+ const played = join(dir, 'site', 'played')
+ for (const name of downloaded.names) {
+ await mkdir(dirname(join(played, name)), { recursive: true })
+ await writeFile(join(played, name), await downloaded.bytes(name))
+ }
+ await downloaded.close()
+ await page.goto(`${site.origin}/played/index.html`)
+ await page.waitForFunction(() => (document.querySelector('h5p-player') as { state?: string } | null)?.state === 'ready', null, { timeout: 60_000 })
+ await context.close()
+ })
+
+ it('shows a refusal in its words, and builds the next file as if nothing had happened', async () => {
+ const unknown = join(dir, 'unknown.h5p')
+ await changedQuiz(unknown, (manifest) => {
+ manifest.preloadedDependencies.push({ machineName: 'H5P.Nowhere', majorVersion: 1, minorVersion: 0 })
+ })
+ const context = await browser.newContext()
+ const page = await context.newPage()
+ await page.goto(`${site.origin}/scorm.html`)
+ await page.setInputFiles('#file', unknown)
+ await page.locator('#notice').waitFor({ state: 'visible', timeout: 60_000 })
+ expect(await page.locator('#notice').textContent()).toMatch(/^unknown\.h5p needs libraries that neither it nor the library pack carries: H5P\.Nowhere 1\.0\./)
+ expect(await page.locator('#download').isHidden()).toBe(true)
+ expect(await page.locator('#status').textContent()).toBe('')
+
+ // An export without its libraries, next: the parts come from the site's own copy of the pack.
+ await page.setInputFiles('#file', formulas)
+ await page.locator('#download').waitFor({ state: 'visible', timeout: 60_000 })
+ expect(await page.locator('#notice').isHidden()).toBe(true)
+ expect(await page.locator('#status').textContent()).toMatch(/ as a SCORM 1\.2 package, with \d+ libraries from the pack\. Build [0-9a-f]{16}\.$/)
+ expect(await page.locator('#download').textContent()).toMatch(/^Download formulas\.scorm\.zip /)
+ await context.close()
+ })
+})
diff --git a/packages/embed/tests/scorm.test.ts b/packages/embed/tests/scorm.test.ts
index 72ec0c8d..31c87873 100644
--- a/packages/embed/tests/scorm.test.ts
+++ b/packages/embed/tests/scorm.test.ts
@@ -8,20 +8,20 @@ import { tmpdir } from 'node:os'
import { basename, dirname, extname, join, normalize, resolve } from 'node:path'
import { promisify } from 'node:util'
import { crc32 } from 'node:zlib'
-import { BlobReader, BlobWriter, TextWriter, Uint8ArrayReader, Uint8ArrayWriter, ZipReader, ZipWriter } from '@zip.js/zip.js'
+import { BlobReader, ZipReader } from '@zip.js/zip.js'
import { chromium, type Browser, type BrowserContext, type Frame, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { EmbedError } from '../lib/build.mjs'
import { buildScorm } from '../lib/scorm.mjs'
+import { changedQuiz, entriesOf, formulas, quiz } from './helpers/zip.js'
/**
* The SCORM package `--scorm` writes: what is in the zip and what is refused, in Node; and in
* Chromium, the launch page framed by a stand-in for an LMS's player page, which puts the SCORM
- * 1.2 API in its window and keeps the values, as Moodle's does, across launches.
+ * 1.2 API in its window and keeps the values, as Moodle's does, across launches. The same zip
+ * built in a page is `scorm-browser.test.ts`'s and `scorm-page.test.ts`'s.
*/
-const quiz = resolve(import.meta.dirname, '../../../apps/demo/demo/content/quiz.h5p')
-const formulas = resolve(import.meta.dirname, '../../../apps/demo/demo/content/formulas.h5p')
const bin = resolve(import.meta.dirname, '../bin/h5p-embed.mjs')
let dir: string
@@ -32,38 +32,6 @@ afterAll(async () => {
await rm(dir, { recursive: true, force: true })
})
-/** A zip's entries, by name, with a way to read each as text. */
-async function entriesOf(path: string) {
- const reader = new ZipReader(new BlobReader(new Blob([await readFile(path)])))
- const entries = await reader.getEntries()
- const file = (name: string) => {
- const entry = entries.find((candidate) => candidate.filename === name)
- if (!entry || entry.directory) throw new Error(`${name} is not in ${path}`)
- return entry
- }
- const text = async (name: string) => file(name).getData!(new TextWriter())
- const bytes = async (name: string) => file(name).getData!(new Uint8ArrayWriter())
- return { names: entries.filter((entry) => !entry.directory).map((entry) => entry.filename), text, bytes, close: () => reader.close() }
-}
-
-/** The quiz, changed: its `h5p.json` edited, and the entries `drop` names left out. */
-async function changedQuiz(path: string, edit: (manifest: Record) => void, drop: (name: string) => boolean = () => false) {
- const reader = new ZipReader(new BlobReader(new Blob([await readFile(quiz)])))
- const writer = new ZipWriter(new BlobWriter('application/zip'))
- for (const entry of await reader.getEntries()) {
- if (entry.directory || drop(entry.filename)) continue
- let bytes = await entry.getData!(new Uint8ArrayWriter())
- if (entry.filename === 'h5p.json') {
- const manifest = JSON.parse(new TextDecoder().decode(bytes))
- edit(manifest)
- bytes = new TextEncoder().encode(JSON.stringify(manifest))
- }
- await writer.add(entry.filename, new Uint8ArrayReader(bytes))
- }
- await reader.close()
- await writeFile(path, new Uint8Array(await (await writer.close()).arrayBuffer()))
-}
-
describe('the package', () => {
it('carries the launch page, the player, the runtime and the package, every file in the manifest', async () => {
const out = join(dir, 'quiz.zip')
diff --git a/packages/embed/tsconfig.json b/packages/embed/tsconfig.json
index da6a79d7..eb4fec5b 100644
--- a/packages/embed/tsconfig.json
+++ b/packages/embed/tsconfig.json
@@ -13,5 +13,5 @@
"skipLibCheck": true,
"checkJs": true
},
- "include": ["lib/**/*.mjs", "site/embed.js", "scorm/scorm.js", "tests/**/*.ts"]
+ "include": ["lib/**/*.mjs", "site/embed.js", "site/scorm-page.js", "scorm/scorm.js", "tests/**/*.ts"]
}
diff --git a/packages/embed/tsconfig.types.json b/packages/embed/tsconfig.types.json
index 660a9b83..64c04820 100644
--- a/packages/embed/tsconfig.types.json
+++ b/packages/embed/tsconfig.types.json
@@ -8,5 +8,5 @@
"rootDir": ".",
"outDir": "types"
},
- "include": ["lib/build.mjs", "lib/scorm.mjs", "site/embed.js"]
+ "include": ["lib/build.mjs", "lib/scorm.mjs", "lib/scorm-browser.mjs", "site/embed.js", "site/scorm-page.js"]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d4a56e7b..2f512b85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -162,6 +162,9 @@ importers:
'@types/node':
specifier: ^26.6.5
version: 26.6.5
+ esbuild:
+ specifier: ^0.28.2
+ version: 0.28.2
playwright:
specifier: ^1.64.1
version: 1.64.1
From ff48287cf2a30eef54562dc13ce992b539254b22 Mon Sep 17 00:00:00 2001
From: Aleksandr Shevchuk
Date: Tue, 3 Nov 2026 15:37:22 +0200
Subject: [PATCH 2/3] fix(nav): update SCORM link in topbar navigation
---
apps/demo/demo/scorm.html | 2 +-
apps/demo/partials/topbar-nav.html | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/apps/demo/demo/scorm.html b/apps/demo/demo/scorm.html
index ba6b8c9c..de5d4721 100644
--- a/apps/demo/demo/scorm.html
+++ b/apps/demo/demo/scorm.html
@@ -63,7 +63,7 @@
In the LMS
no result of its own, an Accordion or a Virtual Tour, stays incomplete. The package plays
with its own code on the LMS's origin, as every SCORM package does.
-
+
Checked in
Add the zip as
Change from the defaults
diff --git a/apps/demo/partials/topbar-nav.html b/apps/demo/partials/topbar-nav.html
index f9c3fe46..e3094d86 100644
--- a/apps/demo/partials/topbar-nav.html
+++ b/apps/demo/partials/topbar-nav.html
@@ -2,7 +2,7 @@
PlayerSetupCompare
- Normalize
+ SCORMExamplesApp
From b379bf4defb037bf049e01fe3d9852836183cfb0 Mon Sep 17 00:00:00 2001
From: Aleksandr Shevchuk
Date: Tue, 3 Nov 2026 15:47:18 +0200
Subject: [PATCH 3/3] feat(scorm): add eyebrow text to SCORM section in demo
page
---
apps/demo/demo/scorm.html | 1 +
1 file changed, 1 insertion(+)
diff --git a/apps/demo/demo/scorm.html b/apps/demo/demo/scorm.html
index de5d4721..c97b7fcd 100644
--- a/apps/demo/demo/scorm.html
+++ b/apps/demo/demo/scorm.html
@@ -29,6 +29,7 @@
+
SCORM
H5P to SCORM
Drop a .h5p file here, or choose one, and download it as a SCORM 1.2 package