@node-ctypes/comtypes 0.3.0 → 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 (54) 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 +102 -29
  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 +15 -10
  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/interfaces/typeinfo.js +3 -0
  29. package/dist/low-level/iids.d.ts +14 -0
  30. package/dist/low-level/iids.js +14 -0
  31. package/dist/low-level/index.d.ts +2 -2
  32. package/dist/low-level/index.js +1 -1
  33. package/dist/low-level/native.d.ts +23 -0
  34. package/dist/low-level/native.js +53 -0
  35. package/dist/low-level/registry.js +4 -2
  36. package/dist/low-level/vtable.d.ts +10 -0
  37. package/dist/low-level/vtable.js +32 -5
  38. package/dist/pointer.d.ts +2 -0
  39. package/dist/pointer.js +154 -84
  40. package/dist/pump.d.ts +32 -8
  41. package/dist/pump.js +87 -15
  42. package/dist/runtime.d.ts +6 -0
  43. package/dist/runtime.js +15 -1
  44. package/dist/server/automation.js +3 -3
  45. package/dist/server/comobject.d.ts +53 -0
  46. package/dist/server/comobject.js +319 -27
  47. package/dist/server/index.d.ts +1 -1
  48. package/dist/server/index.js +1 -1
  49. package/dist/server/marshal.d.ts +1 -0
  50. package/dist/server/marshal.js +16 -8
  51. package/dist/server/register.js +8 -6
  52. package/dist/tracking.d.ts +2 -0
  53. package/dist/tracking.js +13 -0
  54. package/package.json +6 -2
package/dist/pump.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import * as ctypes from "node-ctypes";
2
- import { setTimeout as delay } from "node:timers/promises";
3
2
  import { checkHRESULT } from "./errors.js";
4
3
  import { ole32 } from "./low-level/native.js";
5
4
  // The Node.js event loop does not dispatch Win32 messages. Single-threaded
6
5
  // apartments receive cross-apartment and cross-process calls, and many event
7
6
  // sources fire events, through window messages: they need a message pump.
8
7
  const PM_REMOVE = 0x1;
8
+ const QS_ALLINPUT = 0x04ff;
9
+ const MWMO_INPUTAVAILABLE = 0x0004;
9
10
  const COWAIT_DISPATCH_CALLS = 0x8;
10
11
  const COWAIT_DISPATCH_WINDOW_MESSAGES = 0x10;
11
12
  const RPC_S_CALLPENDING = 0x80010115 | 0;
@@ -16,6 +17,7 @@ function bindUser32(library) {
16
17
  PeekMessageW: library.func("PeekMessageW", ctypes.c_int32, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]),
17
18
  TranslateMessage: library.func("TranslateMessage", ctypes.c_int32, [ctypes.c_void_p]),
18
19
  DispatchMessageW: library.func("DispatchMessageW", ctypes.c_void_p, [ctypes.c_void_p]),
20
+ MsgWaitForMultipleObjectsEx: library.func("MsgWaitForMultipleObjectsEx", ctypes.c_uint32, [ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]),
19
21
  };
20
22
  }
