fix: use no-modules WASM target for simpler loading

This commit is contained in:
Accusys
2026-05-18 11:33:55 +08:00
parent e61ff88bf8
commit a1ac722b2f
8 changed files with 464 additions and 69 deletions

View File

@@ -1,5 +1,5 @@
PYTHON := /opt/homebrew/bin/python3.11
WASM_PKG := ../../doc_wasm/pkg
WASM_PKG := ../../md_wasm/pkg
deploy:
@echo "Building HTML docs from modules..."
@@ -7,9 +7,9 @@ deploy:
@echo " ✅ Updated ../doc/ (user docs)"
@echo " ✅ Updated ../doc_developer/ (developer docs)"
@echo "Building WASM doc..."
cd ../../doc_wasm && wasm-pack build --target web --no-opt 2>&1 | tail -2
cp $(WASM_PKG)/doc_wasm_bg.wasm ../doc_wasm/pkg/
cp $(WASM_PKG)/doc_wasm.js ../doc_wasm/pkg/
cd ../../md_wasm && wasm-pack build --target no-modules --no-opt 2>&1 | tail -2
cp $(WASM_PKG)/../md_wasm/pkg/md_wasm_bg.wasm ../doc_wasm/pkg/
cp $(WASM_PKG)/../md_wasm/pkg/md_wasm.js ../doc_wasm/pkg/
cp ../../docs_v1.0/API_WORKSPACE/modules/0*.md ../doc_wasm/modules/
cp ../../docs_v1.0/API_WORKSPACE/modules/1*.md ../doc_wasm/modules/
@echo " ✅ Updated ../doc_wasm/ (WASM docs)"

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Momentry API Docs (WASM)</title>
<title>Momentry API Docs</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; }
@@ -13,13 +13,10 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-
.sidebar a { display: block; padding: 6px 0; color: #0066cc; text-decoration: none; font-size: 14px; cursor: pointer; }
.sidebar a:hover { color: #003d80; }
.sidebar .active { font-weight: 600; color: #003d80; }
.sidebar .lang-toggle { margin: 12px 0; font-size: 12px; }
.sidebar .lang-toggle a { display: inline; font-size: 12px; padding: 2px 6px; }
.sidebar .logout { margin-top: auto; padding-top: 16px; border-top: 1px solid #eee; }
.sidebar .logout a { font-size: 12px; color: #999; }
.sidebar .logout a { font-size: 12px; color: #999; cursor: pointer; }
.sidebar .logout a:hover { color: #cc0000; }
.content { flex: 1; padding: 40px; max-width: 960px; }
.content.loading { opacity: 0.5; }
.content table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
.content th, .content td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
.content th { background: #f0f0f0; font-weight: 600; }
@@ -31,104 +28,89 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-
.content h3 { font-size: 16px; margin: 16px 0 8px; color: #444; }
.content p { line-height: 1.6; margin: 8px 0; }
.content a { color: #0066cc; }
.hidden { display: none; }
</style>
</head>
<body>
<script src="/doc-wasm/pkg/md_wasm.js"></script>
<div id="app">
<div class="sidebar">
<h1>Momentry Docs</h1>
<div id="module-list"></div>
<div class="logout">
<a href="#" id="logout-btn">Logout</a>
<a id="logout-btn">Logout</a>
</div>
</div>
<div class="content" id="content">
<p>Loading...</p>
<p>Loading WASM...</p>
</div>
</div>
<script>
const MODULES = [
["01_auth","安全認證","Authentication"],
["02_health","健康檢查","Health"],
["03_register","檔案註冊","File Registration"],
["04_lookup","檔案屬性查詢","File Lookup"],
["05_process","處理流程","Processing"],
["06_search","搜尋功能","Search"],
["07_identity","身份識別","Identity"],
["08_identity_agent","智能身份綁定","Smart Identity Binding"],
["08_media","串流與截圖","Streaming & Thumbnails"],
["09_tmdb","TMDb 整合","TMDb Integration"],
["10_pipeline","生產線","Pipeline"],
["12_agent","智慧代理","AI Agents"],
];
<script type="module">
import init, { render_markdown, module_list } from '/doc-wasm/pkg/doc_wasm.js';
const API = '';
let currentModule = null;
let modules = [];
const el = document.getElementById('content');
let wasm = null;
async function loadDoc(name) {
const el = document.getElementById('content');
el.classList.add('loading');
el.innerHTML = '<p>Loading...</p>';
try {
const resp = await fetch(`/doc-wasm/modules/${name}.md`);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const resp = await fetch('/doc-wasm/modules/' + name + '.md');
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const md = await resp.text();
el.innerHTML = render_markdown(md);
el.classList.remove('loading');
// highlight active module
if (!wasm) throw new Error('WASM not initialized');
el.innerHTML = wasm.render(md);
document.querySelectorAll('.sidebar a.module-link').forEach(a => a.classList.remove('active'));
const link = document.querySelector(`.sidebar a[data-module="${name}"]`);
const link = document.querySelector('.sidebar a[data-module="' + name + '"]');
if (link) link.classList.add('active');
history.pushState(null, '', `#${name}`);
history.pushState(null, '', '#' + name);
} catch(e) {
el.innerHTML = `<p style="color:red">Failed to load: ${e.message}</p>`;
el.classList.remove('loading');
el.innerHTML = '<p style="color:red">Error: ' + e.message + '</p>';
}
}
async function checkAuth() {
const resp = await fetch(`${API}/api/v1/auth/login`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username:'demo',password:'demo'})
});
return resp.ok;
}
async function initApp() {
const el = document.getElementById('content');
async function init() {
try {
await init();
el.innerHTML = '<p>WASM initialized. Loading modules...</p>';
// Parse module list
modules = JSON.parse(module_list());
el.innerHTML = '<p>Initializing WASM...</p>';
wasm = await wasm_bindgen();
el.innerHTML = '<p>Loading modules...</p>';
const listEl = document.getElementById('module-list');
modules.forEach(([name, cn, en]) => {
const a = document.createElement('a');
MODULES.forEach(function(m) {
var a = document.createElement('a');
a.className = 'module-link';
a.dataset.module = name;
a.textContent = `${cn} - ${en}`;
a.onclick = (e) => { e.preventDefault(); loadDoc(name); };
a.setAttribute('data-module', m[0]);
a.textContent = m[0] + ' ' + m[1];
a.onclick = function(e) { e.preventDefault(); loadDoc(m[0]); };
listEl.appendChild(a);
});
// Logout
document.getElementById('logout-btn').onclick = async (e) => {
e.preventDefault();
await fetch(`${API}/api/v1/auth/logout`, {method:'POST'});
document.getElementById('logout-btn').onclick = async function(e) {
await fetch('/api/v1/auth/logout', {method:'POST'});
window.location.reload();
};
// Load initial module from hash or default
const hash = location.hash.slice(1);
if (hash) {
loadDoc(hash);
} else {
loadDoc('01_auth');
}
var hash = location.hash.slice(1);
loadDoc(hash || '01_auth');
} catch(e) {
el.innerHTML = `<p style="color:red">WASM init error: ${e.message}</p><pre>${e.stack}</pre>`;
el.innerHTML = '<p style="color:red">Init error: ' + e.message + '</p>';
}
}
// Handle browser back/forward
window.onpopstate = () => {
const hash = location.hash.slice(1);
window.onpopstate = function() {
var hash = location.hash.slice(1);
if (hash) loadDoc(hash);
};
document.getElementById('content').innerHTML = '<p>Starting WASM...</p>';
initApp();
init();
</script>
</body>
</html>

View File

@@ -0,0 +1,207 @@
let wasm_bindgen = (function(exports) {
let script_src;
if (typeof document !== 'undefined' && document.currentScript !== null) {
script_src = new URL(document.currentScript.src, location.href).toString();
}
/**
* @param {string} md
* @returns {string}
*/
function render(md) {
let deferred2_0;
let deferred2_1;
try {
const ptr0 = passStringToWasm0(md, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.render(ptr0, len0);
deferred2_0 = ret[0];
deferred2_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
exports.render = render;
function __wbg_get_imports() {
const import0 = {
__proto__: null,
__wbindgen_init_externref_table: function() {
const table = wasm.__wbindgen_externrefs;
const offset = table.grow(4);
table.set(0, undefined);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
},
};
return {
__proto__: null,
"./md_wasm_bg.js": import0,
};
}
function getStringFromWasm0(ptr, len) {
return decodeText(ptr >>> 0, len);
}
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = cachedTextEncoder.encodeInto(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
function decodeText(ptr, len) {
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
const cachedTextEncoder = new TextEncoder();
if (!('encodeInto' in cachedTextEncoder)) {
cachedTextEncoder.encodeInto = function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
};
}
let WASM_VECTOR_LEN = 0;
let wasmModule, wasmInstance, wasm;
function __wbg_finalize_init(instance, module) {
wasmInstance = instance;
wasm = instance.exports;
wasmModule = module;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
const validResponse = module.ok && expectedResponseType(module.type);
if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else { throw e; }
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
function expectedResponseType(type) {
switch (type) {
case 'basic': case 'cors': case 'default': return true;
}
return false;
}
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (module !== undefined) {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (module_or_path !== undefined) {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (module_or_path === undefined && script_src !== undefined) {
module_or_path = script_src.replace(/\.js$/, "_bg.wasm");
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
return Object.assign(__wbg_init, { initSync }, exports);
})({ __proto__: null });

Binary file not shown.

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head><title>WASM Test</title></head>
<body>
<h1>WASM Test Page</h1>
<div id="output">Loading...</div>
<script type="module">
try {
const mod = await WebAssembly.compileStreaming(
fetch('/doc-wasm/pkg/doc_wasm_bg.wasm')
);
document.getElementById('output').textContent = 'WASM compiled OK! Size: ' + mod.byteLength + ' bytes';
} catch(e) {
document.getElementById('output').textContent = 'ERROR: ' + e.message;
}
</script>
</body>
</html>