@node-ctypes/comtypes 0.3.1 → 0.4.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.
Files changed (53) hide show
  1. package/README.md +50 -624
  2. package/dist/automation/dispatch.js +10 -3
  3. package/dist/automation/record.js +3 -1
  4. package/dist/automation/variant.d.ts +4 -4
  5. package/dist/automation/variant.js +93 -28
  6. package/dist/client/dynamic.js +7 -8
  7. package/dist/client/events.js +18 -2
  8. package/dist/client/index.js +3 -1
  9. package/dist/commethod.d.ts +1 -1
  10. package/dist/commethod.js +151 -57
  11. package/dist/errorinfo.d.ts +10 -3
  12. package/dist/errorinfo.js +66 -18
  13. package/dist/errors.d.ts +7 -1
  14. package/dist/executor/apartment.d.ts +7 -3
  15. package/dist/executor/apartment.js +65 -29
  16. package/dist/executor/executor.d.ts +2 -0
  17. package/dist/executor/executor.js +65 -14
  18. package/dist/guid.d.ts +1 -1
  19. package/dist/guid.js +7 -9
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +4 -4
  22. package/dist/interfaces/agile.d.ts +52 -0
  23. package/dist/interfaces/agile.js +59 -0
  24. package/dist/interfaces/errorinfo.d.ts +8 -0
  25. package/dist/interfaces/errorinfo.js +10 -0
  26. package/dist/interfaces/index.d.ts +2 -1
  27. package/dist/interfaces/index.js +2 -1
  28. package/dist/low-level/iids.d.ts +14 -0
  29. package/dist/low-level/iids.js +14 -0
  30. package/dist/low-level/index.d.ts +2 -2
  31. package/dist/low-level/index.js +1 -1
  32. package/dist/low-level/native.d.ts +13 -0
  33. package/dist/low-level/native.js +33 -0
  34. package/dist/low-level/registry.js +4 -2
  35. package/dist/low-level/vtable.d.ts +10 -0
  36. package/dist/low-level/vtable.js +32 -5
  37. package/dist/pointer.d.ts +2 -0
  38. package/dist/pointer.js +154 -84
  39. package/dist/pump.d.ts +32 -8
  40. package/dist/pump.js +87 -15
  41. package/dist/runtime.d.ts +6 -0
  42. package/dist/runtime.js +15 -1
  43. package/dist/server/automation.js +3 -3
  44. package/dist/server/comobject.d.ts +53 -0
  45. package/dist/server/comobject.js +319 -27
  46. package/dist/server/index.d.ts +1 -1
  47. package/dist/server/index.js +1 -1
  48. package/dist/server/marshal.d.ts +1 -0
  49. package/dist/server/marshal.js +13 -7
  50. package/dist/server/register.js +8 -6
  51. package/dist/tracking.d.ts +2 -0
  52. package/dist/tracking.js +13 -0
  53. package/package.json +6 -2
@@ -2,7 +2,7 @@ import * as ctypes from "node-ctypes";
2
2
  import { COMError, systemMessage } from "../errors.js";
3
3
  import { GUID_NULL } from "../guid.js";
4
4
  import { DISP_E_EXCEPTION, DISP_E_PARAMNOTFOUND, DISP_E_TYPEMISMATCH, DISP_E_UNKNOWNNAME } from "../hresult.js";
5
- import { POINTER_SIZE, takeBSTR } from "../low-level/native.js";
5
+ import { POINTER_SIZE, flushMirror, refreshMirror, takeBSTR } from "../low-level/native.js";
6
6
  import { DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF, DISPID_PROPERTYPUT, LOCALE_NEUTRAL } from "./constants.js";
7
7
  import { DISPPARAMS, EXCEPINFO } from "./types.js";
8
8
  import { ByRef, VARIANT, VARIANT_SIZE, byRefArgument, clearVariant, missing, readVariant, writeVariant } from "./variant.js";
@@ -14,7 +14,11 @@ export function setDefaultLCID(lcid) {
14
14
  defaultLCID = lcid >>> 0;
15
15
  }