21
23
  function bindKernel32(library) {
@@ -30,19 +32,27 @@ function user32() {
30
32
  function kernel32() {
31
33
  return (kernel32Functions ??= bindKernel32(new ctypes.WinDLL("kernel32.dll")));
32
34
  }
33
- let message = null;
35
+ let msgSize = 0;
36
+ const msgPool = [];
34
37
  /**
35
38
  * Dispatch the messages waiting in the thread's queue, without blocking.
36
- * Returns how many were dispatched (at most `limit`).
39
+ * Returns how many were dispatched (at most `limit`). Re-entrant safe: nested
40
+ * `pumpMessages()` calls from inside `DispatchMessageW` use their own MSG buffer.
37
41
  */
38
42
  export function pumpMessages(limit = Number.POSITIVE_INFINITY) {
39
43
  const api = user32();
40
- const msg = (message ??= Buffer.alloc(ctypes.sizeof(ctypes.wintypes.MSG)));
44
+ const msg = msgPool.pop() ?? Buffer.alloc((msgSize ||= ctypes.sizeof(ctypes.wintypes.MSG)));
41
45
  let count = 0;
42
- while (count < limit && api.PeekMessageW(msg, null, 0, 0, PM_REMOVE)) {
43
- api.TranslateMessage(msg);
44
- api.DispatchMessageW(msg);
45
- count++;
46
+ try {
47
+ while (count < limit && api.PeekMessageW(msg, null, 0, 0, PM_REMOVE)) {
48
+ api.TranslateMessage(msg);
49
+ api.DispatchMessageW(msg);
50
+ count++;
51
+ }
52
+ }
53
+ finally {
54
+ if (msgPool.length < 4)
55
+ msgPool.push(msg);
46
56
  }
47
57
  return count;
48
58
  }
@@ -69,15 +79,69 @@ export function PumpEvents(milliseconds) {
69
79
  }
70
80
  }
71
81
  /**
72
- * Pump messages periodically from the event loop (`setInterval`, unref'd so
73
- * it does not keep the process alive). The JavaScript thread stays free between
74
- * ticks: use this for events and incoming calls while the program runs.
82
+ * Drain all queued Win32 messages, or if the queue is empty sleep in the
83
+ * Windows kernel via `MsgWaitForMultipleObjectsEx` (~0% CPU) until any input
84
+ * or COM STA message arrives or `timeoutMs` elapses, then drain immediately.
85
+ */
86
+ export function waitAndPumpMessages(timeoutMs = 8, limit = Number.POSITIVE_INFINITY) {
87
+ let count = pumpMessages(limit);
88
+ if (count > 0)
89
+ return count;
90
+ const wait = user32().MsgWaitForMultipleObjectsEx(0, null, Math.max(0, Math.floor(timeoutMs)) >>> 0, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
91
+ if (wait === 0)
92
+ count += pumpMessages(limit);
93
+ return count;
94
+ }
95
+ /**
96
+ * Pump Win32 messages from the Node.js event loop.
97
+ *
98
+ * - Default (`mode: "interval"`): periodic unref'd `setInterval` — leaves the
99
+ * JS thread completely idle between ticks.
100
+ * - Low-latency (`mode: "wait"`): `MsgWaitForMultipleObjectsEx` + `setImmediate`
101
+ * — sub-millisecond wakeup for interactive UI / STA COM callbacks.
75
102
  */
76
103
  export function startMessagePump(options = {}) {
104
+ const mode = options.mode ?? "interval";
105
+ let running = true;
106
+ if (mode === "wait") {
107
+ const idleYieldMs = options.interval ?? 8;
108
+ const keepRef = options.ref ?? true;
109
+ let handle = null;
110
+ const step = () => {
111
+ handle = null;
112
+ if (!running)
113
+ return;
114
+ waitAndPumpMessages(idleYieldMs);
115
+ if (running) {
116
+ handle = setImmediate(step);
117
+ if (!keepRef)
118
+ handle.unref();
119
+ }
120
+ };
121
+ handle = setImmediate(step);
122
+ if (!keepRef)
123
+ handle.unref();
124
+ const stop = () => {
125
+ if (!running)
126
+ return;
127
+ running = false;
128
+ if (handle !== null) {
129
+ clearImmediate(handle);
130
+ handle = null;
131
+ }
132
+ };
133
+ return {
134
+ stop,
135
+ get running() {
136
+ return running;
137
+ },
138
+ [Symbol.dispose]: stop,
139
+ };
140
+ }
77
141
  const interval = options.interval ?? 10;
78
142
  const timer = setInterval(() => pumpMessages(), interval);
79
- timer.unref();
80
- let running = true;
143
+ if (!options.ref)
144
+ timer.unref();
81
145
  const stop = () => {
82
146
  if (!running)
83
147
  return;
@@ -94,16 +158,24 @@ export function startMessagePump(options = {}) {
94
158
  }
95
159
  /**
96
160
  * Pump messages until `condition()` holds or `timeout` elapses; resolves to
97
- * the last value of the condition. The event loop runs between checks.
161
+ * the last value of the condition. Uses `waitAndPumpMessages` so STA COM events
162
+ * wake immediately (< 0.1 ms) while still yielding to the Node.js event loop.
98
163
  */
99
164
  export async function waitFor(condition, options = {}) {
100
165
  const deadline = performance.now() + (options.timeout ?? 10_000);
166
+ const sliceMs = options.interval ?? 8;
101
167
  for (;;) {
102
168
  pumpMessages();
169
+ if (condition())
170
+ return true;
171
+ const remaining = deadline - performance.now();
172
+ if (remaining <= 0)
173
+ return false;
174
+ waitAndPumpMessages(Math.min(sliceMs, remaining));
103
175
  if (condition())
104
176
  return true;
105
177
  if (performance.now() >= deadline)
106
178
  return false;
107
- await delay(options.interval ?? 5);
179
+ await new Promise((resolve) => setImmediate(resolve));
108
180
  }
109
181
  }
package/dist/runtime.d.ts CHANGED
@@ -68,3 +68,9 @@ export declare function CoGetClassObject<T extends InterfaceDef = typeof IClassF
68
68
  export declare function CoTaskMemAlloc(size: number | bigint): bigint;
69
69
  export declare function CoTaskMemRealloc(pointer: bigint | null, size: number | bigint): bigint;
70
70
  export declare function CoTaskMemFree(pointer: bigint | null): void;
71
+ /**
72
+ * Create the aggregatable Windows Free-Threaded Marshaler (`CoCreateFreeThreadedMarshaler`).
73
+ * Returns the FTM's non-delegating `IUnknown` pointer; when aggregating into a
74
+ * `COMObject`, prefer {@link COMObject.enableFreeThreadedMarshaler}.
75
+ */
76
+ export declare function CoCreateFreeThreadedMarshaler(outer?: COMPointer | bigint | null): InterfacePointer<typeof IUnknown>;
package/dist/runtime.js CHANGED
@@ -5,7 +5,7 @@ import { toGUID } from "./guid.js";
5
5
  import { CO_E_NOTINITIALIZED, E_OUTOFMEMORY, E_POINTER } from "./hresult.js";
6
6
  import { IClassFactory } from "./interfaces/classfactory.js";
7
7
  import { IUnknown } from "./interfaces/unknown.js";
8
- import { ole32 } from "./low-level/native.js";
8
+ import { flushMirror, ole32 } from "./low-level/native.js";
9
9
  import { COSERVERINFO, MULTI_QI } from "./low-level/types.js";
10
10
  import { COMPointer } from "./pointer.js";
11
11
  import { initCount, initialized, liveCount, uninitializing } from "./tracking.js";
@@ -97,9 +97,12 @@ export function CoCreateInstance(clsid, iface, options = {}) {
97
97
  export function CoCreateInstanceEx(clsid, iface, options = {}) {
98
98
  const target = (iface ?? IUnknown);
99
99
  const machine = options.machine ? ctypes.create_unicode_buffer(options.machine) : null;
100
+ if (machine)
101
+ flushMirror(machine);
100
102
  const server = machine ? new COSERVERINFO() : null;
101
103
  if (server && machine)
102
104
  server.pwszName = ctypes.addressof(machine);
105
+ flushMirror(target.iid._buffer);
103
106
  const result = new MULTI_QI();
104
107
  result.pIID = ctypes.addressof(target.iid);
105
108
  const clsctx = options.clsctx ?? (machine ? CLSCTX_SERVER & ~CLSCTX_INPROC_SERVER : CLSCTX_SERVER);
@@ -134,6 +137,17 @@ export function CoTaskMemRealloc(pointer, size) {
134
137
  export function CoTaskMemFree(pointer) {
135
138
  ole32().CoTaskMemFree(pointer);
136
139
  }
140
+ /**
141
+ * Create the aggregatable Windows Free-Threaded Marshaler (`CoCreateFreeThreadedMarshaler`).
142
+ * Returns the FTM's non-delegating `IUnknown` pointer; when aggregating into a
143
+ * `COMObject`, prefer {@link COMObject.enableFreeThreadedMarshaler}.
144
+ */
145
+ export function CoCreateFreeThreadedMarshaler(outer = null) {
146
+ const outerAddress = outer === null ? null : typeof outer === "bigint" ? outer : outer.address;
147
+ const out = new ctypes.c_void_p();
148
+ checkHRESULT(ole32().CoCreateFreeThreadedMarshaler(outerAddress, ctypes.byref(out)), "CoCreateFreeThreadedMarshaler");
149
+ return COMPointer.fromAddress(nonNull(out.value, "CoCreateFreeThreadedMarshaler"), IUnknown);
150
+ }
137
151
  function nonNull(address, method) {
138
152
  if (!address)
139
153
  throw new COMError(E_POINTER, { method, text: `${method} returned a NULL interface pointer` });
@@ -8,7 +8,7 @@ import { DISP_E_BADPARAMCOUNT, DISP_E_EXCEPTION, DISP_E_MEMBERNOTFOUND, DISP_E_U
8
8
  import { derivesFrom } from "../interface.js";
9
9
  import { IDispatch } from "../interfaces/dispatch.js";
10
10
  import { IUnknown } from "../interfaces/unknown.js";
11
- import { allocBSTR, POINTER_SIZE, readMemory } from "../low-level/native.js";
11
+ import { allocBSTR, POINTER_SIZE, readMemory, writeMemory } from "../low-level/native.js";
12
12
  import { COMPointer } from "../pointer.js";
13
13
  import { COMObject, VariantEnumerator } from "./comobject.js";
14
14
  import { omittedToUndefined } from "./marshal.js";
@@ -202,12 +202,12 @@ function releaseIncoming(values) {
202
202
  }
203
203
  function fillException(pExcepInfo, object, error) {
204
204
  const type = object.constructor;
205
- const info = EXCEPINFO.from_address(pExcepInfo);
206
- info._buffer.fill(0);
205
+ const info = new EXCEPINFO();
207
206
  const description = error instanceof COMError ? (error.details?.description ?? error.text) : error instanceof Error ? error.message : String(error);
208
207
  info.bstrSource = allocBSTR(type._reg_progid_ ?? type.name);
209
208
  info.bstrDescription = allocBSTR(description);
210
209
  info.scode = error instanceof COMError && error.hresult < 0 ? error.hresult : E_FAIL;
210
+ writeMemory(pExcepInfo, info._buffer);
211
211
  }
212
212
  /**
213
213
  * `IDispatch::Invoke` for a `COMObject`: converts `DISPPARAMS`, calls
@@ -73,6 +73,42 @@ export declare class COMObject {
73
73
  /** Interfaces this object answers `QueryInterface` for (listed and implicit ones). */
74
74
  get interfaces(): readonly InterfaceDef<any>[];
75
75
  supportsInterface(iid: GUIDLike): boolean;
76
+ /**
77
+ * Native address of the vtable block implementing `iface` (default: primary
78
+ * interface block `[0]`, suitable as `outer` / `baseInterface` in COM or
79
+ * WinRT aggregation) without adding a reference.
80
+ */
81
+ addressOf(iface?: InterfaceDef<any>): bigint;
82
+ /**
83
+ * Attach an inner non-delegating `IUnknown` for COM / WinRT aggregation.
84
+ * Any `QueryInterface` for an IID not implemented or delegated by this
85
+ * object is forwarded to `inner`.
86
+ *
87
+ * - Passing a `COMPointer` takes its own `AddRef` (safe with `using inner`).
88
+ * - Passing a raw `bigint` adopts 1 reference by default (`own: true`); pass
89
+ * `{ own: false }` if the caller retains ownership.
90
+ * - Passing `null` detaches and releases the current owned inner object.
91
+ */
92
+ setAggregateInner(inner: COMPointer | bigint | null, options?: {
93
+ readonly own?: boolean;
94
+ }): void;
95
+ /**
96
+ * Delegate `QueryInterface(iface)` to `target`. Resolves `iface` once and
97
+ * caches the pointer so incoming native `QueryInterface` calls only `AddRef`.
98
+ */
99
+ delegateInterface(iface: InterfaceDef<any>, target: COMPointer | COMObject | bigint, options?: {
100
+ readonly own?: boolean;
101
+ }): void;
102
+ /** Remove a previously delegated interface and release its cached reference. */
103
+ undelegateInterface(iface: InterfaceDef<any>): void;
104
+ /**
105
+ * Aggregate the Windows Free-Threaded Marshaler (`CoCreateFreeThreadedMarshaler`)
106
+ * so `QueryInterface(IMarshal)` forwards to the FTM without creating reference
107
+ * cycles. Can be combined with {@link setAggregateInner}.
108
+ */
109
+ enableFreeThreadedMarshaler(): void;
110
+ /** Release the attached aggregate inner object, FTM, and all cached delegate references. */
111
+ releaseAggregate(): void;
76
112
  /** A new owned pointer to this object (`AddRef`); throws `E_NOINTERFACE`. */
77
113
  QueryInterface<T extends InterfaceDef<any>>(iface: T): InterfacePointer<T>;
78
114
  /** Native `AddRef`/`Release` for code managing references by hand. */
@@ -83,6 +119,8 @@ export declare class COMObject {
83
119
  /** Called when the native reference count drops to zero. Python: `_final_release_`. */
84
120
  _final_release_(): void;
85
121
  InterfaceSupportsErrorInfo(riid: GUID | null): number;
122
+ /** Return a weak reference (`IWeakReference`) to this `COMObject`. */
123
+ GetWeakReference(): WeakReference;
86
124
  GetTypeInfoCount(pctinfo: bigint | null): number;
87
125
  /** Type information of the first dispatch interface built from a type library (`GetModule`, generated modules). */
88
126
  GetTypeInfo(index: number, _lcid: number, ppTInfo: bigint | null): number;
@@ -176,8 +214,23 @@ export declare class ConnectionPoint extends COMObject {
176
214
  Advise(sink: COMPointer | null): number;
177
215
  Unadvise(cookie: number): void;
178
216
  EnumConnections(): never;
217
+ /** Disconnect and release every advised sink (called automatically when the container is released). */
218
+ disconnectAll(): void;
179
219
  _final_release_(): void;
180
220
  }
221
+ /**
222
+ * `IWeakReference` implementation for a JavaScript `COMObject`. Resolves to
223
+ * `null` (`S_OK` with `*objectReference = NULL`) once the target's native
224
+ * reference count drops to zero, matching COM/WinRT weak-reference semantics.
225
+ */
226
+ export declare class WeakReference extends COMObject {
227
+ #private;
228
+ static _com_interfaces_: import("../interface.ts").ComInterfaceDef<import("../interface.ts").ComInterfaceDef<undefined, readonly [MethodSpec<"QueryInterface", import("../interface.ts").RawFunction<ctypes.SimpleCDataConstructor<"int32"> & {
229
+ _isHResult: true;
230
+ }, readonly [ctypes.PointerTypeDef<typeof GUID>, ctypes.PointerTypeDef<ctypes.SimpleCDataConstructor<"pointer">>]>, "method", "QueryInterface">, MethodSpec<"AddRef", import("../interface.ts").RawFunction<ctypes.SimpleCDataConstructor<"uint32">, readonly []>, "method", "AddRef">, MethodSpec<"Release", import("../interface.ts").RawFunction<ctypes.SimpleCDataConstructor<"uint32">, readonly []>, "method", "Release">], readonly []>, readonly [], readonly []>[];
231
+ constructor(target: COMObject);
232
+ Resolve(riid: bigint | null, objectReference: bigint | null): number;
233
+ }
181
234
  /** `IClassFactory` creating instances of a `COMObject` class. */
182
235
  export declare class ClassFactory extends COMObject {
183
236
  static _com_interfaces_: import("../interface.ts").ComInterfaceDef<import("../interface.ts").ComInterfaceDef<undefined, readonly [MethodSpec<"QueryInterface", import("../interface.ts").RawFunction<ctypes.SimpleCDataConstructor<"int32"> & {