@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
@@ -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
- ctypes.memset(pExcepInfo, 0, ctypes.sizeof(EXCEPINFO));
206
- const info = EXCEPINFO.from_address(pExcepInfo);
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"> & {
@@ -4,23 +4,28 @@ import { getIDsOfNames, invoke } from "../automation/dispatch.js";
4
4
  import { DISPATCH_METHOD } from "../automation/constants.js";
5
5
  import { VARIANT_SIZE, comReference, writeVariant } from "../automation/variant.js";
6
6
  import { classifyParamType } from "../commethod.js";
7
- import { COMError } from "../errors.js";
7
+ import { checkHRESULT, COMError } from "../errors.js";
8
8
  import { GUID, toGUID } from "../guid.js";
9
9
  import { DISP_E_BADINDEX, TYPE_E_ELEMENTNOTFOUND, CLASS_E_NOAGGREGATION, CONNECT_E_CANNOTCONNECT, CONNECT_E_NOCONNECTION, E_FAIL, E_NOINTERFACE, E_NOTIMPL, E_POINTER, E_UNEXPECTED, S_FALSE, S_OK } from "../hresult.js";
10
10
  import { derivesFrom } from "../interface.js";
11
+ import { IAgileObject, IWeakReference } from "../interfaces/agile.js";
11
12
  import { IClassFactory } from "../interfaces/classfactory.js";
12
13
  import { IConnectionPoint, IConnectionPointContainer, IProvideClassInfo2 } from "../interfaces/connectionpoint.js";
13
14
  import { IDispatch, IEnumVARIANT } from "../interfaces/dispatch.js";
14
15
  import { ISupportErrorInfo } from "../interfaces/errorinfo.js";
15
16
  import { IUnknown } from "../interfaces/unknown.js";
16
- import { POINTER_SIZE, readMemory, writeMemory } from "../low-level/native.js";
17
+ import { IID_IMarshal } from "../low-level/iids.js";
18
+ import { isAggregateClass, ole32, POINTER_SIZE, writeMemory } from "../low-level/native.js";
19
+ import { QueryInterfaceAt, rawAddRef, rawQueryInterface, rawRelease, readGuidString, vtableEntry } from "../low-level/vtable.js";
17
20
  import { COMPointer, setLocalThreading, sync } from "../pointer.js";
21
+ import { onApartmentTeardown } from "../tracking.js";
18
22
  import { ReturnHRESULT, dispatchGetIDsOfNames, dispatchInvoke, defaultIdsOfNames, defaultInvoke } from "./automation.js";
19
23
  import { setErrorInfo } from "./errorinfo.js";
20
24
  import { typeLibLocationOf } from "../typelib/coclass.js";
21
25
  import { loadTypeLib } from "../typelib/load.js";
22
26
  import { ITypeInfo, ITypeLib } from "../interfaces/typeinfo.js";
23
- import { callbackArgtype, decodeIndirect, decodeInput, encodeOutput, resetOutput } from "./marshal.js";
27
+ import { callbackArgtype, decodeIndirect, decodeInput, encodeOutput, resetOutput, structureBytes } from "./marshal.js";
28
+ const IID_IMARSHAL_KEY = IID_IMarshal.toString();
24
29
  // Block address -> object. Weak: the JavaScript object owns its blocks; while
25
30
  // COM holds references it is kept in `alive`.
26
31
  const instances = new Map();
