@node-ctypes/comtypes 0.1.0 → 0.2.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 (57) hide show
  1. package/README.md +114 -47
  2. package/dist/automation/dispatch.d.ts +6 -0
  3. package/dist/automation/dispatch.js +78 -29
  4. package/dist/automation/members.js +31 -22
  5. package/dist/automation/variant.d.ts +2 -0
  6. package/dist/automation/variant.js +38 -1
  7. package/dist/cli.js +7 -2
  8. package/dist/client/best.d.ts +6 -0
  9. package/dist/client/best.js +89 -45
  10. package/dist/client/constants.js +2 -2
  11. package/dist/client/dual.d.ts +14 -0
  12. package/dist/client/dual.js +122 -0
  13. package/dist/client/dynamic.d.ts +21 -9
  14. package/dist/client/dynamic.js +123 -18
  15. package/dist/client/events.js +11 -11
  16. package/dist/client/index.d.ts +39 -19
  17. package/dist/client/index.js +124 -17
  18. package/dist/commethod.js +67 -18
  19. package/dist/dispmethod.js +26 -5
  20. package/dist/executor/apartment.d.ts +32 -0
  21. package/dist/executor/apartment.js +226 -0
  22. package/dist/executor/classes.d.ts +10 -0
  23. package/dist/executor/classes.js +18 -0
  24. package/dist/executor/executor.d.ts +76 -0
  25. package/dist/executor/executor.js +208 -0
  26. package/dist/executor/operations.d.ts +29 -0
  27. package/dist/executor/operations.js +95 -0
  28. package/dist/index.d.ts +6 -2
  29. package/dist/index.js +3 -1
  30. package/dist/interface.d.ts +43 -3
  31. package/dist/interface.js +28 -8
  32. package/dist/interfaces/servprov.js +2 -2
  33. package/dist/low-level/index.d.ts +2 -0
  34. package/dist/low-level/index.js +1 -0
  35. package/dist/low-level/native.d.ts +6 -0
  36. package/dist/low-level/native.js +13 -1
  37. package/dist/pointer.d.ts +57 -6
  38. package/dist/pointer.js +233 -9
  39. package/dist/server/comobject.js +9 -3
  40. package/dist/server/errorinfo.js +6 -6
  41. package/dist/server/register.js +5 -0
  42. package/dist/threads.js +4 -4
  43. package/dist/tracking.d.ts +2 -0
  44. package/dist/tracking.js +4 -0
  45. package/dist/typelib/build.d.ts +5 -0
  46. package/dist/typelib/build.js +8 -1
  47. package/dist/typelib/generate.js +14 -11
  48. package/dist/typelib/getmodule.d.ts +14 -3
  49. package/dist/typelib/getmodule.js +61 -19
  50. package/dist/typelib/index.d.ts +1 -1
  51. package/dist/typelib/index.js +1 -1
  52. package/dist/typelib/load.js +32 -8
  53. package/dist/typelib/model.d.ts +3 -0
  54. package/dist/typelib/model.js +87 -66
  55. package/dist/typelib/steps.d.ts +12 -0
  56. package/dist/typelib/steps.js +51 -0
  57. package/package.json +2 -2
package/dist/pointer.d.ts CHANGED
@@ -1,6 +1,17 @@
1
+ import type { ResultLocation } from "./executor/apartment.ts";
2
+ import type { Operation } from "./executor/operations.ts";
1
3
  import { GUID } from "./guid.ts";
2
- import type { InterfaceDef, InterfacePointer, MethodSpec } from "./interface.ts";
4
+ import type { InterfaceDef, InterfacePointer, MethodSpec, SyncPointer } from "./interface.ts";
3
5
  type Callable = (...args: any[]) => any;
6
+ /** How an asynchronous call reaches the executor. */
7
+ export interface AsyncContext {
8
+ /** The home thread is single-threaded: interface results are handed back to it. */
9
+ readonly handOver: boolean;
10
+ /** Further result locations to hand over (e.g. the VARIANT of `IDispatch::Invoke`). */
11
+ readonly results?: readonly ResultLocation[];
12
+ /** The operation recording the call: `run()` cancels it while it is queued. */
13
+ readonly operation?: Operation;
14
+ }
4
15
  /** A vtable slot of an interface: binds the function found at a given address. */
