/** * One XSLT transform with the module built from xslt.c (libxslt, libexslt, * libxml2): the data and stylesheet go in as UTF-8, the output comes back as * a string. Used by worker.mjs in the browser and by the site's tests in Node. * * transform(module, xmlString, xslString, maxOutBytes, options?) * -> { ok: true, output } or { ok: false, error, code, missing } * options: { stylePath, files: [{ path, text }], byName } * stylePath the stylesheet's own path ("styles/form.xsl"): the base its * xsl:import and xsl:include hrefs resolve against * files the only stylesheets those may load, by path * byName also match a file by its name alone, when exactly one has * it (files chosen loose rather than as a folder) * code: 'data' (the data is not XML), 'stylesheet' (not XML or not XSLT), * 'transform' (the stylesheet failed), 'size' (output over the cap), * 'missing' (it imports or includes files not handed over: `missing` * lists them, "?name" where several loose files had that name) * * Written for johnmcm.com (2026); part of the module published at /source/xslt/. */ const CODES = ['', 'data', 'stylesheet', 'transform', 'size']; export const MAX_OUTPUT = 16 * 1024 * 1024; function put(m, s) { const bytes = new TextEncoder().encode(s); const p = m._malloc(bytes.length + 1); if (!p) throw new Error('not enough memory'); m.HEAPU8.set(bytes, p); m.HEAPU8[p + bytes.length] = 0; return [p, bytes.length]; } function cString(m, p) { let end = p; while (m.HEAPU8[end]) end++; return new TextDecoder().decode(m.HEAPU8.subarray(p, end)); } export function transform(m, xml, xsl, maxOut = MAX_OUTPUT, options = {}) { const owned = []; const alloc = (s) => { const r = put(m, String(s)); owned.push(r[0]); return r; }; try { m._xt_clear_files(); for (const f of options.files ?? []) { const [pp] = alloc(f.path); const [dp, dl] = alloc(f.text); if (m._xt_add_file(pp, dp, dl) !== 0) throw new Error('too many files'); } m._xt_set_match_names(options.byName ? 1 : 0); const [xp, xl] = alloc(xml); const [sp, sl] = alloc(xsl); const [up] = alloc(options.stylePath ?? ''); const rc = m._xt_transform(xp, xl, sp, sl, maxOut, up); if (rc !== 0) { const missing = cString(m, m._xt_missing()).split('\n').filter(Boolean); const code = missing.length ? 'missing' : CODES[rc] || 'transform'; return { ok: false, error: cString(m, m._xt_error()) || 'the transform failed', code, missing }; } const len = m._xt_result_len(); const out = len ? new TextDecoder().decode(m.HEAPU8.subarray(m._xt_result(), m._xt_result() + len)) : ''; return { ok: true, output: out }; } finally { m._xt_release(); m._xt_clear_files(); for (const p of owned) m._free(p); } }