@@ -81,8 +86,9 @@ function vtableFor(iface, threading) {
81
86
  let vtable = byThreading.get(threading);
82
87
  if (!vtable) {
83
88
  const callbacks = iface.allMethods.map((spec, slot) => {
84
- const restype = slot === 1 || slot === 2 ? ctypes.c_uint32 : spec.restype === ctypes.HRESULT ? ctypes.c_int32 : spec.restype;
85
- const argtypes = [ctypes.c_void_p, ...spec.argtypes.map(callbackArgtype)];
89
+ const structReturn = slot > 2 && spec.restype !== ctypes.HRESULT && isAggregateClass(spec.restype) ? spec.restype : null;
90
+ const restype = slot === 1 || slot === 2 ? ctypes.c_uint32 : spec.restype === ctypes.HRESULT ? ctypes.c_int32 : structReturn ? ctypes.c_void_p : spec.restype;
91
+ const argtypes = structReturn ? [ctypes.c_void_p, ctypes.c_void_p, ...spec.argtypes.map(callbackArgtype)] : [ctypes.c_void_p, ...spec.argtypes.map(callbackArgtype)];
86
92
  const handler = (self, ...args) => dispatchSlot(self, iface, slot, args);
87
93
  if (threading === "free")
88
94
  return ctypes.threadSafeCallback(handler, restype, argtypes, "stdcall").unref();
@@ -125,7 +131,7 @@ function releaseArguments(values) {
125
131
  if (value instanceof COMPointer && !value.released)
126
132
  value.Release();
127
133
  }
128
- function callCommethod(object, implementation, spec, declaring, args) {
134
+ function callCommethod(object, implementation, spec, declaring, args, rawReturn = false) {
129
135
  const params = spec.params ?? [];
130
136
  const kinds = kindsOf(spec);
131
137
  const inputs = [];
@@ -154,7 +160,7 @@ function callCommethod(object, implementation, spec, declaring, args) {
154
160
  });
155
161
  const result = implementation.apply(object, inputs);
156
162
  if (!outputs.length)
157
- return typeof result === "number" ? result : S_OK;
163
+ return rawReturn ? result : typeof result === "number" ? result : S_OK;
158
164
  const values = outputs.length === 1 ? [result] : result;
159
165
  if (!Array.isArray(values) || values.length !== outputs.length)
160
166
  throw new TypeError(`${spec.name} must return ${outputs.length} values`);
@@ -240,10 +246,28 @@ export class COMObject {
240
246
  static {
241
247
  queryReference = (object, iid) => {
242
248
  const address = object.#blockFor(iid);
243
- if (address === null)
244
- return null;
245
- object.#addRef();
246
- return address;
249
+ if (address !== null) {
250
+ object.#addRef();
251
+ return address;
252
+ }
253
+ const guid = toGUID(iid);
254
+ const key = guid.toString();
255
+ const delegated = object.#state.delegates?.get(key);
256
+ if (delegated) {
257
+ rawAddRef(delegated.address);
258
+ return delegated.address;
259
+ }
260
+ const ftm = object.#state.ftm;
261
+ if (ftm && key === IID_IMARSHAL_KEY) {
262
+ const [hr, ptr] = rawQueryInterface(ftm, guid);
263
+ return hr >= 0 && ptr ? ptr : null;
264
+ }
265
+ const inner = object.#state.inner;
266
+ if (inner) {
267
+ const [hr, ptr] = rawQueryInterface(inner.address, guid);
268
+ return hr >= 0 && ptr ? ptr : null;
269
+ }
270
+ return null;
247
271
  };
248
272
  dispatchSlot = (self, iface, slot, args) => {
249
273
  const entry = self ? instances.get(self) : undefined;
@@ -270,7 +294,7 @@ export class COMObject {
270
294
  return block;
271
295
  });
272
296
  const addresses = blocks.map((block) => ctypes.addressof(block));
273
- this.#state = { references: 0, info, blocks, addresses, connectionPoints: null };
297
+ this.#state = { references: 0, info, blocks, addresses, connectionPoints: null, inner: null, ftm: null, delegates: null, weakReference: null };
274
298
  const reference = new WeakRef(this);
275
299
  addresses.forEach((address, index) => instances.set(address, { object: reference, index }));
276
300
  forget.register(this, Object.freeze([...addresses]));
@@ -292,12 +316,26 @@ export class COMObject {
292
316
  catch (error) {
293
317
  this.constructor.onError?.(error, this);
294
318
  }
319
+ finally {
320
+ if (state.connectionPoints) {
321
+ for (const [key, point] of state.connectionPoints) {
322
+ if (point.refCount === 0) {
323
+ point.disconnectAll();
324
+ state.connectionPoints.delete(key);
325
+ }
326
+ }
327
+ if (state.connectionPoints.size === 0)
328
+ state.connectionPoints = null;
329
+ }
330
+ this.releaseAggregate();
331
+ }
295
332
  }
296
333
  return state.references;
297
334
  }
298
- /** Address of the block implementing `iid`, or `null`. */
335
+ /** Address of the block implementing `iid` (GUID, GUID string, or pre-normalized uppercase string), or `null`. */
299
336
  #blockFor(iid) {
300
- const index = this.#state.info.lookup.get(toGUID(iid).toString());
337
+ const key = typeof iid === "string" && iid.length === 38 && iid[0] === "{" && iid[37] === "}" ? iid.toUpperCase() : toGUID(iid).toString();
338
+ const index = this.#state.info.lookup.get(key);
301
339
  return index === undefined ? null : this.#state.addresses[index];
302
340
  }
303
341
  #queryInterface(riid, out) {
@@ -306,17 +344,65 @@ export class COMObject {
306
344
  ctypes.writeValue(out, ctypes.c_void_p, 0n);
307
345
  if (!riid)
308
346
  return E_POINTER;
309
- const address = this.#blockFor(new GUID(new Uint8Array(readMemory(riid, 16))));
310
- if (address === null)
311
- return E_NOINTERFACE;
312
- this.#addRef();
313
- ctypes.writeValue(out, ctypes.c_void_p, address);
314
- return S_OK;
347
+ const iidKey = readGuidString(riid);
348
+ const index = this.#state.info.lookup.get(iidKey);
349
+ if (index !== undefined) {
350
+ this.#addRef();
351
+ ctypes.writeValue(out, ctypes.c_void_p, this.#state.addresses[index]);
352
+ return S_OK;
353
+ }
354
+ const delegated = this.#state.delegates?.get(iidKey);
355
+ if (delegated) {
356
+ rawAddRef(delegated.address);
357
+ ctypes.writeValue(out, ctypes.c_void_p, delegated.address);
358
+ return S_OK;
359
+ }
360
+ const ftm = this.#state.ftm;
361
+ if (ftm && iidKey === IID_IMARSHAL_KEY) {
362
+ try {
363
+ return QueryInterfaceAt(vtableEntry(ftm, 0))(ftm, riid, out);
364
+ }
365
+ catch {
366
+ return E_NOINTERFACE;
367
+ }
368
+ }
369
+ const inner = this.#state.inner;
370
+ if (inner) {
371
+ try {
372
+ return QueryInterfaceAt(vtableEntry(inner.address, 0))(inner.address, riid, out);
373
+ }
374
+ catch {
375
+ return E_NOINTERFACE;
376
+ }
377
+ }
378
+ return E_NOINTERFACE;
315
379
  }
316
380
  #call(iface, slot, args) {
317
381
  const spec = iface.allMethods[slot];
318
382
  const declaring = declaringInterface(iface, slot);
319
383
  const hresult = spec.restype === ctypes.HRESULT;
384
+ const structReturn = !hresult && isAggregateClass(spec.restype) ? spec.restype : null;
385
+ if (structReturn) {
386
+ const sret = args[0];
387
+ if (!sret)
388
+ return 0n;
389
+ const methodArgs = args.slice(1);
390
+ try {
391
+ const implementation = implementationOf(this, spec);
392
+ if (!implementation) {
393
+ writeMemory(sret, Buffer.alloc(ctypes.sizeof(structReturn)));
394
+ return sret;
395
+ }
396
+ const value = spec.marshal ? callCommethod(this, implementation, spec, declaring, methodArgs, true) : implementation.apply(this, methodArgs);
397
+ writeMemory(sret, structureBytes(structReturn, value));
398
+ return sret;
399
+ }
400
+ catch (error) {
401
+ this.constructor.onError?.(error, this);
402
+ writeMemory(sret, Buffer.alloc(ctypes.sizeof(structReturn)));
403
+ return sret;
404
+ }
405
+ }
320
406
  try {
321
407
  const implementation = implementationOf(this, spec);
322
408
  if (!implementation)
@@ -346,15 +432,170 @@ export class COMObject {
346
432
  return this.#state.info.interfaces;
347
433
  }
348
434
  supportsInterface(iid) {
349
- return this.#blockFor(iid) !== null;
435
+ if (this.#blockFor(iid) !== null)
436
+ return true;
437
+ const guid = toGUID(iid);
438
+ const key = guid.toString();
439
+ if (this.#state.delegates?.has(key))
440
+ return true;
441
+ if (this.#state.ftm && key === IID_IMARSHAL_KEY)
442
+ return true;
443
+ const inner = this.#state.inner;
444
+ if (inner) {
445
+ const [hr, ptr] = rawQueryInterface(inner.address, guid);
446
+ if (hr >= 0 && ptr) {
447
+ rawRelease(ptr);
448
+ return true;
449
+ }
450
+ }
451
+ return false;
452
+ }
453
+ /**
454
+ * Native address of the vtable block implementing `iface` (default: primary
455
+ * interface block `[0]`, suitable as `outer` / `baseInterface` in COM or
456
+ * WinRT aggregation) without adding a reference.
457
+ */
458
+ addressOf(iface) {
459
+ if (!iface)
460
+ return this.#state.addresses[0];
461
+ const address = this.#blockFor(iface.iid);
462
+ if (address === null)
463
+ throw new COMError(E_NOINTERFACE, { method: `${this.constructor.name}::addressOf(${iface.name})` });
464
+ return address;
465
+ }
466
+ /**
467
+ * Attach an inner non-delegating `IUnknown` for COM / WinRT aggregation.
468
+ * Any `QueryInterface` for an IID not implemented or delegated by this
469
+ * object is forwarded to `inner`.
470
+ *
471
+ * - Passing a `COMPointer` takes its own `AddRef` (safe with `using inner`).
472
+ * - Passing a raw `bigint` adopts 1 reference by default (`own: true`); pass
473
+ * `{ own: false }` if the caller retains ownership.
474
+ * - Passing `null` detaches and releases the current owned inner object.
475
+ */
476
+ setAggregateInner(inner, options = {}) {
477
+ const prev = this.#state.inner;
478
+ this.#state.inner = null;
479
+ if (prev?.owned)
480
+ rawRelease(prev.address);
481
+ if (inner === null || inner === 0n)
482
+ return;
483
+ if (inner instanceof COMPointer) {
484
+ const addr = inner.address;
485
+ rawAddRef(addr);
486
+ this.#state.inner = { address: addr, owned: true };
487
+ return;
488
+ }
489
+ if (typeof inner !== "bigint")
490
+ throw new TypeError("setAggregateInner expects a COMPointer, bigint address, or null");
491
+ this.#state.inner = { address: inner, owned: options.own ?? true };
492
+ }
493
+ /**
494
+ * Delegate `QueryInterface(iface)` to `target`. Resolves `iface` once and
495
+ * caches the pointer so incoming native `QueryInterface` calls only `AddRef`.
496
+ */
497
+ delegateInterface(iface, target, options = {}) {
498
+ const key = iface.iid.toString();
499
+ let entry;
500
+ if (target instanceof COMPointer) {
501
+ const qi = target.QueryInterface(iface);
502
+ const addr = qi.detach();
503
+ entry = { address: addr, owned: true };
504
+ }
505
+ else if (target instanceof _a) {
506
+ const addr = queryObject(target, iface.iid);
507
+ if (addr === null)
508
+ throw new COMError(E_NOINTERFACE, { method: `${this.constructor.name}::delegateInterface(${iface.name})` });
509
+ entry = { address: addr, owned: true };
510
+ }
511
+ else if (typeof target === "bigint" && target !== 0n) {
512
+ const owned = options.own ?? false;
513
+ if (!owned)
514
+ rawAddRef(target);
515
+ entry = { address: target, owned: true };
516
+ }
517
+ else {
518
+ throw new TypeError("delegateInterface expects a COMPointer, COMObject, or non-NULL bigint address");
519
+ }
520
+ const delegates = (this.#state.delegates ??= new Map());
521
+ const prev = delegates.get(key);
522
+ delegates.set(key, entry);
523
+ if (prev?.owned)
524
+ rawRelease(prev.address);
525
+ }
526
+ /** Remove a previously delegated interface and release its cached reference. */
527
+ undelegateInterface(iface) {
528
+ const delegates = this.#state.delegates;
529
+ if (!delegates)
530
+ return;
531
+ const key = iface.iid.toString();
532
+ const prev = delegates.get(key);
533
+ if (!prev)
534
+ return;
535
+ delegates.delete(key);
536
+ if (prev.owned)
537
+ rawRelease(prev.address);
538
+ }
539
+ /**
540
+ * Aggregate the Windows Free-Threaded Marshaler (`CoCreateFreeThreadedMarshaler`)
541
+ * so `QueryInterface(IMarshal)` forwards to the FTM without creating reference
542
+ * cycles. Can be combined with {@link setAggregateInner}.
543
+ */
544
+ enableFreeThreadedMarshaler() {
545
+ if (this.#state.ftm !== null)
546
+ return;
547
+ const out = new ctypes.c_void_p();
548
+ checkHRESULT(ole32().CoCreateFreeThreadedMarshaler(this.#state.addresses[0], ctypes.byref(out)), "CoCreateFreeThreadedMarshaler");
549
+ if (!out.value)
550
+ throw new COMError(E_POINTER, { method: "CoCreateFreeThreadedMarshaler" });
551
+ this.#state.ftm = out.value;
552
+ }
553
+ /** Release the attached aggregate inner object, FTM, and all cached delegate references. */
554
+ releaseAggregate() {
555
+ const inner = this.#state.inner;
556
+ this.#state.inner = null;
557
+ if (inner?.owned)
558
+ rawRelease(inner.address);
559
+ const ftm = this.#state.ftm;
560
+ this.#state.ftm = null;
561
+ if (ftm)
562
+ rawRelease(ftm);
563
+ const delegates = this.#state.delegates;
564
+ this.#state.delegates = null;
565
+ if (delegates) {
566
+ for (const entry of delegates.values()) {
567
+ if (entry.owned)
568
+ rawRelease(entry.address);
569
+ }
570
+ delegates.clear();
571
+ }
350
572
  }
351
573
  /** A new owned pointer to this object (`AddRef`); throws `E_NOINTERFACE`. */
352
574
  QueryInterface(iface) {
353
575
  const address = this.#blockFor(iface.iid);
354
- if (address === null)
355
- throw new COMError(E_NOINTERFACE, { method: `${this.constructor.name}::QueryInterface(${iface.name})` });
356
- this.#addRef();
357
- return COMPointer.fromAddress(address, iface);
576
+ if (address !== null) {
577
+ this.#addRef();
578
+ return COMPointer.fromAddress(address, iface);
579
+ }
580
+ const key = iface.iid.toString();
581
+ const delegated = this.#state.delegates?.get(key);
582
+ if (delegated) {
583
+ rawAddRef(delegated.address);
584
+ return COMPointer.fromAddress(delegated.address, iface);
585
+ }
586
+ const ftm = this.#state.ftm;
587
+ if (ftm && key === IID_IMARSHAL_KEY) {
588
+ const [hr, ptr] = rawQueryInterface(ftm, iface.iid);
589
+ if (hr >= 0 && ptr)
590
+ return COMPointer.fromAddress(ptr, iface);
591
+ }
592
+ const inner = this.#state.inner;
593
+ if (inner) {
594
+ const [hr, ptr] = rawQueryInterface(inner.address, iface.iid);
595
+ if (hr >= 0 && ptr)
596
+ return COMPointer.fromAddress(ptr, iface);
597
+ }
598
+ throw new COMError(E_NOINTERFACE, { method: `${this.constructor.name}::QueryInterface(${iface.name})` });
358
599
  }
359
600
  /** Native `AddRef`/`Release` for code managing references by hand. */
360
601
  AddRef() {
@@ -373,6 +614,16 @@ export class COMObject {
373
614
  InterfaceSupportsErrorInfo(riid) {
374
615
  return riid && this.supportsInterface(riid) ? S_OK : S_FALSE;
375
616
  }
617
+ // ── IWeakReferenceSource ──
618
+ /** Return a weak reference (`IWeakReference`) to this `COMObject`. */
619
+ GetWeakReference() {
620
+ const existing = this.#state.weakReference?.deref();
621
+ if (existing)
622
+ return existing;
623
+ const weak = this.#state.info.threading === "free" ? new FreeWeakReference(this) : new WeakReference(this);
624
+ this.#state.weakReference = new WeakRef(weak);
625
+ return weak;
626
+ }
376
627
  // ── IDispatch (late binding over the JavaScript members) ──
377
628
  GetTypeInfoCount(pctinfo) {
378
629
  if (!pctinfo)
@@ -505,6 +756,7 @@ function dispatchTypeInfoSource(object) {
505
756
  return null;
506
757
  }
507
758
  const typeLibraries = new Map();
759
+ onApartmentTeardown(() => typeLibraries.clear());
508
760
  /**
509
761
  * Type library of a class: `_reg_typelib_` (with `_typelib_path_`), else the
510
762
  * library of the first interface built from one.
@@ -630,9 +882,49 @@ export class ConnectionPoint extends COMObject {
630
882
  EnumConnections() {
631
883
  throw new COMError(E_NOTIMPL);
632
884
  }
885
+ /** Disconnect and release every advised sink (called automatically when the container is released). */
886
+ disconnectAll() {
887
+ for (const sink of this.#sinks.values()) {
888
+ if (!sink.released)
889
+ sink.Release();
890
+ }
891
+ this.#sinks.clear();
892
+ }
633
893
  _final_release_() {
634
- // The container keeps its connection points; sinks stay until Unadvise.
894
+ // No COM client holds this connection point anymore; release any forgotten sinks.
895
+ this.disconnectAll();
896
+ }
897
+ }
898
+ /**
899
+ * `IWeakReference` implementation for a JavaScript `COMObject`. Resolves to
900
+ * `null` (`S_OK` with `*objectReference = NULL`) once the target's native
901
+ * reference count drops to zero, matching COM/WinRT weak-reference semantics.
902
+ */
903
+ export class WeakReference extends COMObject {
904
+ static _com_interfaces_ = [IWeakReference, IAgileObject];
905
+ #target;
906
+ constructor(target) {
907
+ super();
908
+ this.#target = new WeakRef(target);
635
909
  }
910
+ Resolve(riid, objectReference) {
911
+ if (!objectReference)
912
+ return E_POINTER;
913
+ ctypes.writeValue(objectReference, ctypes.c_void_p, 0n);
914
+ if (!riid)
915
+ return E_POINTER;
916
+ const target = this.#target.deref();
917
+ if (!target || target.refCount === 0)
918
+ return S_OK;
919
+ const address = queryObject(target, readGuidString(riid));
920
+ if (address === null)
921
+ return E_NOINTERFACE;
922
+ ctypes.writeValue(objectReference, ctypes.c_void_p, address);
923
+ return S_OK;
924
+ }
925
+ }
926
+ class FreeWeakReference extends WeakReference {
927
+ static _threading_ = "free";
636
928
  }
637
929
  /** `IClassFactory` creating instances of a `COMObject` class. */
638
930
  export class ClassFactory extends COMObject {
@@ -652,7 +944,7 @@ export class ClassFactory extends COMObject {
652
944
  if (!riid)
653
945
  return E_POINTER;
654
946
  const object = new this.type();
655
- const address = queryObject(object, new GUID(new Uint8Array(readMemory(riid, 16))));
947
+ const address = queryObject(object, readGuidString(riid));
656
948
  if (address === null)
657
949
  return E_NOINTERFACE;
658
950
  ctypes.writeValue(ppv, ctypes.c_void_p, address);
@@ -1,4 +1,4 @@
1
- export { COMObject, VariantEnumerator, ConnectionPoint, ClassFactory, getLiveObjectCount, queryObject } from "./comobject.ts";
1
+ export { COMObject, VariantEnumerator, ConnectionPoint, WeakReference, ClassFactory, getLiveObjectCount, queryObject } from "./comobject.ts";
2
2
  export type { Threading } from "./comobject.ts";
3
3
  export { DispatchError, ReturnHRESULT, defaultIdsOfNames, defaultInvoke } from "./automation.ts";
4
4
  export type { InvokeArguments } from "./automation.ts";
@@ -1,4 +1,4 @@
1
- export { COMObject, VariantEnumerator, ConnectionPoint, ClassFactory, getLiveObjectCount, queryObject } from "./comobject.js";
1
+ export { COMObject, VariantEnumerator, ConnectionPoint, WeakReference, ClassFactory, getLiveObjectCount, queryObject } from "./comobject.js";
2
2
  export { DispatchError, ReturnHRESULT, defaultIdsOfNames, defaultInvoke } from "./automation.js";
3
3
  export { setErrorInfo } from "./errorinfo.js";
4
4
  export { registerClassObject, registerServer, unregisterServer, runLocalServer, UseCommandLine, REGCLS_SINGLEUSE, REGCLS_MULTIPLEUSE, REGCLS_MULTI_SEPARATE, REGCLS_SUSPENDED } from "./register.js";
@@ -13,5 +13,6 @@ export declare function decodeInput(kind: ParamKind, native: unknown, self: Inte
13
13
  export declare function decodeIndirect(kind: ParamKind, address: bigint, self: InterfaceDef<any>): unknown;
14
14
  /** Reset a pure `out` parameter, so that a failure leaves NULL / VT_EMPTY. */
15
15
  export declare function resetOutput(kind: ParamKind, address: bigint): void;
16
+ export declare function structureBytes(type: new (...args: any[]) => ctypes.CDataAggregate, value: unknown): Buffer;
16
17
  /** Write an `out` value at `address`; `inout` releases the previous value first. */
17
18
  export declare function encodeOutput(kind: ParamKind, address: bigint, value: unknown, inout: boolean, self: InterfaceDef<any>): void;
@@ -8,7 +8,7 @@ import { checkHRESULT } from "../errors.js";
8
8
  import { GUID, toGUID } from "../guid.js";
9
9
  import { DISP_E_PARAMNOTFOUND } from "../hresult.js";
10
10
  import { derivesFrom } from "../interface.js";
11
- import { allocBSTR, flushMirror, ole32, oleaut32, readBSTR, readMemory, writeMemory } from "../low-level/native.js";
11
+ import { allocBSTR, flushMirror, isPointerType, ole32, oleaut32, readBSTR, readMemory, refreshMirror, writeMemory } 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
  // Server side of the parameter conversions: what a JavaScript implementation
@@ -21,7 +21,7 @@ function writePointer(address, value) {
21
21
  }
22
22
  /** Callback argument type: pointers arrive as raw addresses. */
23
23
  export function callbackArgtype(type) {
24
- return typeof type === "object" && type !== null && "_type_" in type && "_pointerTo" in type ? ctypes.c_void_p : type;
24
+ return isPointerType(type) ? ctypes.c_void_p : type;
25
25
  }
26
26
  /** `VT_ERROR`/`DISP_E_PARAMNOTFOUND` (an omitted optional argument) becomes `undefined`. */
27
27
  export function omittedToUndefined(value) {
@@ -54,7 +54,7 @@ export function decodeInput(kind, native, self) {
54
54
  case "lpolestr":
55
55
  return native ? ctypes.wstring_at(native) : null;
56
56
  case "refguid":
57
- return native ? new GUID(new Uint8Array(readMemory(native, 16))) : null;
57
+ return native ? new GUID(readMemory(native, 16)) : null;
58
58
  case "safearray":
59
59
  return native ? readSafeArray(native, kind.vt) : null;
60
60
  case "interface":
@@ -94,7 +94,7 @@ export function decodeIndirect(kind, address, self) {
94
94
  case "variant":
95
95
  return omittedToUndefined(readVariant(readMemory(address, VARIANT_SIZE)));
96
96
  case "refguid":
97
- return new GUID(new Uint8Array(readMemory(address, 16)));
97
+ return new GUID(readMemory(address, 16));
98
98
  case "struct":
99
99
  return kind.type.from_buffer_copy(readMemory(address, ctypes.sizeof(kind.type)));
100
100
  case "simple":
@@ -122,12 +122,18 @@ export function resetOutput(kind, address) {
122
122
  return;
123
123
  }
124
124
  }
125
- function structureBytes(type, value) {
126
- if (value instanceof type)
125
+ export function structureBytes(type, value) {
126
+ if (value instanceof type) {
127
+ refreshMirror(value._buffer);
127
128
  return value._buffer;
129
+ }
130
+ if (value === undefined || value === null)
131
+ return Buffer.alloc(ctypes.sizeof(type));
128
132
  if ((type === GUID || type.prototype instanceof GUID) && (typeof value === "string" || value instanceof GUID))
129
133
  return toGUID(value)._buffer;
130
- return type.create(value)._buffer;
134
+ const created = type.create(value);
135
+ refreshMirror(created._buffer);
136
+ return created._buffer;
131
137
  }
132
138
  /** Write an `out` value at `address`; `inout` releases the previous value first. */
133
139
  export function encodeOutput(kind, address, value, inout, self) {