@node-ctypes/comtypes 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +50 -624
  2. package/dist/automation/dispatch.js +10 -3
  3. package/dist/automation/record.js +3 -1
  4. package/dist/automation/variant.d.ts +4 -4
  5. package/dist/automation/variant.js +102 -29
  6. package/dist/client/dynamic.js +7 -8
  7. package/dist/client/events.js +18 -2
  8. package/dist/client/index.js +3 -1
  9. package/dist/commethod.d.ts +1 -1
  10. package/dist/commethod.js +151 -57
  11. package/dist/errorinfo.d.ts +10 -3
  12. package/dist/errorinfo.js +66 -18
  13. package/dist/errors.d.ts +7 -1
  14. package/dist/executor/apartment.d.ts +7 -3
  15. package/dist/executor/apartment.js +65 -29
  16. package/dist/executor/executor.d.ts +2 -0
  17. package/dist/executor/executor.js +65 -14
  18. package/dist/guid.d.ts +1 -1
  19. package/dist/guid.js +15 -10
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +4 -4
  22. package/dist/interfaces/agile.d.ts +52 -0
  23. package/dist/interfaces/agile.js +59 -0
  24. package/dist/interfaces/errorinfo.d.ts +8 -0
  25. package/dist/interfaces/errorinfo.js +10 -0
  26. package/dist/interfaces/index.d.ts +2 -1
  27. package/dist/interfaces/index.js +2 -1
  28. package/dist/interfaces/typeinfo.js +3 -0
  29. package/dist/low-level/iids.d.ts +14 -0
  30. package/dist/low-level/iids.js +14 -0
  31. package/dist/low-level/index.d.ts +2 -2
  32. package/dist/low-level/index.js +1 -1
  33. package/dist/low-level/native.d.ts +23 -0
  34. package/dist/low-level/native.js +53 -0
  35. package/dist/low-level/registry.js +4 -2
  36. package/dist/low-level/vtable.d.ts +10 -0
  37. package/dist/low-level/vtable.js +32 -5
  38. package/dist/pointer.d.ts +2 -0
  39. package/dist/pointer.js +154 -84
  40. package/dist/pump.d.ts +32 -8
  41. package/dist/pump.js +87 -15
  42. package/dist/runtime.d.ts +6 -0
  43. package/dist/runtime.js +15 -1
  44. package/dist/server/automation.js +3 -3
  45. package/dist/server/comobject.d.ts +53 -0
  46. package/dist/server/comobject.js +319 -27
  47. package/dist/server/index.d.ts +1 -1
  48. package/dist/server/index.js +1 -1
  49. package/dist/server/marshal.d.ts +1 -0
  50. package/dist/server/marshal.js +16 -8
  51. package/dist/server/register.js +8 -6
  52. package/dist/tracking.d.ts +2 -0
  53. package/dist/tracking.js +13 -0
  54. package/package.json +6 -2
package/README.md CHANGED
@@ -1,35 +1,33 @@
1
1
  # node-comtypes (`@node-ctypes/comtypes`)
2
2
 
