3D engine that AI agents drive
Publish one self-contained ES module in the npm package (#990)
Nguyen Xuan An61384aafc63d
diff --git a/changes/990-cdn-single-file.md b/changes/990-cdn-single-file.mdnew file mode 100644index 00000000..721ec348--- /dev/null+++ b/changes/990-cdn-single-file.md@@ -0,0 +1 @@+- The npm package now ships `build/67.standalone.js`, one self-contained ES module with no relative chunk import, so `https://cdn.jsdelivr.net/npm/@codepawlhq/67js@<version>/build/67.standalone.js` loads from a single script tag. It is also exported as `@codepawlhq/67js/standalone`, and the site copy at `/releases/<version>/67.module.js` is checked to have the same bytes. `docs/learn/install.md` has the jsdelivr snippet. (#990)diff --git a/docs/learn/install.md b/docs/learn/install.mdindex 842d4e0d..95db4dcd 100644--- a/docs/learn/install.md+++ b/docs/learn/install.md@@ -71,6 +71,28 @@ A plain HTML page can import 67js from this site. Use the exact `module` URL froServe the page over HTTP, for example with `npx serve`. A page opened from a `file://` path cannot import modules. This file has the core only. Addons such as `67js/addons/gltf` need the npm package.+## Use 67js from jsdelivr++From version 0.20.0 the npm package holds one self-contained module, `build/67.standalone.js`. It has no relative imports, so jsdelivr (and unpkg) serve it from one URL. Pin the version in the URL. This works in a plain HTML file and in a claude.ai artifact, which loads scripts only from cdnjs, jsdelivr and unpkg.++```html+<canvas id="view" width="640" height="400"></canvas>+<script type="module">+ import { Renderer67, box } from 'https://cdn.jsdelivr.net/npm/@codepawlhq/[email protected]/build/67.standalone.js';++ const parts = [{+ name: 'Cube',+ geometry: box(),+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),+ material: { color: [0.8, 0.3, 0.2], metallic: 0, roughness: 0.4, emission: 0 },+ }];+ const renderer = new Renderer67(document.querySelector('#view'), parts, { samples: 4 });+ renderer.render({ eye: [2.5, 2, 3.5], target: [0, 0, 0] });+</script>+```++The file has the core only. Addons such as `67js/addons/gltf` need the npm package. Versions before 0.20.0 have no standalone file; their `build/67.module.js` also loads from jsdelivr, but it imports 16 chunk files.+## Good to know> **Note:** 67js is plain JavaScript and has no TypeScript types. In a strict TypeScript project, add the line `declare module '67js';` to a `.d.ts` file. The imports then have the type `any`.diff --git a/package.json b/package.jsonindex 8add6fa2..26b885ae 100644--- a/package.json+++ b/package.json@@ -68,6 +68,7 @@},"exports": {".": "./build/67.module.js",+ "./standalone": "./build/67.standalone.js","./addons/model": "./build/model.js","./addons/nature": "./build/nature.js","./addons/motion": "./build/motion.js",@@ -147,7 +148,7 @@"prepare": "node scripts/install-git-hooks.mjs","dev": "vite --host 127.0.0.1","build": "node scripts/prepare-release.mjs && vite build",- "build:lib": "vite build --config vite.lib.config.js",+ "build:lib": "vite build --config vite.lib.config.js && vite build --config vite.browser.config.js","prepare:release": "node scripts/prepare-release.mjs","prepack": "npm run build:lib","deploy": "node scripts/deploy.mjs",diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 182d55df..f9cc0d2c 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -22,6 +22,8 @@ function run(executable, argumentsList, capture = false) {const commit = run('git', ['rev-parse', 'HEAD'], true);if (process.argv.includes('--require-clean') && run('git', ['status', '--porcelain'], true)) throw new Error('Commit release changes before production preparation.');run(process.execPath, ['node_modules/vite/bin/vite.js', 'build', '--config', 'vite.lib.config.js']);+// The standalone module goes into build/ before npm pack, so the package carries it.+run(process.execPath, ['node_modules/vite/bin/vite.js', 'build', '--config', 'vite.browser.config.js']);const releases = resolve(root, 'public/releases');await mkdir(releases, { recursive: true });const npmCli = process.env.npm_execpath ?? resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');@@ -33,8 +35,12 @@ const tarball = `/releases/${packed.filename}`;let archive = await readFile(resolve(releases, packed.filename));let integrity = `sha512-${createHash('sha512').update(archive).digest('base64')}`;await cp(resolve(root, 'build'), resolve(releases, metadata.version), { recursive: true });-run(process.execPath, ['node_modules/vite/bin/vite.js', 'build', '--config', 'vite.browser.config.js']);-await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, metadata.version, '67.module.js'));+// The site keeps its old file name. The bytes must equal the npm file, so a CDN and the site serve the same module.+const standaloneBytes = await readFile(resolve(root, 'build/67.standalone.js'));+const siteModulePath = resolve(releases, metadata.version, '67.module.js');+await writeFile(siteModulePath, standaloneBytes);+const sha512 = (bytes) => createHash('sha512').update(bytes).digest('hex');+if (sha512(await readFile(siteModulePath)) !== sha512(standaloneBytes)) throw new Error('The site copy of the standalone module differs from build/67.standalone.js.');// The site shows pending change notes above the released sections. Nothing here is kept by hand.const changelogText = await readFile(resolve(root, 'CHANGELOG.md'), 'utf8');await writeFile(resolve(root, 'public/changelog.md'), await changelogWithUnreleased(changelogText));diff --git a/scripts/smoke-cdn-single-file.mjs b/scripts/smoke-cdn-single-file.mjsnew file mode 100644index 00000000..12110d3b--- /dev/null+++ b/scripts/smoke-cdn-single-file.mjs@@ -0,0 +1,88 @@+// Proves that the packed npm tarball serves a cube from one script tag with no failed request.+// Usage: node scripts/smoke-cdn-single-file.mjs <tarball> [--published-url <url>]+// It unpacks the tarball, serves its package folder under a jsdelivr-like path, loads a page with a single+// <script type="module"> and reads the pixels. With --published-url it loads that real URL instead of the local one.+import { chromium } from 'playwright';+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { mkdtemp, readFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, extname, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { gzipSync } from 'node:zlib';++const tarball = process.argv[2];+const urlFlag = process.argv.indexOf('--published-url');+const publishedUrl = urlFlag > 0 ? process.argv[urlFlag + 1] : null;+const version = JSON.parse(await readFile('package.json', 'utf8')).version;++let moduleUrl = publishedUrl;+let server;+if (!publishedUrl) {+ assert.ok(tarball, 'Pass the packed tarball path.');+ const unpacked = await mkdtemp(join(tmpdir(), '67js-cdn-'));+ const extracted = spawnSync('tar', ['-xzf', resolve(tarball), '-C', unpacked], { encoding: 'utf8' });+ assert.equal(extracted.status, 0, extracted.stderr);+ const packageFolder = join(unpacked, 'package');+ const mountPath = `/npm/@codepawlhq/67js@${version}/`;+ const standalone = await readFile(join(packageFolder, 'build/67.standalone.js'));+ console.log(`standalone bytes=${standalone.length} gzip=${gzipSync(standalone, { level: 9 }).length}`);+ server = createServer(async (request, response) => {+ const path = decodeURIComponent(new URL(request.url, 'http://x').pathname);+ const relative = path.startsWith(mountPath) ? path.slice(mountPath.length) : null;+ const file = relative && !relative.includes('..') ? join(packageFolder, relative) : null;+ if (!file || !existsSync(file)) { response.writeHead(404); response.end(); return; }+ response.writeHead(200, { 'content-type': extname(file) === '.js' ? 'text/javascript' : 'application/octet-stream', 'access-control-allow-origin': '*' });+ response.end(await readFile(file));+ });+ await new Promise((done) => server.listen(0, '127.0.0.1', done));+ moduleUrl = `http://127.0.0.1:${server.address().port}${mountPath}build/67.standalone.js`;+}++const page = `<!doctype html><canvas id="view" width="320" height="240"></canvas>+<script type="module">+ import { Renderer67, box } from ${JSON.stringify(moduleUrl)};+ const parts = [{ name: 'Cube', geometry: box(), matrix: new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]), material: { color: [0.8, 0.3, 0.2], metallic: 0, roughness: 0.4, emission: 0 } }];+ const renderer = new Renderer67(document.querySelector('#view'), parts, { samples: 4 });+ renderer.render({ eye: [2.5, 2, 3.5], target: [0, 0, 0] });+ const context = renderer.context;+ const pixels = new Uint8Array(320 * 240 * 4);+ context.readPixels(0, 0, 320, 240, context.RGBA, context.UNSIGNED_BYTE, pixels);+ let lit = 0;+ for (let index = 0; index < pixels.length; index += 4) if (pixels[index] > 100 && pixels[index + 2] < 120) lit++;+ window.__result = { lit };+</script>`;++const pageServer = createServer((request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end(page); });+await new Promise((done) => pageServer.listen(0, '127.0.0.1', done));+const chromePath = process.env.CHROME_PATH;+const browser = await chromium.launch({+ headless: true,+ ...(chromePath ? { executablePath: chromePath } : {}),+ args: ['--enable-webgl', '--ignore-gpu-blocklist', '--no-sandbox', '--use-angle=vulkan', '--enable-features=Vulkan'],+});+try {+ const tab = await browser.newPage();+ const requests = [];+ const failures = [];+ const errors = [];+ tab.on('response', (response) => { requests.push(`${response.status()} ${response.url()}`); if (response.status() >= 400) failures.push(`${response.status()} ${response.url()}`); });+ tab.on('requestfailed', (request) => failures.push(`failed ${request.url()} ${request.failure()?.errorText}`));+ tab.on('pageerror', (error) => errors.push(error.message));+ await tab.goto(`http://127.0.0.1:${pageServer.address().port}/`);+ await tab.waitForFunction(() => window.__result, null, { timeout: 30000 });+ const { lit } = await tab.evaluate(() => window.__result);+ console.log(`requests=${requests.length}`);+ for (const line of requests) console.log(line);+ console.log(`lit cube pixels=${lit} failures=${failures.length} pageErrors=${errors.length}`);+ assert.ok(lit > 500, 'The cube must cover visible pixels.');+ assert.deepEqual(failures, []);+ assert.deepEqual(errors, []);+ assert.equal(requests.filter((line) => line.includes('.js')).length, 1, 'Only the one module file may load.');+ console.log('cdn single file smoke passed');+} finally {+ await browser.close();+ pageServer.close();+ server?.close();+}diff --git a/tests/standalone-build.test.js b/tests/standalone-build.test.jsnew file mode 100644index 00000000..1c7cb437--- /dev/null+++ b/tests/standalone-build.test.js@@ -0,0 +1,36 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import browserConfiguration, { STANDALONE_FILE_NAME } from '../vite.browser.config.js';++const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));+const prepareRelease = await readFile(new URL('../scripts/prepare-release.mjs', import.meta.url), 'utf8');+const installGuide = await readFile(new URL('../docs/learn/install.md', import.meta.url), 'utf8');++test('the standalone module builds into build/ after the library build without emptying it', () => {+ assert.equal(STANDALONE_FILE_NAME, '67.standalone.js');+ assert.equal(browserConfiguration.build.outDir, 'build');+ assert.equal(browserConfiguration.build.emptyOutDir, false);+ assert.deepEqual(browserConfiguration.build.lib.formats, ['es']);+ assert.equal(browserConfiguration.build.lib.fileName(), STANDALONE_FILE_NAME);+ const libraryStep = metadata.scripts['build:lib'].indexOf('vite.lib.config.js');+ const standaloneStep = metadata.scripts['build:lib'].indexOf('vite.browser.config.js');+ assert.ok(libraryStep >= 0 && standaloneStep > libraryStep, 'build:lib must run the standalone build after the library build.');+});++test('the package ships the standalone module and exports it', () => {+ assert.ok(metadata.files.includes('build'));+ assert.ok(!metadata.files.includes('!build/67.standalone.js'));+ assert.equal(metadata.exports['./standalone'], './build/67.standalone.js');+});++test('release preparation builds the standalone module before npm pack and checks the site copy byte for byte', () => {+ const standaloneBuild = prepareRelease.indexOf('vite.browser.config.js');+ const pack = prepareRelease.indexOf("'pack'");+ assert.ok(standaloneBuild >= 0 && standaloneBuild < pack, 'The standalone build must come before npm pack.');+ assert.match(prepareRelease, /sha512\(await readFile\(siteModulePath\)\) !== sha512\(standaloneBytes\)/);+});++test('the install guide shows a pinned jsdelivr snippet with a single module script', () => {+ assert.match(installGuide, /https:\/\/cdn\.jsdelivr\.net\/npm\/@codepawlhq\/67js@\d+\.\d+\.\d+\/build\/67\.standalone\.js/);+});diff --git a/vite.browser.config.js b/vite.browser.config.jsindex 0abf1cbc..797e463c 100644--- a/vite.browser.config.js+++ b/vite.browser.config.js@@ -1,12 +1,18 @@import { readFileSync } from 'node:fs';import { defineConfig } from 'vite';+// One self-contained ES module with no relative chunk import. It lands in build/ beside the library files, so the npm package+// carries it and a CDN that mirrors npm (jsdelivr, unpkg) serves it from a single URL. The library build runs first and empties+// build/, so this build must not empty it again. The site copies the same bytes to /releases/<version>/67.module.js.+export const STANDALONE_FILE_NAME = '67.standalone.js';+export default defineConfig({build: {copyPublicDir: false,+ emptyOutDir: false,rolldownOptions: { output: { banner: `/*! ${readFileSync('LICENSE', 'utf8')} */` } },- outDir: 'build-browser',- lib: { entry: 'src/index.js', formats: ['es'], fileName: () => '67.module.js' },+ outDir: 'build',+ lib: { entry: 'src/index.js', formats: ['es'], fileName: () => STANDALONE_FILE_NAME },minify: true,},});