5
16
  export interface Slot {
6
17
  readonly spec: MethodSpec;
@@ -9,6 +20,8 @@ export interface Slot {
9
20
  bind(address: bigint): Callable;
10
21
  /** Call the bound function: raw arguments, or converted by the spec's marshal (COMMETHOD). */
11
22
  call(fn: Callable, address: bigint, args: readonly unknown[]): unknown;
23
+ /** Call the function `entry` of object `target` on the COM executor. */
24
+ callAsync(entry: bigint, target: bigint, args: readonly unknown[], context: AsyncContext): Promise<unknown>;
12
25
  }
13
26
  /** Interface declaring a slot; `definition` is set once the interface is complete. */
14
27
  export interface SlotOwner {
@@ -30,8 +43,41 @@ export interface FromAddressOptions {
30
43
  */
31
44
  readonly addRef?: boolean;
32
45
  }
33
- /** Call vtable slot `slot` of `pointer` (used by the generated interface methods). */
46
+ /**
47
+ * Decides whether the arguments of a call can travel to the executor: COM
48
+ * objects among them must be usable there (installed by the automation
49
+ * layer, which knows VARIANT, ByRef and named arguments).
50
+ */
51
+ export type ArgumentInspector = (args: readonly unknown[], homeMultithreaded: boolean) => boolean;
52
+ export declare function setArgumentInspector(inspector: ArgumentInspector): void;
53
+ /**
54
+ * Threading model of an object implemented in JavaScript at `address`
55
+ * (`COMObject`), `null` for other objects (installed by the server layer).
56
+ */
57
+ export type LocalThreading = (address: bigint) => "apartment" | "free" | null;
58
+ export declare function setLocalThreading(resolver: LocalThreading): void;
59
+ /** Call vtable slot `slot` of `pointer` synchronously, on the home thread (used by accessors and internal code). */
34
60
  export declare function invokeSlot(pointer: COMPointer, slot: number, args: unknown[]): unknown;
61
+ export interface AsyncInvokeOptions {
62
+ /** Further locations of interface results to hand back to a single-threaded home (e.g. raw VARIANT outputs). */
63
+ readonly results?: readonly ResultLocation[];
64
+ /** JavaScript values behind already converted arguments, checked instead of `args` (e.g. the arguments of `IDispatch::Invoke`). */
65
+ readonly inspect?: readonly unknown[];
66
+ }
67
+ /**
68
+ * Call vtable slot `slot` of `pointer` on the COM executor (used by the
69
+ * generated interface methods). When the object or the arguments cannot
70
+ * travel to the executor, the call runs synchronously on the home thread.
71
+ */
72
+ export declare function invokeSlotAsync(pointer: COMPointer, slot: number, args: unknown[], options?: AsyncInvokeOptions): Promise<unknown>;
73
+ /** Whether a home pointer is usable as it is on the executor (agile, or both in the MTA). */
74
+ export declare function sharedWithExecutor(pointer: COMPointer): boolean;
75
+ /**
76
+ * A view of `pointer` whose interface methods run synchronously on the home
77
+ * thread, sharing its reference (releasing either releases both). For event
78
+ * handlers, COM servers and code that needs the lowest latency.
79
+ */
80
+ export declare function sync<I extends InterfaceDef<any>>(pointer: COMPointer<I> | InterfacePointer<I>): SyncPointer<I>;
35
81
  /**
36
82
  * An owned reference to a COM interface. Python equivalent: `POINTER(IUnknown)`.
37
83
  *
@@ -40,8 +86,9 @@ export declare function invokeSlot(pointer: COMPointer, slot: number, args: unkn
40
86
  * net, never after the apartment has been uninitialized.
41
87
  *
42
88
  * Interface methods are installed by {@link COMInterface} on per-interface
43
- * subclasses; obtain pointers from `CoCreateInstance`, `QueryInterface` or
44
- * {@link COMPointer.fromAddress}.
89
+ * subclasses: they return promises and run on the COM executor; properties
90
+ * stay synchronous. Obtain pointers from `CoCreateInstance`, `QueryInterface`
91
+ * or {@link COMPointer.fromAddress}.
45
92
  */
46
93
  export declare class COMPointer<I extends InterfaceDef = InterfaceDef> implements Disposable {
47
94
  #private;
@@ -54,7 +101,7 @@ export declare class COMPointer<I extends InterfaceDef = InterfaceDef> implement
54
101
  /** Passed as the pointer value to node-ctypes functions (Python parity). */
55
102
  get _as_parameter_(): bigint;
56
103
  get released(): boolean;
57
- /** Call a vtable method by name, bypassing the typed accessors (e.g. the raw `QueryInterface`). */
104
+ /** Call a vtable method by name, synchronously, bypassing the typed accessors (e.g. the raw `QueryInterface`). */
58
105
  callMethod(name: string, ...args: unknown[]): unknown;
59
106
  /** New owned pointer for `iface`; throws {@link COMError} (`E_NOINTERFACE`) when unsupported. */
60
107
  QueryInterface<T extends InterfaceDef>(iface: T): InterfacePointer<T>;
@@ -65,7 +112,11 @@ export declare class COMPointer<I extends InterfaceDef = InterfaceDef> implement
65
112
  * by this pointer: balance it with `callMethod("Release")` or hand it over.
66
113
  */
67
114
  AddRef(): number;
68
- /** Release the owned reference and invalidate this pointer. Returns the new count. */
115
+ /**
116
+ * Release the owned reference and invalidate this pointer. Returns the new
117
+ * count, or 0 while asynchronous calls on the same address are still
118
+ * running: the release then follows them on the executor.
119
+ */
69
120
  Release(): number;
70
121
  /** COM identity: both pointers reach the same `IUnknown`. */
71
122
  isSameObject(other: COMPointer): boolean;
package/dist/pointer.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import * as ctypes from "node-ctypes";
2
2
  import { COMError } from "./errors.js";
3
3
  import { errorInfoFor } from "./errorinfo.js";
4
+ import { handOver, homeApartment, isAgile, isProxy, referenceForExecutor, releaseOnExecutor } from "./executor/apartment.js";
5
+ import { executorAlive, executorCall, executorGeneration } from "./executor/executor.js";
6
+ import { operation } from "./executor/operations.js";
4
7
  import { GUID } from "./guid.js";
5
8
  import { E_NOINTERFACE } from "./hresult.js";
6
9
  import { functionCache, rawQueryInterface, rawRelease, vtableEntry } from "./low-level/vtable.js";
@@ -16,13 +19,16 @@ export function createSlot(spec, owner) {
16
19
  const hresult = spec.restype === ctypes.HRESULT;
17
20
  // IUnknown methods never set error info (and QueryInterface failures are common).
18
21
  const errorInfo = !owner.iid.equals(IID_IUnknown);
19
- const cache = functionCache(() => ctypes.WINFUNCTYPE(hresult ? ctypes.c_int32 : spec.restype, ctypes.c_void_p, ...spec.argtypes));
22
+ const nativeRestype = hresult ? ctypes.c_int32 : spec.restype;
23
+ // 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));
20
26
  const errcheck = (result, _fn, args) => {
21
27
  if (result < 0)
22
28
  throw new COMError(result, { method: label, details: errorInfo ? errorInfoFor(args[0], owner.iid) : null });
23
29
  return result;
24
30
  };
25
- const { marshal } = spec;
31
+ const { marshal, marshalAsync } = spec;
26
32
  return {
27
33
  spec,
28
34
  label,
@@ -33,13 +39,70 @@ export function createSlot(spec, owner) {
33
39
  fn.errcheck = errcheck;
34
40
  return fn;
35
41
  },
42
+ callAsync(entry, target, args, context) {
43
+ // 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
+ });
50
+ return marshalAsync ? marshalAsync(run, args, owner.definition) : run(args, []);
51
+ },
36
52
  };
37
53
  }
54
+ const HOME = Object.freeze({ kind: "home" });
55
+ const SHARED_MTA = Object.freeze({ kind: "shared", handOver: false });
56
+ const SHARED_AGILE = Object.freeze({ kind: "shared", handOver: true });
57
+ let inspectArguments = () => true;
58
+ export function setArgumentInspector(inspector) {
59
+ inspectArguments = inspector;
60
+ }
61
+ let localThreading = () => null;
62
+ export function setLocalThreading(resolver) {
63
+ localThreading = resolver;
64
+ }
65
+ // The executor's references of `proxy` routes, released if their pointer is forgotten.
66
+ const executorReferences = new FinalizationRegistry(({ address, generation }) => {
67
+ try {
68
+ releaseOnExecutor(address, generation);
69
+ }
70
+ catch {
71
+ // Nothing can be reported from a finalizer.
72
+ }
73
+ });
38
74
  let invoke;
39
- /** Call vtable slot `slot` of `pointer` (used by the generated interface methods). */
75
+ let invokeAsync;
76
+ let shared;
77
+ let createView;
78
+ /** Call vtable slot `slot` of `pointer` synchronously, on the home thread (used by accessors and internal code). */
40
79
  export function invokeSlot(pointer, slot, args) {
41
80
  return invoke(pointer, slot, args);
42
81
  }
82
+ /**
83
+ * Call vtable slot `slot` of `pointer` on the COM executor (used by the
84
+ * generated interface methods). When the object or the arguments cannot
85
+ * travel to the executor, the call runs synchronously on the home thread.
86
+ */
87
+ export function invokeSlotAsync(pointer, slot, args, options = {}) {
88
+ return invokeAsync(pointer, slot, args, options);
89
+ }
90
+ /** Whether a home pointer is usable as it is on the executor (agile, or both in the MTA). */
91
+ export function sharedWithExecutor(pointer) {
92
+ return shared(pointer);
93
+ }
94
+ /**
95
+ * A view of `pointer` whose interface methods run synchronously on the home
96
+ * thread, sharing its reference (releasing either releases both). For event
97
+ * handlers, COM servers and code that needs the lowest latency.
98
+ */
99
+ export function sync(pointer) {
100
+ if (!(pointer instanceof COMPointer))
101
+ throw new TypeError("sync() expects a COM pointer");
102
+ return createView(pointer);
103
+ }
104
+ // Set while constructing a synchronous view: the new instance shares this pointer's state.
105
+ let viewOf = null;
43
106
  /**
44
107
  * An owned reference to a COM interface. Python equivalent: `POINTER(IUnknown)`.
45
108
  *
@@ -48,20 +111,46 @@ export function invokeSlot(pointer, slot, args) {
48
111
  * net, never after the apartment has been uninitialized.
49
112
  *
50
113
  * Interface methods are installed by {@link COMInterface} on per-interface
51
- * subclasses; obtain pointers from `CoCreateInstance`, `QueryInterface` or
52
- * {@link COMPointer.fromAddress}.
114
+ * subclasses: they return promises and run on the COM executor; properties
115
+ * stay synchronous. Obtain pointers from `CoCreateInstance`, `QueryInterface`
116
+ * or {@link COMPointer.fromAddress}.
53
117
  */
54
118
  export class COMPointer {
55
119
  interface;
56
120
  #reference;
57
121
  #functions = [];
122
+ #state = { route: null, inflight: 0, view: null, entries: null };
123
+ // A view keeps its pointer (the owner tracked for release) alive.
124
+ #owner = null;
58
125
  static {
59
126
  invoke = (pointer, slot, args) => pointer.#invoke(slot, args);
127
+ invokeAsync = (pointer, slot, args, options) => pointer.#invokeAsync(slot, args, options);
128
+ shared = (pointer) => pointer.#shared();
129
+ createView = (pointer) => {
130
+ if (pointer.#state.view)
131
+ return pointer.#state.view;
132
+ viewOf = pointer;
133
+ try {
134
+ const SyncClass = pointer.interface.SyncPointer;
135
+ return (pointer.#state.view = new SyncClass(pointer.#reference.address, pointer.interface));
136
+ }
137
+ finally {
138
+ viewOf = null;
139
+ }
140
+ };
60
141
  }
61
142
  constructor(address, iface) {
62
143
  if (typeof address !== "bigint" || address === 0n)
63
144
  throw new TypeError("COMPointer requires a non-NULL address");
64
145
  this.interface = iface;
146
+ if (viewOf) {
147
+ // A synchronous view: same reference, same state.
148
+ this.#reference = viewOf.#reference;
149
+ this.#functions = viewOf.#functions;
150
+ this.#state = viewOf.#state;
151
+ this.#owner = viewOf;
152
+ return;
153
+ }
65
154
  this.#reference = track(address, this);
66
155
  }
67
156
  /** Wrap a raw interface pointer. */
@@ -78,16 +167,130 @@ export class COMPointer {
78
167
  throw new Error(`${this.interface.name} pointer has been released`);
79
168
  return this.#reference;
80
169
  }
81
- #invoke(slot, args) {
82
- const { address } = this.#live();
170
+ #slot(slot) {
83
171
  const binding = this.interface.slots[slot];
84
172
  if (!binding)
85
173
  throw new RangeError(`${this.interface.name} has no vtable slot ${slot}`);
174
+ return binding;
175
+ }
176
+ #invoke(slot, args) {
177
+ const { address } = this.#live();
178
+ const binding = this.#slot(slot);
86
179
  let fn = this.#functions[slot];
87
180
  if (fn === undefined)
88
181
  fn = this.#functions[slot] = binding.bind(vtableEntry(address, slot));
89
182
  return binding.call(fn, address, args);
90
183
  }
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;
190
+ const local = localThreading(address);
191
+ const home = homeApartment();
192
+ let route;
193
+ // Objects implemented in JavaScript run their callbacks on the home thread
194
+ // unless free-threaded; without COM on the home thread, calls stay there.
195
+ 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;
201
+ // 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;
210
+ return route;
211
+ }
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);
220
+ }
221
+ executorReferences.register(this, { address: executorAddress, generation: route.generation }, this.#state);
222
+ return (this.#state.route = route);
223
+ }, () => (this.#state.route = HOME));
224
+ }
225
+ #shared() {
226
+ const route = this.#state.route;
227
+ if (route !== null && !(route instanceof Promise))
228
+ return route.kind === "shared";
229
+ if (route !== null)
230
+ 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;
242
+ return true;
243
+ }
244
+ return false;
245
+ }
246
+ #invokeAsync(slot, args, options) {
247
+ return operation((current) => {
248
+ try {
249
+ this.#live();
250
+ const binding = this.#slot(slot);
251
+ const route = this.#route();
252
+ if (route instanceof Promise)
253
+ return route.then((settled) => this.#dispatch(settled, slot, binding, args, options, current));
254
+ return this.#dispatch(route, slot, binding, args, options, current);
255
+ }
256
+ catch (error) {
257
+ return Promise.reject(error);
258
+ }
259
+ });
260
+ }
261
+ #dispatch(route, slot, binding, args, options, current) {
262
+ const reference = this.#live();
263
+ // A reference of an executor stopped meanwhile (finalize): route again on the current one.
264
+ if (route.kind === "proxy" && !executorAlive(route.generation)) {
265
+ if (this.#state.route === route) {
266
+ this.#state.route = null;
267
+ this.#state.entries = null;
268
+ }
269
+ const fresh = this.#route();
270
+ return fresh instanceof Promise ? fresh.then((settled) => this.#dispatch(settled, slot, binding, args, options, current)) : this.#dispatch(fresh, slot, binding, args, options, current);
271
+ }
272
+ const { results, inspect } = options;
273
+ if (route.kind === "home" || !inspectArguments(inspect ?? args, route.kind === "shared" && !route.handOver)) {
274
+ // Called where the object lives: on the home thread, synchronously.
275
+ try {
276
+ return Promise.resolve(this.#invoke(slot, args));
277
+ }
278
+ catch (error) {
279
+ return Promise.reject(error);
280
+ }
281
+ }
282
+ const target = route.kind === "proxy" ? route.address : reference.address;
283
+ const handOverResults = route.kind === "proxy" || route.handOver;
284
+ // The vtable of an address does not change: read each entry once.
285
+ let entries = this.#state.entries;
286
+ if (entries?.address !== target)
287
+ entries = this.#state.entries = { address: target, slots: [] };
288
+ const entry = (entries.slots[slot] ??= vtableEntry(target, slot));
289
+ this.#state.inflight++;
290
+ return binding.callAsync(entry, target, args, { handOver: handOverResults, results, operation: current }).finally(() => {
291
+ this.#state.inflight--;
292
+ });
293
+ }
91
294
  /** Interface pointer value; throws once released. */
92
295
  get address() {
93
296
  return this.#live().address;
@@ -99,7 +302,7 @@ export class COMPointer {
99
302
  get released() {
100
303
  return this.#reference.released;
101
304
  }
102
- /** Call a vtable method by name, bypassing the typed accessors (e.g. the raw `QueryInterface`). */
305
+ /** Call a vtable method by name, synchronously, bypassing the typed accessors (e.g. the raw `QueryInterface`). */
103
306
  callMethod(name, ...args) {
104
307
  const slot = this.interface.methodIndex.get(name);
105
308
  if (slot === undefined)
@@ -130,10 +333,30 @@ export class COMPointer {
130
333
  AddRef() {
131
334
  return this.#invoke(1, []);
132
335
  }
133
- /** Release the owned reference and invalidate this pointer. Returns the new count. */
336
+ /** Forget the executor's reference of a `proxy` route. */
337
+ #dropExecutorReference() {
338
+ const route = this.#state.route;
339
+ if (route !== null && !(route instanceof Promise) && route.kind === "proxy") {
340
+ executorReferences.unregister(this.#state);
341
+ releaseOnExecutor(route.address, route.generation);
342
+ }
343
+ this.#state.route = null;
344
+ this.#state.entries = null;
345
+ }
346
+ /**
347
+ * Release the owned reference and invalidate this pointer. Returns the new
348
+ * count, or 0 while asynchronous calls on the same address are still
349
+ * running: the release then follows them on the executor.
350
+ */
134
351
  Release() {
135
352
  const reference = this.#live();
353
+ const route = this.#state.route;
136
354
  untrack(reference);
355
+ this.#dropExecutorReference();
356
+ if (this.#state.inflight > 0 && route !== null && !(route instanceof Promise) && route.kind === "shared") {
357
+ releaseOnExecutor(reference.address, executorGeneration());
358
+ return 0;
359
+ }
137
360
  return rawRelease(reference.address);
138
361
  }
139
362
  /** COM identity: both pointers reach the same `IUnknown`. */
@@ -153,6 +376,7 @@ export class COMPointer {
153
376
  detach() {
154
377
  const reference = this.#live();
155
378
  untrack(reference);
379
+ this.#dropExecutorReference();
156
380
  return reference.address;
157
381
  }
158
382
  [Symbol.dispose]() {
@@ -14,7 +14,7 @@ import { IDispatch, IEnumVARIANT } from "../interfaces/dispatch.js";
14
14
  import { ISupportErrorInfo } from "../interfaces/errorinfo.js";
15
15
  import { IUnknown } from "../interfaces/unknown.js";
16
16
  import { POINTER_SIZE, readMemory, writeMemory } from "../low-level/native.js";
17
- import { COMPointer } from "../pointer.js";
17
+ import { COMPointer, setLocalThreading, sync } from "../pointer.js";
18
18
  import { ReturnHRESULT, dispatchGetIDsOfNames, dispatchInvoke, defaultIdsOfNames, defaultInvoke } from "./automation.js";
19
19
  import { setErrorInfo } from "./errorinfo.js";
20
20
  import { typeLibLocationOf } from "../typelib/coclass.js";
@@ -365,7 +365,7 @@ export class COMObject {
365
365
  }
366
366
  /** Lends the first interface (`borrowReference`), e.g. to pass the object as an argument. */
367
367
  [comReference]() {
368
- return { address: this.#state.addresses[0], interface: this.#state.info.interfaces[0] };
368
+ return { address: this.#state.addresses[0], interface: this.#state.info.interfaces[0], threading: this.#state.info.threading };
369
369
  }
370
370
  /** Called when the native reference count drops to zero. Python: `_final_release_`. */
371
371
  _final_release_() { }
@@ -531,7 +531,7 @@ function typeInfoFor(guid, location) {
531
531
  typeLibraries.set(key, library);
532
532
  }
533
533
  const out = new ctypes.c_void_p();
534
- library.GetTypeInfoOfGuid(guid instanceof GUID ? guid : guid.iid, ctypes.byref(out));
534
+ sync(library).GetTypeInfoOfGuid(guid instanceof GUID ? guid : guid.iid, ctypes.byref(out));
535
535
  return out.value;
536
536
  }
537
537
  catch {
@@ -663,3 +663,9 @@ export class ClassFactory extends COMObject {
663
663
  return S_OK;
664
664
  }
665
665
  }
666
+ // Asynchronous calls on objects implemented here follow their threading model
667
+ // (see pointer.ts): "apartment" objects are called on the home thread.
668
+ setLocalThreading((address) => {
669
+ const object = instances.get(address)?.object.deref();
670
+ return object ? (object[comReference]().threading ?? "apartment") : null;
671
+ });
@@ -54,7 +54,7 @@ import * as ctypes from "node-ctypes";
54
54
  import { checkHRESULT } from "../errors.js";
55
55
  import { ICreateErrorInfo, IErrorInfo } from "../interfaces/errorinfo.js";
56
56
  import { oleaut32 } from "../low-level/native.js";
57
- import { COMPointer } from "../pointer.js";
57
+ import { COMPointer, sync } from "../pointer.js";
58
58
  /**
59
59
  * Set the thread's error object (`CreateErrorInfo` + `SetErrorInfo`), read
60
60
  * by callers through `GetErrorInfo`. Python equivalent: `comtypes.ReportError`.
@@ -66,15 +66,15 @@ export function setErrorInfo(fields) {
66
66
  checkHRESULT(oleaut32().CreateErrorInfo(ctypes.byref(out)), "CreateErrorInfo");
67
67
  const create = __addDisposableResource(env_1, COMPointer.fromAddress(out.value, ICreateErrorInfo), false);
68
68
  if (fields.description)
69
- create.SetDescription(fields.description);
69
+ sync(create).SetDescription(fields.description);
70
70
  if (fields.source)
71
- create.SetSource(fields.source);
71
+ sync(create).SetSource(fields.source);
72
72
  if (fields.guid)
73
- create.SetGUID(fields.guid);
73
+ sync(create).SetGUID(fields.guid);
74
74
  if (fields.helpFile)
75
- create.SetHelpFile(fields.helpFile);
75
+ sync(create).SetHelpFile(fields.helpFile);
76
76
  if (fields.helpContext)
77
- create.SetHelpContext(fields.helpContext);
77
+ sync(create).SetHelpContext(fields.helpContext);
78
78
  const info = __addDisposableResource(env_1, create.QueryInterface(IErrorInfo), false);
79
79
  checkHRESULT(oleaut32().SetErrorInfo(0, info.address), "SetErrorInfo");
80
80
  }
@@ -11,6 +11,7 @@ import { ClassFactory, COMObject, classTypeLib, getLiveObjectCount, queryObject
11
11
  import { registerTypeLib, unregisterTypeLib } from "../typelib/load.js";
12
12
  import { IUnknown } from "../interfaces/unknown.js";
13
13
  import { rawRelease } from "../low-level/vtable.js";
14
+ import { markLocalClass, unmarkLocalClass } from "../executor/classes.js";
14
15
  export const REGCLS_SINGLEUSE = 0;
15
16
  export const REGCLS_MULTIPLEUSE = 1;
16
17
  export const REGCLS_MULTI_SEPARATE = 2;
@@ -36,11 +37,15 @@ export function registerClassObject(type, options = {}) {
36
37
  // COM keeps its own reference while registered.
37
38
  rawRelease(address);
38
39
  }
40
+ // CreateObject creates objects of this class on this thread (see client/index.ts).
41
+ const clsid = classId(type);
42
+ markLocalClass(clsid);
39
43
  let registered = true;
40
44
  const revoke = () => {
41
45
  if (!registered)
42
46
  return;
43
47
  registered = false;
48
+ unmarkLocalClass(clsid);
44
49
  checkHRESULT(ole32().CoRevokeClassObject(cookie.value), "CoRevokeClassObject");
45
50
  };
46
51
  return { cookie: cookie.value, factory, revoke, [Symbol.dispose]: revoke };
package/dist/threads.js CHANGED
@@ -9,7 +9,7 @@ import { IDispatch } from "./interfaces/dispatch.js";
9
9
  import { IUnknown } from "./interfaces/unknown.js";
10
10
  import { ole32 } from "./low-level/native.js";
11
11
  import { rawRelease } from "./low-level/vtable.js";
12
- import { COMPointer } from "./pointer.js";
12
+ import { COMPointer, sync } from "./pointer.js";
13
13
  import { CoCreateInstance } from "./runtime.js";
14
14
  function source(object) {
15
15
  const borrowed = borrowReference(object);
@@ -74,19 +74,19 @@ export class GlobalInterfaceTable {
74
74
  /** Register `object` (as `iface`, default its own interface); returns the cookie, valid in every thread. */
75
75
  register(object, iface) {
76
76
  const { iid } = source(object);
77
- return this.#table.RegisterInterfaceInGlobal(object, iface?.iid ?? iid);
77
+ return sync(this.#table).RegisterInterfaceInGlobal(object, iface?.iid ?? iid);
78
78
  }
79
79
  /** A pointer usable in the calling thread. */
80
80
  get(cookie, iface) {
81
81
  const out = new ctypes.c_void_p();
82
- this.#table.GetInterfaceFromGlobal(cookie, iface.iid._buffer, ctypes.byref(out));
82
+ sync(this.#table).GetInterfaceFromGlobal(cookie, iface.iid._buffer, ctypes.byref(out));
83
83
  return COMPointer.fromAddress(out.value, iface);
84
84
  }
85
85
  getDispatch(cookie) {
86
86
  return adoptDispatch(this.get(cookie, IDispatch));
87
87
  }
88
88
  revoke(cookie) {
89
- this.#table.RevokeInterfaceFromGlobal(cookie);
89
+ sync(this.#table).RevokeInterfaceFromGlobal(cookie);
90
90
  }
91
91
  [Symbol.dispose]() {
92
92
  if (!this.#table.released)
@@ -10,6 +10,8 @@ export declare function track(address: bigint, owner: object): Reference;
10
10
  export declare function untrack(reference: Reference): void;
11
11
  /** Release all live references, newest first. Returns how many were released. */
12
12
  export declare function releaseAll(): number;
13
+ /** Apartment generation of this thread: changes when the apartment is torn down. */
14
+ export declare function apartmentGeneration(): number;
13
15
  export declare function liveCount(): number;
14
16
  export declare function initCount(): number;
15
17
  export declare function initialized(): void;
package/dist/tracking.js CHANGED
@@ -46,6 +46,10 @@ export function releaseAll() {
46
46
  }
47
47
  return references.length;
48
48
  }
49
+ /** Apartment generation of this thread: changes when the apartment is torn down. */
50
+ export function apartmentGeneration() {
51
+ return state.generation;
52
+ }
49
53
  export function liveCount() {
50
54
  return state.live.size;
51
55
  }
@@ -1,6 +1,7 @@
1
1
  import { GUID } from "../guid.ts";
2
2
  import type { InterfaceDef } from "../interface.ts";
3
3
  import type { DefaultValue, TypeLibModel, TypeModel, TypeRef } from "./model.ts";
4
+ import type { Steps } from "./steps.ts";
4
5
  /** Interfaces defined by node-comtypes, by IID: type libraries reuse them. */
5
6
  export declare const builtinInterfaceDefs: ReadonlyMap<string, {
6
7
  readonly name: string;
@@ -33,3 +34,7 @@ export declare class ModelIndex {
33
34
  export declare function buildModule(model: TypeLibModel, options?: {
34
35
  readonly path?: string;
35
36
  }): TypeLibModule;
37
+ /** {@link buildModule} in steps: yields after each type. */
38
+ export declare function buildModuleSteps(model: TypeLibModel, options?: {
39
+ readonly path?: string;
40
+ }): Steps<TypeLibModule>;
@@ -13,6 +13,8 @@ import { IUnknown } from "../interfaces/unknown.js";
13
13
  import { setRecordTypeInfo, setTypeLibLocation } from "./coclass.js";
14
14
  import { loadTypeLib } from "./load.js";
15
15
  import { ITypeLib } from "../interfaces/typeinfo.js";
16
+ import { sync } from "../pointer.js";
17
+ import { runSync } from "./steps.js";
16
18
  /** Interfaces defined by node-comtypes, by IID: type libraries reuse them. */
17
19
  export const builtinInterfaceDefs = new Map(Object.entries(builtinInterfaces)
18
20
  .filter((entry) => typeof entry[1] === "object" && entry[1] !== null && "Pointer" in entry[1] && "iid" in entry[1])
@@ -82,7 +84,7 @@ function typeInfoAddress(location, guid) {
82
84
  libraries.set(key, library);
83
85
  }
84
86
  const out = new ctypes.c_void_p();
85
- library.GetTypeInfoOfGuid(new GUID(guid), ctypes.byref(out));
87
+ sync(library).GetTypeInfoOfGuid(new GUID(guid), ctypes.byref(out));
86
88
  return out.value;
87
89
  }
88
90
  /** Builds runtime definitions from a model (shared by GetModule and generated modules). */
@@ -374,6 +376,10 @@ class Builder {
374
376
  * dispinterfaces (DISPMETHOD / DISPPROPERTY), coclasses and module constants.
375
377
  */
376
378
  export function buildModule(model, options = {}) {
379
+ return runSync(buildModuleSteps(model, options));
380
+ }
381
+ /** {@link buildModule} in steps: yields after each type. */
382
+ export function* buildModuleSteps(model, options = {}) {
377
383
  const location = { libid: model.libid, major: model.major, minor: model.minor, lcid: model.lcid, ...(options.path ? { path: options.path } : {}) };
378
384
  const builder = new Builder(model, location);
379
385
  const { types: _types, ...library } = model;
@@ -403,6 +409,7 @@ export function buildModule(model, options = {}) {
403
409
  define(constant.name, decodeDefault(constant.value));
404
410
  break;
405
411
  }
412
+ yield;
406
413
  }
407
414
  // Aliases of local enums, records and interfaces name the same definition
408
415
  // (MIDL often names the enum itself __MIDL___MIDL_itf_...).