@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
@@ -5,9 +5,16 @@ import type { COMErrorDetails } from "./errors.ts";
5
5
  * Returns `null` when no error object is set.
6
6
  */
7
7
  export declare function takeErrorInfo(): COMErrorDetails | null;
8
+ /**
9
+ * Take the current thread's `IRestrictedErrorInfo` (`GetRestrictedErrorInfo`),
10
+ * clearing it. When `expectedHresult` is provided, returns `null` if the stored
11
+ * restricted error does not match that HRESULT.
12
+ */
13
+ export declare function takeRestrictedErrorInfo(expectedHresult?: number): COMErrorDetails | null;
8
14
  /**
9
15
  * Error details for a failed method of interface `iid` called on `object`:
10
- * read only if the object declares `ISupportErrorInfo` support for `iid`,
11
- * as Python ctypes/comtypes do.
16
+ * reads `IErrorInfo` when the object declares `ISupportErrorInfo` support for
17
+ * `iid` (as Python ctypes/comtypes do), and falls back to `IRestrictedErrorInfo`
18
+ * (WinRT / modern COM) when `ISupportErrorInfo` is not implemented.
12
19
  */
13
- export declare function errorInfoFor(object: bigint, iid: GUID): COMErrorDetails | null;
20
+ export declare function errorInfoFor(object: bigint, iid: GUID, hresult?: number): COMErrorDetails | null;
package/dist/errorinfo.js CHANGED
@@ -1,12 +1,10 @@
1
1
  import * as ctypes from "node-ctypes";
2
2
  import { GUID } from "./guid.js";
3
- import { oleaut32, takeBSTR } from "./low-level/native.js";
4
- import { functionCache, rawQueryInterface, rawRelease, vtableEntry } from "./low-level/vtable.js";
3
+ import { IID_ISupportErrorInfo } from "./low-level/iids.js";
4
+ import { combase, oleaut32, takeBSTR } from "./low-level/native.js";
5
+ import { functionCache, PointerArgAt, rawQueryInterface, rawRelease, vtableEntry } from "./low-level/vtable.js";
5
6
  const { c_int32, c_uint32, c_void_p } = ctypes;
6
- const IID_ISupportErrorInfo = new GUID("{DF0B3D60-548F-101B-8E65-08002B2BD119}");
7
- // IErrorInfo getters and ISupportErrorInfo::InterfaceSupportsErrorInfo share
8
- // the HRESULT (this, pointer) signature.
9
- const PointerArgAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p));
7
+ const RestrictedDetailsAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p));
10
8
  function readBSTR(errorInfo, slot) {
11
9
  const out = new c_void_p();
12
10
  if (PointerArgAt(vtableEntry(errorInfo, slot))(errorInfo, ctypes.byref(out)) < 0)
@@ -39,24 +37,74 @@ export function takeErrorInfo() {
39
37
  rawRelease(errorInfo);
40
38
  }
41
39
  }
