Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an API reference and a Resources page to the docs (part of #508)

Nguyen Xuan An7362174be7ff
diff --git a/.gitignore b/.gitignore
index 5eff4bd9..6470326e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,7 @@ public/release.json
public/changelog.md
public/changelog.json
public/guide.md
+public/api-reference.json
public/gltf.md
public/gltf-morph.md
public/morph-targets.md
diff --git a/changes/508-api-reference.md b/changes/508-api-reference.md
new file mode 100644
index 00000000..ec2aa03e
--- /dev/null
+++ b/changes/508-api-reference.md
@@ -0,0 +1 @@
+- Docs: add an API reference and a Resources page (part of #508). `scripts/api-reference.mjs` reads the exports of `67js` and every addon, with signatures, the comment above each declaration and a source link. `npm run build` writes it to `/api-reference.json`, so the page always matches the code. Resources links the demos, the agent guides, every contract, the changelog and npm.
diff --git a/docs/learn/api-reference.md b/docs/learn/api-reference.md
new file mode 100644
index 00000000..4ec0c614
--- /dev/null
+++ b/docs/learn/api-reference.md
@@ -0,0 +1,10 @@
+# API reference
+
+This page lists every export of `67js` and of each addon, with its signature and the comment above it in the source. A script reads the package itself to make the list, so it matches the current code. Each entry links to its source on GitHub.
+
+Import the core from `67js`. Import an addon from its own path, such as `67js/addons/gltf`. If you installed the package without the `67js` alias, start each path with `@codepawlhq/67js` instead.
+
+```api
+```
+
+The topic pages explain how the exports work together. [Renderer reference](#renderer-reference) lists the options of `Renderer67`, and [Addons and limits](#addons-and-limits) lists what each addon is for.
diff --git a/docs/learn/resources.md b/docs/learn/resources.md
new file mode 100644
index 00000000..ee4303c8
--- /dev/null
+++ b/docs/learn/resources.md
@@ -0,0 +1,41 @@
+# Resources
+
+## Examples
+
+Each demo is a 67js scene with its source in the repository.
+
+```cards
+Object studio | /object.html | Orbit, lighting looks, an exploded view and PNG export. | /previews/wall-e.webp
+Procedural modeling | /modeling.html | Lathe, extrude and tube geometry in one lantern. | /previews/modeling.webp
+Nature | /nature.html | Terrain, trees, grass, wind and a moving sun. | /previews/grass.webp
+Assets | /assets.html | GLB models with their animation. | /previews/assets.webp
+Film | /film.html | A short film with a timeline, physics and sound. | /previews/film-contact.webp
+Showcase | /showcase.html | An airport, a data center and a port. | /previews/showcase-port.webp
+```
+
+## Guides for AI agents
+
+An agent can build scenes through the MCP server, without writing engine code. These files are plain text for agents and for people.
+
+- [MCP server](/mcp.md): install, client setup, the tools and their limits.
+- [Scene recipes](/agent-scene.md): the JSON format that the tools accept.
+- [Look](/agent-look.md), [motion](/agent-motion.md), [character motion](/agent-character-motion.md) and [assets](/agent-asset.md): the parts of a recipe.
+- [Render jobs](/agent-render-jobs.md) and [visual review](/agent-review.md): images, sequences, video and review grids.
+- [The plain-text guide](/guide.md): all of this documentation in one Markdown file.
+
+## Contracts
+
+A contract is the exact rule set of one module: inputs, limits, memory and errors. The topic pages link to the matching contract.
+
+- Modeling: [procedural modeling](/modeling.md), [mesh editing](/mesh.md), [primitives](/primitives.md), [sculpt](/sculpt.md), [surface patches](/surface.md), [shrinkwrap](/shrinkwrap.md), [mesh queries](/mesh-query.md), [scene graph](/scene-graph.md).
+- Look: [lighting](/lighting.md), [volume fog](/volumetric.md), [path tracer](/path-tracer.md), [light bake](/light-bake.md), [Gaussian splats](/gaussian-splats.md).
+- Worlds: [terrain](/terrain.md), [vegetation](/vegetation.md), [grass](/grass.md), [clutter](/clutter.md), [vehicles](/vehicle.md), [Spume liquid](/spume.md).
+- Motion: [animation curves](/animation-curves.md), [mixer](/animation-mixer.md), [skinning](/skinning.md), [morph targets](/morph-targets.md), [retargeting](/retarget.md), [skeleton pose](/skeleton-pose.md), [camera paths](/camera-path.md), [physics](/physics.md), [film physics](/film-physics.md).
+- Files: [glTF import](/gltf.md), [glTF morphs](/gltf-morph.md), [GLB export](/export-glb.md).
+
+## Project
+
+- [Changelog](/changelog.html): every release and the unreleased changes. Agents can read [changelog.json](/changelog.json).
+- [npm package](https://www.npmjs.com/package/@codepawlhq/67js): `@codepawlhq/67js`.
+- [Source on GitHub](https://github.com/codepawl/67.js): issues, pull requests and the contributing guide.
+- [Release metadata](/release.json): the published version, the browser module URL and the archive checksum.
diff --git a/scripts/api-reference.mjs b/scripts/api-reference.mjs
new file mode 100644
index 00000000..2e5ff263
--- /dev/null
+++ b/scripts/api-reference.mjs
@@ -0,0 +1,135 @@
+// Build the API reference from the package's real exports: every name that `67js` and each documented addon export,
+// with its kind, its signature and the comment above its declaration.
+// `node scripts/api-reference.mjs` writes public/api-reference.json. `npm run build` runs it, so the site always matches the code.
+import { readFile, writeFile } from 'node:fs/promises';
+import { dirname, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+// Package export path to source file. The library build maps each addon entry name to its source.
+async function entryFiles() {
+ const packageJson = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
+ const libraryConfig = await readFile(resolve(root, 'vite.lib.config.js'), 'utf8');
+ const sources = Object.fromEntries([...libraryConfig.matchAll(/^\s*'?([\w-]+)'?:\s*'(src\/[\w-]+\.js)'/gm)].map(match => [match[1], match[2]]));
+ const entries = [];
+ for (const exportPath of Object.keys(packageJson.exports)) {
+ if (exportPath === '.') entries.push({ module: '67js', file: sources.core });
+ const addon = exportPath.match(/^\.\/addons\/([\w-]+)$/);
+ if (addon && sources[addon[1]]) entries.push({ module: `67js/addons/${addon[1]}`, file: sources[addon[1]] });
+ }
+ return entries;
+}
+
+const fileCache = new Map();
+async function sourceText(file) {
+ if (!fileCache.has(file)) fileCache.set(file, (await readFile(resolve(root, file), 'utf8')).replace(/\r\n/g, '\n'));
+ return fileCache.get(file);
+}
+
+function resolveImport(fromFile, specifier) {
+ return relative(root, resolve(root, dirname(fromFile), specifier)).replace(/\\/g, '/');
+}
+
+// The comment lines directly above a declaration, without the comment markers.
+function leadingComment(text, index) {
+ const lines = text.slice(0, index).split('\n');
+ lines.pop();
+ const comment = [];
+ while (lines.length) {
+ const line = lines[lines.length - 1].trim();
+ if (!/^(\/\/|\/\*\*?|\*)/.test(line)) break;
+ comment.unshift(line.replace(/^\/\*\*?\s?|\*\/$|^\*\s?|^\/\/\s?/g, '').trim());
+ lines.pop();
+ }
+ return comment.filter(Boolean).join(' ').trim();
+}
+
+// Read the parameter list of `name(...)`, counting brackets so default objects and arrays stay whole.
+function parameterList(text, start) {
+ let depth = 0;
+ for (let index = start; index < text.length; index++) {
+ const character = text[index];
+ if ('([{'.includes(character)) depth++;
+ if (')]}'.includes(character)) depth--;
+ if (depth === 0) return text.slice(start, index + 1).replace(/\s+/g, ' ');
+ }
+ return '()';
+}
+
+async function declaration(file, name, seen = new Set()) {
+ const key = `${file}#${name}`;
+ if (seen.has(key)) return null;
+ seen.add(key);
+ const text = await sourceText(file);
+ const patterns = [
+ { kind: 'function', pattern: new RegExp(`^export (?:async )?function\\*? ${name}\\s*\\(`, 'm') },
+ { kind: 'class', pattern: new RegExp(`^export class ${name}\\b`, 'm') },
+ { kind: 'constant', pattern: new RegExp(`^export (?:const|let) ${name}\\b`, 'm') },
+ ];
+ for (const { kind, pattern } of patterns) {
+ const match = pattern.exec(text);
+ if (!match) continue;
+ const line = text.slice(0, match.index).split('\n').length;
+ let signature = name;
+ if (kind === 'function') signature = `${name}${parameterList(text, match.index + match[0].length - 1)}`;
+ if (kind === 'class') {
+ const constructorMatch = /\n\s+constructor\s*\(/.exec(text.slice(match.index));
+ if (constructorMatch) signature = `new ${name}${parameterList(text, match.index + constructorMatch.index + constructorMatch[0].length - 1)}`;
+ }
+ return { kind, signature, summary: leadingComment(text, match.index), source: `${file}:${line}` };
+ }
+ // A local declaration exported later by an `export { name }` list.
+ const local = new RegExp(`^(?:async )?function ${name}\\s*\\(|^(?:const|let) ${name}\\b|^class ${name}\\b`, 'm').exec(text);
+ if (local && new RegExp(`^export \\{[^}]*\\b${name}\\b[^}]*\\};?$`, 'm').test(text)) {
+ const kind = local[0].includes('function') ? 'function' : local[0].includes('class') ? 'class' : 'constant';
+ const line = text.slice(0, local.index).split('\n').length;
+ const signature = kind === 'function' ? `${name}${parameterList(text, local.index + local[0].length - 1)}` : name;
+ return { kind, signature, summary: leadingComment(text, local.index), source: `${file}:${line}` };
+ }
+ // `import { name } from './other.js'` followed by `export { name }`.
+ if (new RegExp(`^export \\{[^}]*\\b${name}\\b[^}]*\\};?$`, 'm').test(text)) {
+ for (const match of text.matchAll(/^import \{([^}]+)\} from '(\.[^']+)';?$/gm)) {
+ for (const item of match[1].split(',').map(part => part.trim()).filter(Boolean)) {
+ const [original, alias = original] = item.split(/\s+as\s+/);
+ if (alias === name) return declaration(resolveImport(file, match[2]), original, seen);
+ }
+ }
+ }
+ for (const match of text.matchAll(/^export \{([^}]+)\} from '([^']+)';?$/gm)) {
+ for (const item of match[1].split(',').map(part => part.trim()).filter(Boolean)) {
+ const [original, alias = original] = item.split(/\s+as\s+/);
+ if (alias === name) return declaration(resolveImport(file, match[2]), original, seen);
+ }
+ }
+ for (const match of text.matchAll(/^export \* from '([^']+)';?$/gm)) {
+ const found = await declaration(resolveImport(file, match[1]), name, seen);
+ if (found) return found;
+ }
+ return null;
+}
+
+/** Return the reference for every documented entry point, in package order. */
+export async function buildApiReference() {
+ const modules = [];
+ for (const { module, file } of await entryFiles()) {
+ const namespace = await import(`file://${resolve(root, file).replace(/\\/g, '/')}`).catch(() => null);
+ if (!namespace) continue;
+ const exports = [];
+ for (const name of Object.keys(namespace).sort((first, second) => first.localeCompare(second))) {
+ const found = await declaration(file, name);
+ const value = namespace[name];
+ const kind = found?.kind ?? (typeof value === 'function' ? 'function' : 'constant');
+ exports.push({ name, kind, signature: found?.signature ?? name, summary: found?.summary ?? '', source: found?.source ?? file });
+ }
+ modules.push({ module, file, exports });
+ }
+ return { modules };
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const reference = await buildApiReference();
+ await writeFile(resolve(root, 'public/api-reference.json'), `${JSON.stringify(reference, null, 1)}\n`);
+ const count = reference.modules.reduce((total, entry) => total + entry.exports.length, 0);
+ console.log(`Wrote public/api-reference.json: ${reference.modules.length} modules, ${count} exports.`);
+}
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 4a4dfe16..05789a33 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -6,6 +6,7 @@ import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { changelogWithUnreleased, readChangelogData } from './changelog-fragments.mjs';
import { plainGuide } from './plain-guide.mjs';
+import { buildApiReference } from './api-reference.mjs';
const root = fileURLToPath(new URL('..', import.meta.url));
const metadata = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
@@ -40,6 +41,8 @@ await writeFile(resolve(root, 'public/changelog.md'), await changelogWithUnrelea
await writeFile(resolve(root, 'public/changelog.json'), `${JSON.stringify(await readChangelogData({ changelogText, version: metadata.version }), null, 2)}
`);
await writeFile(resolve(root, 'public/guide.md'), await plainGuide(root));
+await writeFile(resolve(root, 'public/api-reference.json'), `${JSON.stringify(await buildApiReference())}
+`);
await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));
const sourceDocuments = [
'scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',
diff --git a/src/docs-api.js b/src/docs-api.js
new file mode 100644
index 00000000..284bd4f0
--- /dev/null
+++ b/src/docs-api.js
@@ -0,0 +1,91 @@
+// The API reference: every export of `67js` and its addons, from /api-reference.json, which `npm run build` makes with
+// scripts/api-reference.mjs. In development, run that script once.
+import { highlightCode } from './code-highlight.js';
+
+const sourceBase = 'https://github.com/codepawl/67.js/blob/main/';
+
+function escapeHtml(value) {
+ return value.replace(/[&<>"']/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[character]));
+}
+
+function entryElement(module, entry) {
+ const element = document.createElement('div');
+ element.className = 'api-entry';
+ element.id = `api-${module.replace(/\W+/g, '-')}-${entry.name}`;
+ element.dataset.search = `${module} ${entry.name} ${entry.summary}`.toLowerCase();
+ const [file, line] = entry.source.split(':');
+ const summary = entry.summary ? `<p>${escapeHtml(entry.summary).replace(/`([^`]+)`/g, '<code>$1</code>')}</p>` : '';
+ element.innerHTML = `
+ <div class="api-entry-heading"><h4>${escapeHtml(entry.name)}</h4><span class="api-kind">${entry.kind}</span><a class="api-source" href="${sourceBase}${file}${line ? `#L${line}` : ''}" rel="noopener">Source</a></div>
+ <pre><code class="hljs language-javascript">${highlightCode(entry.signature, 'javascript')}</code></pre>
+ ${summary}`;
+ return element;
+}
+
+function moduleElement(module) {
+ const element = document.createElement('section');
+ element.className = 'api-module';
+ element.dataset.module = module.module;
+ const heading = document.createElement('h3');
+ heading.id = `api-${module.module.replace(/\W+/g, '-')}`;
+ heading.innerHTML = `<code>${escapeHtml(module.module)}</code><span>${module.exports.length}</span>`;
+ element.append(heading);
+ const importLine = document.createElement('p');
+ importLine.className = 'api-import';
+ const example = module.exports.find(entry => entry.kind !== 'constant') ?? module.exports[0];
+ importLine.innerHTML = example
+ ? `<code>import { ${escapeHtml(example.name)} } from '${escapeHtml(module.module)}';</code>`
+ : `<code>import '${escapeHtml(module.module)}';</code> Importing it registers shader code. It has no exports.`;
+ element.append(importLine);
+ for (const entry of module.exports) element.append(entryElement(module.module, entry));
+ return element;
+}
+
+/** Render the reference with a filter box. The data loads on first use, so other pages do not download it. */
+export function createApiReference() {
+ const container = document.createElement('div');
+ container.className = 'api-reference';
+ container.innerHTML = `
+ <label class="api-filter"><span>Filter exports</span><input type="search" placeholder="Name or word, such as camera or gltf" autocomplete="off"></label>
+ <p class="api-count" role="status" aria-live="polite">Loading the reference…</p>
+ <div class="api-modules"></div>`;
+ const input = container.querySelector('input');
+ const count = container.querySelector('.api-count');
+ const list = container.querySelector('.api-modules');
+ fetch('/api-reference.json').then(response => {
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return response.json();
+ }).then(reference => {
+ const core = reference.modules.filter(module => module.module === '67js');
+ const addons = reference.modules.filter(module => module.module !== '67js');
+ for (const [title, modules] of [['Core', core], ['Addons', addons]]) {
+ const heading = document.createElement('h2');
+ heading.id = title.toLowerCase();
+ heading.dataset.outline = title;
+ heading.textContent = title;
+ list.append(heading, ...modules.map(moduleElement));
+ }
+ const total = reference.modules.reduce((sum, module) => sum + module.exports.length, 0);
+ function filter() {
+ const words = input.value.toLowerCase().trim().split(/\s+/).filter(Boolean);
+ let shown = 0;
+ for (const module of list.querySelectorAll('.api-module')) {
+ let moduleShown = 0;
+ for (const entry of module.querySelectorAll('.api-entry')) {
+ const match = words.every(word => entry.dataset.search.includes(word));
+ entry.hidden = !match;
+ if (match) moduleShown++;
+ }
+ module.hidden = moduleShown === 0 && words.length > 0;
+ shown += moduleShown;
+ }
+ count.textContent = words.length ? `${shown} of ${total} exports match.` : `${total} exports in ${reference.modules.length} modules.`;
+ }
+ input.addEventListener('input', filter);
+ filter();
+ container.dispatchEvent(new CustomEvent('api-ready', { bubbles: true }));
+ }).catch(() => {
+ count.textContent = '⚠ The reference did not load. Reload the page to try again.';
+ });
+ return container;
+}
diff --git a/src/documentation-topics.js b/src/documentation-topics.js
index fe546b1f..5f94eb41 100644
--- a/src/documentation-topics.js
+++ b/src/documentation-topics.js
@@ -7,7 +7,7 @@ export const documentationGroups = [
{ title: 'Worlds', icon: 'world', ids: ['terrain-and-ground-textures', 'trees-and-grass', 'grass-fields', 'wheeled-vehicles', 'baked-liquid'] },
{ title: 'Animate and interact', icon: 'motion', ids: ['deterministic-animation', 'animation-curves-and-mixing', 'skeletal-and-morph-animation', 'humanoid-retargeting-and-crowds', 'recorded-physics', 'assemblies-and-interaction'] },
{ title: 'Assets and media', icon: 'image', ids: ['import-and-export-models', 'images-and-films', 'render-a-png-from-a-script-without-mcp'] },
- { title: 'Reference and workflows', icon: 'book', ids: ['performance-and-memory', 'lifecycle-and-troubleshooting', 'models-and-ai-agents', 'addons-and-limits', 'release-and-source-availability'] },
+ { title: 'Reference and workflows', icon: 'book', ids: ['api-reference', 'performance-and-memory', 'lifecycle-and-troubleshooting', 'models-and-ai-agents', 'addons-and-limits', 'release-and-source-availability', 'resources'] },
];
// Old links keep working after the start pages replaced the first sections of the guide.
diff --git a/src/documentation.css b/src/documentation.css
index eead04f2..6d6fea2f 100644
--- a/src/documentation.css
+++ b/src/documentation.css
@@ -171,3 +171,20 @@
.documentation .live-status { order:5; flex-basis:100%; margin:6px 0 0; }
.documentation .live-status:empty { display:none; }
}
+
+/* API reference: a filter, then one block per module and one row per export. */
+.api-filter { display:block; margin:8px 0 10px; }
+.api-filter > span { display:block; font-size:13px; color:var(--muted); margin-bottom:8px; }
+.documentation .api-filter input { width:100%; min-height:44px; padding:11px 13px; font-size:14px; border-radius:var(--radius); background:var(--bg); border:1px solid var(--border); color:var(--text); }
+.documentation #doc-article .api-count { font-size:13px; color:var(--muted); margin:0 0 8px; }
+.documentation #doc-article .api-module h3 { display:flex; align-items:baseline; gap:10px; margin:40px 0 6px; font-size:17px; }
+.api-module h3 code { background:none !important; padding:0 !important; font-size:16px !important; }
+.api-module h3 span { font-size:12px; font-weight:500; color:var(--muted); }
+.documentation #doc-article .api-import { margin:0 0 12px; font-size:13px; color:var(--muted); }
+.api-entry { margin:0 0 6px; padding:14px 16px; border-radius:var(--radius); background:var(--bg); scroll-margin-top:calc(var(--navigation-height,80px) + 24px); }
+.api-entry-heading { display:flex; flex-wrap:wrap; align-items:baseline; gap:4px 10px; }
+.documentation #doc-article .api-entry h4 { margin:0; font:600 14px ui-monospace,Consolas,monospace; min-width:0; overflow-wrap:anywhere; }
+.api-kind { font-size:12px; color:var(--muted); }
+.documentation #doc-article .api-source { margin-left:auto; font-size:12px; color:var(--muted); }
+.documentation .docs .api-entry pre { padding:6px 0 0; font-size:12.5px; line-height:1.6; white-space:pre-wrap; overflow-wrap:anywhere; }
+.documentation #doc-article .api-entry p { margin:6px 0 0; font-size:13.5px; line-height:1.65; color:var(--muted); }
diff --git a/src/documentation.js b/src/documentation.js
index 7a9e5cd2..762f8959 100644
--- a/src/documentation.js
+++ b/src/documentation.js
@@ -3,6 +3,7 @@ import './documentation.css';
import guide from '../docs/guide.md?raw';
import { highlightCode } from './code-highlight.js';
import { createLiveExample, autoRunVisibleExamples } from './docs-live.js';
+import { createApiReference } from './docs-api.js';
import { topicAliases, topicSlug, guideTopics, learnTopics, orderTopics } from './documentation-topics.js';
const learnSources = import.meta.glob('../docs/learn/*.md', { query: '?raw', import: 'default', eager: true });
@@ -213,6 +214,8 @@ function renderFence(block, section) {
section.append(installBlock(info, currentTopic.title));
} else if (info.language === 'cards') {
section.append(cardList(info));
+ } else if (info.language === 'api') {
+ section.append(createApiReference());
} else if (info.language === 'check') {
section.append(webglCheck());
} else {
@@ -396,6 +399,10 @@ function openTopic(focus = false) {
renderNavigation();
renderOutline(section);
exampleStarter = autoRunVisibleExamples(article);
+ section.addEventListener('api-ready', () => {
+ renderOutline(section);
+ if (requestedSection) document.getElementById(requestedSection)?.scrollIntoView();
+ }, { once: true });
if (requestedSection) {
requestAnimationFrame(() => document.getElementById(requestedSection)?.scrollIntoView());
} else if (focus) {
diff --git a/tests/docs-pages.test.js b/tests/docs-pages.test.js
index a1385fe2..eb903351 100644
--- a/tests/docs-pages.test.js
+++ b/tests/docs-pages.test.js
@@ -75,3 +75,15 @@ test('links to plain-text contracts point at files the site publishes', () => {
}
}
});
+
+test('the API reference finds the declaration of the core exports', async () => {
+ const { buildApiReference } = await import('../scripts/api-reference.mjs');
+ const reference = await buildApiReference();
+ const core = reference.modules.find(module => module.module === '67js');
+ for (const name of ['Renderer67', 'box', 'cameraView', 'exportGlb']) {
+ const entry = core.exports.find(item => item.name === name);
+ assert.ok(entry?.source.includes(':'), `${name} has no source line`);
+ }
+ assert.match(core.exports.find(item => item.name === 'Renderer67').signature, /^new Renderer67\(canvas/);
+ assert.ok(reference.modules.some(module => module.module === '67js/addons/gltf'));
+});