16
16
  function wideStrings(values) {
17
- const keep = values.map((value) => Buffer.from(`${value}\0`, "utf16le"));
17
+ const keep = values.map((value) => {
18
+ const buffer = Buffer.from(`${value}\0`, "utf16le");
19
+ flushMirror(buffer);
20
+ return buffer;
21
+ });
18
22
  const pointers = Buffer.alloc(POINTER_SIZE * values.length);
19
23
  keep.forEach((buffer, index) => {
20
24
  const address = ctypes.addressof(buffer);
@@ -47,8 +51,10 @@ export function getIDsOfNames(dispatch, names, lcid = defaultLCID) {
47
51
  }
48
52
  const DeferredFillIn = ctypes.WINFUNCTYPE(ctypes.c_int32, ctypes.c_void_p);
49
53
  function exceptionError(info, method, cause) {
50
- if (info.pfnDeferredFillIn)
54
+ if (info.pfnDeferredFillIn) {
51
55
  DeferredFillIn(info.pfnDeferredFillIn)(info._buffer);
56
+ refreshMirror(info._buffer);
57
+ }
52
58
  const source = takeBSTR(info.bstrSource);
53
59
  // Some servers (e.g. the Scripting runtime) set only the scode.
54
60
  const description = takeBSTR(info.bstrDescription) || (info.scode ? systemMessage(info.scode) : null);
@@ -77,6 +83,7 @@ function prepareInvoke(dispid, flags, args, options) {
77
83
  const variants = Buffer.alloc(VARIANT_SIZE * count);
78
84
  const dispids = Buffer.alloc(4 * namedDispids.length);
79
85
  namedDispids.forEach((id, index) => dispids.writeInt32LE(id, index * 4));
86
+ flushMirror(dispids);
80
87
  const method = `IDispatch::Invoke(${options.name ?? `DISPID ${dispid}`})`;
81
88
  const result = new VARIANT();
82
89
  const info = new EXCEPINFO();
@@ -6,6 +6,7 @@ import { IUnknown } from "../interfaces/unknown.js";
6
6
  import { oleaut32, POINTER_SIZE, takeBSTR } from "../low-level/native.js";
7
7
  import { functionCache, vtableEntry } from "../low-level/vtable.js";
8
8
  import { COMPointer } from "../pointer.js";
9
+ import { onApartmentTeardown } from "../tracking.js";
9
10
  import { recordTypeInfoOf } from "../typelib/coclass.js";
10
11
  import { VARIANT_SIZE, clearVariant, readVariant, writeVariant } from "./variant.js";
11
12
  // User-defined types (VT_RECORD) through IRecordInfo, called by vtable slot
@@ -21,8 +22,9 @@ const CreateAt = functionCache(() => ctypes.WINFUNCTYPE(c_void_p, c_void_p));
21
22
  /** The `IRecordInfo` of a value read from a `VT_RECORD`, kept for writing it back. */
22
23
  export const recordInfo = Symbol.for("node-comtypes.recordInfo");
23
24
  // IRecordInfo address -> wrapper. Record infos are per type (oleaut32 caches
24
- // them), so this stays small; the pointers are released with the apartment.
25
+ // them), so this stays small; cleared on apartment teardown before CoUninitialize.
25
26
  const shared = new Map();
27
+ onApartmentTeardown(() => shared.clear());
26
28
  /** A user-defined type described by `IRecordInfo`. */
27
29
  export class RecordInfo {
28
30
  /** Owned `IRecordInfo` reference. */
@@ -118,10 +118,10 @@ export declare class VARIANT extends ctypes.Structure {
118
118
  wReserved2: number;
119
119
  wReserved3: number;
120
120
  /**
121
- * `new VARIANT(value)` converts `value`. As for any node-ctypes structure, a
122
- * `Buffer` (or a plain object of fields) is wrapped instead: node-ctypes
123
- * builds views (`from_address`, callback arguments) this way. Use
124
- * {@link VARIANT.from} to convert a `Buffer` into a `VT_ARRAY | VT_UI1`.
121
+ * `new VARIANT(value)` converts `value`. A `Buffer` is wrapped instead (a
122
+ * view of its bytes, as `VARIANT.from_buffer`), and a plain object of fields
123
+ * initializes the structure. Use {@link VARIANT.from} to convert a `Buffer`
124
+ * into a `VT_ARRAY | VT_UI1`.
125
125
  */
126
126
  constructor(value?: unknown);
127
127
  /** A new VARIANT holding `value`, whatever its type (`Buffer` included). */
@@ -3,6 +3,7 @@ import { checkHRESULT } from "../errors.js";
3
3
  import { GUID } from "../guid.js";
4
4
  import { DISP_E_PARAMNOTFOUND } from "../hresult.js";
5
5
  import { derivesFrom, findInterface } from "../interface.js";
6
+ import { IID_IDispatch, IID_IUnknown } from "../low-level/iids.js";
6
7
  import { allocBSTR, flushMirror, oleaut32, POINTER_SIZE, readBSTR, readMemory, refreshMirror, writeMemory } from "../low-level/native.js";
7
8
  import { rawAddRef, rawQueryInterface, rawRelease } from "../low-level/vtable.js";
8
9
  import { RecordInfo, recordParts } from "./record.js";
@@ -14,8 +15,6 @@ import { currencyToString, readDecimal, writeDecimal } from "./decimal.js";
14
15
  /** Size of a VARIANT: 16 bytes on 32-bit Windows, 24 on 64-bit. */
15
16
  export const VARIANT_SIZE = 8 + 2 * POINTER_SIZE;
16
17
  const DATA = 8;
17
- const IID_IUnknown = new GUID("{00000000-0000-0000-C000-000000000046}");
18
- const IID_IDispatch = new GUID("{00020400-0000-0000-C000-000000000046}");
19
18
  /**
20
19
  * Objects exposing a COM pointer under this symbol (e.g. dynamic dispatch
21
20
  * proxies) are converted like that pointer.
@@ -316,9 +315,65 @@ export function readSafeArray(psa, vtHint = VT_VARIANT) {
316
315
  finally {
317
316
  api.SafeArrayUnaccessData(psa);
318
317
  }
318
+ if (dimensions <= 1) {
319
+ const length = lengths[0] ?? 0;
320
+ if (records)
321
+ return records;
322
+ const out = new Array(length);
323
+ switch (vt) {
324
+ case VT_UI1:
325
+ for (let i = 0; i < length; i++)
326
+ out[i] = bytes[i];
327
+ return out;
328
+ case VT_I1:
329
+ for (let i = 0; i < length; i++)
330
+ out[i] = bytes.readInt8(i);
331
+ return out;
332
+ case VT_I2:
333
+ for (let i = 0; i < length; i++)
334
+ out[i] = bytes.readInt16LE(i * 2);
335
+ return out;
336
+ case VT_UI2:
337
+ for (let i = 0; i < length; i++)
338
+ out[i] = bytes.readUInt16LE(i * 2);
339
+ return out;
340
+ case VT_I4:
341
+ case VT_INT:
342
+ for (let i = 0; i < length; i++)
343
+ out[i] = bytes.readInt32LE(i * 4);
344
+ return out;
345
+ case VT_UI4:
346
+ case VT_UINT:
347
+ for (let i = 0; i < length; i++)
348
+ out[i] = bytes.readUInt32LE(i * 4);
349
+ return out;
350
+ case VT_R4:
351
+ for (let i = 0; i < length; i++)
352
+ out[i] = bytes.readFloatLE(i * 4);
353
+ return out;
354
+ case VT_R8:
355
+ for (let i = 0; i < length; i++)
356
+ out[i] = bytes.readDoubleLE(i * 8);
357
+ return out;
358
+ case VT_I8:
359
+ for (let i = 0; i < length; i++)
360
+ out[i] = bytes.readBigInt64LE(i * 8);
361
+ return out;
362
+ case VT_UI8:
363
+ for (let i = 0; i < length; i++)
364
+ out[i] = bytes.readBigUInt64LE(i * 8);
365
+ return out;
366
+ case VT_BOOL:
367
+ for (let i = 0; i < length; i++)
368
+ out[i] = bytes.readInt16LE(i * 2) !== 0;
369
+ return out;
370
+ default:
371
+ for (let i = 0; i < length; i++)
372
+ out[i] = readScalar(vt, bytes, i * size);
373
+ return out;
374
+ }
375
+ }
319
376
  const element = (index) => (records ? records[index] : readScalar(vt, bytes, index * size));
320
- if (dimensions <= 1)
321
- return Array.from({ length: lengths[0] ?? 0 }, (_, index) => element(index));
322
377
  // Column-major storage: the first index varies fastest.
323
378
  const build = (dimension, base, stride) => {
324
379
  const length = lengths[dimension];
@@ -598,29 +653,34 @@ export function createSafeArray(vt, values, dimensions = 1) {
598
653
  throw new TypeError(`SafeArrayCreate failed for ${vartypeName(VT_ARRAY | vt)}`);
599
654
  const size = elementSize(vt);
600
655
  const count = shape.reduce((total, length) => total * length, 1);
601
- const data = Buffer.alloc(count * size);
602
656
  const target = new ctypes.c_void_p();
603
657
  checkHRESULT(api.SafeArrayAccessData(psa, ctypes.byref(target)), "SafeArrayAccessData");
604
- let filled = false;
605
- try {
606
- if (dimensions === 1 && ArrayBuffer.isView(values) && typedArrayVartype(values) === vt) {
607
- data.set(new Uint8Array(values.buffer, values.byteOffset, values.byteLength));
658
+ // Fast path: 1-D TypedArray with matching VARTYPE copies directly into SAFEARRAY memory (zero intermediate Buffer).
659
+ if (dimensions === 1 && ArrayBuffer.isView(values) && typedArrayVartype(values) === vt) {
660
+ try {
661
+ writeMemory(target.value ?? 0n, new Uint8Array(values.buffer, values.byteOffset, values.byteLength));
608
662
  }
609
- else {
610
- // Column-major storage: the first index varies fastest.
611
- const fill = (level, dimension, base, stride) => {
612
- if (!isList(level) || level.length !== shape[dimension])
613
- throw new TypeError("SAFEARRAY values must be rectangular");
614
- for (let index = 0; index < level.length; index++) {
615
- const flat = base + index * stride;
616
- if (dimension === dimensions - 1)
617
- writeScalar(vt, data, flat * size, level[index]);
618
- else
619
- fill(level[index], dimension + 1, flat, stride * shape[dimension]);
620
- }
621
- };
622
- fill(values, 0, 0, 1);
663
+ finally {
664
+ api.SafeArrayUnaccessData(psa);
623
665
  }
666
+ return psa;
667
+ }
668
+ const data = Buffer.alloc(count * size);
669
+ let filled = false;
670
+ try {
671
+ // Column-major storage: the first index varies fastest.
672
+ const fill = (level, dimension, base, stride) => {
673
+ if (!isList(level) || level.length !== shape[dimension])
674
+ throw new TypeError("SAFEARRAY values must be rectangular");
675
+ for (let index = 0; index < level.length; index++) {
676
+ const flat = base + index * stride;
677
+ if (dimension === dimensions - 1)
678
+ writeScalar(vt, data, flat * size, level[index]);
679
+ else
680
+ fill(level[index], dimension + 1, flat, stride * shape[dimension]);
681
+ }
682
+ };
683
+ fill(values, 0, 0, 1);
624
684
  filled = true;
625
685
  }
626
686
  finally {
@@ -717,13 +777,17 @@ export class VARIANT extends ctypes.Structure {
717
777
  ["data", ctypes.array(ctypes.c_uint64, POINTER_SIZE === 8 ? 2 : 1)],
718
778
  ];
719
779
  /**
720
- * `new VARIANT(value)` converts `value`. As for any node-ctypes structure, a
721
- * `Buffer` (or a plain object of fields) is wrapped instead: node-ctypes
722
- * builds views (`from_address`, callback arguments) this way. Use
723
- * {@link VARIANT.from} to convert a `Buffer` into a `VT_ARRAY | VT_UI1`.
780
+ * `new VARIANT(value)` converts `value`. A `Buffer` is wrapped instead (a
781
+ * view of its bytes, as `VARIANT.from_buffer`), and a plain object of fields
782
+ * initializes the structure. Use {@link VARIANT.from} to convert a `Buffer`
783
+ * into a `VT_ARRAY | VT_UI1`.
724
784
  */
725
785
  constructor(value) {
726
- if (Buffer.isBuffer(value) || (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype && !recordParts(value))) {
786
+ if (Buffer.isBuffer(value)) {
787
+ // node-ctypes (as CPython) reads a positional Buffer as a field value: build the view explicitly.
788
+ return VARIANT.from_buffer(value);
789
+ }
790
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype && !recordParts(value)) {
727
791
  super(value);
728
792
  return;
729
793
  }
@@ -771,6 +835,7 @@ export class VARIANT extends ctypes.Structure {
771
835
  copy() {
772
836
  const copy = new VARIANT();
773
837
  checkHRESULT(oleaut32().VariantCopy(copy._buffer, this._buffer), "VariantCopy");
838
+ refreshMirror(copy._buffer);
774
839
  return copy;
775
840
  }
776
841
  [Symbol.dispose]() {
@@ -174,25 +174,24 @@ function isObject(value) {
174
174
  function getMember(current, name, synchronous) {
175
175
  const dispid = dispidOf(current, name);
176
176
  const member = memberOf(current, dispid);
177
- const syncCaller = (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
178
- // Methods run on the COM executor (synchronously on a sync() view).
179
- const caller = synchronous ? syncCaller : (...args) => callAsync(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
180
177
  if (member) {
181
178
  if (member.get && member.getArguments === 0)
182
179
  return call(current, name, dispid, DISPATCH_PROPERTYGET, []);
183
- if (member.method)
184
- return caller;
180
+ if (member.method) {
181
+ return synchronous ? (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args) : (...args) => callAsync(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
182
+ }
185
183
  // A parameterized property: read synchronously.
186
184
  if (member.get)
187
- return syncCaller;
185
+ return (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
188
186
  return undefined;
189
187
  }
190
188
  try {
191
189
  return call(current, name, dispid, DISPATCH_PROPERTYGET, []);
192
190
  }
193
191
  catch (error) {
194
- if (error instanceof COMError && BAD_CONTEXT.has(error.hresult))
195
- return caller;
192
+ if (error instanceof COMError && BAD_CONTEXT.has(error.hresult)) {
193
+ return synchronous ? (...args) => call(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args) : (...args) => callAsync(current, name, dispid, DISPATCH_METHOD | DISPATCH_PROPERTYGET, args);
194
+ }
196
195
  throw error;
197
196
  }
198
197
  }
@@ -64,6 +64,7 @@ import { IDispatch } from "../interfaces/dispatch.js";
64
64
  import { IProvideClassInfo, ITypeInfo, ITypeLib } from "../interfaces/typeinfo.js";
65
65
  import { IUnknown } from "../interfaces/unknown.js";
66
66
  import { COMPointer, sync } from "../pointer.js";
67
+ import { onApartmentTeardown } from "../tracking.js";
67
68
  import { COMObject } from "../server/comobject.js";
68
69
  function sourcePointer(source) {
69
70
  const borrowed = borrowReference(source);
@@ -268,6 +269,17 @@ function sinkClassFor(definition) {
268
269
  sinkClasses.set(definition, type);
269
270
  return type;
270
271
  }
272
+ const activeConnections = new Set();
273
+ onApartmentTeardown(() => {
274
+ for (const disconnect of [...activeConnections]) {
275
+ try {
276
+ disconnect();
277
+ }
278
+ catch {
279
+ // Keep tearing down remaining connections.
280
+ }
281
+ }
282
+ });
271
283
  /**
272
284
  * Connect `handler` to the events of `source`. Python equivalent:
273
285
  * `comtypes.client.GetEvents`.
@@ -302,13 +314,17 @@ export function GetEvents(source, handler, options = {}) {
302
314
  if (!connected)
303
315
  return;
304
316
  connected = false;
317
+ activeConnections.delete(disconnect);
305
318
  try {
306
- sync(point).Unadvise(cookie);
319
+ if (!point.released)
320
+ sync(point).Unadvise(cookie);
307
321
  }
308
322
  finally {
309
- point.Release();
323
+ if (!point.released)
324
+ point.Release();
310
325
  }
311
326
  };
327
+ activeConnections.add(disconnect);
312
328
  return {
313
329
  cookie,
314
330
  interface: definition,
@@ -61,7 +61,7 @@ import { GUID } from "../guid.js";
61
61
  import { E_POINTER } from "../hresult.js";
62
62
  import { IDispatch } from "../interfaces/dispatch.js";
63
63
  import { IUnknown } from "../interfaces/unknown.js";
64
- import { ole32, oleaut32 } from "../low-level/native.js";
64
+ import { flushMirror, ole32, oleaut32 } from "../low-level/native.js";
65
65
  import { COSERVERINFO, MULTI_QI } from "../low-level/types.js";
66
66
  import { COMPointer, sync as syncPointer } from "../pointer.js";
67
67
  import { CoCreateInstance, CoCreateInstanceEx } from "../runtime.js";
@@ -168,8 +168,10 @@ function obtainHome(method, call) {
168
168
  /** `CoCreateInstanceEx` for `IUnknown` on the executor (remote machines). */
169
169
  function createInstanceEx(target, clsid, clsctx, machine, out) {
170
170
  const name = ctypes.create_unicode_buffer(machine);
171
+ flushMirror(name);
171
172
  const server = new COSERVERINFO();
172
173
  server.pwszName = ctypes.addressof(name);
174
+ flushMirror(IUnknown.iid._buffer);
173
175
  const result = new MULTI_QI();
174
176
  result.pIID = ctypes.addressof(IUnknown.iid);
175
177
  return ole32()
@@ -167,7 +167,7 @@ export type ParamKind = {
167
167
  readonly kind: "variant";
168
168
  } | {
169
169
  readonly kind: "struct";
170
- readonly type: new (...args: any[]) => ctypes.Structure;
170
+ readonly type: new (...args: any[]) => ctypes.CDataAggregate;
171
171
  } | {
172
172
  readonly kind: "simple";
173
173
  readonly type: ctypes.SimpleCDataConstructor;
package/dist/commethod.js CHANGED
@@ -8,7 +8,7 @@ import { Typed, VARIANT, borrowReference, comPointer, comReference, createSafeAr
8
8
  import { checkHRESULT } from "./errors.js";
9
9
  import { GUID, toGUID } from "./guid.js";
10
10
  import { HRESULT, derivesFrom } from "./interface.js";
11
- import { allocBSTR, ole32, oleaut32, readBSTR, takeCoTaskMemString } from "./low-level/native.js";
11
+ import { allocBSTR, flushMirror, isAggregateClass, isPointerType, ole32, oleaut32, readBSTR, refreshMirror, takeCoTaskMemString } from "./low-level/native.js";
12
12
  import { rawAddRef, rawQueryInterface, rawRelease } from "./low-level/vtable.js";
13
13
  import { COMPointer } from "./pointer.js";
14
14
  export const BSTR = Object.freeze({ __comtype: "BSTR" });
@@ -40,15 +40,9 @@ export function helpstring(text) {
40
40
  function isInterfaceDef(type) {
41
41
  return typeof type === "object" && type !== null && "Pointer" in type && "iid" in type && "slots" in type;
42
42
  }
43
- function isStructureClass(type) {
44
- return typeof type === "function" && type.prototype instanceof ctypes.Structure;
45
- }
46
43
  function isSimpleType(type) {
47
44
  return typeof type === "function" && type._isSimpleCData === true;
48
45
  }
49
- function isPointerType(type) {
50
- return typeof type === "object" && type !== null && "_type_" in type && "_pointerTo" in type;
51
- }
52
46
  function pointerHolder(arg, read, release, initial = null) {
53
47
  const out = new ctypes.c_void_p(initial ?? 0n);
54
48
  let consumed = false;
@@ -246,9 +240,20 @@ function structureCodec(type) {
246
240
  input: make,
247
241
  output(initial, hasInitial) {
248
242
  const holder = new type();
249
- if (hasInitial && initial !== undefined)
250
- holder._buffer.set(make(initial)._buffer);
251
- return { arg: holder._buffer, read: () => holder, free: () => undefined };
243
+ if (hasInitial && initial !== undefined) {
244
+ const src = make(initial);
245
+ refreshMirror(src._buffer);
246
+ holder._buffer.set(src._buffer);
247
+ flushMirror(holder._buffer);
248
+ }
249
+ return {
250
+ arg: holder._buffer,
251
+ read: () => {
252
+ refreshMirror(holder._buffer);
253
+ return holder;
254
+ },
255
+ free: () => undefined,
256
+ };
252
257
  },
253
258
  };
254
259
  }
@@ -274,7 +279,7 @@ function isRawPointerValue(value) {
274
279
  /** `POINTER(T)` input: raw pointers pass through, plain values are copied to a temporary `T`. */
275
280
  function pointerCodec(type) {
276
281
  const base = type._type_;
277
- const target = base === VARIANT || isSimpleType(base) || isStructureClass(base) ? codecFor(base) : null;
282
+ const target = base === VARIANT || isSimpleType(base) || isAggregateClass(base) ? codecFor(base) : null;
278
283
  return {
279
284
  ffi: type,
280
285
  input(value, cleanup, self) {
@@ -319,7 +324,7 @@ export function classifyParamType(type) {
319
324
  return { kind: "variant" };
320
325
  if (isInterfaceDef(type))
321
326
  return { kind: "interface", iface: type };
322
- if (isStructureClass(type))
327
+ if (isAggregateClass(type))
323
328
  return { kind: "struct", type };
324
329
  if (isSimpleType(type))
325
330
  return { kind: "simple", type };
@@ -420,6 +425,7 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
420
425
  defaultValue: spec[3],
421
426
  });
422
427
  });
428
+ const paramKinds = infos.map((info) => (info.lcid ? null : classifyParamType(info.type)));
423
429
  const codecs = infos.map((info) => {
424
430
  if (info.lcid)
425
431
  return lcidCodec;
@@ -432,6 +438,30 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
432
438
  const inputs = infos.filter((info) => info.input);
433
439
  const required = inputs.filter((info) => !info.optional).length;
434
440
  const hasOutputs = infos.some((info) => info.output);
441
+ const lowerNames = infos.map((info) => info.name.toLowerCase());
442
+ const validInputNames = new Set(inputs.map((info) => info.name.toLowerCase()));
443
+ const hasInterfaceOutputs = infos.some((info, index) => {
444
+ if (!info.output)
445
+ return false;
446
+ const k = paramKinds[index];
447
+ if (!k)
448
+ return false;
449
+ if (k.kind === "interface" || k.kind === "variant" || k.kind === "safearray")
450
+ return true;
451
+ return k.kind === "pointer" && (k.base.kind === "interface" || k.base.kind === "variant" || k.base.kind === "safearray");
452
+ });
453
+ // Fast-path eligibility:
454
+ // 1) Zero-param method (`Ping()`, `Invoke()`, `Close()`): no allocation at all.
455
+ const isZeroParam = infos.length === 0;
456
+ // 2) Pure positional simple-scalar inputs with a single trailing pure-out simple scalar (`Add(a, b) -> int32`).
457
+ const singleOutSimpleType = !isZeroParam &&
458
+ infos.length >= 1 &&
459
+ infos[infos.length - 1].output &&
460
+ !infos[infos.length - 1].input &&
461
+ paramKinds[infos.length - 1]?.kind === "simple" &&
462
+ infos.slice(0, -1).every((info, i) => info.input && !info.output && !info.lcid && paramKinds[i]?.kind === "simple")
463
+ ? paramKinds[infos.length - 1].type
464
+ : null;
435
465
  // Converts the arguments; on failure, releases what was already converted.
436
466
  const prepare = (args, self) => {
437
467
  let positional = args;
@@ -439,17 +469,21 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
439
469
  const last = args[args.length - 1];
440
470
  if (last instanceof NamedArguments) {
441
471
  positional = args.slice(0, -1);
442
- byName = new Map(Object.entries(last.values).map(([key, value]) => [key.toLowerCase(), value]));
443
- for (const key of byName.keys())
444
- if (!inputs.some((info) => info.name.toLowerCase() === key))
445
- throw new TypeError(`${name}: unknown argument ${JSON.stringify(key)}`);
472
+ byName = new Map();
473
+ for (const [key, value] of Object.entries(last.values)) {
474
+ const lower = key.toLowerCase();
475
+ if (!validInputNames.has(lower))
476
+ throw new TypeError(`${name}: unknown argument ${JSON.stringify(lower)}`);
477
+ byName.set(lower, value);
478
+ }
446
479
  }
447
480
  if (positional.length > inputs.length)
448
481
  throw new TypeError(`${name}: expected at most ${inputs.length} arguments, got ${positional.length}`);
449
- const prepared = { native: [], holders: [], cleanup: [] };
482
+ const prepared = { native: new Array(infos.length), holders: [], cleanup: [] };
450
483
  try {
451
484
  let position = 0;
452
- infos.forEach((info, index) => {
485
+ for (let index = 0; index < infos.length; index++) {
486
+ const info = infos[index];
453
487
  const codec = codecs[index];
454
488
  let value;
455
489
  let supplied = false;
@@ -457,8 +491,8 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
457
491
  if (position < positional.length)
458
492
  value = positional[position];
459
493
  position++;
460
- if (value === undefined && byName?.has(info.name.toLowerCase()))
461
- value = byName.get(info.name.toLowerCase());
494
+ if (value === undefined && byName !== null && byName.has(lowerNames[index]))
495
+ value = byName.get(lowerNames[index]);
462
496
  supplied = value !== undefined;
463
497
  if (!supplied && info.hasDefault) {
464
498
  value = info.defaultValue;
@@ -470,12 +504,12 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
470
504
  if (info.output) {
471
505
  const holder = codec.output(value, info.input && supplied, self);
472
506
  prepared.holders.push(holder);
473
- prepared.native.push(holder.arg);
507
+ prepared.native[index] = holder.arg;
474
508
  }
475
509
  else {
476
- prepared.native.push(codec.input(value, prepared.cleanup, self));
510
+ prepared.native[index] = codec.input(value, prepared.cleanup, self);
477
511
  }
478
- });
512
+ }
479
513
  return prepared;
480
514
  }
481
515
  catch (error) {
@@ -486,49 +520,109 @@ export function COMMETHOD(idlflags, restype, name, ...params) {
486
520
  const finish = (prepared, result) => {
487
521
  if (!hasOutputs)
488
522
  return result;
489
- const values = prepared.holders.map((holder) => wrapOutput(holder.read()));
490
- return values.length === 1 ? values[0] : values;
523
+ const holders = prepared.holders;
524
+ if (holders.length === 1)
525
+ return wrapOutput(holders[0].read());
526
+ return holders.map((holder) => wrapOutput(holder.read()));
491
527
  };
492
- const marshal = (fn, address, args, self) => {
493
- const prepared = prepare(args, self);
494
- try {
495
- return finish(prepared, fn(address, ...prepared.native));
496
- }
497
- finally {
498
- release(prepared);
528
+ const EMPTY_ARGS = Object.freeze([]);
529
+ const EMPTY_RESULTS = Object.freeze([]);
530
+ const marshal = isZeroParam
531
+ ? (fn, address, args) => {
532
+ if (args.length === 0)
533
+ return fn(address);
534
+ const prepared = prepare(args, null);
535
+ try {
536
+ return fn(address, ...prepared.native);
537
+ }
538
+ finally {
539
+ release(prepared);
540
+ }
499
541
  }
500
- };
542
+ : singleOutSimpleType
543
+ ? (fn, address, args, self) => {
544
+ if (args.length === inputs.length && (args.length === 0 || !(args[args.length - 1] instanceof NamedArguments))) {
545
+ let allDefined = true;
546
+ for (let i = 0; i < args.length; i++) {
547
+ if (args[i] === undefined) {
548
+ allDefined = false;
549
+ break;
550
+ }
551
+ }
552
+ if (allDefined) {
553
+ const out = new singleOutSimpleType();
554
+ const ref = ctypes.byref(out);
555
+ if (args.length === 0)
556
+ fn(address, ref);
557
+ else if (args.length === 1)
558
+ fn(address, args[0], ref);
559
+ else if (args.length === 2)
560
+ fn(address, args[0], args[1], ref);
561
+ else
562
+ fn(address, ...args, ref);
563
+ return wrapOutput(out.value);
564
+ }
565
+ }
566
+ const prepared = prepare(args, self);
567
+ try {
568
+ return finish(prepared, fn(address, ...prepared.native));
569
+ }
570
+ finally {
571
+ release(prepared);
572
+ }
573
+ }
574
+ : (fn, address, args, self) => {
575
+ const prepared = prepare(args, self);
576
+ try {
577
+ return finish(prepared, fn(address, ...prepared.native));
578
+ }
579
+ finally {
580
+ release(prepared);
581
+ }
582
+ };
501
583
  // The converted arguments stay alive (and owned here) until the call completes.
502
584
  // Promise steps instead of an async function: this runs for every method call.
503
- const marshalAsync = (run, args, self) => {
504
- let prepared;
505
- let pending;
506
- try {
507
- prepared = prepare(args, self);
508
- }
509
- catch (error) {
510
- return Promise.reject(error);
511
- }
512
- try {
513
- const results = prepared.holders.flatMap((holder) => (holder.result ? [{ location: ctypes.addressof(holder.arg), ...holder.result }] : []));
514
- pending = run(prepared.native, results);
515
- }
516
- catch (error) {
517
- release(prepared);
518
- return Promise.reject(error);
585
+ const marshalAsync = isZeroParam
586
+ ? (run, args) => {
587
+ if (args.length === 0)
588
+ return run(EMPTY_ARGS, EMPTY_RESULTS);
589
+ try {
590
+ prepare(args, null);
591
+ }
592
+ catch (error) {
593
+ return Promise.reject(error);
594
+ }
595
+ return run(EMPTY_ARGS, EMPTY_RESULTS);
519
596
  }
520
- return pending.then((value) => {
597
+ : (run, args, self) => {
598
+ let prepared;
599
+ let pending;
521
600
  try {
522
- return finish(prepared, value);
601
+ prepared = prepare(args, self);
523
602
  }
524
- finally {
603
+ catch (error) {
604
+ return Promise.reject(error);
605
+ }
606
+ try {
607
+ const results = hasInterfaceOutputs ? prepared.holders.flatMap((holder) => (holder.result ? [{ location: ctypes.addressof(holder.arg), ...holder.result }] : [])) : EMPTY_RESULTS;
608
+ pending = run(prepared.native, results);
609
+ }
610
+ catch (error) {
525
611
  release(prepared);
612
+ return Promise.reject(error);
526
613
  }
527
- }, (error) => {
528
- release(prepared);
529
- throw error;
530
- });
531
- };
614
+ return pending.then((value) => {
615
+ try {
616
+ return finish(prepared, value);
617
+ }
618
+ finally {
619
+ release(prepared);
620
+ }
621
+ }, (error) => {
622
+ release(prepared);
623
+ throw error;
624
+ });
625
+ };
532
626
  const methodName = kind === "propget" ? `_get_${name}` : kind === "propput" ? `_set_${name}` : kind === "propputref" ? `_setref_${name}` : name;
533
627
  return Object.freeze({
534
628
  name: methodName,