@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
package/dist/pointer.js CHANGED
@@ -6,9 +6,32 @@ import { executorAlive, executorCall, executorGeneration } from "./executor/exec
6
6
  import { operation } from "./executor/operations.js";
7
7
  import { GUID } from "./guid.js";
8
8
  import { E_NOINTERFACE } from "./hresult.js";
9
- import { functionCache, rawQueryInterface, rawRelease, vtableEntry } from "./low-level/vtable.js";
9
+ import { IID_IUnknown } from "./low-level/iids.js";
10
+ import { isAggregateClass, refreshMirror } from "./low-level/native.js";
11
+ import { functionCache, rawQueryInterface, rawRelease, vtableEntry, vtableEntryFromTable, vtableOf } from "./low-level/vtable.js";
10
12
  import { track, untrack } from "./tracking.js";
11
- const IID_IUnknown = new GUID("{00000000-0000-0000-C000-000000000046}");
13
+ const COM_POINTER_BRAND = Symbol.for("node-comtypes.COMPointer");
14
+ function isCOMPointer(value) {
15
+ return value instanceof COMPointer || (typeof value === "object" && value !== null && value[COM_POINTER_BRAND] === true);
16
+ }
17
+ const MAX_VTABLE_CACHES_PER_INTERFACE = 1024;
18
+ // Per-interface, per-vtable-pointer bound-slot cache shared across all COMPointer instances of a COM class.
19
+ const vtableMethodCaches = new WeakMap();
20
+ function vtableSlotsFor(iface, vtable) {
21
+ let byVtable = vtableMethodCaches.get(iface);
22
+ if (!byVtable)
23
+ vtableMethodCaches.set(iface, (byVtable = new Map()));
24
+ let slots = byVtable.get(vtable);
25
+ if (!slots) {
26
+ if (byVtable.size >= MAX_VTABLE_CACHES_PER_INTERFACE) {
27
+ const oldest = byVtable.keys().next().value;
28
+ if (oldest !== undefined)
29
+ byVtable.delete(oldest);
30
+ }
31
+ byVtable.set(vtable, (slots = []));
32
+ }
33
+ return slots;
34
+ }
12
35
  /**
13
36
  * Create the slot for `spec`, declared by interface `owner`. HRESULT methods
14
37
  * are bound with a `c_int32` restype and an errcheck raising {@link COMError},
@@ -17,22 +40,41 @@ const IID_IUnknown = new GUID("{00000000-0000-0000-C000-000000000046}");
17
40
  export function createSlot(spec, owner) {
18
41
  const label = `${owner.name}::${spec.name}`;
19
42
  const hresult = spec.restype === ctypes.HRESULT;
43
+ // MSVC C++ member-function ABI (x86/x64/ARM64): COM virtual methods returning
44
+ // a struct/union by value always receive a hidden return buffer pointer (`sret`)
45
+ // as the second argument right after `this`, even for 8-byte POD structs
46
+ // (e.g. Direct2D `GetSize()`, `GetPixelFormat()`, Direct3D `GetDesc()`).
47
+ const structReturn = !hresult && isAggregateClass(spec.restype) ? spec.restype : null;
20
48
  // IUnknown methods never set error info (and QueryInterface failures are common).
21
49
  const errorInfo = !owner.iid.equals(IID_IUnknown);
22
- const nativeRestype = hresult ? ctypes.c_int32 : spec.restype;
50
+ const nativeRestype = hresult ? ctypes.c_int32 : structReturn ? ctypes.c_void_p : spec.restype;
23
51
  // One array per slot: the executor caches its bindings by it.
24
- const nativeArgtypes = [ctypes.c_void_p, ...spec.argtypes];
25
- const cache = functionCache(() => ctypes.WINFUNCTYPE(nativeRestype, ctypes.c_void_p, ...spec.argtypes));
52
+ const nativeArgtypes = structReturn ? [ctypes.c_void_p, ctypes.c_void_p, ...spec.argtypes] : [ctypes.c_void_p, ...spec.argtypes];
53
+ const cache = functionCache(() => ctypes.WINFUNCTYPE(nativeRestype, ...nativeArgtypes));
26
54
  const errcheck = (result, _fn, args) => {
27
55
  if (result < 0)
28
- throw new COMError(result, { method: label, details: errorInfo ? errorInfoFor(args[0], owner.iid) : null });
56
+ throw new COMError(result, { method: label, details: errorInfo ? errorInfoFor(args[0], owner.iid, result) : null });
29
57
  return result;
30
58
  };
31
59
  const { marshal, marshalAsync } = spec;
60
+ const invokeStructSync = structReturn
61
+ ? (fn, address, nativeArgs) => {
62
+ const out = new structReturn();
63
+ fn(address, out._buffer, ...nativeArgs);
64
+ refreshMirror(out._buffer);
65
+ return out;
66
+ }
67
+ : null;
32
68
  return {
33
69
  spec,
34
70
  label,
35
- call: marshal ? (fn, address, args) => marshal(fn, address, args, owner.definition) : (fn, address, args) => fn(address, ...args),
71
+ call: invokeStructSync
72
+ ? marshal
73
+ ? (fn, address, args) => marshal((addr, ...nativeArgs) => invokeStructSync(fn, addr, nativeArgs), address, args, owner.definition)
74
+ : (fn, address, args) => invokeStructSync(fn, address, args)
75
+ : marshal
76
+ ? (fn, address, args) => marshal(fn, address, args, owner.definition)
77
+ : (fn, address, args) => fn(address, ...args),
36
78
  bind(address) {
37
79
  const fn = cache(address);
38
80
  if (hresult && fn.errcheck !== errcheck)
@@ -41,12 +83,21 @@ export function createSlot(spec, owner) {
41
83
  },
42
84
  callAsync(entry, target, args, context) {
43
85
  // Promise steps instead of an async function: this runs for every method call.
44
- const run = (native, results) => executorCall({ fn: entry, restype: nativeRestype, argtypes: nativeArgtypes, args: [target, ...native], ...(hresult && errorInfo ? { errorInfo: { object: target, iid: owner.iid } } : {}) }, { operation: context.operation }).then(({ value, details }) => {
45
- if (hresult && value < 0)
46
- throw new COMError(value, { method: label, details });
47
- const locations = context.results?.length ? [...results, ...context.results] : results;
48
- return context.handOver && locations.length ? handOver(locations).then(() => value) : value;
49
- });
86
+ const run = structReturn
87
+ ? (native, results) => {
88
+ const out = new structReturn();
89
+ return executorCall({ fn: entry, restype: nativeRestype, argtypes: nativeArgtypes, args: [target, out._buffer, ...native] }, { operation: context.operation }).then(() => {
90
+ refreshMirror(out._buffer);
91
+ const locations = context.results?.length ? [...results, ...context.results] : results;
92
+ return context.handOver && locations.length ? handOver(locations).then(() => out) : out;
93
+ });
94
+ }
95
+ : (native, results) => executorCall({ fn: entry, restype: nativeRestype, argtypes: nativeArgtypes, args: [target, ...native], ...(hresult && errorInfo ? { errorInfo: { object: target, iid: owner.iid } } : {}) }, { operation: context.operation }).then(({ value, details }) => {
96
+ if (hresult && value < 0)
97
+ throw new COMError(value, { method: label, details });
98
+ const locations = context.results?.length ? [...results, ...context.results] : results;
99
+ return context.handOver && locations.length ? handOver(locations).then(() => value) : value;
100
+ });
50
101
  return marshalAsync ? marshalAsync(run, args, owner.definition) : run(args, []);
51
102
  },
52
103
  };
@@ -97,7 +148,7 @@ export function sharedWithExecutor(pointer) {
97
148
  * handlers, COM servers and code that needs the lowest latency.
98
149
  */
