lineadraw 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -20
- package/bin/lineadraw.mjs +60 -10
- package/dist/bridge.d.ts +1 -0
- package/dist/bridge.js +1 -1
- package/dist/{chunk-BQCSFVAF.js → chunk-7UFXC7OI.js} +5570 -1174
- package/dist/chunk-7UFXC7OI.js.map +1 -0
- package/dist/chunk-FDLANLIC.js +1161 -0
- package/dist/chunk-FDLANLIC.js.map +1 -0
- package/dist/chunk-M3EDRSHW.js +81 -0
- package/dist/chunk-M3EDRSHW.js.map +1 -0
- package/dist/chunk-MYP7RUYK.js +9 -0
- package/dist/chunk-MYP7RUYK.js.map +1 -0
- package/dist/{chunk-L2CWZAKW.js → chunk-RNA2RDGL.js} +13 -6
- package/dist/chunk-RNA2RDGL.js.map +1 -0
- package/dist/dist-56K6CNML.js +188 -0
- package/dist/dist-56K6CNML.js.map +1 -0
- package/dist/dist-IEN64QSV.js +10 -0
- package/dist/dist-IEN64QSV.js.map +1 -0
- package/dist/emscripten-module-Q67P5WYC-ITCU5LXL.js +2424 -0
- package/dist/emscripten-module-Q67P5WYC-ITCU5LXL.js.map +1 -0
- package/dist/{exportDxf-T2RTSTH5.js → exportDxf-6XTXQ4XN.js} +2 -2
- package/dist/ffi-SHMEF5YV.js +82 -0
- package/dist/ffi-SHMEF5YV.js.map +1 -0
- package/dist/module-ES6BEMUI-BJFWC656.js +14 -0
- package/dist/module-ES6BEMUI-BJFWC656.js.map +1 -0
- package/dist/module-asyncify-2EFITU5U-7F5WZXRA.js +9 -0
- package/dist/module-asyncify-2EFITU5U-7F5WZXRA.js.map +1 -0
- package/dist/sdk.d.ts +1118 -128
- package/dist/sdk.js +742 -620
- package/dist/sdk.js.map +1 -1
- package/lineadraw.d.ts +666 -44
- package/package.json +1 -1
- package/templates/README.md +6 -4
- package/dist/chunk-BQCSFVAF.js.map +0 -1
- package/dist/chunk-L2CWZAKW.js.map +0 -1
- /package/dist/{exportDxf-T2RTSTH5.js.map → exportDxf-6XTXQ4XN.js.map} +0 -0
|
@@ -48,7 +48,8 @@ var connectEditors = async (opts = {}) => {
|
|
|
48
48
|
};
|
|
49
49
|
var createBridge = (opts = {}) => {
|
|
50
50
|
const file = readBridgeFile(opts.bridgeFile ?? bridgeFilePath());
|
|
51
|
-
const
|
|
51
|
+
const notServing = opts.port === void 0 && file.port === 0;
|
|
52
|
+
const port = opts.port ?? (file.port || DEFAULT_BRIDGE_PORT);
|
|
52
53
|
const token = opts.token ?? process.env.LINEA_BRIDGE_TOKEN ?? file.token;
|
|
53
54
|
const doFetch = opts.fetch ?? fetch;
|
|
54
55
|
const url = `http://127.0.0.1:${port}`;
|
|
@@ -57,6 +58,11 @@ var createBridge = (opts = {}) => {
|
|
|
57
58
|
};
|
|
58
59
|
if (token) headers.authorization = `Bearer ${token}`;
|
|
59
60
|
const request = async (method, path, body) => {
|
|
61
|
+
if (notServing)
|
|
62
|
+
throw new BridgeError(
|
|
63
|
+
`Linea is not serving agents: when it last started, port ${DEFAULT_BRIDGE_PORT} could not be opened (another program holds it \u2014 see the Agents popover). Free the port and restart Linea, or pass --port.`,
|
|
64
|
+
{ code: "unreachable" }
|
|
65
|
+
);
|
|
60
66
|
let response;
|
|
61
67
|
try {
|
|
62
68
|
response = await doFetch(`${url}${path}`, {
|
|
@@ -119,10 +125,11 @@ var createBridge = (opts = {}) => {
|
|
|
119
125
|
url,
|
|
120
126
|
status: () => request("GET", "/status"),
|
|
121
127
|
editors: () => request("GET", "/api/editors"),
|
|
122
|
-
tools: async () => (await request(
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
128
|
+
tools: async () => (await request("GET", "/api/tools")).tools?.map(({ name, description, inputSchema }) => ({
|
|
129
|
+
name,
|
|
130
|
+
description,
|
|
131
|
+
inputSchema
|
|
132
|
+
})) ?? [],
|
|
126
133
|
open: (path) => request("POST", "/api/linea_open_editor", {
|
|
127
134
|
path: isAbsolute(path) ? path : resolve(path)
|
|
128
135
|
}),
|
|
@@ -138,4 +145,4 @@ export {
|
|
|
138
145
|
connectEditors,
|
|
139
146
|
createBridge
|
|
140
147
|
};
|
|
141
|
-
//# sourceMappingURL=chunk-
|
|
148
|
+
//# sourceMappingURL=chunk-RNA2RDGL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridge.ts"],"sourcesContent":["// A client for RUNNING Linea editors: the desktop app serves the bridge on\n// 127.0.0.1:7431 (docs/desktop-bridge.md in the linea repo) and every open\n// window — plus any paired web tab — registers with it. Operations are the\n// shared `linea_*` tool catalog, each one undo step in that editor;\n// `runScript` sends a whole `defineCommand` module, which runs inside the\n// editor against the real Drawing API as ONE step and ONE round trip.\n//\n// Deliberately dependency-free (node: built-ins + fetch): the `lineadraw`\n// CLI loads it on its own (dist/bridge.js) without the rest of the SDK.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\n/** Where the desktop app keeps its bridge settings (`bridge.json`). */\nconst APP_ID = \"com.lineadraw.desktop\";\nexport const DEFAULT_BRIDGE_PORT = 7431;\n\n/** A running editor as the bridge lists it. */\nexport interface EditorInfo {\n /** The drawing's document id — the stable way to address it. */\n id: string;\n name: string;\n /** The file it is bound to; absent for an unsaved drawing / a web tab. */\n path?: string | null;\n kind: \"desktop\" | \"web\";\n readOnly: boolean;\n /** Changed since the last file save. */\n dirty: boolean;\n}\n\n/** `GET /status`: the app's version, the bridge port, the open editors. */\nexport interface BridgeStatus {\n version: string;\n port: number;\n editors: EditorInfo[];\n}\n\nexport interface BridgeOptions {\n /** Default: bridge.json's port, else 7431. */\n port?: number;\n /** Agent token, when the app requires one. Default: LINEA_BRIDGE_TOKEN,\n * else bridge.json's token. */\n token?: string;\n /** The bridge.json to read, or `false` to read none. Default: the\n * desktop app's own (per-OS app-data folder). */\n bridgeFile?: string | false;\n /** Injected fetch (tests, proxies). Default: the global one. */\n fetch?: typeof fetch;\n}\n\n/** A bridge or editor refusal: `code` is the bridge's (`ambiguous`,\n * `noSuchEditor`, `readOnly`, `validation`, `fileNotFound`…). */\nexport class BridgeError extends Error {\n readonly code?: string;\n readonly status?: number;\n /** The rest of the error body (e.g. `candidates` for `ambiguous`). */\n readonly details?: Record<string, unknown>;\n constructor(\n message: string,\n opts: {\n code?: string;\n status?: number;\n details?: Record<string, unknown>;\n cause?: unknown;\n } = {},\n ) {\n super(message, { cause: opts.cause });\n this.name = \"BridgeError\";\n this.code = opts.code;\n this.status = opts.status;\n this.details = opts.details;\n }\n}\n\n/** The desktop app's bridge.json path on this OS. */\nexport const bridgeFilePath = (): string => {\n const home = homedir();\n if (process.platform === \"win32\")\n return join(\n process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\"),\n APP_ID,\n \"bridge.json\",\n );\n if (process.platform === \"darwin\")\n return join(home, \"Library\", \"Application Support\", APP_ID, \"bridge.json\");\n return join(\n process.env.XDG_DATA_HOME ?? join(home, \".local\", \"share\"),\n APP_ID,\n \"bridge.json\",\n );\n};\n\nconst readBridgeFile = (\n path: string | false,\n): { port?: number; token?: string } => {\n if (path === false || !existsSync(path)) return {};\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return {};\n }\n};\n\n/** One editor, addressed by document id, file path or (unique) name. */\nexport interface EditorHandle {\n /** How this handle addresses the editor. */\n readonly ref: string;\n /** Run one `linea_*` operation; resolves its result. */\n call<T = unknown>(\n operation: string,\n args?: Record<string, unknown>,\n ): Promise<T>;\n /**\n * Run a `defineCommand` module inside the editor as ONE undo step —\n * loops, reads and edits against the full Drawing API, one round trip.\n * `inputs` / `params` answer the module's declared ones (the user is\n * never asked).\n */\n runScript<T = unknown>(\n source: string,\n opts?: {\n inputs?: readonly (readonly [number, number])[];\n params?: Record<string, unknown>;\n },\n ): Promise<T>;\n /** Close it like its window's x; a dirty desktop drawing is refused\n * unless `discard`. */\n close(opts?: { discard?: boolean }): Promise<unknown>;\n}\n\n/** The running app: its editors and the operations they offer. */\nexport interface LineaBridge {\n /** The bridge's address, e.g. http://127.0.0.1:7431. */\n readonly url: string;\n status(): Promise<BridgeStatus>;\n /** The open editors. */\n editors(): Promise<EditorInfo[]>;\n /** The operations the bridge offers (name + description). */\n tools(): Promise<\n { name: string; description?: string; inputSchema?: unknown }[]\n >;\n /** Open a `.linea` file in a window of its own (an absolute path, or one\n * relative to the current directory); resolves once it has loaded. */\n open(path: string): Promise<EditorInfo>;\n /** A handle on one editor (id, path or unique name). Omitted: the only\n * open editor — with several, calls fail as `ambiguous`. */\n editor(ref?: string): EditorHandle;\n /** One operation on an editor (`editor` as for `editor()`). */\n call<T = unknown>(\n operation: string,\n args?: Record<string, unknown>,\n opts?: { editor?: string },\n ): Promise<T>;\n}\n\n/**\n * Connect to the running Linea desktop app's bridge: reads its bridge.json\n * (port, agent token), checks that it answers, and returns the client.\n * Rejects with a BridgeError when nothing answers.\n */\nexport const connectEditors = async (\n opts: BridgeOptions = {},\n): Promise<LineaBridge> => {\n const bridge = createBridge(opts);\n await bridge.status(); // fail fast, with the \"is it running?\" message\n return bridge;\n};\n\n/** The client without the reachability check (the CLI's one-shot calls). */\nexport const createBridge = (opts: BridgeOptions = {}): LineaBridge => {\n const file = readBridgeFile(opts.bridgeFile ?? bridgeFilePath());\n // Port 0 in bridge.json: the app could not open its port last launch\n // (another program holds it) — 7431 would reach that program instead.\n const notServing = opts.port === undefined && file.port === 0;\n const port = opts.port ?? (file.port || DEFAULT_BRIDGE_PORT);\n const token = opts.token ?? process.env.LINEA_BRIDGE_TOKEN ?? file.token;\n const doFetch = opts.fetch ?? fetch;\n const url = `http://127.0.0.1:${port}`;\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n };\n if (token) headers.authorization = `Bearer ${token}`;\n\n const request = async <T>(\n method: \"GET\" | \"POST\",\n path: string,\n body?: unknown,\n ): Promise<T> => {\n if (notServing)\n throw new BridgeError(\n `Linea is not serving agents: when it last started, port ${DEFAULT_BRIDGE_PORT} could not be opened (another program holds it — see the Agents popover). Free the port and restart Linea, or pass --port.`,\n { code: \"unreachable\" },\n );\n let response: Response;\n try {\n response = await doFetch(`${url}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (e) {\n const c = (e as { cause?: { code?: string; message?: string } })?.cause;\n const cause = c?.code ?? c?.message ?? (e as Error)?.message ?? e;\n throw new BridgeError(\n `Nothing answers on ${url} (${cause}). Is the Linea desktop app running?`,\n { code: \"unreachable\", cause: e },\n );\n }\n const text = await response.text();\n let parsed: unknown = text;\n try {\n parsed = JSON.parse(text);\n } catch {\n // not JSON: keep the text\n }\n if (!response.ok) {\n const error = (parsed as { error?: Record<string, unknown> })?.error;\n const { code, message, ...details } = error ?? {};\n throw new BridgeError(\n typeof message === \"string\"\n ? message\n : `HTTP ${response.status}: ${text.slice(0, 200)}`,\n {\n code: typeof code === \"string\" ? code : undefined,\n status: response.status,\n details,\n },\n );\n }\n return parsed as T;\n };\n\n const call = <T>(\n operation: string,\n args: Record<string, unknown> = {},\n o: { editor?: string } = {},\n ): Promise<T> =>\n request<T>(\n \"POST\",\n `/api/${encodeURIComponent(operation)}${\n o.editor ? `?editor=${encodeURIComponent(o.editor)}` : \"\"\n }`,\n args,\n );\n\n const editor = (ref?: string): EditorHandle => ({\n ref: ref ?? \"\",\n call: (operation, args) => call(operation, args, { editor: ref }),\n runScript: (source, so = {}) =>\n call(\n \"linea_run_script\",\n {\n source,\n ...(so.inputs && { inputs: so.inputs }),\n ...(so.params && { params: so.params }),\n },\n { editor: ref },\n ),\n close: (co = {}) =>\n call(\n \"linea_close_document\",\n { discard: co.discard === true },\n { editor: ref },\n ),\n });\n\n return {\n url,\n status: () => request<BridgeStatus>(\"GET\", \"/status\"),\n editors: () => request<EditorInfo[]>(\"GET\", \"/api/editors\"),\n tools: async () =>\n (\n await request<{\n tools?: {\n name: string;\n description?: string;\n inputSchema?: unknown;\n }[];\n }>(\"GET\", \"/api/tools\")\n ).tools?.map(({ name, description, inputSchema }) => ({\n name,\n description,\n inputSchema,\n })) ?? [],\n open: (path) =>\n request<EditorInfo>(\"POST\", \"/api/linea_open_editor\", {\n path: isAbsolute(path) ? path : resolve(path),\n }),\n editor,\n call,\n };\n};\n"],"mappings":";AAUA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,YAAY,MAAM,eAAe;AAG1C,IAAM,SAAS;AACR,IAAM,sBAAsB;AAqC5B,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACT,YACE,SACA,OAKI,CAAC,GACL;AACA,UAAM,SAAS,EAAE,OAAO,KAAK,MAAM,CAAC;AACpC,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AACjB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;AAGO,IAAM,iBAAiB,MAAc;AAC1C,QAAM,OAAO,QAAQ;AACrB,MAAI,QAAQ,aAAa;AACvB,WAAO;AAAA,MACL,QAAQ,IAAI,WAAW,KAAK,MAAM,WAAW,SAAS;AAAA,MACtD;AAAA,MACA;AAAA,IACF;AACF,MAAI,QAAQ,aAAa;AACvB,WAAO,KAAK,MAAM,WAAW,uBAAuB,QAAQ,aAAa;AAC3E,SAAO;AAAA,IACL,QAAQ,IAAI,iBAAiB,KAAK,MAAM,UAAU,OAAO;AAAA,IACzD;AAAA,IACA;AAAA,EACF;AACF;AAEA,IAAM,iBAAiB,CACrB,SACsC;AACtC,MAAI,SAAS,SAAS,CAAC,WAAW,IAAI,EAAG,QAAO,CAAC;AACjD,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AA2DO,IAAM,iBAAiB,OAC5B,OAAsB,CAAC,MACE;AACzB,QAAM,SAAS,aAAa,IAAI;A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E,KAAK,CAAC;AAAA,IACV,MAAM,CAAC,SACL,QAAoB,QAAQ,0BAA0B;AAAA,MACpD,MAAM,WAAW,IAAI,IAAI,OAAO,QAAQ,IAAI;AAAA,IAC9C,CAAC;AAAA,IACH;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import {
|
|
2
|
+
QuickJSAsyncContext,
|
|
3
|
+
QuickJSAsyncRuntime,
|
|
4
|
+
QuickJSAsyncWASMModule
|
|
5
|
+
} from "./chunk-M3EDRSHW.js";
|
|
6
|
+
import {
|
|
7
|
+
DefaultIntrinsics,
|
|
8
|
+
DisposableFail,
|
|
9
|
+
DisposableResult,
|
|
10
|
+
DisposableSuccess,
|
|
11
|
+
EvalFlags,
|
|
12
|
+
GetOwnPropertyNamesFlags,
|
|
13
|
+
IntrinsicsFlags,
|
|
14
|
+
IsEqualOp,
|
|
15
|
+
JSPromiseStateEnum,
|
|
16
|
+
Lifetime,
|
|
17
|
+
QuickJSContext,
|
|
18
|
+
QuickJSDeferredPromise,
|
|
19
|
+
QuickJSEmscriptenModuleError,
|
|
20
|
+
QuickJSMemoryLeakDetected,
|
|
21
|
+
QuickJSRuntime,
|
|
22
|
+
QuickJSWASMModule,
|
|
23
|
+
Scope,
|
|
24
|
+
StaticLifetime,
|
|
25
|
+
UsingDisposable,
|
|
26
|
+
WeakLifetime,
|
|
27
|
+
assertSync,
|
|
28
|
+
createDisposableArray,
|
|
29
|
+
debugLog,
|
|
30
|
+
errors_exports,
|
|
31
|
+
setDebugMode
|
|
32
|
+
} from "./chunk-FDLANLIC.js";
|
|
33
|
+
import "./chunk-PZ5AY32C.js";
|
|
34
|
+
|
|
35
|
+
// ../../node_modules/quickjs-emscripten-core/dist/index.mjs
|
|
36
|
+
async function newQuickJSWASMModuleFromVariant(variantOrPromise) {
|
|
37
|
+
let variant = smartUnwrap(await variantOrPromise), [wasmModuleLoader, QuickJSFFI, { QuickJSWASMModule: QuickJSWASMModule2 }] = await Promise.all([variant.importModuleLoader().then(smartUnwrap), variant.importFFI(), import("./module-ES6BEMUI-BJFWC656.js").then(smartUnwrap)]), wasmModule = await wasmModuleLoader();
|
|
38
|
+
wasmModule.type = "sync";
|
|
39
|
+
let ffi = new QuickJSFFI(wasmModule);
|
|
40
|
+
return new QuickJSWASMModule2(wasmModule, ffi);
|
|
41
|
+
}
|
|
42
|
+
async function newQuickJSAsyncWASMModuleFromVariant(variantOrPromise) {
|
|
43
|
+
let variant = smartUnwrap(await variantOrPromise), [wasmModuleLoader, QuickJSAsyncFFI, { QuickJSAsyncWASMModule: QuickJSAsyncWASMModule2 }] = await Promise.all([variant.importModuleLoader().then(smartUnwrap), variant.importFFI(), import("./module-asyncify-2EFITU5U-7F5WZXRA.js").then(smartUnwrap)]), wasmModule = await wasmModuleLoader();
|
|
44
|
+
wasmModule.type = "async";
|
|
45
|
+
let ffi = new QuickJSAsyncFFI(wasmModule);
|
|
46
|
+
return new QuickJSAsyncWASMModule2(wasmModule, ffi);
|
|
47
|
+
}
|
|
48
|
+
function memoizePromiseFactory(fn) {
|
|
49
|
+
let promise;
|
|
50
|
+
return () => promise ?? (promise = fn());
|
|
51
|
+
}
|
|
52
|
+
function smartUnwrap(val) {
|
|
53
|
+
return val && "default" in val && val.default ? val.default && "default" in val.default && val.default.default ? val.default.default : val.default : val;
|
|
54
|
+
}
|
|
55
|
+
function newVariant(baseVariant, options) {
|
|
56
|
+
return { ...baseVariant, async importModuleLoader() {
|
|
57
|
+
let moduleLoader = smartUnwrap(await baseVariant.importModuleLoader());
|
|
58
|
+
return async function() {
|
|
59
|
+
let moduleLoaderArg = options.emscriptenModule ? { ...options.emscriptenModule } : {}, log = options.log ?? ((...args) => debugLog("newVariant moduleLoader:", ...args)), tapValue = (message, val) => (log(...message, val), val), force = (val) => typeof val == "function" ? val() : val;
|
|
60
|
+
(options.wasmLocation || options.wasmSourceMapLocation || options.locateFile) && (moduleLoaderArg.locateFile = (fileName, relativeTo) => {
|
|
61
|
+
let args = { fileName, relativeTo };
|
|
62
|
+
if (fileName.endsWith(".wasm") && options.wasmLocation !== void 0) return tapValue(["locateFile .wasm: provide wasmLocation", args], options.wasmLocation);
|
|
63
|
+
if (fileName.endsWith(".map")) {
|
|
64
|
+
if (options.wasmSourceMapLocation !== void 0) return tapValue(["locateFile .map: provide wasmSourceMapLocation", args], options.wasmSourceMapLocation);
|
|
65
|
+
if (options.wasmLocation && !options.locateFile) return tapValue(["locateFile .map: infer from wasmLocation", args], options.wasmLocation + ".map");
|
|
66
|
+
}
|
|
67
|
+
return options.locateFile ? tapValue(["locateFile: use provided fn", args], options.locateFile(fileName, relativeTo)) : tapValue(["locateFile: unhandled, passthrough", args], fileName);
|
|
68
|
+
}), options.wasmBinary && (moduleLoaderArg.wasmBinary = await force(options.wasmBinary)), options.wasmMemory && (moduleLoaderArg.wasmMemory = await force(options.wasmMemory));
|
|
69
|
+
let optionsWasmModule = options.wasmModule, modulePromise;
|
|
70
|
+
optionsWasmModule && (moduleLoaderArg.instantiateWasm = async (imports, onSuccess) => {
|
|
71
|
+
modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
|
|
72
|
+
let wasmModule = await modulePromise;
|
|
73
|
+
if (!wasmModule) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule)}`);
|
|
74
|
+
let instance = await WebAssembly.instantiate(wasmModule, imports);
|
|
75
|
+
return onSuccess(instance), instance.exports;
|
|
76
|
+
}), moduleLoaderArg.monitorRunDependencies = (left) => {
|
|
77
|
+
log("monitorRunDependencies:", left);
|
|
78
|
+
}, moduleLoaderArg.quickjsEmscriptenInit = () => newMockExtensions(log);
|
|
79
|
+
let resultPromise = moduleLoader(moduleLoaderArg), extensions = moduleLoaderArg.quickjsEmscriptenInit?.(log);
|
|
80
|
+
if (optionsWasmModule && extensions?.receiveWasmOffsetConverter && !extensions.existingWasmOffsetConverter) {
|
|
81
|
+
let wasmBinary = await force(options.wasmBinary) ?? new ArrayBuffer(0);
|
|
82
|
+
modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
|
|
83
|
+
let wasmModule = await modulePromise;
|
|
84
|
+
if (!wasmModule) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule)}`);
|
|
85
|
+
extensions.receiveWasmOffsetConverter(wasmBinary, wasmModule);
|
|
86
|
+
}
|
|
87
|
+
if (extensions?.receiveSourceMapJSON) {
|
|
88
|
+
let loadedSourceMapData = await force(options.wasmSourceMapData);
|
|
89
|
+
typeof loadedSourceMapData == "string" ? extensions.receiveSourceMapJSON(JSON.parse(loadedSourceMapData)) : loadedSourceMapData ? extensions.receiveSourceMapJSON(loadedSourceMapData) : extensions.receiveSourceMapJSON({ version: 3, names: [], sources: [], mappings: "" });
|
|
90
|
+
}
|
|
91
|
+
return resultPromise;
|
|
92
|
+
};
|
|
93
|
+
} };
|
|
94
|
+
}
|
|
95
|
+
function newMockExtensions(log) {
|
|
96
|
+
let mockMessage = "mock called, emscripten module may not be initialized yet";
|
|
97
|
+
return { mock: true, removeRunDependency(name) {
|
|
98
|
+
log(`${mockMessage}: removeRunDependency called:`, name);
|
|
99
|
+
}, receiveSourceMapJSON(data) {
|
|
100
|
+
log(`${mockMessage}: receiveSourceMapJSON called:`, data);
|
|
101
|
+
}, WasmOffsetConverter: void 0, receiveWasmOffsetConverter(bytes, mod) {
|
|
102
|
+
log(`${mockMessage}: receiveWasmOffsetConverter called:`, bytes, mod);
|
|
103
|
+
} };
|
|
104
|
+
}
|
|
105
|
+
function isSuccess(successOrFail) {
|
|
106
|
+
return !("error" in successOrFail);
|
|
107
|
+
}
|
|
108
|
+
function isFail(successOrFail) {
|
|
109
|
+
return "error" in successOrFail;
|
|
110
|
+
}
|
|
111
|
+
function shouldInterruptAfterDeadline(deadline) {
|
|
112
|
+
let deadlineAsNumber = typeof deadline == "number" ? deadline : deadline.getTime();
|
|
113
|
+
return function() {
|
|
114
|
+
return Date.now() > deadlineAsNumber;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
var TestQuickJSWASMModule = class {
|
|
118
|
+
constructor(parent) {
|
|
119
|
+
this.parent = parent;
|
|
120
|
+
this.contexts = /* @__PURE__ */ new Set();
|
|
121
|
+
this.runtimes = /* @__PURE__ */ new Set();
|
|
122
|
+
}
|
|
123
|
+
newRuntime(options) {
|
|
124
|
+
let runtime = this.parent.newRuntime({ ...options, ownedLifetimes: [new Lifetime(void 0, void 0, () => this.runtimes.delete(runtime)), ...options?.ownedLifetimes ?? []] });
|
|
125
|
+
return this.runtimes.add(runtime), runtime;
|
|
126
|
+
}
|
|
127
|
+
newContext(options) {
|
|
128
|
+
let context = this.parent.newContext({ ...options, ownedLifetimes: [new Lifetime(void 0, void 0, () => this.contexts.delete(context)), ...options?.ownedLifetimes ?? []] });
|
|
129
|
+
return this.contexts.add(context), context;
|
|
130
|
+
}
|
|
131
|
+
evalCode(code, options) {
|
|
132
|
+
return this.parent.evalCode(code, options);
|
|
133
|
+
}
|
|
134
|
+
disposeAll() {
|
|
135
|
+
let allDisposables = [...this.contexts, ...this.runtimes];
|
|
136
|
+
this.runtimes.clear(), this.contexts.clear(), allDisposables.forEach((d) => {
|
|
137
|
+
d.alive && d.dispose();
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
assertNoMemoryAllocated() {
|
|
141
|
+
if (this.getFFI().QTS_RecoverableLeakCheck()) throw new QuickJSMemoryLeakDetected("Leak sanitizer detected un-freed memory");
|
|
142
|
+
if (this.contexts.size > 0) throw new QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`);
|
|
143
|
+
if (this.runtimes.size > 0) throw new QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`);
|
|
144
|
+
}
|
|
145
|
+
getWasmMemory() {
|
|
146
|
+
return this.parent.getWasmMemory();
|
|
147
|
+
}
|
|
148
|
+
getFFI() {
|
|
149
|
+
return this.parent.getFFI();
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
export {
|
|
153
|
+
DefaultIntrinsics,
|
|
154
|
+
DisposableFail,
|
|
155
|
+
DisposableResult,
|
|
156
|
+
DisposableSuccess,
|
|
157
|
+
EvalFlags,
|
|
158
|
+
GetOwnPropertyNamesFlags,
|
|
159
|
+
IntrinsicsFlags,
|
|
160
|
+
IsEqualOp,
|
|
161
|
+
JSPromiseStateEnum,
|
|
162
|
+
Lifetime,
|
|
163
|
+
QuickJSAsyncContext,
|
|
164
|
+
QuickJSAsyncRuntime,
|
|
165
|
+
QuickJSAsyncWASMModule,
|
|
166
|
+
QuickJSContext,
|
|
167
|
+
QuickJSDeferredPromise,
|
|
168
|
+
QuickJSRuntime,
|
|
169
|
+
QuickJSWASMModule,
|
|
170
|
+
Scope,
|
|
171
|
+
StaticLifetime,
|
|
172
|
+
TestQuickJSWASMModule,
|
|
173
|
+
UsingDisposable,
|
|
174
|
+
WeakLifetime,
|
|
175
|
+
assertSync,
|
|
176
|
+
createDisposableArray,
|
|
177
|
+
debugLog,
|
|
178
|
+
errors_exports as errors,
|
|
179
|
+
isFail,
|
|
180
|
+
isSuccess,
|
|
181
|
+
memoizePromiseFactory,
|
|
182
|
+
newQuickJSAsyncWASMModuleFromVariant,
|
|
183
|
+
newQuickJSWASMModuleFromVariant,
|
|
184
|
+
newVariant,
|
|
185
|
+
setDebugMode,
|
|
186
|
+
shouldInterruptAfterDeadline
|
|
187
|
+
};
|
|
188
|
+
//# sourceMappingURL=dist-56K6CNML.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/quickjs-emscripten-core/src/index.ts","../../../node_modules/quickjs-emscripten-core/src/from-variant.ts","../../../node_modules/quickjs-emscripten-core/src/vm-interface.ts","../../../node_modules/quickjs-emscripten-core/src/interrupt-helpers.ts","../../../node_modules/quickjs-emscripten-core/src/module-test.ts"],"sourcesContent":["export * from \"@jitl/quickjs-ffi-types\"\n\n// Sync classes\nexport { QuickJSWASMModule } from \"./module\"\nexport { QuickJSContext } from \"./context\"\nexport { QuickJSRuntime } from \"./runtime\"\nexport type { InterruptHandler, ExecutePendingJobsResult } from \"./runtime\"\n\n// Async classes\nexport { QuickJSAsyncWASMModule } from \"./module-asyncify\"\nexport { QuickJSAsyncRuntime } from \"./runtime-asyncify\"\nexport { QuickJSAsyncContext } from \"./context-asyncify\"\nexport type { AsyncFunctionImplementation } from \"./context-asyncify\"\n\n// Build variants\nexport * from \"./from-variant\"\n\n// Export helpers\nexport * from \"./vm-interface\"\nexport * from \"./lifetime\"\nexport * from \"./interrupt-helpers\"\n/** Collects the informative errors this library may throw. */\nexport * as errors from \"./errors\"\nexport * from \"./deferred-promise\"\nexport * from \"./module-test\"\nexport type {\n StaticJSValue,\n JSValueConst,\n JSValue,\n QuickJSHandle,\n ContextOptions,\n ContextEvalOptions,\n RuntimeOptions,\n AsyncRuntimeOptions,\n RuntimeOptionsBase,\n JSModuleLoader,\n JSModuleLoadResult,\n JSModuleLoaderAsync,\n JSModuleLoadSuccess,\n JSModuleLoadFailure,\n JSModuleNormalizer,\n JSModuleNormalizerAsync,\n JSModuleNormalizeResult,\n JSModuleNormalizeFailure,\n JSModuleNormalizeSuccess,\n Intrinsics,\n} from \"./types\"\nexport { DefaultIntrinsics } from \"./types\"\nexport type { ModuleEvalOptions } from \"./module\"\nexport type { QuickJSPropertyKey } from \"./context\"\nexport { debugLog, setDebugMode } from \"./debug\"\n","import type {\n QuickJSSyncVariant,\n QuickJSAsyncVariant,\n QuickJSVariant,\n EmscriptenModuleLoaderOptions,\n SourceMapData,\n QuickJSEmscriptenExtensions,\n} from \"@jitl/quickjs-ffi-types\"\nimport type { QuickJSWASMModule } from \"./module.js\"\nimport type { QuickJSAsyncWASMModule } from \"./module-asyncify.js\"\nimport { QuickJSEmscriptenModuleError } from \"./errors.js\"\nimport { debugLog } from \"./debug.js\"\n\n// Otherwise we have build errors?\nexport { QuickJSSyncVariant, QuickJSAsyncVariant, QuickJSVariant }\n\nexport type PromisedDefault<T> =\n | T\n | Promise<T>\n | Promise<{ default: T }>\n | Promise<{ default: { default: T } }>\n\n/**\n * Create a new, completely isolated WebAssembly module containing the QuickJS library.\n * See the documentation on {@link QuickJSWASMModule}.\n *\n * Note that there is a hard limit on the number of WebAssembly modules in older\n * versions of v8:\n * https://bugs.chromium.org/p/v8/issues/detail?id=12076\n *\n * @example\n * ```ts\n * const quickjs = new newQuickJSWASMModuleFromVariant(\n * import('@jitl/quickjs-browser-release-sync-wasm')\n * )\n * ```\n */\nexport async function newQuickJSWASMModuleFromVariant(\n /**\n * A {@link QuickJSSyncVariant} to construct the WebAssembly module.\n */\n variantOrPromise: PromisedDefault<QuickJSSyncVariant>,\n): Promise<QuickJSWASMModule> {\n const variant = smartUnwrap(await variantOrPromise)\n const [wasmModuleLoader, QuickJSFFI, { QuickJSWASMModule }] = await Promise.all([\n variant.importModuleLoader().then(smartUnwrap),\n variant.importFFI(),\n import(\"./module.js\").then(smartUnwrap),\n ])\n const wasmModule = await wasmModuleLoader()\n wasmModule.type = \"sync\"\n const ffi = new QuickJSFFI(wasmModule)\n return new QuickJSWASMModule(wasmModule, ffi)\n}\n\n/**\n * Create a new, completely isolated WebAssembly module containing a version of the QuickJS library\n * compiled with Emscripten's [ASYNCIFY](https://emscripten.org/docs/porting/asyncify.html) transform.\n *\n * This version of the library offers features that enable synchronous code\n * inside the VM to interact with asynchronous code in the host environment.\n * See the documentation on {@link QuickJSAsyncWASMModule}, {@link QuickJSAsyncRuntime},\n * and {@link QuickJSAsyncContext}.\n *\n * Note that there is a hard limit on the number of WebAssembly modules in older\n * versions of v8:\n * https://bugs.chromium.org/p/v8/issues/detail?id=12076\n *\n * @example\n * ```ts\n * const quickjs = new newQuickJSAsyncWASMModuleFromVariant(\n * import('@jitl/quickjs-browser-debug-asyncify-wasm')\n * )\n * ```\n */\nexport async function newQuickJSAsyncWASMModuleFromVariant(\n /**\n * A {@link QuickJSAsyncVariant} to construct the WebAssembly module.\n */\n variantOrPromise: PromisedDefault<QuickJSAsyncVariant>,\n): Promise<QuickJSAsyncWASMModule> {\n const variant = smartUnwrap(await variantOrPromise)\n const [wasmModuleLoader, QuickJSAsyncFFI, { QuickJSAsyncWASMModule }] = await Promise.all([\n variant.importModuleLoader().then(smartUnwrap),\n variant.importFFI(),\n import(\"./module-asyncify.js\").then(smartUnwrap),\n ])\n const wasmModule = await wasmModuleLoader()\n wasmModule.type = \"async\"\n const ffi = new QuickJSAsyncFFI(wasmModule)\n return new QuickJSAsyncWASMModule(wasmModule, ffi)\n}\n\n/**\n * Helper intended to memoize the creation of a WebAssembly module.\n * ```typescript\n * const getDebugModule = memoizePromiseFactory(() => newQuickJSWASMModule(DEBUG_SYNC))\n * ```\n */\nexport function memoizePromiseFactory<T>(fn: () => Promise<T>): () => Promise<T> {\n let promise: Promise<T> | undefined\n return () => {\n return (promise ??= fn())\n }\n}\n\nfunction smartUnwrap<T extends object>(val: T | { default: T } | { default: { default: T } }): T {\n if (val && `default` in val && val.default) {\n if (val.default && `default` in val.default && val.default.default) {\n return val.default.default\n }\n return val.default as T\n }\n return val as T\n}\n\nexport type OrLoader<T> = T | (() => Promise<T>)\n\nexport interface CustomizeVariantOptions {\n /** If given, Emscripten will try to load the WebAssembly module data from this location (path or URI) as appropriate for the current platform. */\n wasmLocation?: string\n /** If given, Emscripten will compile the WebAssembly.Module from these bytes. */\n wasmBinary?: OrLoader<ArrayBuffer>\n /** If given, Emscripten will instantiate the WebAssembly.Instance from this existing WebAssembly.Module */\n wasmModule?: OrLoader<WebAssembly.Module>\n /** If given, use the Memory when instantiating the WebAssembly.Instance. */\n wasmMemory?: OrLoader<WebAssembly.Memory>\n /** If given, Emscripten will try to load the source map for the WebAssembly module from this location (path or URI) as appropriate for the current platform. */\n wasmSourceMapLocation?: string\n /** If given, we will provide the source map to Emscripten directly. This may only be respected if wasmModule is also provided. */\n wasmSourceMapData?: OrLoader<string | SourceMapData>\n /**\n * If set, this method will be called when the runtime needs to load a file,\n * such as a .wasm WebAssembly file, .mem memory init file, or a file\n * generated by the file packager.\n *\n * The function receives two parameters:\n *\n * - `fileName`, the relative path to the file as configured in build\n * process, eg `\"emscripten-module.wasm\"`.\n * - `prefix` (path to the main JavaScript file’s directory). This may be `''`\n * (empty string) in some cases if the Emscripten Javascript code can't locate\n * itself. Try logging it in your environment.\n *\n * It should return the actual URI or path to the requested file.\n *\n * This lets you host file packages on a different location than the directory\n * of the JavaScript file (which is the default expectation), for example if\n * you want to host them on a CDN.\n */\n locateFile?: EmscriptenModuleLoaderOptions[\"locateFile\"]\n /** The enumerable properties of this object will be passed verbatim, although they may be overwritten if you pass other options. */\n emscriptenModule?: EmscriptenModuleLoaderOptions\n /** Debug logger */\n log?: typeof console.log\n}\n\n/**\n * Create a new variant by overriding how Emscripten obtains the WebAssembly module.\n * This may be necessary in Cloudflare Workers, which can't compile WebAssembly modules from binary data.\n */\nexport function newVariant<T extends QuickJSVariant>(\n baseVariant: T,\n options: CustomizeVariantOptions,\n): T {\n const variant: T = {\n ...baseVariant,\n async importModuleLoader() {\n const moduleLoader = smartUnwrap(await baseVariant.importModuleLoader())\n return async function newModuleLoader() {\n const moduleLoaderArg: EmscriptenModuleLoaderOptions = options.emscriptenModule\n ? { ...options.emscriptenModule }\n : {}\n const log =\n options.log ?? ((...args: unknown[]) => debugLog(\"newVariant moduleLoader:\", ...args))\n const tapValue = <T>(message: unknown[], val: T) => {\n log(...message, val)\n return val\n }\n\n const force = <T>(val: OrLoader<T> | undefined): T | undefined | Promise<T> => {\n if (typeof val === \"function\") {\n return (val as () => Promise<T>)()\n }\n return val\n }\n\n if (options.wasmLocation || options.wasmSourceMapLocation || options.locateFile) {\n moduleLoaderArg.locateFile = (fileName: string, relativeTo: string) => {\n const args = { fileName, relativeTo }\n if (fileName.endsWith(\".wasm\") && options.wasmLocation !== undefined) {\n return tapValue(\n [\"locateFile .wasm: provide wasmLocation\", args],\n options.wasmLocation,\n )\n }\n\n if (fileName.endsWith(\".map\")) {\n if (options.wasmSourceMapLocation !== undefined) {\n return tapValue(\n [\"locateFile .map: provide wasmSourceMapLocation\", args],\n options.wasmSourceMapLocation,\n )\n }\n\n if (options.wasmLocation && !options.locateFile) {\n return tapValue(\n [\"locateFile .map: infer from wasmLocation\", args],\n options.wasmLocation + \".map\",\n )\n }\n }\n\n if (options.locateFile) {\n return tapValue(\n [\"locateFile: use provided fn\", args],\n options.locateFile(fileName, relativeTo),\n )\n }\n\n return tapValue([\"locateFile: unhandled, passthrough\", args], fileName)\n }\n }\n\n if (options.wasmBinary) {\n moduleLoaderArg.wasmBinary = await force(options.wasmBinary)\n }\n\n if (options.wasmMemory) {\n moduleLoaderArg.wasmMemory = await force(options.wasmMemory)\n }\n\n const optionsWasmModule = options.wasmModule\n let modulePromise: Promise<WebAssembly.Module | undefined> | undefined\n if (optionsWasmModule) {\n moduleLoaderArg.instantiateWasm = async (imports, onSuccess) => {\n modulePromise ??= Promise.resolve(force(optionsWasmModule))\n const wasmModule = await modulePromise\n if (!wasmModule) {\n // This should never happen\n throw new QuickJSEmscriptenModuleError(\n `options.wasmModule returned ${String(wasmModule)}`,\n )\n }\n const instance = await WebAssembly.instantiate(wasmModule, imports)\n onSuccess(instance)\n return instance.exports\n }\n }\n\n moduleLoaderArg.monitorRunDependencies = (left: number) => {\n log(\"monitorRunDependencies:\", left)\n }\n\n // This will be replaced with the actual function by --pre-js\n // Having the mock around makes our code simpler gives us handy logging\n // if we need to understand any issues\n moduleLoaderArg.quickjsEmscriptenInit = () => newMockExtensions(log)\n\n const resultPromise = moduleLoader(moduleLoaderArg)\n const extensions = moduleLoaderArg.quickjsEmscriptenInit?.(log)\n if (\n optionsWasmModule &&\n extensions?.receiveWasmOffsetConverter &&\n !extensions.existingWasmOffsetConverter\n ) {\n // Unlikely to be available, we'll usually end up mocking this.\n // Still if the user has both, we'll take it.\n const wasmBinary = (await force(options.wasmBinary)) ?? new ArrayBuffer(0)\n\n modulePromise ??= Promise.resolve(force(optionsWasmModule))\n const wasmModule = await modulePromise\n if (!wasmModule) {\n // This should never happen\n throw new QuickJSEmscriptenModuleError(\n `options.wasmModule returned ${String(wasmModule)}`,\n )\n }\n extensions.receiveWasmOffsetConverter(wasmBinary, wasmModule)\n }\n\n if (extensions?.receiveSourceMapJSON) {\n const loadedSourceMapData = await force(options.wasmSourceMapData)\n if (typeof loadedSourceMapData === \"string\") {\n extensions.receiveSourceMapJSON(JSON.parse(loadedSourceMapData))\n } else if (loadedSourceMapData) {\n extensions.receiveSourceMapJSON(loadedSourceMapData)\n } else {\n extensions.receiveSourceMapJSON({ version: 3, names: [], sources: [], mappings: \"\" })\n }\n }\n\n return resultPromise\n }\n },\n }\n return variant\n}\n\nfunction newMockExtensions(log: typeof console.log): QuickJSEmscriptenExtensions {\n const mockMessage = `mock called, emscripten module may not be initialized yet`\n return {\n mock: true,\n removeRunDependency(name: string) {\n log(`${mockMessage}: removeRunDependency called:`, name)\n },\n receiveSourceMapJSON(data: unknown) {\n log(`${mockMessage}: receiveSourceMapJSON called:`, data)\n },\n WasmOffsetConverter: undefined,\n receiveWasmOffsetConverter(bytes: ArrayBuffer, mod: WebAssembly.Module) {\n log(`${mockMessage}: receiveWasmOffsetConverter called:`, bytes, mod)\n },\n }\n}\n","/**\n * Used as an optional.\n * `{ value: S } | { error: E }`.\n */\nexport type SuccessOrFail<S, F> =\n | {\n value: S\n error?: undefined\n }\n | {\n error: F\n }\n\nexport function isSuccess<S, F>(successOrFail: SuccessOrFail<S, F>): successOrFail is { value: S } {\n return \"error\" in successOrFail === false\n}\n\nexport function isFail<S, F>(successOrFail: SuccessOrFail<S, F>): successOrFail is { error: F } {\n return \"error\" in successOrFail === true\n}\n\n/**\n * Used as an optional for results of a Vm call.\n * `{ value: VmHandle } | { error: VmHandle }`.\n */\nexport type VmCallResult<VmHandle> = SuccessOrFail<VmHandle, VmHandle>\n\n/**\n * A VmFunctionImplementation takes handles as arguments.\n * It should return a handle, or be void.\n *\n * To indicate an exception, a VMs can throw either a handle (transferred\n * directly) or any other Javascript value (only the poperties `name` and\n * `message` will be transferred). Or, the VmFunctionImplementation may return\n * a VmCallResult's `{ error: handle }` error variant.\n *\n * VmFunctionImplementation should not free its arguments or its return value.\n * It should not retain a reference to its return value or thrown error.\n */\nexport type VmFunctionImplementation<VmHandle> = (\n this: VmHandle,\n ...args: VmHandle[]\n) => VmHandle | VmCallResult<VmHandle> | void\n\n/**\n * A minimal interface to a Javascript execution environment.\n *\n * Higher-level tools should build over the LowLevelJavascriptVm interface to\n * share as much as possible between executors.\n *\n * From https://www.figma.com/blog/how-we-built-the-figma-plugin-system/\n */\nexport interface LowLevelJavascriptVm<VmHandle> {\n global: VmHandle\n undefined: VmHandle\n\n typeof(handle: VmHandle): string\n\n getNumber(handle: VmHandle): number\n getString(handle: VmHandle): string\n\n newNumber(value: number): VmHandle\n newString(value: string): VmHandle\n newObject(prototype?: VmHandle): VmHandle\n newFunction(name: string, value: VmFunctionImplementation<VmHandle>): VmHandle\n\n // For accessing properties of objects\n getProp(handle: VmHandle, key: string | VmHandle): VmHandle\n setProp(handle: VmHandle, key: string | VmHandle, value: VmHandle): void\n defineProp(\n handle: VmHandle,\n key: string | VmHandle,\n descriptor: VmPropertyDescriptor<VmHandle>,\n ): void\n\n callFunction(func: VmHandle, thisVal: VmHandle, ...args: VmHandle[]): VmCallResult<VmHandle>\n evalCode(code: string, filename?: string): VmCallResult<VmHandle>\n}\n\n/**\n * From https://www.figma.com/blog/how-we-built-the-figma-plugin-system/\n */\nexport interface VmPropertyDescriptor<VmHandle> {\n value?: VmHandle\n configurable?: boolean\n enumerable?: boolean\n get?: (this: VmHandle) => VmHandle\n set?: (this: VmHandle, value: VmHandle) => void\n}\n","import type { InterruptHandler } from \"./runtime\"\n\n/**\n * Returns an interrupt handler that interrupts Javascript execution after a deadline time.\n *\n * @param deadline - Interrupt execution if it's still running after this time.\n * Number values are compared against `Date.now()`\n */\nexport function shouldInterruptAfterDeadline(deadline: Date | number): InterruptHandler {\n const deadlineAsNumber = typeof deadline === \"number\" ? deadline : deadline.getTime()\n\n return function () {\n return Date.now() > deadlineAsNumber\n }\n}\n","import type { QuickJSContext } from \"./context\"\nimport type { ModuleEvalOptions, QuickJSWASMModule } from \"./module\"\nimport type { QuickJSRuntime } from \"./runtime\"\nimport type { ContextOptions, RuntimeOptions } from \"./types\"\nimport { QuickJSMemoryLeakDetected } from \"./errors\"\nimport { Lifetime } from \"./lifetime\"\n\n/**\n * A test wrapper of {@link QuickJSWASMModule} that keeps a reference to each\n * context or runtime created.\n *\n * Call {@link disposeAll} to reset these sets and calls `dispose` on any left alive\n * (which may throw an error).\n *\n * Call {@link assertNoMemoryAllocated} at the end of a test, when you expect that you've\n * freed all the memory you've ever allocated.\n */\nexport class TestQuickJSWASMModule implements Pick<QuickJSWASMModule, keyof QuickJSWASMModule> {\n contexts = new Set<QuickJSContext>()\n runtimes = new Set<QuickJSRuntime>()\n constructor(private parent: QuickJSWASMModule) {}\n\n newRuntime(options?: RuntimeOptions): QuickJSRuntime {\n const runtime = this.parent.newRuntime({\n ...options,\n ownedLifetimes: [\n new Lifetime(undefined, undefined, () => this.runtimes.delete(runtime)),\n ...(options?.ownedLifetimes ?? []),\n ],\n })\n this.runtimes.add(runtime)\n return runtime\n }\n\n newContext(options?: ContextOptions): QuickJSContext {\n const context = this.parent.newContext({\n ...options,\n ownedLifetimes: [\n new Lifetime(undefined, undefined, () => this.contexts.delete(context)),\n ...(options?.ownedLifetimes ?? []),\n ],\n })\n this.contexts.add(context)\n return context\n }\n\n evalCode(code: string, options?: ModuleEvalOptions): unknown {\n return this.parent.evalCode(code, options)\n }\n\n disposeAll() {\n const allDisposables = [...this.contexts, ...this.runtimes]\n this.runtimes.clear()\n this.contexts.clear()\n allDisposables.forEach((d) => {\n if (d.alive) {\n d.dispose()\n }\n })\n }\n\n assertNoMemoryAllocated() {\n const leaksDetected = this.getFFI().QTS_RecoverableLeakCheck()\n if (leaksDetected) {\n // Note: this is currently only available when building from source\n // with debug builds.\n throw new QuickJSMemoryLeakDetected(\"Leak sanitizer detected un-freed memory\")\n }\n\n if (this.contexts.size > 0) {\n throw new QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`)\n }\n\n if (this.runtimes.size > 0) {\n throw new QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`)\n }\n }\n\n getWasmMemory(): WebAssembly.Memory {\n return this.parent.getWasmMemory()\n }\n\n /** @private */\n getFFI() {\n return this.parent.getFFI()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACqCA,eAAsB,gCAIpB,kBAC4B;AAC5B,MAAM,UAAU,YAAY,MAAM,gBAAgB,GAC5C,CAAC,kBAAkB,YAAY,EAAE,mBAAAA,mBAAkB,CAAC,IAAI,MAAM,QAAQ,IAAI,CAC9E,QAAQ,mBAAmB,EAAE,KAAK,WAAW,GAC7C,QAAQ,UAAU,GAClB,OAAO,+BAAa,EAAE,KAAK,WAAW,CACxC,CAAC,GACK,aAAa,MAAM,iBAAiB;AAC1C,aAAW,OAAO;AAClB,MAAM,MAAM,IAAI,WAAW,UAAU;AACrC,SAAO,IAAIA,mBAAkB,YAAY,GAAG;AAC9C;AAsBA,eAAsB,qCAIpB,kBACiC;AACjC,MAAM,UAAU,YAAY,MAAM,gBAAgB,GAC5C,CAAC,kBAAkB,iBAAiB,EAAE,wBAAAC,wBAAuB,CAAC,IAAI,MAAM,QAAQ,IAAI,CACxF,QAAQ,mBAAmB,EAAE,KAAK,WAAW,GAC7C,QAAQ,UAAU,GAClB,OAAO,wCAAsB,EAAE,KAAK,WAAW,CACjD,CAAC,GACK,aAAa,MAAM,iBAAiB;AAC1C,aAAW,OAAO;AAClB,MAAM,MAAM,IAAI,gBAAgB,UAAU;AAC1C,SAAO,IAAIA,wBAAuB,YAAY,GAAG;AACnD;AAQO,SAAS,sBAAyB,IAAwC;AAC/E,MAAI;AACJ,SAAO,MACG,YAAA,UAAY,GAAG;AAE3B;AAEA,SAAS,YAA8B,KAA0D;AAC/F,SAAI,OA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AS,MAAM,GACpB,KAAK,SAAS,MAAM,GACpB,eAAe,QAAS,OAAM;AACxB,QAAE,SACJ,EAAE,QAAQ;IAEd,CAAC;EACH;EAEA,0BAA0B;AAExB,QADsB,KAAK,OAAO,EAAE,yBAAyB,EAI3D,OAAM,IAAI,0BAA0B,yCAAyC;AAG/E,QAAI,KAAK,SAAS,OAAO,EACvB,OAAM,IAAI,0BAA0B,GAAG,KAAK,SAAS,IAAI,kBAAkB;AAG7E,QAAI,KAAK,SAAS,OAAO,EACvB,OAAM,IAAI,0BAA0B,GAAG,KAAK,SAAS,IAAI,kBAAkB;EAE/E;EAEA,gBAAoC;AAClC,WAAO,KAAK,OAAO,cAAc;EACnC;EAGA,SAAS;AACP,WAAO,KAAK,OAAO,OAAO;EAC5B;AACF;","names":["QuickJSWASMModule","QuickJSAsyncWASMModule"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "./chunk-MYP7RUYK.js";
|
|
2
|
+
import "./chunk-PZ5AY32C.js";
|
|
3
|
+
|
|
4
|
+
// ../../node_modules/@jitl/quickjs-singlefile-mjs-release-sync/dist/index.mjs
|
|
5
|
+
var variant = { type: "sync", importFFI: () => import("./ffi-SHMEF5YV.js").then((mod) => mod.QuickJSFFI), importModuleLoader: () => import("./emscripten-module-Q67P5WYC-ITCU5LXL.js").then((mod) => mod.default) };
|
|
6
|
+
var src_default = variant;
|
|
7
|
+
export {
|
|
8
|
+
src_default as default
|
|
9
|
+
};
|
|
10
|
+
//# sourceMappingURL=dist-IEN64QSV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/@jitl/quickjs-singlefile-mjs-release-sync/src/index.ts"],"sourcesContent":["import type { QuickJSSyncVariant } from \"@jitl/quickjs-ffi-types\"\n\n/**\n * ### @jitl/quickjs-singlefile-mjs-release-sync\n *\n * [Docs](https://github.com/justjake/quickjs-emscripten/blob/main/doc/@jitl/quickjs-singlefile-mjs-release-sync/README.md) |\n * Variant with the WASM data embedded into a NodeJS ESModule.\n *\n * | Variable | Setting | Description |\n * | -- | -- | -- |\n * | library | quickjs | The original [bellard/quickjs](https://github.com/bellard/quickjs) library. Version [2025-09-13+f1139494](https://github.com/bellard/quickjs/commit/f1139494d18a2053630c5ed3384a42bb70db3c53) vendored to quickjs-emscripten on 2026-02-15. |\n * | releaseMode | release | Optimized for performance; use when building/deploying your application. |\n * | syncMode | sync | The default, normal build. Note that both variants support regular async functions. |\n * | emscriptenInclusion | singlefile | The WASM runtime is included directly in the JS file. Use if you run into issues with missing .wasm files when building or deploying your app. |\n * | exports | import | Has these package.json export conditions |\n *\n */\nconst variant: QuickJSSyncVariant = {\n type: \"sync\",\n importFFI: () => import(\"./ffi.js\").then((mod) => mod.QuickJSFFI),\n importModuleLoader: () =>\n import(\"@jitl/quickjs-singlefile-mjs-release-sync/emscripten-module\").then(\n (mod) => mod.default,\n ),\n} as const\n\nexport default variant\n"],"mappings":";;;;AAiBA,IAAM,UAA8B,EAClC,MAAM,QACN,WAAW,MAAM,OAAO,mBAAU,EAAE,KAAM,SAAQ,IAAI,UAAU,GAChE,oBAAoB,MAClB,OAAO,0CAA6D,EAAE,KACnE,SAAQ,IAAI,OACf,EACJ;AAPA,IASO,cAAQ;","names":[]}
|