40
+ /**
41
+ * Take the current thread's `IRestrictedErrorInfo` (`GetRestrictedErrorInfo`),
42
+ * clearing it. When `expectedHresult` is provided, returns `null` if the stored
43
+ * restricted error does not match that HRESULT.
44
+ */
45
+ export function takeRestrictedErrorInfo(expectedHresult) {
46
+ const api = combase();
47
+ if (!api)
48
+ return null;
49
+ const out = new c_void_p();
50
+ if (api.GetRestrictedErrorInfo(ctypes.byref(out)) !== 0 || !out.value)
51
+ return null;
52
+ const restricted = out.value;
53
+ try {
54
+ const desc = new c_void_p();
55
+ const err = new c_int32();
56
+ const restrictedDesc = new c_void_p();
57
+ const capabilitySid = new c_void_p();
58
+ const hr = RestrictedDetailsAt(vtableEntry(restricted, 3))(restricted, ctypes.byref(desc), ctypes.byref(err), ctypes.byref(restrictedDesc), ctypes.byref(capabilitySid));
59
+ const descriptionText = hr >= 0 ? takeBSTR(desc.value) : null;
60
+ const restrictedText = hr >= 0 ? takeBSTR(restrictedDesc.value) : null;
61
+ const capabilityText = hr >= 0 ? takeBSTR(capabilitySid.value) : null;
62
+ if (hr < 0)
63
+ return null;
64
+ if (expectedHresult !== undefined && err.value !== expectedHresult)
65
+ return null;
66
+ const referenceText = readBSTR(restricted, 4);
67
+ const trimmedRestricted = restrictedText?.trim() || null;
68
+ const trimmedDescription = descriptionText?.trim() || null;
69
+ return {
70
+ guid: null,
71
+ source: null,
72
+ description: trimmedRestricted ?? trimmedDescription,
73
+ helpFile: null,
74
+ helpContext: 0,
75
+ restrictedDescription: trimmedRestricted,
76
+ capabilitySid: capabilityText?.trim() || null,
77
+ reference: referenceText?.trim() || null,
78
+ };
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ finally {
84
+ rawRelease(restricted);
85
+ }
86
+ }
42
87
  /**
43
88
  * Error details for a failed method of interface `iid` called on `object`:
44
- * read only if the object declares `ISupportErrorInfo` support for `iid`,
45
- * as Python ctypes/comtypes do.
89
+ * reads `IErrorInfo` when the object declares `ISupportErrorInfo` support for
90
+ * `iid` (as Python ctypes/comtypes do), and falls back to `IRestrictedErrorInfo`
91
+ * (WinRT / modern COM) when `ISupportErrorInfo` is not implemented.
46
92
  */
47
- export function errorInfoFor(object, iid) {
93
+ export function errorInfoFor(object, iid, hresult) {
48
94
  try {
49
95
  const [hr, support] = rawQueryInterface(object, IID_ISupportErrorInfo);
50
- if (hr < 0 || !support)
51
- return null;
52
- let supported;
53
- try {
54
- supported = PointerArgAt(vtableEntry(support, 3))(support, iid._buffer) === 0;
55
- }
56
- finally {
57
- rawRelease(support);
96
+ if (hr >= 0 && support) {
97
+ let supported;
98
+ try {
99
+ supported = PointerArgAt(vtableEntry(support, 3))(support, iid._buffer) === 0;
100
+ }
101
+ finally {
102
+ rawRelease(support);
103
+ }
104
+ if (supported)
105
+ return takeErrorInfo();
58
106
  }
59
- return supported ? takeErrorInfo() : null;
107
+ return takeRestrictedErrorInfo(hresult);
60
108
  }
61
109
  catch {
62
110
  return null;
package/dist/errors.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { GUID } from "./guid.ts";
2
- /** Rich error information from `IErrorInfo` (Python: the `details` tuple). */
2
+ /** Rich error information from `IErrorInfo` or `IRestrictedErrorInfo` (Python: the `details` tuple). */
3
3
  export interface COMErrorDetails {
4
4
  readonly description: string | null;
5
5
  readonly source: string | null;
@@ -10,6 +10,12 @@ export interface COMErrorDetails {
10
10
  readonly scode?: number;
11
11
  /** Index of the offending argument for `DISP_E_TYPEMISMATCH` / `DISP_E_PARAMNOTFOUND`. */
12
12
  readonly argumentIndex?: number;
13
+ /** Detailed restricted error description from `IRestrictedErrorInfo` (WinRT / modern COM), when available. */
14
+ readonly restrictedDescription?: string | null;
15
+ /** Missing capability SID reported by `IRestrictedErrorInfo`, when available. */
16
+ readonly capabilitySid?: string | null;
17
+ /** Diagnostic reference string from `IRestrictedErrorInfo::GetReference`, when available. */
18
+ readonly reference?: string | null;
13
19
  }
14
20
  export interface COMErrorOptions {
15
21
  /** System message for the HRESULT; defaults to `FormatMessageW`. */
@@ -13,10 +13,14 @@ export declare function isAgile(address: bigint): boolean;
13
13
  export declare function releaseOnExecutor(address: bigint, generation: number): void;
14
14
  /**
15
15
  * A reference to the home pointer `address` usable on the executor (owned by
16
- * the executor), through the Global Interface Table; `null` when the
17
- * interface cannot be marshaled (no proxy/stub).
16
+ * the executor), through the Global Interface Table, together with the
17
+ * executor generation that owns it; `null` when the interface cannot be
18
+ * marshaled (no proxy/stub).
18
19
  */
19
- export declare function referenceForExecutor(address: bigint, iid: GUID): Promise<bigint | null>;
20
+ export declare function referenceForExecutor(address: bigint, iid: GUID): Promise<{
21
+ readonly address: bigint;
22
+ readonly generation: number;
23
+ } | null>;
20
24
  /** Memory receiving an interface result: an `out` interface pointer, a VARIANT or a `SAFEARRAY*`. */
21
25
  export interface ResultLocation {
22
26
  readonly location: bigint;
@@ -10,39 +10,39 @@ import { APTTYPE_MTA, CLSCTX_INPROC_SERVER } from "../constants.js";
10
10
  import { COMError } from "../errors.js";
11
11
  import { GUID } from "../guid.js";
12
12
  import { CO_E_NOTINITIALIZED } from "../hresult.js";
13
+ import { CLSID_InProcFreeMarshaler, CLSID_StdGlobalInterfaceTable, IID_IAgileObject, IID_IClientSecurity, IID_IDispatch, IID_IGlobalInterfaceTable, IID_IMarshal, IID_IUnknown } from "../low-level/iids.js";
13
14
  import { ole32, oleaut32 } from "../low-level/native.js";
14
- import { functionCache, rawQueryInterface, rawRelease, vtableEntry } from "../low-level/vtable.js";
15
- import { apartmentGeneration } from "../tracking.js";
16
- import { executorAlive, executorGeneration, executorTarget } from "./executor.js";
15
+ import { functionCache, QueryInterfaceAt, rawQueryInterface, rawRelease, RefCountAt, vtableEntry } from "../low-level/vtable.js";
16
+ import { apartmentGeneration, initCount, onApartmentTeardown } from "../tracking.js";
17
+ import { executorAlive, executorGeneration, executorTarget, onExecutorStopping } from "./executor.js";
17
18
  const { c_int32, c_uint16, c_uint32, c_void_p } = ctypes;
18
- const CLSID_StdGlobalInterfaceTable = new GUID("{00000323-0000-0000-C000-000000000046}");
19
- const IID_IGlobalInterfaceTable = new GUID("{00000146-0000-0000-C000-000000000046}");
20
- const IID_IAgileObject = new GUID("{94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90}");
21
- const IID_IMarshal = new GUID("{00000003-0000-0000-C000-000000000046}");
22
- const IID_IClientSecurity = new GUID("{0000013D-0000-0000-C000-000000000046}");
23
- const IID_IDispatch = new GUID("{00020400-0000-0000-C000-000000000046}");
24
- const IID_IUnknown = new GUID("{00000000-0000-0000-C000-000000000046}");
25
- const CLSID_InProcFreeMarshaler = new GUID("{0000033A-0000-0000-C000-000000000046}");
26
19
  const MSHCTX_INPROC = 3;
27
20
  const MSHLFLAGS_NORMAL = 0;
28
21
  const RegisterAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_void_p));
29
22
  const RevokeAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_uint32));
30
23
  const GetAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_uint32, c_void_p, c_void_p));
31
- const QueryInterfaceAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p));
32
- const ReleaseAt = functionCache(() => ctypes.WINFUNCTYPE(c_uint32, c_void_p));
33
24
  const GetUnmarshalClassAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_uint32, c_void_p, c_uint32, c_void_p));
