@mermanjs/node-wasm 0.10.0 → 0.12.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/dist/engine.mjs CHANGED
@@ -1,18 +1,29 @@
1
1
  import { BoundedExecutor } from "./bounded-executor.mjs";
2
+ import {
3
+ getInstalledWasmSvgResponseSync,
4
+ supportsDirectNativeSvg,
5
+ takeVersionCheckedRuntimeCatalog,
6
+ } from "./native-loader.mjs";
7
+ import { nodeWireContract } from "./transport-contract.mjs";
2
8
  import {
3
9
  MermanInvalidTransportError,
4
10
  NODE_TRANSPORT_FIELD_LIMITS,
5
11
  NODE_TRANSPORT_LIMITS,
6
12
  NODE_WIRE_CONTRACT,
7
13
  abortError,
14
+ addJsonEnvelopeBytes,
15
+ addJsonEnvelopeStringBytes,
8
16
  assertUtf8Field,
9
17
  decodeWireInvocationError,
10
18
  decodeWireResponse,
11
19
  encodeTransportJson,
20
+ jsonStringFieldBytes,
21
+ normalizeOperationSignal,
12
22
  parseRuntimeCatalogJsonText,
13
23
  parseTransportJsonText,
14
24
  sameJsonValue,
15
25
  snapshotTransportJsonValue,
26
+ validateOperationOptionsJson,
16
27
  } from "./errors.mjs";
