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>

167
md_wasm/Cargo.lock generated Normal file
View File

@@ -0,0 +1,167 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "bitflags"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
]
[[package]]
name = "md_wasm"
version = "0.1.0"
dependencies = [
"pulldown-cmark",
"wasm-bindgen",
]
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-cmark"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "679341d22c78c6c649893cbd6c3278dcbe9fc4faa62fea3a9296ae2b50c14625"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "wasm-bindgen"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441"
dependencies = [
"unicode-ident",
]

11
md_wasm/Cargo.toml Normal file
View File

@@ -0,0 +1,11 @@
[package]
name = "md_wasm"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
pulldown-cmark = "0.11"

10
md_wasm/src/lib.rs Normal file
View File

@@ -0,0 +1,10 @@
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn render(md: &str) -> String {
let parser = pulldown_cmark::Parser::new(md);
let mut html = String::new();
pulldown_cmark::html::push_html(&mut html, parser);
html = html.replace("<table>", "<table class=\"table\">");
html
}