25
+ let cachedHomeApartment = null;
34
26
  /**
35
27
  * Apartment of the home thread: `mta` (explicit or implicit: shared with the
36
28
  * executor), `sta` (single-threaded, also NA/main STA), or `none` when COM is
37
29
  * not initialized there (objects are then called on the home thread).
38
30
  */
39
31
  export function homeApartment() {
32
+ const count = initCount();
33
+ const gen = apartmentGeneration();
34
+ if (count > 0 && cachedHomeApartment !== null && cachedHomeApartment.count === count && cachedHomeApartment.generation === gen) {
35
+ return cachedHomeApartment.kind;
36
+ }
40
37
  const type = new c_int32();
41
38
  const qualifier = new c_int32();
42
39
  const hr = ole32().CoGetApartmentType(ctypes.byref(type), ctypes.byref(qualifier));
43
40
  if (hr === CO_E_NOTINITIALIZED || hr < 0)
44
41
  return "none";
45
- return type.value === APTTYPE_MTA ? "mta" : "sta";
42
+ const kind = type.value === APTTYPE_MTA ? "mta" : "sta";
43
+ if (count > 0)
44
+ cachedHomeApartment = { kind, count, generation: gen };
45
+ return kind;
46
46
  }
47
47
  function supports(address, iid) {
48
48
  const [hr, pointer] = rawQueryInterface(address, iid);
@@ -76,6 +76,14 @@ export function isAgile(address) {
76
76
  }
77
77
  // The Global Interface Table of the home thread, per apartment generation.
78
78
  let homeTable = null;
79
+ onApartmentTeardown(() => {
80
+ cachedHomeApartment = null;
81
+ if (homeTable) {
82
+ const addr = homeTable.address;
83
+ homeTable = null;
84
+ rawRelease(addr);
85
+ }
86
+ });
79
87
  function homeGlobalTable() {
80
88
  const generation = apartmentGeneration();
81
89
  if (homeTable?.generation === generation)
@@ -89,35 +97,61 @@ function homeGlobalTable() {
89
97
  }
90
98
  // The executor's own table, per executor generation (created on the executor).
91
99
  let executorTable = null;
92
- function executorGlobalTable() {
93
- const target = executorTarget();
94
- const generation = executorGeneration();
95
- if (executorTable?.generation === generation)
100
+ onExecutorStopping((stopping, gen) => {
101
+ if (executorTable?.generation === gen) {
102
+ const entry = executorTable;
103
+ executorTable = null;
104
+ if (entry.resolved) {
105
+ RefCountAt(vtableEntry(entry.resolved, 2))
106
+ .callOn(stopping, entry.resolved)
107
+ .catch(() => undefined);
108
+ }
109
+ }
110
+ });
111
+ function executorGlobalTable(target = executorTarget(), gen = executorGeneration()) {
112
+ if (executorTable?.generation === gen)
96
113
  return executorTable.address;
97
114
  const out = new c_void_p();
98
- const address = ole32()
115
+ const entry = {
116
+ address: null,
117
+ resolved: null,
118
+ generation: gen,
119
+ };
120
+ entry.address = ole32()
99
121
  .CoCreateInstance.callOn(target, CLSID_StdGlobalInterfaceTable._buffer, null, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable._buffer, ctypes.byref(out))
100
122
  .then((hr) => {
101
123
  if (hr < 0 || !out.value)
102
124
  throw new COMError(hr, { method: "CoCreateInstance(StdGlobalInterfaceTable)" });
125
+ if (executorTable !== entry || !executorAlive(gen)) {
126
+ RefCountAt(vtableEntry(out.value, 2))
127
+ .callOn(target, out.value)
128
+ .catch(() => undefined);
129
+ throw new Error("COM executor stopped while initializing GlobalInterfaceTable");
130
+ }
131
+ entry.resolved = out.value;
103
132
  return out.value;
133
+ }, (err) => {
134
+ if (executorTable === entry)
135
+ executorTable = null;
136
+ throw err;
104
137
  });
105
- executorTable = { address, generation };
106
- return address;
138
+ executorTable = entry;
139
+ return entry.address;
107
140
  }
108
141
  /** Release a reference owned by the executor thread, after the calls already queued. */
109
142
  export function releaseOnExecutor(address, generation) {
110
143
  // An executor that has stopped took its references with its apartment.
111
144
  if (!executorAlive(generation))
112
145
  return;
113
- ReleaseAt(vtableEntry(address, 2))
146
+ RefCountAt(vtableEntry(address, 2))
114
147
  .callOn(executorTarget(), address)
115
148
  .catch(() => undefined);
116
149
  }
117
150
  /**
118
151
  * A reference to the home pointer `address` usable on the executor (owned by
119
- * the executor), through the Global Interface Table; `null` when the
120
- * interface cannot be marshaled (no proxy/stub).
152
+ * the executor), through the Global Interface Table, together with the
153
+ * executor generation that owns it; `null` when the interface cannot be
154
+ * marshaled (no proxy/stub).
121
155
  */
122
156
  export async function referenceForExecutor(address, iid) {
123
157
  const table = homeGlobalTable();
@@ -125,10 +159,12 @@ export async function referenceForExecutor(address, iid) {
125
159
  if (RegisterAt(vtableEntry(table, 3))(table, address, iid._buffer, ctypes.byref(cookie)) < 0)
126
160
  return null;
127
161
  try {
128
- const executorTableAddress = await executorGlobalTable();
162
+ const target = executorTarget();
163
+ const gen = executorGeneration();
164
+ const executorTableAddress = await executorGlobalTable(target, gen);
129
165
  const out = new c_void_p();
130
- const hr = await GetAt(vtableEntry(executorTableAddress, 5)).callOn(executorTarget(), executorTableAddress, cookie.value, iid._buffer, ctypes.byref(out));
131
- return hr >= 0 && out.value ? out.value : null;
166
+ const hr = await GetAt(vtableEntry(executorTableAddress, 5)).callOn(target, executorTableAddress, cookie.value, iid._buffer, ctypes.byref(out));
167
+ return hr >= 0 && out.value ? { address: out.value, generation: gen } : null;
132
168
  }
133
169
  finally {
134
170
  RevokeAt(vtableEntry(table, 4))(table, cookie.value);
@@ -144,7 +180,7 @@ async function handOverPointer(location, offset, interfaceId) {
144
180
  // Agile objects are valid in both apartments: the reference stays as it is.
145
181
  const agile = new c_void_p();
146
182
  if ((await QueryInterfaceAt(vtableEntry(address, 0)).callOn(target, address, IID_IAgileObject._buffer, ctypes.byref(agile))) >= 0 && agile.value) {
147
- void ReleaseAt(vtableEntry(agile.value, 2))
183
+ void RefCountAt(vtableEntry(agile.value, 2))
148
184
  .callOn(target, agile.value)
149
185
  .catch(() => undefined);
150
186
  return;
@@ -153,7 +189,7 @@ async function handOverPointer(location, offset, interfaceId) {
153
189
  const cookie = new c_uint32();
154
190
  const registered = await RegisterAt(vtableEntry(executorTableAddress, 3)).callOn(target, executorTableAddress, address, interfaceId._buffer, ctypes.byref(cookie));
155
191
  // The executor's reference is no longer needed: the table holds its own.
156
- void ReleaseAt(vtableEntry(address, 2))
192
+ void RefCountAt(vtableEntry(address, 2))
157
193
  .callOn(target, address)
158
194
  .catch(() => undefined);
159
195
  if (registered < 0) {
@@ -37,6 +37,8 @@ export interface CallOptions {
37
37
  /** Records the call in this operation, which `run()` can cancel (used by node-comtypes' own calls). */
38
38
  readonly operation?: Operation;
39
39
  }
40
+ /** Register a hook invoked right before an executor runs `CoUninitialize` during `finalize()`. */
41
+ export declare function onExecutorStopping(hook: (stopping: ctypes.Executor, gen: number) => void): void;
40
42
  /** The running executor (started on demand), for code that queues its own calls. */
41
43
  export declare function executorTarget(): ctypes.Executor;
42
44
  /** Counters of the COM executor. Python equivalent: node-python's `python.stats()`. */
@@ -6,15 +6,16 @@
6
6
  import * as ctypes from "node-ctypes";
7
7
  import { COINIT_MULTITHREADED } from "../constants.js";
8
8
  import { GUID } from "../guid.js";
9
+ import { IID_IRestrictedErrorInfo, IID_ISupportErrorInfo } from "../low-level/iids.js";
9
10
  import { ole32, oleaut32, takeBSTR } from "../low-level/native.js";
10
- import { functionCache, vtableEntry } from "../low-level/vtable.js";
11
+ import { functionCache, PointerArgAt, QueryInterfaceAt, RefCountAt, vtableEntry } from "../low-level/vtable.js";
11
12
  const { c_int32, c_uint32, c_void_p } = ctypes;
12
- const IID_ISupportErrorInfo = new GUID("{DF0B3D60-548F-101B-8E65-08002B2BD119}");
13
- // IErrorInfo getters and ISupportErrorInfo::InterfaceSupportsErrorInfo share
14
- // the HRESULT (this, pointer) signature.
15
- const PointerArgAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p));
16
- const QueryInterfaceAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p));
17
- const ReleaseAt = functionCache(() => ctypes.WINFUNCTYPE(c_uint32, c_void_p));
13
+ const RestrictedDetailsAt = functionCache(() => ctypes.WINFUNCTYPE(c_int32, c_void_p, c_void_p, c_void_p, c_void_p, c_void_p));
14
+ const executorStopHooks = new Set();
15
+ /** Register a hook invoked right before an executor runs `CoUninitialize` during `finalize()`. */
16
+ export function onExecutorStopping(hook) {
17
+ executorStopHooks.add(hook);
18
+ }
18
19
  let executor = null;
19
20
  let closing = null;
20
21
  let generation = 0;
@@ -66,11 +67,20 @@ export function finalize() {
66
67
  const stopping = executor;
67
68
  if (!stopping)
68
69
  return Promise.resolve();
70
+ const stoppingGen = generation;
69
71
  executor = null;
70
72
  if (exitHandler) {
71
73
  process.off("beforeExit", exitHandler);
72
74
  exitHandler = null;
73
75
  }
76
+ for (const hook of executorStopHooks) {
77
+ try {
78
+ hook(stopping, stoppingGen);
79
+ }
80
+ catch {
81
+ // Keep shutting down.
82
+ }
83
+ }
74
84
  // FIFO: after every accepted call, before the thread stops.
75
85
  ole32()
76
86
  .CoUninitialize.callOn(stopping)
@@ -112,7 +122,7 @@ function takeErrorObject(target) {
112
122
  .then((hr) => (hr === 0 && out.value ? out.value : null));
113
123
  }
114
124
  function release(target, address) {
115
- ReleaseAt(vtableEntry(address, 2))
125
+ RefCountAt(vtableEntry(address, 2))
116
126
  .callOn(target, address)
117
127
  .catch(() => undefined);
118
128
  }
@@ -150,15 +160,56 @@ async function readErrorObject(target, errorObject) {
150
160
  helpContext: hasContext >= 0 ? context.value : 0,
151
161
  };
152
162
  }
153
- async function errorDetails(target, errorObject, errorInfo) {
163
+ /** Read an `IRestrictedErrorInfo` object on the executor thread when its HRESULT matches `failedHr`. */
164
+ async function readRestrictedErrorObject(target, errorObject, failedHr) {
165
+ const out = new c_void_p();
166
+ const qhr = await QueryInterfaceAt(vtableEntry(errorObject, 0)).callOn(target, errorObject, IID_IRestrictedErrorInfo._buffer, ctypes.byref(out));
167
+ if (qhr < 0 || !out.value)
168
+ return null;
169
+ const restricted = out.value;
170
+ try {
171
+ const desc = new c_void_p();
172
+ const err = new c_int32();
173
+ const restrictedDesc = new c_void_p();
174
+ const capabilitySid = new c_void_p();
175
+ const ref = new c_void_p();
176
+ const [hr, refHr] = await Promise.all([
177
+ RestrictedDetailsAt(vtableEntry(restricted, 3)).callOn(target, restricted, ctypes.byref(desc), ctypes.byref(err), ctypes.byref(restrictedDesc), ctypes.byref(capabilitySid)),
178
+ PointerArgAt(vtableEntry(restricted, 4)).callOn(target, restricted, ctypes.byref(ref)),
179
+ ]);
180
+ const descriptionText = hr >= 0 ? takeBSTR(desc.value) : null;
181
+ const restrictedText = hr >= 0 ? takeBSTR(restrictedDesc.value) : null;
182
+ const capabilityText = hr >= 0 ? takeBSTR(capabilitySid.value) : null;
183
+ const referenceText = refHr >= 0 ? takeBSTR(ref.value) : null;
184
+ if (hr < 0 || err.value !== failedHr)
185
+ return null;
186
+ const trimmedRestricted = restrictedText?.trim() || null;
187
+ const trimmedDescription = descriptionText?.trim() || null;
188
+ return {
189
+ guid: null,
190
+ source: null,
191
+ description: trimmedRestricted ?? trimmedDescription,
192
+ helpFile: null,
193
+ helpContext: 0,
194
+ restrictedDescription: trimmedRestricted,
195
+ capabilitySid: capabilityText?.trim() || null,
196
+ reference: referenceText?.trim() || null,
197
+ };
198
+ }
199
+ finally {
200
+ release(target, restricted);
201
+ }
202
+ }
203
+ async function errorDetails(target, errorObject, errorInfo, failedHr) {
154
204
  const taken = await errorObject;
155
205
  if (!taken)
156
206
  return null;
157
207
  try {
158
- // As Python comtypes: only for an object that declares support for the interface.
159
- if (!(await supportsErrorInfo(target, errorInfo.object, new GUID(errorInfo.iid))))
160
- return null;
161
- return await readErrorObject(target, taken);
208
+ // Classic COM: check ISupportErrorInfo first, as Python comtypes.
209
+ if (await supportsErrorInfo(target, errorInfo.object, new GUID(errorInfo.iid)))
210
+ return await readErrorObject(target, taken);
211
+ // WinRT / modern COM fallback: IRestrictedErrorInfo (stored in the same thread error slot).
212
+ return await readRestrictedErrorObject(target, taken, failedHr);
162
213
  }
163
214
  catch {
164
215
  return null;
@@ -203,6 +254,6 @@ export function executorCall(call, options = {}) {
203
254
  return pending.then((value) => {
204
255
  if (!(typeof value === "number" && value < 0) || !errorInfo || lastJob(target) !== job)
205
256
  return { value, details: null };
206
- return errorDetails(target, takeErrorObject(target), errorInfo).then((details) => ({ value, details }));
257
+ return errorDetails(target, takeErrorObject(target), errorInfo, value).then((details) => ({ value, details }));
207
258
  });
208
259
  }
package/dist/guid.d.ts CHANGED
@@ -5,7 +5,7 @@ import * as ctypes from "node-ctypes";
5
5
  * ```ts
6
6
  * new GUID("{00000000-0000-0000-C000-000000000046}");
7
7
  * new GUID(); // GUID_NULL
8
- * new GUID(buffer); // view of 16 bytes (other Uint8Arrays are copied)
8
+ * new GUID(buffer); // copy of 16 bytes (GUID.from_buffer(buffer) for a view)
9
9
  * ```
10
10
  */
11
11
  export declare class GUID extends ctypes.Structure {
package/dist/guid.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as ctypes from "node-ctypes";
2
- import { ole32, refreshMirror, takeCoTaskMemString } from "./low-level/native.js";
2
+ import { flushMirror, ole32, refreshMirror, takeCoTaskMemString } from "./low-level/native.js";
3
3
  import { checkHRESULT } from "./errors.js";
4
4
  const GUID_PATTERN = /^\{?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}?$/i;
5
5
  /**
@@ -8,7 +8,7 @@ const GUID_PATTERN = /^\{?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4}
8
8
  * ```ts
9
9
  * new GUID("{00000000-0000-0000-C000-000000000046}");
10
10
  * new GUID(); // GUID_NULL
11
- * new GUID(buffer); // view of 16 bytes (other Uint8Arrays are copied)
11
+ * new GUID(buffer); // copy of 16 bytes (GUID.from_buffer(buffer) for a view)
12
12
  * ```
13
13
  */
14
14
  export class GUID extends ctypes.Structure {
@@ -19,13 +19,7 @@ export class GUID extends ctypes.Structure {
19
19
  ["Data4", ctypes.array(ctypes.c_uint8, 8)],
20
20
  ];
21
21
  constructor(init) {
22
- // A Buffer is wrapped (node-ctypes views: from_address, nested fields); other inputs are copied.
23
- if (Buffer.isBuffer(init)) {
24
- if (init.length !== 16)
25
- throw new TypeError("GUID requires a GUID string, another GUID or exactly 16 bytes");
26
- super(init);
27
- return;
28
- }
22
+ // Bytes (Buffers included) are copied, as CPython's GUID(bytes) would not wrap them: use GUID.from_buffer for a view.
29
23
  super();
30
24
  if (init === undefined)
31
25
  return;
@@ -37,6 +31,7 @@ export class GUID extends ctypes.Structure {
37
31
  this.Data2 = parseInt(match[2], 16);
38
32
  this.Data3 = parseInt(match[3], 16);
39
33
  Buffer.from(match[4] + match[5], "hex").copy(this._buffer, 8);
34
+ flushMirror(this._buffer);
40
35
  return;
41
36
  }
42
37
  if (init instanceof GUID)
@@ -45,17 +40,20 @@ export class GUID extends ctypes.Structure {
45
40
  if (!(bytes instanceof Uint8Array) || bytes.length !== 16)
46
41
  throw new TypeError("GUID requires a GUID string, another GUID or exactly 16 bytes");
47
42
  this._buffer.set(bytes);
43
+ flushMirror(this._buffer);
48
44
  }
49
45
  /** A new random GUID (`CoCreateGuid`). Python: `GUID.create_new()`. */
50
46
  static createNew() {
51
47
  const guid = new GUID();
52
48
  checkHRESULT(ole32().CoCreateGuid(guid._buffer), "CoCreateGuid");
49
+ refreshMirror(guid._buffer);
53
50
  return guid;
54
51
  }
55
52
  /** CLSID registered for a ProgID (`CLSIDFromProgID`). Python: `GUID.from_progid()`. */
56
53
  static fromProgID(progid) {
57
54
  const guid = new GUID();
58
55
  checkHRESULT(ole32().CLSIDFromProgID(progid, guid._buffer), "CLSIDFromProgID");
56
+ refreshMirror(guid._buffer);
59
57
  return guid;
60
58
  }
61
59
  /** ProgID registered for this CLSID (`ProgIDFromCLSID`). Python: `GUID.as_progid()`. */
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { GUIDLike } from "./guid.ts";
3
3
  export * from "./hresult.ts";
4
4
  export { COMError, checkHRESULT, hresultText, systemMessage } from "./errors.ts";
5
5
  export type { COMErrorDetails, COMErrorOptions } from "./errors.ts";
6
- export { takeErrorInfo } from "./errorinfo.ts";
6
+ export { takeErrorInfo, takeRestrictedErrorInfo } from "./errorinfo.ts";
7
7
  export { stats, finalize } from "./executor/executor.ts";
8
8
  export { run } from "./executor/operations.ts";
9
9
  export type { RunOptions } from "./executor/operations.ts";
@@ -15,17 +15,17 @@ export type { ComParamType, ParamFlag, ParamSpec, ParamInfo, IdlFlag, DispIdFlag
15
15
  export { COMPointer } from "./pointer.ts";
16
16
  export type { FromAddressOptions } from "./pointer.ts";
17
17
  export * from "./constants.ts";
18
- export { CoInitializeEx, CoInitialize, CoUninitialize, apartment, getApartmentType, getLivePointerCount, CoCreateInstance, CoCreateInstanceEx, CoGetClassObject, CoTaskMemAlloc, CoTaskMemRealloc, CoTaskMemFree } from "./runtime.ts";
18
+ export { CoInitializeEx, CoInitialize, CoUninitialize, apartment, getApartmentType, getLivePointerCount, CoCreateInstance, CoCreateInstanceEx, CoGetClassObject, CoTaskMemAlloc, CoTaskMemRealloc, CoTaskMemFree, CoCreateFreeThreadedMarshaler, } from "./runtime.ts";
19
19
  export type { Apartment, ApartmentType, CreateInstanceOptions, CreateInstanceExOptions } from "./runtime.ts";
20
20
  export * from "./interfaces/index.ts";
21
21
  export * from "./automation/index.ts";
22
22
  export * from "./client/index.ts";
23
23
  export * from "./server/index.ts";
24
- export { pumpMessages, PumpEvents, startMessagePump, waitFor } from "./pump.ts";
24
+ export { pumpMessages, waitAndPumpMessages, PumpEvents, startMessagePump, waitFor } from "./pump.ts";
25
25
  export { DISPMETHOD, DISPPROPERTY } from "./dispmethod.ts";
26
26
  export type { DispSpec } from "./dispmethod.ts";
27
27
  export * from "./typelib/index.ts";
28
28
  export { marshalInterface, unmarshalInterface, unmarshalDispatch, releaseMarshaled, GlobalInterfaceTable, IGlobalInterfaceTable, CLSID_StdGlobalInterfaceTable } from "./threads.ts";
29
29
  export type { MarshaledInterface } from "./threads.ts";
30
- export type { MessagePump } from "./pump.ts";
31
- export declare const version = "0.2.0";
30
+ export type { MessagePump, StartMessagePumpOptions } from "./pump.ts";
31
+ export declare const version = "0.4.0";
package/dist/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  export { GUID, GUID_NULL, toGUID } from "./guid.js";
2
2
  export * from "./hresult.js";
3
3
  export { COMError, checkHRESULT, hresultText, systemMessage } from "./errors.js";
4
- export { takeErrorInfo } from "./errorinfo.js";
4
+ export { takeErrorInfo, takeRestrictedErrorInfo } from "./errorinfo.js";
5
5
  export { stats, finalize } from "./executor/executor.js";
6
6
  export { run } from "./executor/operations.js";
7
7
  export { COMInterface, STDMETHOD, HRESULT, findInterface, derivesFrom } from "./interface.js";
8
8
  export { COMMETHOD, BSTR, LPOLESTR, REFGUID, REFIID, REFCLSID, SAFEARRAY, SELF, DATE, CURRENCY, lazy, dispid, helpstring, classifyParamType, resolveParamInterface } from "./commethod.js";
9
9
  export { COMPointer } from "./pointer.js";
10
10
  export * from "./constants.js";
11
- export { CoInitializeEx, CoInitialize, CoUninitialize, apartment, getApartmentType, getLivePointerCount, CoCreateInstance, CoCreateInstanceEx, CoGetClassObject, CoTaskMemAlloc, CoTaskMemRealloc, CoTaskMemFree } from "./runtime.js";
11
+ export { CoInitializeEx, CoInitialize, CoUninitialize, apartment, getApartmentType, getLivePointerCount, CoCreateInstance, CoCreateInstanceEx, CoGetClassObject, CoTaskMemAlloc, CoTaskMemRealloc, CoTaskMemFree, CoCreateFreeThreadedMarshaler, } from "./runtime.js";
12
12
  export * from "./interfaces/index.js";
13
13
  export * from "./automation/index.js";
14
14
  export * from "./client/index.js";
15
15
  export * from "./server/index.js";
16
- export { pumpMessages, PumpEvents, startMessagePump, waitFor } from "./pump.js";
16
+ export { pumpMessages, waitAndPumpMessages, PumpEvents, startMessagePump, waitFor } from "./pump.js";
17
17
  export { DISPMETHOD, DISPPROPERTY } from "./dispmethod.js";
18
18
  export * from "./typelib/index.js";
19
19
  export { marshalInterface, unmarshalInterface, unmarshalDispatch, releaseMarshaled, GlobalInterfaceTable, IGlobalInterfaceTable, CLSID_StdGlobalInterfaceTable } from "./threads.js";
20
- export const version = "0.2.0";
20
+ export const version = "0.4.0";