17
28
  import {
18
29
  BINDING_OPTION_GROUP_SPECS,
@@ -22,6 +33,7 @@ import {
22
33
  BINDING_TRANSPORT_EXPOSURE_SPECS,
23
34
  CAPABILITY_SPECS,
24
35
  CONSTRUCTOR_SERVICE_SPECS,
36
+ ICON_REGISTRY_CONSTRUCTOR_SERVICE_ID,
25
37
  METADATA_SPECS,
26
38
  RUNTIME_CATALOG_FIELD_IDENTIFIER_PATTERN,
27
39
  RUNTIME_CATALOG_IDENTIFIER_PATTERN,
@@ -88,17 +100,37 @@ const COMPILED_PREREQUISITES_BY_OPERATION_ID = new Map(
88
100
  const KNOWN_OUTPUT_CONTRACT_BY_ID = new Map(
89
101
  NODE_WIRE_CONTRACT.artifact.output_contracts.map((contract) => [contract.id, contract]),
90
102
  );
91
- const THEME_AUTHORING_INPUT_LIMITS = Object.freeze({
103
+ const THEME_REQUEST_LIMITS = Object.freeze({
92
104
  ...NODE_TRANSPORT_LIMITS.metadata,
93
105
  max_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
94
106
  max_string_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
95
107
  });
96
- const THEME_AUTHORING_RESULT_LIMITS = Object.freeze({
108
+ const THEME_RESULT_LIMITS = Object.freeze({
97
109
  ...NODE_TRANSPORT_LIMITS.metadata,
98
110
  max_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.data_utf8_bytes,
99
111
  max_string_utf8_bytes: NODE_TRANSPORT_FIELD_LIMITS.data_utf8_bytes,
100
112
  });
101
113
  const MAX_OPERATION_TIMEOUT_MS = 0xffff_ffff;
114
+ const OPERATION_REQUEST_FIELDS = new Set(["operationId", "source", "uri", "options", "optionsJson"]);
115
+ const SVG_REQUEST_FRAME_BYTES = '{"operation_id":"svg","source":"","uri":null,"include_metadata":false}'.length;
116
+ const DRAW_LIST_REQUEST_FRAME_BYTES = '{"operation_id":"draw-list-json","source":"","uri":null,"include_metadata":false}'.length;
117
+ const SVG_OPTIONS_FRAME_BYTES = ',"options_json":""'.length;
118
+ const SVG_TIMEOUT_FRAME_BYTES = ',"operation_control":{"timeout_ms":}'.length;
119
+ const SVG_ID_OPTIONS_BYTES = '{"svg":{"diagram_id":""}}'.length;
120
+ const ICON_PACK_ENTRY_JSON_FRAME_BYTES = '{"json":}'.length;
121
+ const ICON_PACK_REGISTRATION_NAME_KEY_BYTES = ',"registrationName":'.length;
122
+ const ICON_PACK_ENVELOPE_MIN_ENTRY_BYTES = '{"json":""}'.length;
123
+ const ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES = "[]".length;
124
+ const ICON_PACK_ENVELOPE_OVERHEAD_PER_PACK = '{"json":"","registrationName":""},'.length;
125
+ export const ICON_PACK_MAX_ENVELOPE_PACKS = 1024;
126
+ export const ICON_PACK_MAX_ENVELOPE_BYTES = deriveIconPackMaxEnvelopeBytes();
127
+ // Reserve the largest direct frame, timeout, and six escaped bytes per admitted options byte.
128
+ const DIRECT_SVG_SOURCE_UNIT_BOUND = Math.floor(Math.min(
129
+ NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes / 3,
130
+ (NODE_TRANSPORT_LIMITS.request.max_utf8_bytes -
131
+ directOperationFrameBytes(Math.max(SVG_REQUEST_FRAME_BYTES, DRAW_LIST_REQUEST_FRAME_BYTES), 0, MAX_OPERATION_TIMEOUT_MS) -
132
+ SVG_OPTIONS_FRAME_BYTES - 6 * NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes) / 6,
133
+ ));
102
134
  const MERMAN_ENGINE_CONSTRUCTION_TOKEN = Symbol("MermanEngine construction");
103
135
 
104
136
  export async function createNodeEngine(
@@ -108,7 +140,7 @@ export async function createNodeEngine(
108
140
  concurrency = 1,
109
141
  maxQueue = 64,
110
142
  } = {},
111
- { loadTransport } = {},
143
+ { loadTransport, localLayout = null, candidate = null } = {},
112
144
  ) {
113
145
  if (typeof loadTransport !== "function") {
114
146
  throw new MermanInvalidTransportError("A concrete Node candidate transport loader is required.");
@@ -123,12 +155,18 @@ export async function createNodeEngine(
123
155
  const transport = await loadTransport(optionsJson, iconPacksJson);
124
156
  try {
125
157
  assertTransport(transport);
126
- const runtimeCatalog = validateRuntimeCatalog(await transport.runtimeCatalogJson());
158
+ const catalogText = await transport.runtimeCatalogJson();
159
+ const catalog = takeVersionCheckedRuntimeCatalog(transport, catalogText) ??
160
+ parseRuntimeCatalogJsonText(catalogText);
161
+ const runtimeCatalog = validateParsedRuntimeCatalog(catalog, { localLayout, candidate });
162
+ const supportsSvg = runtimeCatalog.capabilities.operation_ids.includes("svg");
127
163
  return new MermanEngine(
128
164
  MERMAN_ENGINE_CONSTRUCTION_TOKEN,
129
165
  transport,
130
166
  runtimeCatalog,
131
167
  { concurrency, maxQueue },
168
+ supportsSvg && supportsDirectNativeSvg(transport),
169
+ supportsSvg ? getInstalledWasmSvgResponseSync(transport) : undefined,
132
170
  );
133
171
  } catch (error) {
134
172
  await disposeUnusableTransport(transport);
@@ -136,25 +174,131 @@ export async function createNodeEngine(
136
174
  }
137
175
  }
138
176
 
139
- function encodeIconPacks(packs) {
177
+ function deriveIconPackMaxEnvelopeBytes() {
178
+ const spec = CONSTRUCTOR_SERVICE_SPEC_BY_ID.get(ICON_REGISTRY_CONSTRUCTOR_SERVICE_ID);
179
+ if (spec === undefined) {
180
+ throw new Error("Generated binding contract is missing the icon-registry constructor service.");
181
+ }
182
+ const limitById = new Map(spec.resource_limits.map((limit) => [limit.id, limit.value]));
183
+ const maxPacks = limitById.get("max_icon_registry_packs");
184
+ const maxInputBytes = limitById.get("max_icon_registry_input_bytes");
185
+ const maxPrefixBytes = limitById.get("max_icon_registry_prefix_bytes");
186
+ if (
187
+ !positiveSafeInteger(maxPacks) ||
188
+ !positiveSafeInteger(maxInputBytes) ||
189
+ !positiveSafeInteger(maxPrefixBytes)
190
+ ) {
191
+ throw new Error("Generated binding contract is missing icon-registry envelope resource limits.");
192
+ }
193
+ // Matches `build_icon_registry_from_json` in `crates/merman-bindings-core/src/services.rs`.
194
+ return (
195
+ 6 * (maxInputBytes + maxPacks * maxPrefixBytes) +
196
+ maxPacks * ICON_PACK_ENVELOPE_OVERHEAD_PER_PACK +
197
+ ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES
198
+ );
199
+ }
200
+
201
+ export function encodeIconPacks(packs, maxEnvelopeBytes = ICON_PACK_MAX_ENVELOPE_BYTES) {
202
+ if (!Number.isSafeInteger(maxEnvelopeBytes) || maxEnvelopeBytes < 0) {
203
+ throw new RangeError("iconPacks maxEnvelopeBytes must be a non-negative safe integer.");
204
+ }
140
205
  if (packs === undefined) return undefined;
141
206
  if (!Array.isArray(packs)) throw new TypeError("iconPacks must be an array.");
142
- const normalized = [];
143
- for (const pack of packs) {
144
- if (!isPlainObject(pack) || typeof pack.json !== "string") {
145
- throw new TypeError("iconPacks entries must contain an already loaded JSON string.");
207
+
208
+ const packCount = packs.length;
209
+ if (!Number.isSafeInteger(packCount) || packCount < 0) {
210
+ throw new TypeError("iconPacks must be an array.");
211
+ }
212
+ if (packCount > ICON_PACK_MAX_ENVELOPE_PACKS) {
213
+ throw new MermanInvalidTransportError(
214
+ `Merman transport iconPacks exceeds the ${ICON_PACK_MAX_ENVELOPE_PACKS}-pack wire limit.`,
215
+ );
216
+ }
217
+ const budget = { label: "iconPacks", max: maxEnvelopeBytes, used: 0 };
218
+ addJsonEnvelopeBytes(budget, ICON_PACK_ENVELOPE_ARRAY_FRAME_BYTES);
219
+ if (packCount > 0) {
220
+ // Reject arrays whose minimum possible encoded envelope already exceeds the wire ceiling
221
+ // before materializing Reflect.ownKeys() on oversized inputs.
222
+ const minContentBytes = packCount * ICON_PACK_ENVELOPE_MIN_ENTRY_BYTES + (packCount - 1);
223
+ if (minContentBytes > budget.max - budget.used) {
224
+ addJsonEnvelopeBytes(budget, minContentBytes);
146
225
  }
147
- if (Object.keys(pack).some((key) => key !== "json" && key !== "registrationName")) {
148
- throw new TypeError("iconPacks entries only accept json and registrationName.");
226
+ }
227
+
228
+ const packKeys = Reflect.ownKeys(packs);
229
+ if (packKeys.some((key) => typeof key === "symbol")) {
230
+ throw new TypeError("iconPacks must not contain symbol keys.");
231
+ }
232
+ if (packKeys.length < packCount + 1) {
233
+ throw new TypeError("iconPacks arrays must not contain holes.");
234
+ }
235
+ if (packKeys.length !== packCount + 1) {
236
+ throw new TypeError("iconPacks arrays must not contain custom properties.");
237
+ }
238
+
239
+ const normalized = Object.setPrototypeOf([], null);
240
+ for (let index = 0; index < packCount; index += 1) {
241
+ const elementDescriptor = Object.getOwnPropertyDescriptor(packs, String(index));
242
+ if (elementDescriptor === undefined) {
243
+ throw new TypeError("iconPacks arrays must not contain holes.");
244
+ }
245
+ if (!elementDescriptor.enumerable || !("value" in elementDescriptor)) {
246
+ throw new TypeError(`iconPacks[${index}] must be an enumerable data property.`);
247
+ }
248
+ const pack = elementDescriptor.value;
249
+ const jsonCopyHint = "Pass a plain copy such as `{ json: pack.json }`.";
250
+ if (!isPlainObject(pack)) {
251
+ throw new TypeError(`iconPacks[${index}] must be a plain object with a json string. ${jsonCopyHint}`);
252
+ }
253
+
254
+ let json;
255
+ let hasJson = false;
256
+ let registrationName;
257
+ for (const key of Reflect.ownKeys(pack)) {
258
+ if (typeof key === "symbol") {
259
+ throw new TypeError(`iconPacks[${index}] must not contain symbol keys.`);
260
+ }
261
+ if (key !== "json" && key !== "registrationName") {
262
+ throw new TypeError("iconPacks entries only accept json and registrationName.");
263
+ }
264
+ const descriptor = Object.getOwnPropertyDescriptor(pack, key);
265
+ if (!descriptor?.enumerable || !("value" in descriptor)) {
266
+ const hint = key === "json" ? ` ${jsonCopyHint}` : "";
267
+ throw new TypeError(`iconPacks[${index}].${key} must be an enumerable data property.${hint}`);
268
+ }
269
+ if (key === "json") {
270
+ json = descriptor.value;
271
+ hasJson = true;
272
+ } else {
273
+ registrationName = descriptor.value;
274
+ }
275
+ }
276
+
277
+ if (!hasJson || typeof json !== "string") {
278
+ throw new TypeError("iconPacks entries must contain an already loaded JSON string.");
149
279
  }
150
- if (pack.registrationName !== undefined && typeof pack.registrationName !== "string") {
280
+ if (registrationName !== undefined && typeof registrationName !== "string") {
151
281
  throw new TypeError("iconPacks registrationName must be a string.");
152
282
  }
153
- normalized.push({
154
- json: pack.json,
155
- ...(pack.registrationName === undefined ? {} : { registrationName: pack.registrationName }),
156
- });
283
+
284
+ if (index > 0) addJsonEnvelopeBytes(budget, 1);
285
+ addJsonEnvelopeBytes(budget, ICON_PACK_ENTRY_JSON_FRAME_BYTES);
286
+ addJsonEnvelopeStringBytes(json, `iconPacks[${index}].json`, budget);
287
+
288
+ const entry = Object.create(null);
289
+ entry.json = json;
290
+ if (registrationName !== undefined) {
291
+ addJsonEnvelopeBytes(budget, ICON_PACK_REGISTRATION_NAME_KEY_BYTES);
292
+ addJsonEnvelopeStringBytes(
293
+ registrationName,
294
+ `iconPacks[${index}].registrationName`,
295
+ budget,
296
+ );
297
+ entry.registrationName = registrationName;
298
+ }
299
+ normalized[index] = entry;
157
300
  }
301
+
158
302
  return JSON.stringify(normalized);
159
303
  }
160
304
 
@@ -207,6 +351,8 @@ export function normalizeBindingOptions(value = {}) {
207
351
  }
208
352
 
209
353
  export class MermanEngine {
354
+ #directSvg;
355
+ #executeWasmSvgResponseSync;
210
356
  #disposePromise = null;
211
357
  #executor;
212
358
  #metadataIds;
@@ -214,13 +360,18 @@ export class MermanEngine {
214
360
  #runtimeCatalog;
215
361
  #transport;
216
362
 
217
- constructor(constructionToken, transport, runtimeCatalog, queueOptions) {
363
+ constructor(
364
+ constructionToken, transport, runtimeCatalog, queueOptions,
365
+ directSvg, executeWasmSvgResponseSync = undefined,
366
+ ) {
218
367
  if (constructionToken !== MERMAN_ENGINE_CONSTRUCTION_TOKEN) {
219
368
  throw new MermanInvalidTransportError(
220
369
  "MermanEngine instances must be created with createNodeEngine().",
221
370
  );
222
371
  }
223
372
  this.#transport = transport;
373
+ this.#directSvg = directSvg;
374
+ this.#executeWasmSvgResponseSync = executeWasmSvgResponseSync;
224
375
  this.#runtimeCatalog = runtimeCatalog;
225
376
  this.#metadataIds = new Set(
226
377
  runtimeCatalog.metadata_ids.filter((id) => METADATA_SPEC_BY_ID.has(id)),
@@ -237,66 +388,108 @@ export class MermanEngine {
237
388
  return structuredClone(this.#runtimeCatalog);
238
389
  }
239
390
 
240
- renderSvg(source, options = {}) {
391
+ async renderSvg(source, options = {}) {
241
392
  return this.#execute(
242
- { operationId: "svg", source, optionsJson: options.optionsJson },
393
+ { operationId: "svg", source, optionsJson: encodeRequestOptions(options) },
243
394
  { signal: options.signal, timeoutMs: options.timeoutMs },
244
395
  false,
396
+ options.diagramId,
245
397
  );
246
398
  }
247
399
 
248
400
  renderSvgSync(source, options = {}) {
401
+ this.#executor.assertSyncAvailable("renderSvgSync");
249
402
  return this.#executeSync(
250
- { operationId: "svg", source, optionsJson: options.optionsJson },
403
+ { operationId: "svg", source, optionsJson: encodeRequestOptions(options) },
251
404
  { timeoutMs: options.timeoutMs },
252
405
  false,
406
+ options.diagramId,
407
+ "renderSvgSync",
253
408
  );
254
409
  }
255
410
 
256
- svgPlanJson(source, options = {}) {
411
+ async svgPlanJson(source, options = {}) {
257
412
  return this.#execute(
258
- { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
413
+ { operationId: "svg-plan-json", source, optionsJson: encodeRequestOptions(options) },
259
414
  { signal: options.signal, timeoutMs: options.timeoutMs },
260
415
  false,
416
+ options.diagramId,
261
417
  );
262
418
  }
263
419
 
264
420
  svgPlanJsonSync(source, options = {}) {
421
+ this.#executor.assertSyncAvailable("svgPlanJsonSync");
265
422
  return this.#executeSync(
266
- { operationId: "svg-plan-json", source, optionsJson: options.optionsJson },
423
+ { operationId: "svg-plan-json", source, optionsJson: encodeRequestOptions(options) },
267
424
  { timeoutMs: options.timeoutMs },
268
425
  false,
426
+ options.diagramId,
427
+ "svgPlanJsonSync",
269
428
  );
270
429
  }
271
430
 
272
- materializeTheme(input, options = {}) {
273
- return this.#themeAuthoring("materialize-theme-json", input, options);
431
+ async drawListJson(source, options = {}) {
432
+ return this.#execute(
433
+ { operationId: "draw-list-json", source, optionsJson: encodeRequestOptions(options) },
434
+ { signal: options.signal, timeoutMs: options.timeoutMs },
435
+ false,
436
+ options.diagramId,
437
+ );
274
438
  }
275
439
 
276
- describeThemeSupport(query, options = {}) {
277
- return this.#themeAuthoring("describe-theme-support-json", query, options);
440
+ drawListJsonSync(source, options = {}) {
441
+ this.#executor.assertSyncAvailable("drawListJsonSync");
442
+ return this.#executeSync(
443
+ { operationId: "draw-list-json", source, optionsJson: encodeRequestOptions(options) },
444
+ { timeoutMs: options.timeoutMs },
445
+ false,
446
+ options.diagramId,
447
+ "drawListJsonSync",
448
+ );
278
449
  }
279
450
 
280
- exportThemePreset(presetId, options = {}) {
451
+ async exportThemePreset(presetId, options = {}) {
281
452
  if (typeof presetId !== "string") {
282
- return Promise.reject(new TypeError("theme preset ID must be a string."));
453
+ throw new TypeError("theme preset ID must be a string.");
283
454
  }
284
- return this.#themeAuthoring("export-theme-preset-json", presetId, options);
455
+ return this.#executeThemeJson("export-theme-preset", presetId, options);
285
456
  }
286
457
 
287
- async #themeAuthoring(operationId, input, options) {
288
- const source = typeof input === "string"
289
- ? input
290
- : encodeTransportJson(input, "theme authoring input", THEME_AUTHORING_INPUT_LIMITS);
291
- const json = await this.#execute(
292
- { operationId, source, optionsJson: options.optionsJson },
293
- { signal: options.signal, timeoutMs: options.timeoutMs },
294
- false,
458
+ async resolveTheme(document, { appearance, auto_fix_contrast, expand, signal, timeoutMs } = {}) {
459
+ if (typeof document !== "string" && !isPlainObject(document)) {
460
+ throw new TypeError("theme document must be a plain object or JSON text.");
461
+ }
462
+ const source = encodeTransportJson(
463
+ {
464
+ document,
465
+ ...(appearance === undefined ? {} : { appearance }),
466
+ ...(auto_fix_contrast === undefined ? {} : { auto_fix_contrast }),
467
+ ...(expand === undefined ? {} : { expand }),
468
+ },
469
+ "theme resolution request",
470
+ THEME_REQUEST_LIMITS,
295
471
  );
296
- return parseTransportJsonText(json, "theme authoring result", THEME_AUTHORING_RESULT_LIMITS);
472
+ return this.#executeThemeJson("resolve-theme", source, { signal, timeoutMs });
473
+ }
474
+
475
+ async #executeThemeJson(operationId, source, options) {
476
+ const json = await this.#execute({ operationId, source }, options, false);
477
+ return parseTransportJsonText(json, "theme operation result", THEME_RESULT_LIMITS);
478
+ }
479
+
480
+ themeCatalog() {
481
+ const { parsed } = this.#readMetadata("theme-catalog");
482
+ if (parsed?.schema_version !== 2) {
483
+ throw new MermanInvalidTransportError("Merman transport returned an unsupported theme catalog schema.");
484
+ }
485
+ return parsed;
297
486
  }
298
487
 
299
488
  metadataJson(id) {
489
+ return this.#readMetadata(id).json;
490
+ }
491
+
492
+ #readMetadata(id) {
300
493
  this.#executor.assertOpen();
301
494
  if (typeof id !== "string" || id.length === 0) {
302
495
  throw new TypeError("metadata id must be a non-empty string.");
@@ -306,80 +499,150 @@ export class MermanEngine {
306
499
  `metadata id \`${id}\` is not callable through this SDK and artifact contract.`,
307
500
  );
308
501
  }
309
- let value;
502
+ let json;
310
503
  try {
311
- value = this.#transport.metadataJson(id);
504
+ json = this.#transport.metadataJson(id);
312
505
  } catch (cause) {
313
506
  throw decodeWireInvocationError(cause, `Merman metadata \`${id}\``);
314
507
  }
315
- parseTransportJsonText(
316
- value,
508
+ const parsed = parseTransportJsonText(
509
+ json,
317
510
  `metadata \`${id}\``,
318
511
  NODE_TRANSPORT_LIMITS.metadata,
319
512
  );
320
- return value;
513
+ return { json, parsed };
321
514
  }
322
515
 
323
516
  executeOperation(request, options = {}) {
324
517
  return this.#execute(request, options, true);
325
518
  }
326
519
 
327
- #execute(request, { signal, timeoutMs } = {}, includeMetadata) {
520
+ #execute(request, options = {}, includeMetadata, diagramId) {
328
521
  try {
522
+ const { timeoutMs } = options;
329
523
  this.#executor.assertOpen();
524
+ const signal = normalizeOperationSignal(options.signal);
525
+ const directSvg = this.#usesDirectSvg(request, includeMetadata);
526
+ const directDrawList = this.#usesDirectDrawList(request, includeMetadata, false);
527
+ const directData = directSvg || directDrawList;
528
+ const prepared = prepareOperationRequest(request, { timeoutMs, directSvg: directData });
529
+ const { expectation } = prepared;
530
+ if (signal?.aborted) return Promise.reject(abortError());
531
+ const useTypedId = diagramId !== undefined && prepareSvgDiagramId(
532
+ prepared, diagramId, timeoutMs, directSvg && !!this.#transport.executeSvgWithId,
533
+ );
534
+ let execute;
535
+ if (useTypedId) {
536
+ execute = (forwarded) => this.#transport.executeSvgWithId(request.source, diagramId, forwarded, timeoutMs);
537
+ } else if (directSvg) {
538
+ const optionsJson = prepareDirectOperationOptions(prepared, timeoutMs, SVG_REQUEST_FRAME_BYTES);
539
+ const { source } = prepared.request;
540
+ execute = (forwarded) => this.#transport.executeSvg(source, optionsJson, forwarded, timeoutMs);
541
+ } else if (directDrawList) {
542
+ const optionsJson = prepareDirectOperationOptions(prepared, timeoutMs, DRAW_LIST_REQUEST_FRAME_BYTES);
543
+ const { source } = prepared.request;
544
+ execute = (forwarded) => this.#transport.executeDrawList(source, optionsJson, forwarded, timeoutMs);
545
+ } else {
546
+ const requestJson = operationRequestJson(prepared, includeMetadata);
547
+ execute = (forwarded) => this.#transport.execute(requestJson, forwarded, timeoutMs);
548
+ }
549
+ return this.#executor.submit(
550
+ async () => {
551
+ // A signal can flip after queue admission but before this start microtask runs. That work
552
+ // has not crossed the transport boundary, so preserve the established AbortError result.
553
+ if (signal?.aborted) throw abortError();
554
+ let response;
555
+ try {
556
+ response = await executeTransportOperation(execute, signal);
557
+ } catch (cause) {
558
+ throw decodeWireInvocationError(cause, "Merman operation");
559
+ }
560
+ return this.#decodeOperationResponse(response, expectation, {
561
+ includeMetadata,
562
+ directSvgResponse: directData,
563
+ signal,
564
+ timeoutMs,
565
+ });
566
+ },
567
+ { signal },
568
+ );
330
569
  } catch (error) {
331
570
  return Promise.reject(error);
332
571
  }
333
- const prepared = prepareOperationRequest(request, { timeoutMs });
334
- if (signal?.aborted) return Promise.reject(abortError());
335
- const encoded = operationRequestJson(prepared, includeMetadata);
336
- return this.#executor.submit(
337
- async () => {
338
- // A signal can flip after queue admission but before this start microtask runs. That work
339
- // has not crossed the transport boundary, so preserve the established AbortError result.
340
- if (signal?.aborted) throw abortError();
341
- let responseJson;
342
- try {
343
- responseJson = await executeTransportOperation(
344
- this.#transport,
345
- encoded.json,
346
- signal,
347
- timeoutMs,
348
- );
349
- } catch (cause) {
350
- throw decodeWireInvocationError(cause, "Merman operation");
351
- }
352
- return decodeWireResponse(responseJson, encoded.expectation, {
353
- includeMetadata,
354
- allowedCancellationReasons: invocationCancellationReasons(signal, timeoutMs),
355
- requireUnavailable: !this.#operationIds.has(encoded.expectation.operation_id),
356
- availableCapabilityIds: this.#runtimeCatalog.capabilities.capability_ids,
357
- });
358
- },
359
- { signal },
360
- );
361
572
  }
362
573
 
363
574
  executeOperationSync(request, options = {}) {
364
- return this.#executeSync(request, options, true);
575
+ this.#executor.assertSyncAvailable("executeOperationSync");
576
+ return this.#executeSync(request, options, true, undefined, "executeOperationSync");
365
577
  }
366
578
 
367
- #executeSync(request, { timeoutMs } = {}, includeMetadata) {
368
- this.#executor.assertSyncAvailable();
369
- const encoded = operationRequestJson(
370
- prepareOperationRequest(request, { timeoutMs }),
371
- includeMetadata,
579
+ #executeSync(request, { timeoutMs } = {}, includeMetadata, diagramId, syncMethod = "executeOperationSync") {
580
+ const directSvg = this.#usesDirectSvg(request, includeMetadata);
581
+ const directDrawList = this.#usesDirectDrawList(request, includeMetadata, true);
582
+ const directData = directSvg || directDrawList;
583
+ const prepared = prepareOperationRequest(request, { timeoutMs, directSvg: directData });
584
+ const useTypedId = diagramId !== undefined && prepareSvgDiagramId(
585
+ prepared, diagramId, timeoutMs, directSvg && !!this.#transport.executeSvgWithIdSync,
372
586
  );
373
- let responseJson;
587
+ let payload = diagramId;
588
+ if (!useTypedId) {
589
+ payload = directSvg
590
+ ? prepareDirectOperationOptions(prepared, timeoutMs, SVG_REQUEST_FRAME_BYTES)
591
+ : directDrawList
592
+ ? prepareDirectOperationOptions(prepared, timeoutMs, DRAW_LIST_REQUEST_FRAME_BYTES)
593
+ : operationRequestJson(prepared, includeMetadata);
594
+ }
595
+ this.#executor.assertSyncAvailable(syncMethod);
596
+ const wasmSvgResponse = this.#executeWasmSvgResponseSync !== undefined &&
597
+ !includeMetadata && prepared.expectation.operation_id === "svg";
598
+ let response;
374
599
  try {
375
- responseJson = this.#transport.executeSync(encoded.json, timeoutMs);
600
+ if (directSvg) {
601
+ response = useTypedId
602
+ ? this.#transport.executeSvgWithIdSync(request.source, payload, timeoutMs)
603
+ : this.#transport.executeSvgSync(request.source, payload, timeoutMs);
604
+ } else if (directDrawList) {
605
+ response = this.#transport.executeDrawListSync(request.source, payload, timeoutMs);
606
+ } else if (wasmSvgResponse) {
607
+ response = this.#executeWasmSvgResponseSync(payload, timeoutMs);
608
+ } else {
609
+ response = this.#transport.executeSync(payload, timeoutMs);
610
+ }
376
611
  } catch (cause) {
377
612
  throw decodeWireInvocationError(cause, "Merman operation");
378
613
  }
379
- return decodeWireResponse(responseJson, encoded.expectation, {
614
+ return this.#decodeOperationResponse(response, prepared.expectation, {
380
615
  includeMetadata,
381
- allowedCancellationReasons: invocationCancellationReasons(undefined, timeoutMs),
382
- requireUnavailable: !this.#operationIds.has(encoded.expectation.operation_id),
616
+ directSvgResponse: directData || wasmSvgResponse,
617
+ timeoutMs,
618
+ });
619
+ }
620
+
621
+ #usesDirectSvg(request, includeMetadata) {
622
+ return this.#directSvg && !includeMetadata && request.operationId === "svg";
623
+ }
624
+
625
+ #usesDirectDrawList(request, includeMetadata, sync) {
626
+ return this.#directSvg &&
627
+ !includeMetadata &&
628
+ request.operationId === "draw-list-json" &&
629
+ Boolean(sync ? this.#transport.executeDrawListSync : this.#transport.executeDrawList);
630
+ }
631
+
632
+ #decodeOperationResponse(response, expectation, { includeMetadata, directSvgResponse, signal, timeoutMs }) {
633
+ if (directSvgResponse) {
634
+ if (typeof response === "string") return response;
635
+ if (response === null || typeof response !== "object" || !Object.hasOwn(response, "errorJson")) {
636
+ const label = expectation.operation_id === "svg" ? "SVG" : "DrawList";
637
+ throw new MermanInvalidTransportError(`The direct ${label} operation returned an invalid result.`);
638
+ }
639
+ response = response.errorJson;
640
+ }
641
+ return decodeWireResponse(response, expectation, {
642
+ includeMetadata,
643
+ requireError: directSvgResponse,
644
+ allowedCancellationReasons: invocationCancellationReasons(signal, timeoutMs),
645
+ requireUnavailable: !this.#operationIds.has(expectation.operation_id),
383
646
  availableCapabilityIds: this.#runtimeCatalog.capabilities.capability_ids,
384
647
  });
385
648
  }
@@ -391,6 +654,28 @@ export class MermanEngine {
391
654
  });
392
655
  return this.#disposePromise;
393
656
  }
657
+
658
+ [Symbol.dispose]() {
659
+ // Synchronous resource management starts disposal without awaiting in-flight work.
660
+ // dispose() and async disposal still expose the same promise and its result.
661
+ void this.dispose().catch(() => {});
662
+ }
663
+
664
+ [Symbol.asyncDispose]() {
665
+ return this.dispose();
666
+ }
667
+ }
668
+
669
+ function encodeRequestOptions({ options, optionsJson, diagramId }) {
670
+ if (options === undefined) return optionsJson;
671
+ if (optionsJson !== undefined) {
672
+ throw new TypeError("options and optionsJson cannot be used together.");
673
+ }
674
+ if (diagramId !== undefined) {
675
+ throw new TypeError("Use options.svg.diagram_id when supplying options with an SVG ID.");
676
+ }
677
+ if (!isPlainObject(options)) throw new TypeError("options must be a plain object.");
678
+ return encodeTransportJson(options, "operation request options", NODE_TRANSPORT_LIMITS.binding_options);
394
679
  }
395
680
 
396
681
  function invocationCancellationReasons(signal, timeoutMs) {
@@ -400,11 +685,10 @@ function invocationCancellationReasons(signal, timeoutMs) {
400
685
  return reasons;
401
686
  }
402
687
 
403
- function prepareOperationRequest(value, { timeoutMs } = {}) {
688
+ function prepareOperationRequest(value, { timeoutMs, directSvg }) {
404
689
  if (!isPlainObject(value)) throw new TypeError("operation request must be a plain object.");
405
- const knownFields = new Set(["operationId", "source", "uri", "optionsJson"]);
406
690
  for (const field of Object.keys(value)) {
407
- if (!knownFields.has(field)) {
691
+ if (!OPERATION_REQUEST_FIELDS.has(field)) {
408
692
  throw new TypeError(`unknown operation request field \`${field}\`.`);
409
693
  }
410
694
  }
@@ -434,11 +718,18 @@ function prepareOperationRequest(value, { timeoutMs } = {}) {
434
718
  "operation request operationId",
435
719
  NODE_TRANSPORT_FIELD_LIMITS.operation_id_utf8_bytes,
436
720
  );
437
- assertUtf8Field(
438
- source,
439
- "operation request source",
440
- NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
441
- );
721
+ let sourceByteBound;
722
+ if (directSvg && source.length <= DIRECT_SVG_SOURCE_UNIT_BOUND && source.isWellFormed()) {
723
+ // Every admitted options or typed-ID frame still fits with this upper bound.
724
+ sourceByteBound = source.length * 6;
725
+ } else {
726
+ const measureSource = directSvg ? jsonStringFieldBytes : assertUtf8Field;
727
+ sourceByteBound = measureSource(
728
+ source,
729
+ "operation request source",
730
+ NODE_TRANSPORT_FIELD_LIMITS.source_utf8_bytes,
731
+ );
732
+ }
442
733
  if (normalizedUri !== null) {
443
734
  assertUtf8Field(
444
735
  normalizedUri,
@@ -463,36 +754,96 @@ function prepareOperationRequest(value, { timeoutMs } = {}) {
463
754
  }
464
755
  request.operation_control = { timeout_ms: timeoutMs };
465
756
  }
466
- return { expectation, request, value };
757
+ return { expectation, request, value, sourceByteBound, diagramIdOptionsJson: undefined };
758
+ }
759
+
760
+ function operationOptionsJsonBytes(optionsJson, fromDiagramId, countJsonEscapes = false) {
761
+ if (!fromDiagramId) return validateOperationOptionsJson(optionsJson, countJsonEscapes);
762
+
763
+ // The diagram ID fallback already encoded and checked the binding options document.
764
+ const measureField = countJsonEscapes ? jsonStringFieldBytes : assertUtf8Field;
765
+ return measureField(
766
+ optionsJson,
767
+ "operation request optionsJson",
768
+ NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes,
769
+ );
467
770
  }
468
771
 
469
- function operationRequestJson({ expectation, request, value }, includeMetadata) {
772
+ function operationRequestJson({ request, value, diagramIdOptionsJson }, includeMetadata) {
470
773
  if (!includeMetadata) request.include_metadata = false;
471
- const optionsJson = value.optionsJson;
774
+ const optionsJson = diagramIdOptionsJson ?? encodeRequestOptions(value);
472
775
  if (optionsJson !== undefined) {
473
- if (typeof optionsJson !== "string") {
474
- throw new TypeError("optionsJson must be a JSON string when provided.");
475
- }
476
- assertUtf8Field(
477
- optionsJson,
478
- "operation request optionsJson",
479
- NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes,
776
+ operationOptionsJsonBytes(optionsJson, diagramIdOptionsJson !== undefined);
777
+ request.options_json = optionsJson;
778
+ }
779
+ return encodeTransportJson(request, "operation request", NODE_TRANSPORT_LIMITS.request);
780
+ }
781
+
782
+ function prepareDirectOperationOptions(
783
+ { value, sourceByteBound, diagramIdOptionsJson },
784
+ timeoutMs,
785
+ baseFrameBytes,
786
+ ) {
787
+ // Match the former fixed request's byte budget without building or scanning the document.
788
+ let requestByteBound = directOperationFrameBytes(baseFrameBytes, sourceByteBound, timeoutMs);
789
+ const optionsJson = diagramIdOptionsJson ?? value.optionsJson;
790
+ if (optionsJson !== undefined) {
791
+ const optionsBytes = operationOptionsJsonBytes(optionsJson, diagramIdOptionsJson !== undefined, true);
792
+ requestByteBound += SVG_OPTIONS_FRAME_BYTES + optionsBytes;
793
+ }
794
+ const max = NODE_TRANSPORT_LIMITS.request.max_utf8_bytes;
795
+ if (requestByteBound > max) {
796
+ throw new MermanInvalidTransportError(
797
+ `Merman transport operation request exceeds the ${max}-byte wire limit.`,
480
798
  );
481
- parseTransportJsonText(
482
- optionsJson,
483
- "operation request optionsJson",
484
- NODE_TRANSPORT_LIMITS.binding_options,
799
+ }
800
+ return optionsJson;
801
+ }
802
+
803
+ function directOperationFrameBytes(baseFrameBytes, sourceByteBound, timeoutMs) {
804
+ const timeoutBytes = timeoutMs === undefined ? 0 : SVG_TIMEOUT_FRAME_BYTES + String(timeoutMs).length;
805
+ return baseFrameBytes + sourceByteBound + timeoutBytes;
806
+ }
807
+
808
+ function directSvgFrameBytes(sourceByteBound, timeoutMs) {
809
+ return directOperationFrameBytes(SVG_REQUEST_FRAME_BYTES, sourceByteBound, timeoutMs);
810
+ }
811
+
812
+ function prepareSvgDiagramId(prepared, diagramId, timeoutMs, typedTransport) {
813
+ if (prepared.request.operation_id !== "svg") {
814
+ throw new TypeError("diagramId is only supported by renderSvg() and renderSvgSync().");
815
+ }
816
+ if (typeof diagramId !== "string") throw new TypeError("diagramId must be a string when provided.");
817
+ if (prepared.value.optionsJson !== undefined) {
818
+ throw new TypeError("diagramId and optionsJson cannot be used together.");
819
+ }
820
+
821
+ // A UTF-16 unit needs at most six bytes in compact JSON, and enclosing that JSON as a
822
+ // request field expands it by at most twice. Use the exact wire path near either limit.
823
+ const optionsLimit = NODE_TRANSPORT_FIELD_LIMITS.options_json_utf8_bytes;
824
+ const maxOptionsBytes = SVG_ID_OPTIONS_BYTES + diagramId.length * 6;
825
+ if (typedTransport && maxOptionsBytes <= optionsLimit &&
826
+ directSvgFrameBytes(prepared.sourceByteBound, timeoutMs) + SVG_OPTIONS_FRAME_BYTES + maxOptionsBytes * 2 <=
827
+ NODE_TRANSPORT_LIMITS.request.max_utf8_bytes) {
828
+ assertUtf8Field(diagramId, "operation request diagramId", optionsLimit);
829
+ return true;
830
+ }
831
+
832
+ try {
833
+ prepared.diagramIdOptionsJson = encodeTransportJson(
834
+ { svg: { diagram_id: diagramId } }, "operation request diagramId", NODE_TRANSPORT_LIMITS.binding_options,
485
835
  );
486
- request.options_json = optionsJson;
836
+ } catch (error) {
837
+ // The encoder can exhaust the document budget before reaching the end of the ID.
838
+ // Give raw ID field and UTF-16 errors the same priority as the typed input path.
839
+ assertUtf8Field(diagramId, "operation request diagramId.svg.diagram_id", optionsLimit);
840
+ throw error;
487
841
  }
488
- return {
489
- expectation,
490
- json: encodeTransportJson(request, "operation request", NODE_TRANSPORT_LIMITS.request),
491
- };
842
+ return false;
492
843
  }
493
844
 
494
- async function executeTransportOperation(transport, requestJson, signal, timeoutMs) {
495
- if (!signal) return transport.execute(requestJson, undefined, timeoutMs);
845
+ async function executeTransportOperation(execute, signal) {
846
+ if (!signal) return execute(undefined);
496
847
 
497
848
  // Forward into a private signal so the N-API bridge cannot replace a caller-owned `onabort`
498
849
  // handler while it installs its cooperative cancellation callback.
@@ -508,7 +859,7 @@ async function executeTransportOperation(transport, requestJson, signal, timeout
508
859
  };
509
860
  signal.addEventListener("abort", forwardAbort, { once: true });
510
861
  try {
511
- const operation = transport.execute(requestJson, transportAbort.signal, timeoutMs);
862
+ const operation = execute(transportAbort.signal);
512
863
  transportReady = true;
513
864
  if (pendingAbort || signal.aborted) transportAbort.abort(signal.reason);
514
865
  return await operation;
@@ -539,19 +890,17 @@ async function disposeUnusableTransport(transport) {
539
890
  }
540
891
  }
541
892
 
542
- export function validateRuntimeCatalog(value) {
543
- if (typeof value !== "string") {
544
- throw new MermanInvalidTransportError(
545
- "Merman transport runtime catalog must be JSON text.",
546
- );
547
- }
548
- const catalog = parseRuntimeCatalogJsonText(value);
893
+ export function validateRuntimeCatalog(value, { localLayout = null, candidate = null } = {}) {
894
+ return validateParsedRuntimeCatalog(parseRuntimeCatalogJsonText(value), { localLayout, candidate });
895
+ }
896
+
897
+ function validateParsedRuntimeCatalog(catalog, { localLayout, candidate }) {
549
898
  if (!isPlainObject(catalog)) {
550
899
  throw new MermanInvalidTransportError("Merman transport returned an invalid runtime catalog.");
551
900
  }
552
901
  if (
553
902
  catalog.schema_version !== RUNTIME_CATALOG_SCHEMA_VERSION ||
554
- catalog.transport_api_version !== 1
903
+ catalog.transport_api_version !== NODE_WIRE_CONTRACT.transport_api_version
555
904
  ) {
556
905
  throw new MermanInvalidTransportError("Merman transport returned an unsupported runtime catalog version.");
557
906
  }
@@ -596,7 +945,9 @@ export function validateRuntimeCatalog(value) {
596
945
  validateOperationRelations({ capabilityIds, operationIds, outputIds });
597
946
  const metadataIds = validateMetadataIds(catalog.metadata_ids, new Set(capabilityIds));
598
947
  validateKnownArtifactIdentity({
948
+ candidate,
599
949
  capabilityIds,
950
+ localLayout,
600
951
  metadataIds,
601
952
  operationIds,
602
953
  outputIds,
@@ -636,13 +987,17 @@ export function validateRuntimeCatalog(value) {
636
987
  }
637
988
 
638
989
  function validateKnownArtifactIdentity({
990
+ candidate,
639
991
  capabilityIds,
992
+ localLayout,
640
993
  metadataIds,
641
994
  operationIds,
642
995
  outputIds,
643
996
  systemAdapterIds,
644
997
  }) {
645
- const expected = NODE_WIRE_CONTRACT.artifact;
998
+ const expected = nodeWireContract(
999
+ localLayout, candidate === "node-wasm" ? "wasm" : "napi", capabilityIds,
1000
+ ).artifact;
646
1001
  validateKnownIds(
647
1002
  capabilityIds,
648
1003
  expected.capability_ids,