99
150
  export function sync(pointer) {
100
- if (!(pointer instanceof COMPointer))
151
+ if (!isCOMPointer(pointer))
101
152
  throw new TypeError("sync() expects a COM pointer");
102
153
  return createView(pointer);
103
154
  }
@@ -116,10 +167,12 @@ let viewOf = null;
116
167
  * or {@link COMPointer.fromAddress}.
117
168
  */
118
169
  export class COMPointer {
170
+ [COM_POINTER_BRAND] = true;
119
171
  interface;
120
172
  #reference;
121
- #functions = [];
122
- #state = { route: null, inflight: 0, view: null, entries: null };
173
+ #vtable = 0n;
174
+ #bound = null;
175
+ #state = null;
123
176
  // A view keeps its pointer (the owner tracked for release) alive.
124
177
  #owner = null;
125
178
  static {
@@ -127,12 +180,13 @@ export class COMPointer {
127
180
  invokeAsync = (pointer, slot, args, options) => pointer.#invokeAsync(slot, args, options);
128
181
  shared = (pointer) => pointer.#shared();
129
182
  createView = (pointer) => {
130
- if (pointer.#state.view)
131
- return pointer.#state.view;
183
+ const state = pointer.#ensureState();
184
+ if (state.view)
185
+ return state.view;
132
186
  viewOf = pointer;
133
187
  try {
134
188
  const SyncClass = pointer.interface.SyncPointer;
135
- return (pointer.#state.view = new SyncClass(pointer.#reference.address, pointer.interface));
189
+ return (state.view = new SyncClass(pointer.#reference.address, pointer.interface));
136
190
  }
137
191
  finally {
138
192
  viewOf = null;
@@ -146,13 +200,17 @@ export class COMPointer {
146
200
  if (viewOf) {
147
201
  // A synchronous view: same reference, same state.
148
202
  this.#reference = viewOf.#reference;
149
- this.#functions = viewOf.#functions;
203
+ this.#vtable = viewOf.#vtable;
204
+ this.#bound = viewOf.#bound;
150
205
  this.#state = viewOf.#state;
151
206
  this.#owner = viewOf;
152
207
  return;
153
208
  }
154
209
  this.#reference = track(address, this);
155
210
  }
211
+ #ensureState() {
212
+ return (this.#state ??= { route: null, inflight: 0, view: null, entries: null });
213
+ }
156
214
  /** Wrap a raw interface pointer. */
157
215
  static fromAddress(address, iface, options = {}) {
158
216
  if (typeof address !== "bigint" || address === 0n)
@@ -176,69 +234,72 @@ export class COMPointer {
176
234
  #invoke(slot, args) {
177
235
  const { address } = this.#live();
178
236
  const binding = this.#slot(slot);
179
- let fn = this.#functions[slot];
237
+ let bound = this.#bound;
238
+ if (bound === null) {
239
+ const vtable = (this.#vtable = vtableOf(address));
240
+ bound = this.#bound = vtableSlotsFor(this.interface, vtable);
241
+ if (this.#owner && this.#owner.#bound === null) {
242
+ this.#owner.#vtable = vtable;
243
+ this.#owner.#bound = bound;
244
+ }
245
+ }
246
+ let fn = bound[slot];
180
247
  if (fn === undefined)
181
- fn = this.#functions[slot] = binding.bind(vtableEntry(address, slot));
248
+ fn = bound[slot] = binding.bind(vtableEntryFromTable(this.#vtable, slot));
182
249
  return binding.call(fn, address, args);
183
250
  }
184
- /** The route for asynchronous calls, computed once (a `proxy` route again for a new executor). */
185
- #route() {
186
- const cached = this.#state.route;
187
- if (cached !== null && (cached instanceof Promise || cached.kind !== "proxy" || executorAlive(cached.generation)))
188
- return cached;
189
- const address = this.#live().address;
251
+ /** Classify the non-proxy route of `address`, or `null` when it is a cross-apartment proxy. */
252
+ #classifyRoute(address) {
190
253
  const local = localThreading(address);
191
254
  const home = homeApartment();
192
- let route;
193
255
  // Objects implemented in JavaScript run their callbacks on the home thread
194
256
  // unless free-threaded; without COM on the home thread, calls stay there.
195
257
  if (local === "apartment" || home === "none")
196
- route = HOME;
197
- else if (home === "mta")
198
- route = SHARED_MTA;
199
- else if (local === "free")
200
- route = SHARED_AGILE;
258
+ return HOME;
259
+ if (home === "mta")
260
+ return SHARED_MTA;
261
+ if (local === "free")
262
+ return SHARED_AGILE;
201
263
  // A proxy answers IClientSecurity locally; QueryInterface(IAgileObject) would go to the server.
202
- else if (isProxy(address))
203
- route = this.#proxyRoute(address);
204
- else if (isAgile(address))
205
- route = SHARED_AGILE;
206
- else
207
- route = HOME;
208
- this.#state.entries = null;
209
- this.#state.route = route;
264
+ if (isProxy(address))
265
+ return null;
266
+ return isAgile(address) ? SHARED_AGILE : HOME;
267
+ }
268
+ /** The route for asynchronous calls, computed once (a `proxy` route again for a new executor). */
269
+ #route() {
270
+ const state = this.#ensureState();
271
+ const cached = state.route;
272
+ if (cached !== null && (cached instanceof Promise || cached.kind !== "proxy" || executorAlive(cached.generation)))
273
+ return cached;
274
+ const address = this.#live().address;
275
+ const classified = this.#classifyRoute(address);
276
+ const route = classified ?? this.#proxyRoute(address, state);
277
+ state.entries = null;
278
+ state.route = route;
210
279
  return route;
211
280
  }
212
- #proxyRoute(address) {
213
- return referenceForExecutor(address, this.interface.iid).then((executorAddress) => {
214
- if (!executorAddress)
215
- return (this.#state.route = HOME);
216
- const route = { kind: "proxy", address: executorAddress, generation: executorGeneration() };
217
- if (this.#reference.released) {
218
- releaseOnExecutor(executorAddress, route.generation);
219
- return (this.#state.route = HOME);
281
+ #proxyRoute(address, state) {
282
+ return referenceForExecutor(address, this.interface.iid).then((resolved) => {
283
+ if (!resolved)
284
+ return (state.route = HOME);
285
+ const route = { kind: "proxy", address: resolved.address, generation: resolved.generation };
286
+ if (this.#reference.released || !executorAlive(route.generation)) {
287
+ releaseOnExecutor(resolved.address, route.generation);
288
+ return (state.route = HOME);
220
289
  }
221
- executorReferences.register(this, { address: executorAddress, generation: route.generation }, this.#state);
222
- return (this.#state.route = route);
223
- }, () => (this.#state.route = HOME));
290
+ executorReferences.register(this, { address: resolved.address, generation: route.generation }, state);
291
+ return (state.route = route);
292
+ }, () => (state.route = HOME));
224
293
  }
225
294
  #shared() {
226
- const route = this.#state.route;
227
- if (route !== null && !(route instanceof Promise))
228
- return route.kind === "shared";
295
+ const route = this.#state?.route ?? null;
229
296
  if (route !== null)
297
+ return !(route instanceof Promise) && route.kind === "shared";
298
+ const classified = this.#classifyRoute(this.#live().address);
299
+ if (classified === null)
230
300
  return false;
231
- const address = this.#live().address;
232
- const local = localThreading(address);
233
- const home = homeApartment();
234
- if (local === "apartment" || home === "none")
235
- return false;
236
- if (home === "mta") {
237
- this.#state.route = SHARED_MTA;
238
- return true;
239
- }
240
- if (local === "free" || (!isProxy(address) && isAgile(address))) {
241
- this.#state.route = SHARED_AGILE;
301
+ if (classified.kind === "shared") {
302
+ this.#ensureState().route = classified;
242
303
  return true;
243
304
  }
244
305
  return false;
@@ -260,11 +321,12 @@ export class COMPointer {
260
321
  }
261
322
  #dispatch(route, slot, binding, args, options, current) {
262
323
  const reference = this.#live();
324
+ const state = this.#ensureState();
263
325
  // A reference of an executor stopped meanwhile (finalize): route again on the current one.
264
326
  if (route.kind === "proxy" && !executorAlive(route.generation)) {
265
- if (this.#state.route === route) {
266
- this.#state.route = null;
267
- this.#state.entries = null;
327
+ if (state.route === route) {
328
+ state.route = null;
329
+ state.entries = null;
268
330
  }
269
331
  const fresh = this.#route();
270
332
  return fresh instanceof Promise ? fresh.then((settled) => this.#dispatch(settled, slot, binding, args, options, current)) : this.#dispatch(fresh, slot, binding, args, options, current);
@@ -282,13 +344,13 @@ export class COMPointer {
282
344
  const target = route.kind === "proxy" ? route.address : reference.address;
283
345
  const handOverResults = route.kind === "proxy" || route.handOver;
284
346
  // The vtable of an address does not change: read each entry once.
285
- let entries = this.#state.entries;
347
+ let entries = state.entries;
286
348
  if (entries?.address !== target)
287
- entries = this.#state.entries = { address: target, slots: [] };
349
+ entries = state.entries = { address: target, slots: [] };
288
350
  const entry = (entries.slots[slot] ??= vtableEntry(target, slot));
289
- this.#state.inflight++;
351
+ state.inflight++;
290
352
  return binding.callAsync(entry, target, args, { handOver: handOverResults, results, operation: current }).finally(() => {
291
- this.#state.inflight--;
353
+ state.inflight--;
292
354
  });
293
355
  }
294
356
  /** Interface pointer value; throws once released. */
@@ -335,13 +397,16 @@ export class COMPointer {
335
397
  }
336
398
  /** Forget the executor's reference of a `proxy` route. */
337
399
  #dropExecutorReference() {
338
- const route = this.#state.route;
400
+ const state = this.#state;
401
+ if (!state)
402
+ return;
403
+ const route = state.route;
339
404
  if (route !== null && !(route instanceof Promise) && route.kind === "proxy") {
340
- executorReferences.unregister(this.#state);
405
+ executorReferences.unregister(state);
341
406
  releaseOnExecutor(route.address, route.generation);
342
407
  }
343
- this.#state.route = null;
344
- this.#state.entries = null;
408
+ state.route = null;
409
+ state.entries = null;
345
410
  }
346
411
  /**
347
412
  * Release the owned reference and invalidate this pointer. Returns the new
@@ -350,10 +415,11 @@ export class COMPointer {
350
415
  */
351
416
  Release() {
352
417
  const reference = this.#live();
353
- const route = this.#state.route;
418
+ const state = this.#state;
419
+ const route = state?.route ?? null;
354
420
  untrack(reference);
355
421
  this.#dropExecutorReference();
356
- if (this.#state.inflight > 0 && route !== null && !(route instanceof Promise) && route.kind === "shared") {
422
+ if (state && state.inflight > 0 && route !== null && !(route instanceof Promise) && route.kind === "shared") {
357
423
  releaseOnExecutor(reference.address, executorGeneration());
358
424
  return 0;
359
425
  }
@@ -361,16 +427,20 @@ export class COMPointer {
361
427
  }
362
428
  /** COM identity: both pointers reach the same `IUnknown`. */
363
429
  isSameObject(other) {
364
- if (!(other instanceof COMPointer))
430
+ if (!isCOMPointer(other))
365
431
  throw new TypeError("isSameObject expects a COMPointer");
366
- const identity = (pointer) => {
367
- const [hr, address] = rawQueryInterface(pointer.address, IID_IUnknown);
432
+ const a = this.address;
433
+ const b = other.address;
434
+ if (a === b)
435
+ return true;
436
+ const identity = (addr) => {
437
+ const [hr, address] = rawQueryInterface(addr, IID_IUnknown);
368
438
  if (hr < 0 || !address)
369
439
  throw new COMError(hr, { method: "IUnknown::QueryInterface" });
370
440
  rawRelease(address);
371
441
  return address;
372
442
  };
373
- return identity(this) === identity(other);
443
+ return identity(a) === identity(b);
374
444
  }
375
445
  /** Give up ownership without releasing: the caller becomes responsible for the reference. */
376
446
  detach() {
package/dist/pump.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Dispatch the messages waiting in the thread's queue, without blocking.
3
- * Returns how many were dispatched (at most `limit`).
3
+ * Returns how many were dispatched (at most `limit`). Re-entrant safe: nested
4
+ * `pumpMessages()` calls from inside `DispatchMessageW` use their own MSG buffer.
4
5
  */
5
6
  export declare function pumpMessages(limit?: number): number;
6
7
  /**
@@ -8,21 +9,44 @@ export declare function pumpMessages(limit?: number): number;
8
9
  * event loop does not run meanwhile). Python equivalent: `comtypes.client.PumpEvents`.
9
10
  */
10
11
  export declare function PumpEvents(milliseconds: number): void;
12
+ /**
13
+ * Drain all queued Win32 messages, or if the queue is empty sleep in the
14
+ * Windows kernel via `MsgWaitForMultipleObjectsEx` (~0% CPU) until any input
15
+ * or COM STA message arrives or `timeoutMs` elapses, then drain immediately.
16
+ */
17
+ export declare function waitAndPumpMessages(timeoutMs?: number, limit?: number): number;
11
18
  export interface MessagePump extends Disposable {
12
19
  stop(): void;
13
20
  readonly running: boolean;
14
21
  }
22
+ export interface StartMessagePumpOptions {
23
+ /**
24
+ * Polling interval in ms when `mode === "interval"` (default `10`), or kernel
25
+ * idle yield in ms when `mode === "wait"` (default `8`).
26
+ */
27
+ readonly interval?: number;
28
+ /**
29
+ * - `"interval"` (default): `setInterval` pump (non-blocking, ~15.6 ms timer granularity on Windows).
30
+ * - `"wait"`: `MsgWaitForMultipleObjectsEx` + `setImmediate` pump — wakes in < 0.1 ms on incoming
31
+ * Win32/COM/UI messages, sleeps at ~0% CPU when idle, and yields every `interval` ms to libuv.
32
+ */
33
+ readonly mode?: "interval" | "wait";
34
+ /** Whether the pump keeps the Node.js event loop alive (default `false` for `"interval"`, `true` for `"wait"`). */
35
+ readonly ref?: boolean;
36
+ }
15
37
  /**
16
- * Pump messages periodically from the event loop (`setInterval`, unref'd so
17
- * it does not keep the process alive). The JavaScript thread stays free between
18
- * ticks: use this for events and incoming calls while the program runs.
38
+ * Pump Win32 messages from the Node.js event loop.
39
+ *
40
+ * - Default (`mode: "interval"`): periodic unref'd `setInterval` — leaves the
41
+ * JS thread completely idle between ticks.
42
+ * - Low-latency (`mode: "wait"`): `MsgWaitForMultipleObjectsEx` + `setImmediate`
43
+ * — sub-millisecond wakeup for interactive UI / STA COM callbacks.
19
44
  */
20
- export declare function startMessagePump(options?: {
21
- readonly interval?: number;
22
- }): MessagePump;
45
+ export declare function startMessagePump(options?: StartMessagePumpOptions): MessagePump;
23
46
  /**
24
47
  * Pump messages until `condition()` holds or `timeout` elapses; resolves to
25
- * the last value of the condition. The event loop runs between checks.
48
+ * the last value of the condition. Uses `waitAndPumpMessages` so STA COM events
49
+ * wake immediately (< 0.1 ms) while still yielding to the Node.js event loop.
26
50
  */
27
51
  export declare function waitFor(condition: () => boolean, options?: {
28
52
  readonly timeout?: number;
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` });