3
- Typed Windows COM support for Node.js powered by [node-ctypes](https://www.npmjs.com/package/node-ctypes), modelled on Python [comtypes](https://github.com/enthought/comtypes).
3
+ [![npm version](https://img.shields.io/npm/v/@node-ctypes/comtypes.svg)](https://www.npmjs.com/package/@node-ctypes/comtypes)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@node-ctypes/comtypes.svg)](https://www.npmjs.com/package/@node-ctypes/comtypes)
5
+ [![CI](https://github.com/dmazzella/node-comtypes/actions/workflows/ci.yml/badge.svg)](https://github.com/dmazzella/node-comtypes/actions/workflows/ci.yml)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
7
 
5
- - **Node.js 24+**, ESM, TypeScript declarations.
6
- - Windows only at runtime (`ole32.dll`, `oleaut32.dll`). The package imports on Linux and macOS, and GUID/HRESULT/interface definitions work there, so shared code and unit tests run everywhere.
7
- - Independent package: no native addon of its own, only `node-ctypes`.
8
- - Client and server side: vtable interfaces with IDL flags, automation (`IDispatch`, `VARIANT`, `SAFEARRAY`), type libraries and code generation, COM objects written in JavaScript, events, LocalServer32 servers.
9
- - **Asynchronous calls**: methods return promises and run on a dedicated COM thread, so slow objects never block the event loop (or an Electron UI); properties stay synchronous. See [Execution model](#execution-model).
8
+ **Typed Windows COM client and server support for Node.js**, powered by
9
+ [node-ctypes](https://www.npmjs.com/package/node-ctypes) and modelled on Python
10
+ [comtypes](https://github.com/enthought/comtypes).
10
11
 
11
- ```sh
12
- npm install @node-ctypes/comtypes
13
- ```
12
+ - **Node.js 24+**, ESM, TypeScript declarations, zero native addon of its own.
13
+ - **Full COM stack**: vtable interfaces (`COMMETHOD` / `STDMETHOD`), automation (`IDispatch`, `VARIANT`, `SAFEARRAY`, `VT_RECORD`), type libraries and code generation, JavaScript `COMObject` servers with aggregation/delegation, events, and `LocalServer32`.
14
+ - **Non-blocking by default**: methods return promises and run on a dedicated COM executor thread so slow objects never freeze the event loop or an Electron UI; properties stay synchronous, and `sync()` provides direct synchronous views.
14
15
 
15
- To build from source, run from this directory:
16
+ ---
17
+
18
+ ## Quick start
16
19
 
17
20
  ```sh
18
- npm install
19
- npm run build
20
- npm test
21
- npm pack
21
+ npm install @node-ctypes/comtypes
22
22
  ```
23
23
 
24
- ## Quick start
25
-
26
24
  ```typescript
27
25
  import { create_unicode_buffer } from "node-ctypes";
28
26
  import { apartment, CreateObject, IPersistFile, ShellLink } from "@node-ctypes/comtypes";
29
27
 
30
28
  using _ = apartment(); // CoInitializeEx(COINIT_APARTMENTTHREADED) ... CoUninitialize()
31
29
 
32
- // Vtable interface: the ShellLink coclass gives an IShellLinkW pointer.
30
+ // Vtable interface: the ShellLink coclass returns an IShellLinkW pointer.
33
31
  using link = await CreateObject(ShellLink);
34
32
  await link.SetPath("C:\\Windows\\notepad.exe");
35
33
  await link.SetDescription("Notepad");
@@ -39,630 +37,58 @@ const text = create_unicode_buffer(260);
39
37
  await link.GetPath(text, 260, null, 0);
40
38
  console.log(text.value);
41
39
 
42
- // Automation: typed from the type library of the object.
40
+ // Automation: typed automatically from the object's type library.
43
41
  using dict = await CreateObject("Scripting.Dictionary"); // IDictionary
44
42
  await dict.Add("a", 1); // methods return promises
45
43
  console.log(dict.Count, dict.Item("a")); // properties are synchronous
46
44
  ```
47
45
 
48
- Failures reject (or throw, for synchronous members) with a `COMError`. Raw methods (`STDMETHOD`) resolve to the HRESULT (`S_OK`, `S_FALSE`); methods declared with `COMMETHOD` resolve to their output parameters.
49
-
50
- ## Apartments and lifetime
51
-
52
- ### Apartments
53
-
54
- `CoInitializeEx()` defaults to `COINIT_APARTMENTTHREADED`, like comtypes; Shell and most automation objects require it. `apartment()` initializes and uninitializes with `using`. This is the apartment of the JavaScript thread, the **home** apartment; method calls run on the COM executor (see [Execution model](#execution-model)). The Node.js event loop does not pump Win32 messages: calls into in-process STA objects work directly, while incoming calls and events delivered through window messages need a pump (see [Message pump](#message-pump)).
55
-
56
- ### Pointers
57
-
58
- `COMPointer` (Python: `POINTER(IUnknown)`) owns exactly one reference:
59
-
60
- | Operation | Effect |
61
- | -------------------------------------------- | ---------------------------------------------------------------------------------- |
62
- | `CoCreateInstance`, `QueryInterface` | New owned pointer |
63
- | `tryQueryInterface(iface)` | Owned pointer, or `null` on `E_NOINTERFACE` |
64
- | `Release()` / `using` / `[Symbol.dispose]()` | Releases the owned reference; the pointer becomes unusable |
65
- | `detach()` | Gives the reference to the caller without releasing it |
66
- | `COMPointer.fromAddress(p, iface)` | Adopts an existing reference (e.g. an out parameter); `{ addRef: true }` to borrow |
67
- | `AddRef()` / `callMethod("Release")` | Raw reference counting, not tied to ownership |
68
- | `isSameObject(other)` | COM identity through `IUnknown` |
69
-
70
- JavaScript has no reference counting, so release pointers deterministically with `using` or `Release()`. A `FinalizationRegistry` releases forgotten pointers as a safety net. It never runs after the last `CoUninitialize` of the thread, which releases every pointer still alive and invalidates it. `getLivePointerCount()` helps detect leaks.
71
-
72
- ### Threads
73
-
74
- Each worker thread has its own apartment state, and a COM pointer belongs to its apartment: pass it to another thread marshaled.
75
-
76
- ```typescript
77
- import { Worker } from "node:worker_threads";
78
- import { COMPointer, GlobalInterfaceTable, IDispatch, marshalInterface, startMessagePump } from "@node-ctypes/comtypes";
79
-
80
- declare const object: COMPointer; // or a dispatch object, or a COMObject
81
-
82
- // Owner thread (an STA: incoming calls arrive as window messages, so pump).
83
- using pump = startMessagePump();
84
- new Worker("./worker.ts", { workerData: { token: marshalInterface(object, IDispatch) } });
85
- // worker.ts: using _ = apartment(); using proxy = unmarshalDispatch(workerData.token); await proxy.Add(1, 2);
86
-
87
- // Or register once and get a proxy in any thread, any number of times:
88
- using table = new GlobalInterfaceTable();
89
- const cookie = table.register(object, IDispatch); // table.get(cookie, IFoo) / table.getDispatch(cookie)
90
- ```
91
-
92
- `marshalInterface` (`CoMarshalInterThreadInterfaceInStream`) returns a single-use token that can be cloned with `postMessage`. `unmarshalInterface(token, IFoo)` and `unmarshalDispatch(token)` consume it; `releaseMarshaled(token)` discards it. `IDispatch` always crosses apartments; custom vtable interfaces need a registered proxy/stub or type library (see [Servers](#servers)).
93
-
94
- ## Execution model
95
-
96
- **Calls are asynchronous; live access is synchronous.** Methods return promises and run on the **COM executor**, a native thread owned by node-comtypes (a node-ctypes `Executor`, not a libuv worker) in the multithreaded apartment, one call at a time in FIFO order. The event loop stays free while a call runs, however slow the object (an Office application, a remote server, WMI, an application that does not respond).
97
-
98
- | Asynchronous (`Promise`) | Synchronous |
99
- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
100
- | COMMETHOD / STDMETHOD methods, DISPMETHODs, methods of dynamic objects | properties: get, put, putref, parameterized (`dict.Item("a")`, `_get_X` / `_set_X`) |
101
- | `CreateObject`, `GetObject`, `GetActiveObject` | `QueryInterface`, `AddRef`, `Release`, `using`, `GetBestInterface`, `queryService` |
102
- | `for await` over collections (`IEnumVARIANT::Next` on the executor) | `for...of`, `VARIANT` conversions, `Constants`, `getModuleSync`, `GetEvents`, generated modules |
103
- | `GetModule` (in slices on the JavaScript thread, see below) | |
104
- | `executorCall` (low-level) | the server side: `COMObject` implementations, `fireEvent`, registration; [`sync()`](#synchronous-calls) views |
105
-
106
- ```typescript
107
- import { apartment, CreateObject, run } from "@node-ctypes/comtypes";
108
-
109
- using _ = apartment();
110
- using excel = await CreateObject("Excel.Application", { dynamic: true });
111
- using books = excel.Workbooks; // property: synchronous
112
- using book = await books.Add(); // method: on the executor
113
- for await (const sheet of book.Worksheets) {
114
- using owned = sheet; // fetched on the executor
115
- console.log(owned.Name);
116
- }
117
- await run(book.SaveAs("C:\\Temp\\a.xlsx"), { signal: AbortSignal.timeout(10_000) });
118
- ```
119
-
120
- **Objects and apartments.** Objects are created on the executor, so their calls never run on the JavaScript thread. The JavaScript thread keeps its own reference, valid in its home apartment:
121
-
122
- - a multithreaded home (`apartment(COINIT_MULTITHREADED)`) and agile objects (`IAgileObject`, the free-threaded marshaler) share one reference with the executor;
123
- - in a single-threaded home, objects are passed through the Global Interface Table: properties are read through a proxy, methods on the executor. This needs interfaces that can be marshaled: `IDispatch`, `[oleautomation]` and dual interfaces with a registered type library, interfaces with a proxy/stub. Dual interfaces that cannot be marshaled are called through `IDispatch` (same members, with their DISPIDs);
124
- - pointers obtained on the JavaScript thread (`CoCreateInstance`, `QueryInterface` of an STA object, JavaScript `COMObject`s with `_threading_ = "apartment"`) are called on the JavaScript thread, synchronously, while the promise keeps the same shape. Calls passing them as arguments run there too;
125
- - interface results (out pointers, `VARIANT`s, `SAFEARRAY`s of objects) are handed over to the home apartment before the promise settles.
126
-
127
- `{ home: true }` creates or binds an object on the JavaScript thread instead (direct calls, no marshaling, but on that thread): in a single-threaded home, use it for objects whose interfaces cannot be marshaled, such as ADSI `IDirectorySearch`, or choose a multithreaded home. Classes this thread registered with `registerClassObject` are created at home automatically.
128
-
129
- **Cancellation.** `run(promise, { signal })` awaits a COM operation with an `AbortSignal`: on abort it rejects with `signal.reason` and skips the operation's calls still queued on the executor. A call already running completes (COM does not interrupt it).
130
-
131
- **Lifetime.** The executor starts at the first asynchronous call, keeps the process alive only while calls are pending, and stops at exit. `await finalize()` drains the accepted calls and stops it (a later call starts a new one); `stats()` returns `{ running, pending, completed, generation }`.
132
-
133
- ### Synchronous calls
134
-
135
- `sync(pointer)` (or `sync(dynamicObject)`) returns a view of the same object whose methods run synchronously on the JavaScript thread, sharing its reference (releasing either releases both): for event handlers, `COMObject` implementations, or code that must not interleave with other JavaScript.
136
-
137
- Each asynchronous call is a round trip to the executor thread: a typed method costs about 20 µs with its conversions, against 2–4 µs synchronously. That is negligible for most code; `sync()` is there for loops of many fast calls where it adds up.
138
-
139
- ```typescript
140
- import { CreateObject, sync } from "@node-ctypes/comtypes";
141
-
142
- using dict = await CreateObject("Scripting.Dictionary");
143
- sync(dict).Add("a", 1); // S_OK, not a Promise
144
- ```
145
-
146
- Generated modules type both: `XMethods` (promises) for pointers, `XSyncMethods` for `sync()` views.
147
-
148
- ### Electron
149
-
150
- The main process's JavaScript thread is Chromium's UI thread, already a single-threaded apartment (`CoInitializeEx(COINIT_MULTITHREADED)` there fails with `RPC_E_CHANGED_MODE`); `apartment()` keeps it. Methods run on the executor, so the UI does not freeze; Chromium pumps window messages, so events arrive without `startMessagePump`. Synchronous property reads go through a proxy to the object's apartment: keep them out of tight loops on slow objects. [tests/electron/main.mjs](./tests/electron/main.mjs) checks this in Electron (`electron tests/electron/main.mjs` after a build).
151
-
152
- ## Automation
153
-
154
- `CreateObject`, `GetObject` and `GetActiveObject` return, as in Python, the object's **best interface** (`GetBestInterface`): the default interface of its coclass (`IProvideClassInfo`), or the interface `IDispatch::GetTypeInfo` describes, built from its type library with `GetModule` (dual interfaces are called through the vtable). An object without type information becomes a dynamic object, or stays an `IUnknown` pointer when it has no `IDispatch`.
155
-
156
- ```typescript
157
- import { apartment, CreateObject, named, putProperty } from "@node-ctypes/comtypes";
158
-
159
- using _ = apartment();
160
-
161
- using dict = await CreateObject("Scripting.Dictionary"); // IDictionary, typed from scrrun.dll
162
- dict.CompareMode = 1; // property put (only while the dictionary is empty)
163
- await dict.Add("a", 1); // method
164
- console.log(dict.Count, dict.Item("a")); // property get, parameterized property
165
- putProperty(dict, "Item", "a", 2); // parameterized property put (late bound, by name)
166
- for (const key of dict) console.log(key); // _NewEnum / IEnumVARIANT; for await: on the executor
167
-
168
- using fso = await CreateObject("Scripting.FileSystemObject"); // IFileSystem3
169
- using file = await fso.CreateTextFile("C:\\Temp\\a.txt", named({ Overwrite: true })); // named arguments; ITextStream
170
- ```
171
-
172
- - **Static types**: the result is typed at run time, but its TypeScript type is `AutomationObject` (members of type `any`). For static types, create a coclass of a [generated module](#generated-modules).
173
- - **Results**: `IDispatch` values returned by typed calls (a `VARIANT` holding an object, `Application.ActiveSheet`) get their best interface too (Python: `wrap_outparam`). `GetBestInterface(pointer)` (also `wrap`) does it explicitly and returns a new reference.
174
- - **Iteration and helpers**: typed pointers deriving from `IDispatch` iterate their `_NewEnum` collection, and the late-bound helpers (`getProperty`, `putProperty`, `invokeMethod`, ...) accept them.
175
- - **Options**: `{ interface: IFoo }` returns that interface; `{ dynamic: true }` a [dynamic object](#dynamic-objects); `{ home: true }` creates or binds it on the JavaScript thread ([Execution model](#execution-model)); `CreateObject` also takes `clsctx` and `machine` (a remote computer, through `CoCreateInstanceEx`). `GetActiveObject(progid)` attaches to an object of the Running Object Table, `GetObject(displayName)` binds a moniker (`"winmgmts:"`, a file).
176
-
177
- ### Constants
178
-
179
- `Constants(obj)` (Python: `comtypes.client.Constants`) returns the constants of the object's type library: enum members and module constants by name, and enums by name. Unknown names throw, so typos do not become `undefined`.
180
-
181
- ```typescript
182
- import { Constants, CreateObject } from "@node-ctypes/comtypes";
183
-
184
- using fso = await CreateObject("Scripting.FileSystemObject");
185
- const c = Constants(fso);
186
- using temp = await fso.GetSpecialFolder(c.TemporaryFolder); // or c.SpecialFolderConst.TemporaryFolder
187
- ```
188
-
189
- ### Dynamic objects
190
-
191
- `{ dynamic: true }` returns a dynamic object driven by `GetIDsOfNames` + `Invoke` (Python: `dynamic=True`, `comtypes.client.dynamic.Dispatch`). Use it for members that are not in the type library, such as WMI class properties:
192
-
193
- ```typescript
194
- import { CreateObject, GetObject } from "@node-ctypes/comtypes";
195
-
196
- using wmi = await GetObject("winmgmts:", { dynamic: true });
197
- for await (const os of await wmi.ExecQuery("SELECT Caption FROM Win32_OperatingSystem")) console.log(os.Caption);
198
-
199
- using dict = await CreateObject("Scripting.Dictionary", { dynamic: true });
200
- await dict.Add("a", 1);
201
- console.log(dict("a")); // default member (DISPID_VALUE), a property: synchronous
202
- ```
203
-
204
- | Expression | Invoke |
205
- | ------------------------------------------ | ------------------------------------------------------------------------ |
206
- | `obj.Name` | `DISPATCH_PROPERTYGET`, or a method caller (see below) |
207
- | `obj.Name(...args)` | `DISPATCH_METHOD \| DISPATCH_PROPERTYGET` (a `Promise` for methods) |
208
- | `obj.Name = value` | `DISPATCH_PROPERTYPUT` (`PROPERTYPUTREF` for COM objects when supported) |
209
- | `obj(...args)` | default member (`DISPID_VALUE`) |
210
- | `for (const x of obj)`, `for await` | `_NewEnum` (`DISPID_NEWENUM`) and `IEnumVARIANT` |
211
- | `getProperty(obj, name, ...args)` | `DISPATCH_PROPERTYGET` with arguments |
212
- | `putProperty(obj, name, ...args, value)` | `DISPATCH_PROPERTYPUT` with arguments |
213
- | `putRefProperty(...)`, `invokeMethod(...)` | `DISPATCH_PROPERTYPUTREF`, `DISPATCH_METHOD` only |
214
-
215
- Whether `obj.Name` reads a value or returns a callable comes from the type information (`IDispatch::GetTypeInfo`, cached per type):
216
-
217
- - a property whose get has no required arguments is read: `dict.Count`, Excel `range.Value`;
218
- - methods and properties with required arguments (`dict.Item`) return a function: methods resolve a `Promise` (executor), parameterized properties return their value (synchronous);
219
- - without type information (e.g. WMI objects), the property is read, and a function is returned only when the object rejects the get (`DISP_E_MEMBERNOTFOUND`, `DISP_E_BADPARAMCOUNT`, ...), as comtypes does.
220
-
221
- A property whose get has only **optional** arguments is read as a value, so `shell.Environment("PROCESS")` would call the default member of the result: use `getProperty(shell, "Environment", "PROCESS")`.
222
-
223
- Results that are objects are dynamic objects again, also inside arrays. Each dynamic object owns its `IDispatch` reference: use `using` or `release(obj)`, otherwise the finalizer releases it later. `Dispatch(pointer)` wraps an existing pointer or `COMObject`, and `dispatchPointer(obj)` returns the underlying `IDispatch` pointer.
224
-
225
- ### Arguments
226
-
227
- - `undefined` is an omitted optional argument (`missing`: `VT_ERROR` with `DISP_E_PARAMNOTFOUND`).
228
- - Named arguments go in a final `named({ Name: value })`.
229
- - `byRef(value)` passes a variable by reference (VB `ByRef`) as `VT_BYREF | VT_VARIANT`, `byRef(value, VT_BSTR)` as `VT_BYREF | VT_BSTR`; its `value` holds what the callee left after the call (`const n = byRef(1); await obj.Increment(n); n.value`).
230
- - `typed(vt, value)` and `safeArray(values, { vt, dimensions })` choose the VARIANT type.
231
-
232
- ### VARIANT conversions
233
-
234
- | JavaScript | VARIANT | Back to JavaScript |
235
- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------ |
236
- | `undefined` / `null` | `VT_EMPTY` / `VT_NULL` | `undefined` / `null` |
237
- | `boolean` | `VT_BOOL` | `boolean` |
238
- | `number` | `VT_I4` for 32-bit integers, else `VT_R8` | `number` for integer types up to 32 bits, reals, `VT_CY`, `VT_DECIMAL` |
239
- | `bigint` | `VT_I8` (`VT_UI8` above 2^63 - 1) | `bigint` for `VT_I8` / `VT_UI8` |
240
- | `string` | `VT_BSTR` | `string` |
241
- | `Date` | `VT_DATE`, local wall-clock time | `Date` |
242
- | `COMPointer`, dynamic object, `COMObject` | `VT_DISPATCH` (`VT_UNKNOWN` if not an `IDispatch`) | `COMPointer`; best interface from typed calls, dynamic object if dynamic |
243
- | `Array` | `VT_ARRAY \| VT_VARIANT` (nested arrays: arrays of arrays) | `Array`; N-D arrays as nested arrays |
244
- | `Buffer`, typed arrays | `VT_ARRAY` of `VT_UI1`, `VT_I4`, `VT_R8`, ... | `Array` |
245
- | `ErrorValue`, `missing` | `VT_ERROR` | `ErrorValue` |
246
- | record value (`record(type, values)`, a value read from a `VT_RECORD`, an instance of a record class built from a type library) | `VT_RECORD` through `IRecordInfo` (the record type needs a GUID) | a plain object of fields, keeping its `IRecordInfo` under `recordInfo` |
247
- | `typed(vt, value)` | the given type: `typed(VT_UI1, 7)`, `typed(VT_CY, "1.25")` | |
248
- | `safeArray(values, { vt, dimensions })` | `VT_ARRAY` of `vt`; `dimensions: 2` for `values[i][j]` | |
249
-
250
- `VT_BYREF` values are dereferenced when read. A `VARIANT` (`new VARIANT(value)`, `.value`, `.vt`, `.clear()`, `.copy()`, `.changeType(vt, flags, lcid)`, `.exact` for the exact decimal text of `VT_DECIMAL` / `VT_CY`) owns its BSTRs, interfaces and arrays: dispose it. SAFEARRAYs use the Windows column-major layout; `readSafeArray` / `createSafeArray` are exported for vtable interfaces.
251
-
252
- ## Defining interfaces
253
-
254
- The `methods` array is the vtable order after the base interface, as `_methods_` in Python. Signatures are inferred from the specs, inherited methods included.
255
-
256
- ### COMMETHOD (IDL flags)
257
-
258
- `COMMETHOD(idlflags, restype, name, ...params)` (Python: `comtypes.COMMETHOD`) converts arguments and results. Each parameter is `[flags, type, name?, default?]`:
259
-
260
- ```typescript
261
- import { c_int32, c_uint32 } from "node-ctypes";
262
- import { COMInterface, COMMETHOD, HRESULT, BSTR, VARIANT, SELF, IDispatch } from "@node-ctypes/comtypes";
263
-
264
- export const IThing = COMInterface({
265
- name: "IThing",
266
- iid: "{...}",
267
- extends: IDispatch,
268
- methods: [
269
- COMMETHOD(["propget"], HRESULT, "Name", [["out", "retval"], BSTR, "pVal"]), // thing.Name
270
- COMMETHOD(["propput"], HRESULT, "Name", [["in"], BSTR, "value"]), // thing.Name = "x"
271
- COMMETHOD(["propget"], HRESULT, "Item", [["in"], VARIANT, "index"], [["out", "retval"], SELF, "pItem"]), // thing.Item(1): IThing pointer
272
- COMMETHOD([], HRESULT, "Find", [["in"], BSTR, "what"], [["in", "optional"], c_int32, "start", 0], [["out"], c_int32, "index"], [["out", "retval"], VARIANT, "match"]), // [index, match]
273
- COMMETHOD([], HRESULT, "Reset", [["lcid"], c_uint32, "lcid"]), // thing.Reset(): lcid filled
274
- ],
275
- });
276
- ```
277
-
278
- | Parameter flags | Behaviour |
279
- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
280
- | `in` (or none) | a JavaScript argument |
281
- | `out`, `out` + `retval` | allocated and returned: one output is the result, several are a tuple in declaration order; without outputs the HRESULT (`S_OK`/`S_FALSE`) is returned |
282
- | `in` + `out` | passed and returned |
283
- | `optional`, 4th element | may be omitted (pass `undefined`); the default value is used, `missing` for a `VARIANT` |
284
- | `lcid` | filled with the default LCID, not an argument |
46
+ Failures reject (or throw, for synchronous members) with a `COMError`. To build from source, see [Getting started](guides/getting-started.md#building-from-source).
285
47
 
286
- A final `named({ name: value })` passes arguments by name at run time (not in the static signature). Missing required arguments, extra arguments and unknown names throw a `TypeError` before the call.
48
+ ## Supported platforms
287
49
 
288
- | Parameter type (the **value** type; `out` adds the pointer) | `in` | `out` |
289
- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
290
- | `BSTR` | `string \| null`, allocated and freed | `string`, freed |
291
- | `LPOLESTR` | `string \| null` | `string \| null`, freed with `CoTaskMemFree` |
292
- | `VARIANT` | any value (see the conversions), **by value**; a `VARIANT` instance is passed as is | converted value, cleared |
293
- | an interface (`IFoo` means `IFoo*`), `SELF` | `COMPointer`, dynamic object or `COMObject`; queried for the interface when needed | owned `InterfacePointer` or `null` |
294
- | `SAFEARRAY(vt)` | arrays, typed arrays, `typed(...)` | `unknown[]`, destroyed |
295
- | `REFGUID` / `REFIID` / `REFCLSID` | `GUID` or GUID string | `GUID` |
296
- | `GUID` and other `Structure`s | instance or plain object, by value | the structure |
297
- | simple types (`c_int32`, `c_double`, `wintypes.VARIANT_BOOL`, ...) | as node-ctypes | `.value` |
298
- | `POINTER(T)` | raw pointers (`bigint`, `Buffer`, node-ctypes arrays, structures) pass through; for `VARIANT`, simple and structure types, values go through a temporary `T` (\*) | as `T` (Python style `["out"], POINTER(T)`) |
299
- | `DATE` | `Date` or an OLE Automation date | `Date` |
300
- | `CURRENCY` | number, exact decimal string or bigint (whole units) | number |
301
- | `lazy(() => IFoo)` | as an interface defined later (mutual references) | owned `InterfacePointer<IFoo>` or `null` |
50
+ | Operating system | x64 | ARM64 | Notes |
51
+ | ---------------- | --- | ----- | -------------------------------------------------------------------------------------- |
52
+ | Windows | ✅ | ✅ | Full COM runtime (`ole32.dll`, `oleaut32.dll`), tested on Node.js 24 and 26 |
53
+ | macOS / Linux | ✅ | ✅ | Imports cleanly; `GUID`, `HRESULT`, interface definitions and unit tests work anywhere |
302
54
 
303
- (\*) For `POINTER(VARIANT)`, a COM pointer is a value (`VT_DISPATCH`/`VT_UNKNOWN`), not the address to pass, and `undefined` is a `VT_EMPTY` VARIANT.
55
+ Node.js 24 or later. Also verified in Electron and under `NODE_CTYPES_NO_EXTERNAL_BUFFERS=1` (mirror mode).
304
56
 
305
- Property accessors are named as in comtypes (`_get_Name`, `_set_Name`, `_setref_Name`) and also exposed as JavaScript properties:
57
+ ---
306
58
 
307
- - a `propget` without required arguments is a property, writable when a `propput`/`propputref` exists (`propputref` is chosen for COM objects);
308
- - with arguments it is a method named after the property (`thing.Item(1)`), and the put stays available as `_set_Item(1, value)`.
59
+ ## Guides
309
60
 
310
- `SELF` refers to the interface being defined (e.g. `IEnumVARIANT::Clone`, `IStream::Clone`) and is typed as such.
61
+ - [Getting started](guides/getting-started.md) — installation, supported platforms, entry points, building from source
62
+ - [Apartments and lifetime](guides/apartments-and-lifetime.md) — STA/MTA apartments, `COMPointer` ownership, worker threads and marshaling
63
+ - [Execution model](guides/execution-model.md) — the COM executor, `sync()`, cancellation, Electron and mirror mode
64
+ - [Automation and VARIANTs](guides/automation.md) — `CreateObject`, `GetObject`, `Constants`, dynamic objects, `VARIANT` and `SAFEARRAY` conversions
65
+ - [Defining interfaces](guides/interfaces.md) — `COMMETHOD`, dispinterfaces (`DISPMETHOD` / `DISPPROPERTY`), `STDMETHOD`, built-in interfaces
66
+ - [Type libraries](guides/typelib.md) — `GetModule`, code generation (`node-comtypes generate`), creating and registering type libraries
67
+ - [Events and message pump](guides/events-and-pump.md) — `GetEvents`, `ShowEvents`, `COMObject` event sources, `waitAndPumpMessages` and `startMessagePump`
68
+ - [COM servers](guides/servers.md) — `COMObject`, late binding, COM aggregation/delegation, weak references, Free-Threaded Marshaler, `LocalServer32` registration
69
+ - [Errors and limits](guides/errors.md) — `COMError`, `IErrorInfo`, `IRestrictedErrorInfo`, `EXCEPINFO`, Visual Basic errors, compatibility and limits
70
+ - [Python comtypes correspondence](guides/python-comtypes.md) — Python `comtypes` API mapped to `node-comtypes`
71
+ - [Building, testing and internals](guides/contributing.md) — scripts, mirror-mode testing, CI and release workflow
311
72
 
312
- ### Dispinterfaces (DISPMETHOD, DISPPROPERTY)
73
+ Release history: [CHANGELOG.md](CHANGELOG.md). Detailed internal flows (in Italian): [FLOWS.md](FLOWS.md).
313
74
 
314
- Members of a pure dispinterface have no vtable slot: they are called through `IDispatch::Invoke` with their DISPID. Declare them in `dispMethods` (Python: `_disp_methods_`):
75
+ ---
315
76
 
316
- ```typescript
317
- import { c_int32 } from "node-ctypes";
318
- import { BSTR, COMInterface, CURRENCY, DISPMETHOD, DISPPROPERTY, IDispatch, VARIANT, dispid } from "@node-ctypes/comtypes";
319
-
320
- const Font = COMInterface({
321
- name: "Font",
322
- iid: "{BEF6E003-A874-101A-8BBA-00AA00300CAB}",
323
- extends: IDispatch,
324
- dispMethods: [
325
- DISPPROPERTY([dispid(0)], BSTR, "Name"), // font.Name / font.Name = "Arial"
326
- DISPPROPERTY([dispid(2)], CURRENCY, "Size"),
327
- DISPPROPERTY([dispid(9), "readonly"], c_int32, "Charset"),
328
- DISPMETHOD([dispid(10)], VARIANT, "Describe", [["in"], VARIANT, "what"], [["in", "optional"], c_int32, "depth", 1]),
329
- ],
330
- });
331
- ```
332
-
333
- `DISPMETHOD(idlflags, valueType, name, ...params)` takes `in` parameters (optional, defaults, a final `named({...})`); arguments are converted to their declared type, the result is converted from the VARIANT, and interface results are queried for the declared interface. `propget`/`propput` DISPMETHODs and `DISPPROPERTY` become JavaScript properties as for COMMETHOD.
334
-
335
- ### STDMETHOD (raw)
336
-
337
- `STDMETHOD(restype, name, argtypes)` passes node-ctypes arguments as they are, for methods whose buffers the caller manages (e.g. `IShellLinkW::GetPath` with `create_unicode_buffer`):
338
-
339
- ```typescript
340
- import { c_int32, c_uint32, c_void_p } from "node-ctypes";
341
- import { COMInterface, STDMETHOD, HRESULT, IUnknown } from "@node-ctypes/comtypes";
342
-
343
- export const IShellLinkWPart = COMInterface({
344
- name: "IShellLinkW",
345
- iid: "{000214F9-0000-0000-C000-000000000046}",
346
- extends: IUnknown,
347
- methods: [STDMETHOD(HRESULT, "GetPath", [c_void_p, c_int32, c_void_p, c_uint32]) /* ... */],
348
- register: false, // do not replace the built-in definition for this IID
349
- });
350
- // link.GetPath(buffer, 260, null, 0): Promise<number>; sync(link).GetPath(...): number
351
- ```
352
-
353
- Use `c_int32`/`c_uint32` for `LONG`/`DWORD`/`ULONG`: the `wintypes` aliases map the 32-bit `long` types to `bigint`. In-memory structures such as `GUID` can be passed to `POINTER(T)` parameters. `callMethod(name, ...args)` calls any slot by name. Definitions are registered by IID (the most recent wins) unless `register: false`.
354
-
355
- ### Built-in interfaces
356
-
357
- `@node-ctypes/comtypes/interfaces` (also exported by `@node-ctypes/comtypes`) defines:
358
-
359
- - COM core: `IUnknown`, `IClassFactory`, `IErrorInfo`, `ICreateErrorInfo`, `ISupportErrorInfo`, `IServiceProvider` (with `queryService(object, sid, IFoo)`);
360
- - automation: `IDispatch`, `IEnumVARIANT`, `ITypeInfo`, `ITypeLib`, `ITypeComp`, `IProvideClassInfo`, `IProvideClassInfo2`, `ICreateTypeLib`, `ICreateTypeLib2`, `ICreateTypeInfo`;
361
- - connection points: `IConnectionPoint`, `IConnectionPointContainer`, `IEnumConnections`, `IEnumConnectionPoints`;
362
- - persistence and storage: `IPersist`, `IPersistFile`, `IPropertyBag`, `IPersistPropertyBag`, `IPropertyBag2`, `IPersistPropertyBag2`, `IErrorLog`, `ISequentialStream`, `IStream`;
363
- - views: `IViewObject`, `IViewObject2` (`SIZEL`, `DVASPECT_*`);
364
- - shell: `IShellLinkW`, `IShellLinkA`, the `ShellLink` coclass (`CLSID_ShellLink`).
365
-
366
- Most use COMMETHOD. Raw methods (STDMETHOD) remain where the caller passes buffers, arrays or structures: `IUnknown`, `IDispatch`, `IClassFactory`, `ITypeInfo`, `ITypeLib`, `ITypeComp`, `IServiceProvider`, `IShellLinkW`/`IShellLinkA`, and some methods of `IEnumVARIANT` (`Next`), the connection point enumerators, `IPropertyBag2`, `IViewObject` and `ICreateTypeInfo`.
367
-
368
- ## COM objects in JavaScript
369
-
370
- `COMObject` (Python: `comtypes.COMObject`) builds native vtables whose slots call JavaScript:
371
-
372
- ```typescript
373
- import { COMInterface, COMMETHOD, CreateObject, Dispatch, HRESULT, BSTR, VARIANT, IDispatch, dispid } from "@node-ctypes/comtypes";
374
- import { COMObject } from "@node-ctypes/comtypes/server";
375
-
376
- const ICounter = COMInterface({
377
- name: "ICounter",
378
- iid: "{...}",
379
- extends: IDispatch, // dual: vtable and late binding
380
- methods: [
381
- COMMETHOD([dispid(1)], HRESULT, "Increment", [["in", "optional"], VARIANT, "step"], [["out", "retval"], VARIANT, "value"]),
382
- COMMETHOD([dispid(2), "propget"], HRESULT, "Label", [["out", "retval"], BSTR, "label"]),
383
- COMMETHOD([dispid(2), "propput"], HRESULT, "Label", [["in"], BSTR, "label"]),
384
- ],
385
- });
386
-
387
- class Counter extends COMObject {
388
- static _com_interfaces_ = [ICounter];
389
- Label = "counter"; // propget/propput fall back to the JavaScript property
390
- value = 0;
391
- Increment(step = 1) {
392
- return (this.value += step); // the [out, retval] value
393
- }
394
- }
395
-
396
- const counter = new Counter();
397
- using pointer = counter.QueryInterface(ICounter); // owned ICounter pointer (AddRef)
398
- await pointer.Increment(5); // called on the JavaScript thread: an apartment-threaded object
399
- using dynamic = Dispatch(counter); // late binding through the generated IDispatch
400
- using dict = await CreateObject("Scripting.Dictionary");
401
- await dict.Add("counter", counter); // pass it to native code like any COM object
402
- ```
403
-
404
- - **Implementations** are found by vtable name (`Increment`, `_get_Label`, `_set_Label`); accessors fall back to a property of the same name. Missing implementations return `E_NOTIMPL`.
405
- - **Arguments**: COMMETHOD arguments are converted (`in` values as arguments, `out` values returned: one value, or an array; `[in, out]` values are received and returned). A `[in] VARIANT*` parameter arrives as its value; other `T*` parameters as addresses. STDMETHOD slots receive raw arguments (pointers as `bigint`) and may return an HRESULT.
406
- - **Interface arguments** (pointers and dispatch objects) are lent for the duration of the call and released afterwards: `QueryInterface` or `AddRef` them to keep them.
407
- - **Late binding** for interfaces deriving from `IDispatch`: the members of the declared interfaces (their `dispid`s, and their parameter names for named arguments) and the public JavaScript members (methods, accessors and fields, not `_`-prefixed); `_com_default_member_` answers `DISPID_VALUE`; iterable objects answer `_NewEnum` with a `VariantEnumerator`. Override `_invoke_` / `_ids_of_names_` to customize. Interfaces built from a type library (`GetModule`, generated modules) also provide their `ITypeInfo` through `GetTypeInfo`.
408
- - **Lifetime**: native reference counting; while COM holds references the object is kept alive; `_final_release_()` runs when the count drops to zero. `getLiveObjectCount()` helps detect leaks.
409
- - **Threading**: callbacks run on the JavaScript thread. With `_threading_ = "apartment"` (the default, for STA objects) calls on the object, and calls passing it as an argument, run on the JavaScript thread instead of the executor. `"free"` uses thread-safe callbacks: calls from the executor and other threads are queued to the JavaScript thread and wait for it, so they deadlock while that thread is blocked in a synchronous COM call that waits for them (`sync()`, a call at home).
410
-
411
- ### Errors in implementations
412
-
413
- - An exception becomes a failure HRESULT (`COMError.hresult`, otherwise `E_FAIL`) with `IErrorInfo`: description, source (`_reg_progid_` or the class name) and interface GUID. `ISupportErrorInfo` is implemented automatically.
414
- - Through `IDispatch`, exceptions fill `EXCEPINFO` (`DISP_E_EXCEPTION`); a `DispatchError` is returned as its HRESULT (`DISP_E_*`).
415
- - `static onError(error, object)` observes the exceptions.
416
- - `throw new ReturnHRESULT(hresult, text?)` (Python: `comtypes.ReturnHRESULT`) returns any HRESULT, also a success code such as `S_FALSE`, without calling `onError`.
417
-
418
- ## Events
419
-
420
- ```typescript
421
- import { GetEvents, ShowEvents, startMessagePump } from "@node-ctypes/comtypes";
422
-
423
- declare const source: object; // an event source: COM pointer, dispatch object or COMObject
424
-
425
- using pump = startMessagePump(); // out-of-process and many in-process sources need window messages
426
- using connection = GetEvents(source, {
427
- OnObjectReady(object: unknown) {
428
- console.log("ready", object);
429
- }, // event names from the type information
430
- OnCompleted(result: unknown) {
431
- console.log("completed", result);
432
- },
433
- });
434
- using log = ShowEvents(source); // prints every event
435
- ```
436
-
437
- `GetEvents(source, handler, { interface })` (Python: `comtypes.client.GetEvents`) finds the event interface (the option, `IProvideClassInfo2`, the coclass default source, or the type library) and its names, creates a sink (a `COMObject`) and calls `Advise`; disposing the connection calls `Unadvise`.
438
-
439
- - Events call `handler.Name(...)`, `handler.Interface_Name(...)` or `handler.onEvent(name, args)`; unhandled events are ignored.
440
- - Dispatch arguments are dynamic objects lent for the call; by-reference parameters arrive as `ByRef` (`BeforeClose(cancel) { cancel.value = true; }`).
441
- - Dispinterface and vtable event interfaces are supported.
442
-
443
- A `COMObject` becomes an event source with `static _outgoing_interfaces_` (connection points, `IConnectionPointContainer`, `IProvideClassInfo2`) and raises events with `this.fireEvent("Name", ...args)`: through `IDispatch::Invoke` for dispinterfaces (the `dispid` of the spec), through the vtable otherwise.
444
-
445
- ### Message pump
446
-
447
- | Function | Behaviour |
448
- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
449
- | `startMessagePump({ interval })` | `PeekMessage`/`DispatchMessage` every few ms from the event loop (unref'd); the JavaScript thread stays free |
450
- | `await waitFor(condition, { timeout })` | pump until the condition holds |
451
- | `pumpMessages()` | dispatch what is queued, without blocking |
452
- | `PumpEvents(ms)` | block for `ms` in `CoWaitForMultipleHandles`, dispatching calls and messages (Python: `PumpEvents`) |
453
-
454
- ## Servers
455
-
456
- ```typescript
457
- import { CLSCTX_INPROC_SERVER, IDispatch } from "@node-ctypes/comtypes";
458
- import { COMObject, registerClassObject, UseCommandLine } from "@node-ctypes/comtypes/server";
459
-
460
- class Calculator extends COMObject {
461
- static _com_interfaces_ = [IDispatch];
462
- static _reg_clsid_ = "{...}";
463
- static _reg_progid_ = "My.Calculator.1";
464
- static _reg_novers_progid_ = "My.Calculator";
465
- static _reg_desc_ = "Calculator written in JavaScript";
466
- Add(a: number, b: number) {
467
- return a + b;
468
- }
469
- }
470
-
471
- // In-process: creatable by CoCreateInstance(CLSCTX_INPROC_SERVER) in this process, no registry.
472
- using registration = registerClassObject(Calculator, { clsctx: CLSCTX_INPROC_SERVER });
473
-
474
- // LocalServer32 (another process): the script ends with
475
- await UseCommandLine([Calculator]);
476
- // node calculator.ts /regserver registers it for the current user (HKCU\Software\Classes)
477
- // node calculator.ts /unregserver removes the registration
478
- // node calculator.ts -Embedding serves it: COM starts the script this way when a client creates the object
479
- ```
480
-
481
- Clients then use `CreateObject("My.Calculator")`. See [`examples/localserver.ts`](./examples/localserver.ts), which PowerShell can call.
482
-
483
- `UseCommandLine` (Python: `comtypes.server.register.UseCommandLine`) calls `registerServer`, `unregisterServer` and `runLocalServer` (STA, class factories, message pump until idle), which can also be used directly. Switches accept `/` or `-`, in any case (Git Bash rewrites `/regserver` as a path: use `-regserver` there).
484
-
485
- ### Registration
486
-
487
- `registerServer` writes, per user:
488
-
489
- - `LocalServer32`: the Node.js executable, its options (`execArgv`), the script and its arguments;
490
- - `ProgID` and `VersionIndependentProgID` (`_reg_novers_progid_`, with `CurVer`), and the description (`_reg_desc_`);
491
- - `TypeLib` and `Version`, when the class has a type library: `_reg_typelib_` (`[libid, major, minor]`), or the library its interfaces were built from (`GetModule`, generated modules). The library file (`_typelib_path_`, or the file `GetModule` loaded) is registered too, unless `typelib: false`.
492
-
493
- Registering the type library matters across processes. `IDispatch` is marshaled by the system, but **custom vtable interfaces** (`[oleautomation]` or dual) get their proxy/stub from the registered type library (the type library marshaler); without it, `QueryInterface` for them fails with `E_NOINTERFACE` in the client. Classes with a `_reg_clsid_` and a type library also implement `IProvideClassInfo2`, so clients get their default interface typed.
494
-
495
- ## Type libraries
496
-
497
- ```typescript
498
- import { CreateObject, GetModule } from "@node-ctypes/comtypes";
499
-
500
- const Scripting = (await GetModule("scrrun.dll")) as any; // Python: comtypes.client.GetModule; untyped: generate a module for static types
501
- using fso = await CreateObject(Scripting.FileSystemObject); // the coclass default interface (IFileSystem3), through the vtable
502
- using temp = await fso.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder); // IFolder
503
- console.log(temp.Path);
504
- ```
505
-
506
- `GetModule(source)` loads a type library and builds in memory every type: enums (frozen objects), records (`Structure` classes), interfaces (COMMETHOD, dual interfaces through the vtable), dispinterfaces (DISPMETHOD / DISPPROPERTY), coclasses (`CoClass`: `CreateObject(coclass)` returns the default interface), aliases and module constants. Interfaces defined by node-comtypes (`IUnknown`, `IDispatch`, `IEnumVARIANT`, ...) are reused; references between interfaces are resolved lazily. Results are cached per LIBID, version and LCID.
507
-
508
- Reading and building a library is mostly JavaScript work on the calling thread (a large library such as mshtml takes a few seconds). `await GetModule()` does it in slices of a few milliseconds and yields to the event loop between them, so timers, I/O and an Electron UI keep running; concurrent calls for the same library share one build. `getModuleSync(source)` does the same work at once, for code that cannot wait (the cache is shared). `CreateObject`, `GetObject` and `GetActiveObject` load the type library of the object's best interface this way before returning it. The library of an object in another apartment or process is read from the same registered library loaded in-process, not call by call through its proxy.
509
-
510
- Sources: a file (`"scrrun.dll"`, a path, `"file.dll\\2"`), a LIBID (`"{...}"` or `{ libid, major, minor, lcid }`, highest registered version by default), a ProgID (`"Scripting.Dictionary"`, through the registry, without creating the object) or an `ITypeLib` pointer. Lower level: `loadTypeLib`, `typeLibOf(object)`, `readTypeLib` (a JSON-serializable model) and `buildModule(model)`.
511
-
512
- ### Generated modules
513
-
514
- ```sh
515
- npx node-comtypes generate scrrun.dll --out src/com # src/com/Scripting.ts (with the package installed)
516
- npx node-comtypes generate "Excel.Application" --out src/com --js # Excel.js + Excel.d.ts (needs typescript)
517
- npx node-comtypes info msxml6.dll # list the types
518
- npx -p @node-ctypes/comtypes node-comtypes info scrrun.dll # without installing it
519
- ```
520
-
521
- ```typescript
522
- import { CreateObject } from "@node-ctypes/comtypes";
523
- import * as Scripting from "./com/Scripting.ts";
524
-
525
- using dict = await CreateObject(Scripting.Dictionary); // InterfacePointer<IDictionary>
526
- dict.CompareMode = Scripting.CompareMethod.TextCompare;
527
- const count: number = dict.Count; // read-only: assigning it is a type error
528
- const exists: boolean = await dict.Exists("a"); // methods: Promise<...>; sync(dict).Exists("a"): boolean
529
- ```
530
-
531
- A generated module embeds the library model and builds it with `buildModule` at import time (what `GetModule` does), and adds static types:
532
-
533
- - enums as frozen objects with literal member types, and a union type of their values;
534
- - record field interfaces;
535
- - one `…Methods` interface per interface and dispinterface (methods returning promises, properties, read-only properties, `SELF` and cross references), and `…SyncMethods` for `sync()` views;
536
- - typed coclasses and constants.
537
-
538
- Python's `comtypes.gen` cache corresponds to `GetModule(source, { cacheDir })` (or `NODE_COMTYPES_CACHE`), which also writes `<Library>.ts`. The generator is `generateModule(model)` / `writeModule(model, directory)`.
539
-
540
- ### Writing and registering type libraries
541
-
542
- `createTypeLib(file)` (Python: `comtypes.typeinfo.CreateTypeLib`) starts a type library without MIDL, through `ICreateTypeLib2` and `ICreateTypeInfo`; `SaveAllChanges()` writes it. `registerTypeLib(file, { scope })` registers it, per user by default (`"machine"` requires administrator rights), and returns its identity (`{ libid, major, minor, lcid }`), which `unregisterTypeLib(identity, { scope })` takes.
543
-
544
- ## Errors
545
-
546
- `COMError` carries `hresult` (signed), `text` (`FormatMessageW`), `method` (`IShellLinkW::SetPath`, `IDispatch::Invoke(Add)`) and `details`:
547
-
548
- - vtable calls: `IErrorInfo` (description, source, help file and context, GUID), read only when the object reports `ISupportErrorInfo` support for the failing interface, as comtypes does;
549
- - `IDispatch::Invoke`: for `DISP_E_EXCEPTION`, the `EXCEPINFO` with its `scode` (some servers, such as the Scripting runtime, set only the scode, which is shown in the message); for `DISP_E_TYPEMISMATCH` / `DISP_E_PARAMNOTFOUND`, the `argumentIndex`.
550
-
551
- Visual Basic run-time errors (`FACILITY_CONTROL`, `0x800Axxxx`, e.g. from the Scripting runtime) get their text from vbscript.dll when it is installed (a Windows Feature on Demand).
552
-
553
- ## Entry points
554
-
555
- - **`@node-ctypes/comtypes`**: everything except `low-level`, plus the core:
556
- - `GUID`, HRESULT codes and helpers, `COMError`, `checkHRESULT`;
557
- - `COMInterface`, `COMMETHOD`, `STDMETHOD`, `DISPMETHOD`, `DISPPROPERTY` and the parameter types (`BSTR`, `LPOLESTR`, `REFGUID`, `SAFEARRAY`, `SELF`, `DATE`, `CURRENCY`, `lazy`, `dispid`, `helpstring`);
558
- - `COMPointer`, `CoInitializeEx`, `apartment`, `CoCreateInstance(Ex)`, `CoGetClassObject`, `CLSCTX_*` / `COINIT_*`;
559
- - message pump: `startMessagePump`, `waitFor`, `pumpMessages`, `PumpEvents`;
560
- - threads: `marshalInterface`, `unmarshalInterface`, `unmarshalDispatch`, `releaseMarshaled`, `GlobalInterfaceTable`;
561
- - execution: `sync`, `run`, `stats`, `finalize`.
562
- - **`@node-ctypes/comtypes/client`**: `CreateObject`, `GetObject`, `sync`, `GetActiveObject`, `GetBestInterface` / `wrap`, `Constants`, `Dispatch` and the dynamic object helpers (`getProperty`, `putProperty`, `putRefProperty`, `invokeMethod`, `enumerate`, `dispatchPointer`, `isDispatch`, `release`, `memberInfo`, `typeName`), `GetEvents`, `ShowEvents`.
563
- - **`@node-ctypes/comtypes/automation`**: `VARIANT`, `typed`, `safeArray`, `byRef` / `ByRef`, `named`, `missing`, `ErrorValue`, `record` / `RecordInfo`, SAFEARRAY functions, `DECIMAL`, dates, `DISPPARAMS`, `EXCEPINFO`, `invoke` / `getIDsOfNames`, `setDefaultLCID`, type information helpers, `VT_*` / `DISPID_*` and the other automation constants.
564
- - **`@node-ctypes/comtypes/typelib`**: `GetModule`, `getModuleSync`, `loadTypeLib` and the registered library functions, `typeLibOf`, `readTypeLib` and the model types, `buildModule`, `generateModule`, `writeModule`, `createTypeLib`, `registerTypeLib`, `unregisterTypeLib`, `isCoClass` / `CoClass`.
565
- - **`@node-ctypes/comtypes/server`**: `COMObject`, `VariantEnumerator`, `ConnectionPoint`, `ClassFactory`, `DispatchError`, `ReturnHRESULT`, `registerClassObject`, `registerServer`, `unregisterServer`, `runLocalServer`, `UseCommandLine`, `REGCLS_*`, `setErrorInfo`, `getLiveObjectCount`.
566
- - **`@node-ctypes/comtypes/interfaces`**: the [built-in interfaces](#built-in-interfaces) with their structures and constants.
567
- - **`@node-ctypes/comtypes/low-level`**: lazy `ole32`/`oleaut32` bindings, `executorCall` (a raw call on the COM executor, with `IErrorInfo`), raw vtable access (`rawQueryInterface`, `rawAddRef`, `rawRelease`), BSTR and task-memory helpers, registry helpers.
568
-
569
- ## Python comtypes correspondence
570
-
571
- | comtypes | node-comtypes |
572
- | ------------------------------------------------------------ | ----------------------------------------------------------------- |
573
- | **Interfaces and pointers** | |
574
- | `GUID("{...}")`, `GUID.create_new()` | `new GUID("{...}")`, `GUID.createNew()` |
575
- | `GUID.from_progid()`, `.as_progid()` | `GUID.fromProgID()`, `.asProgID()` |
576
- | `class IFoo(IUnknown): _iid_, _methods_` | `COMInterface({ name, iid, extends, methods })` |
577
- | `STDMETHOD(HRESULT, "Name", [args])` | `STDMETHOD(HRESULT, "Name", [args])` |
578
- | `COMMETHOD([flags], HRESULT, "Name", (["in"], T, "x"), ...)` | `COMMETHOD([flags], HRESULT, "Name", [["in"], T, "x"], ...)` |
579
- | `(["out"], POINTER(BSTR), "p")` | `[["out"], BSTR, "p"]` (`POINTER(T)` also accepted) |
580
- | `POINTER(IFoo)` parameter / `POINTER(POINTER(IFoo))` out | `IFoo` (`SELF` for the interface itself) |
581
- | `_midlSAFEARRAY(BSTR)` | `SAFEARRAY(VT_BSTR)` |
582
- | `dispid(n)`, `helpstring(text)` | `dispid(n)`, `helpstring(text)` |
583
- | `DISPMETHOD`, `DISPPROPERTY`, `_disp_methods_` | `DISPMETHOD`, `DISPPROPERTY`, `dispMethods` |
584
- | `p.Name`, `p._get_Name()`, `p.Name = v` | same |
585
- | out parameters as a tuple | out parameters as an array |
586
- | `CoInitializeEx()`, `CoCreateInstance(clsid, interface)` | `CoInitializeEx()` / `apartment()`, `CoCreateInstance(...)` |
587
- | `p.QueryInterface(IFoo)` | `p.QueryInterface(IFoo)` |
588
- | `p == q` | `p.isSameObject(q)` |
589
- | `del p` / refcount | `p.Release()` / `using` |
590
- | `COMError(hresult, text, details)` | `COMError` with `hresult`, `text`, `details` |
591
- | **Client** | |
592
- | `client.CreateObject(progid)` | `await CreateObject(progid)` (best interface) |
593
- | `obj.Method(...)` (blocking) | `await obj.Method(...)`; blocking: `sync(obj).Method(...)` |
594
- | `client.CreateObject(progid, dynamic=True)` | `CreateObject(progid, { dynamic: true })` |
595
- | `client.GetActiveObject`, `client.GetObject` | `GetActiveObject`, `GetObject` |
596
- | `client.GetBestInterface`, `client.wrap` | `GetBestInterface`, `wrap` |
597
- | `client.dynamic.Dispatch(p)` | `Dispatch(p)` |
598
- | `client.Constants(obj)` | `Constants(obj)` |
599
- | `obj.Item[key] = value` | `putProperty(obj, "Item", key, value)` |
600
- | keyword arguments | `named({ Name: value })` |
601
- | byref arguments (win32com: returned values) | `byRef(value)`, read `.value` after the call |
602
- | `automation.VARIANT`, `.value` | `VARIANT`, `.value` |
603
- | `comtypes.automation.Missing` | `missing` |
604
- | `client.GetEvents`, `client.ShowEvents` | `GetEvents`, `ShowEvents` |
605
- | `client.PumpEvents` | `PumpEvents` (+ `startMessagePump`) |
606
- | `CoMarshalInterThreadInterfaceInStream`, GIT | `marshalInterface` / `unmarshalInterface`, `GlobalInterfaceTable` |
607
- | **Type libraries** | |
608
- | `client.GetModule(path)`, `comtypes.gen` | `await GetModule(path, { cacheDir })`, `node-comtypes generate` |
609
- | generated `CoClass` subclasses | `CoClass` objects; `CreateObject(coclass)` |
610
- | `typeinfo.CreateTypeLib`, `RegisterTypeLib` | `createTypeLib`, `registerTypeLib`, `unregisterTypeLib` |
611
- | **Servers** | |
612
- | `class X(COMObject): _com_interfaces_ = [IFoo]` | `class X extends COMObject { static _com_interfaces_ = [IFoo] }` |
613
- | `_outgoing_interfaces_`, `Fire_Event` | `_outgoing_interfaces_`, `fireEvent("Name", ...)` |
614
- | `_final_release_`, `_reg_clsid_`, `_reg_progid_` | same |
615
- | `_reg_desc_`, `_reg_novers_progid_` | same |
616
- | `_reg_typelib_`, `_typelib_path_` | same |
617
- | `ReturnHRESULT(hresult, text)` | `throw new ReturnHRESULT(hresult, text)` |
618
- | `server.register.UseCommandLine`, `register` | `UseCommandLine`, `registerServer` |
619
- | `server.localserver.run` | `runLocalServer` |
620
- | **Other modules** | |
621
- | `comtypes.persist`, `comtypes.viewobject` | `IPropertyBag`, `IPersistPropertyBag`(2), `IViewObject`(2), ... |
622
- | `IServiceProvider.QueryService(sid, interface)` | `queryService(object, sid, interface)` |
623
- | `comtypes.shelllink.ShellLink` | `ShellLink` (`CreateObject(ShellLink)`), `IShellLinkA` |
624
-
625
- ## Compatibility and limits
626
-
627
- - Methods run on one executor thread, in order: a slow call delays the next ones (not the event loop). Each costs a round trip to that thread; see [Synchronous calls](#synchronous-calls) for chatty loops. Win32 messages are pumped only on request ([Message pump](#message-pump)).
628
- - Objects inside `ByRef` arguments and `VARIANT` structures passed by address are not handed over between apartments: in a single-threaded home, pass such arguments to objects created with `{ home: true }` or use `sync()`.
629
- - Hand-rolled vtables (`COMObject`s aside) that are not thread-safe must not be passed to methods of objects shared with the executor in a multithreaded home.
630
- - Objects returned without `{ dynamic: true }` expose the members of their type library only: properties added at run time (WMI class properties, `IDispatchEx`) need a dynamic object, as in Python. An unknown member of a typed pointer is `undefined` (Python raises `AttributeError`), and typed pointers cannot be called for their default member.
631
- - A dynamic property whose get has only optional arguments is read as a value ([Dynamic objects](#dynamic-objects)).
632
- - `named()` works at run time only: static signatures are positional.
633
- - C arrays (`size_is`) have no codec: use STDMETHOD or `POINTER(T)` with your own buffers.
634
- - `VT_RECORD` needs a record type with a GUID in its type library (an `IRecordInfo` requirement).
635
- - Custom vtable interfaces cross apartments and processes only with a registered type library or proxy/stub; `IDispatch` always does.
636
- - In-process servers (InprocServer32) cannot host Node.js, so `_reg_threading_` and `_reg_clsctx_` have no equivalent; a native shim forwarding to a LocalServer is a possible future addition.
637
- - `_threading_ = "free"` objects deadlock when called from another thread while the JavaScript thread is blocked in a synchronous COM call (`sync()` or a call at home) waiting for that call.
638
- - The Scripting runtime and the Shell do not implement `ISupportErrorInfo`: their vtable failures have no `details`.
639
-
640
- Implementation flows, in Italian: [FLOWS.md](./FLOWS.md).
641
-
642
- ## Development
643
-
644
- ```sh
645
- npm run build # dist/
646
- npm run typecheck
647
- npm run test:types # declaration and API type tests
648
- npm run test:unit # GUID, HRESULT, layouts, DECIMAL, DATE, VARIANT scalars, type library build and generation: any OS
649
- npm test # everything; COM tests are skipped outside Windows
650
- npm pack --dry-run # package contents
651
- ```
77
+ ## Examples
652
78
 
653
- The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Node.js 24 and 26 on Windows x64 and ARM64. It is discovered only when this package is a repository root, not while nested in another repository. Pushing a `v<version>` tag that matches `package.json` publishes to npm once the whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
79
+ Runnable TypeScript examples live in `examples/`; see the [index](examples/README.md).
654
80
 
655
- Examples, after a build (`node examples/<name>.ts`):
81
+ - [shortcut.ts](examples/shortcut.ts) — shell links through `IShellLinkW` and `IPersistFile`
82
+ - [automation.ts](examples/automation.ts) — `Scripting.Dictionary`, `FileSystemObject` and WMI
83
+ - [stream.ts](examples/stream.ts) — `IStream` and `COMMETHOD` outputs
84
+ - [server.ts](examples/server.ts) — JavaScript `COMObject` with events, called through vtable, `IDispatch` and native code
85
+ - [events.ts](examples/events.ts) — WMI event subscription with `GetEvents` and the low-latency `waitAndPumpMessages` pump
86
+ - [localserver.ts](examples/localserver.ts) — out-of-process `LocalServer32` server with `UseCommandLine`
87
+ - [active-directory.ts](examples/active-directory.ts) — Active Directory search via ADSI `IDirectorySearch` and `activeds.tlb`
88
+ - [typelib.ts](examples/typelib.ts) — `GetModule` and typed coclasses
656
89
 
657
- - [shortcut.ts](./examples/shortcut.ts): a shell link through `IShellLinkW` and `IPersistFile`;
658
- - [automation.ts](./examples/automation.ts): Scripting.Dictionary, FileSystemObject and WMI;
659
- - [stream.ts](./examples/stream.ts): `IStream` and COMMETHOD outputs;
660
- - [server.ts](./examples/server.ts): a `COMObject` with events, used through the vtable, `IDispatch` and native code;
661
- - [localserver.ts](./examples/localserver.ts): a LocalServer32 registered with `UseCommandLine`;
662
- - [active-directory.ts](./examples/active-directory.ts): Active Directory search through ADSI `IDirectorySearch`, with the structures and enums of the Active DS type library;
663
- - [active-directory-sync.ts](./examples/active-directory-sync.ts): the same search with every call synchronous on the JavaScript thread (`sync()`, `getModuleSync`, `CoGetObject`): faster, but it blocks the event loop for the whole search;
664
- - [typelib.ts](./examples/typelib.ts): `GetModule` and coclasses.
90
+ ---
665
91
 
666
92
  ## License
667
93
 
668
- [MIT](./LICENSE). See [NOTICE](./NOTICE) for the Python comtypes attribution.
94
+ [MIT](LICENSE). See [NOTICE](NOTICE) for the Python `comtypes` attribution.