@node-ctypes/comtypes 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +114 -47
  2. package/dist/automation/dispatch.d.ts +6 -0
  3. package/dist/automation/dispatch.js +78 -29
  4. package/dist/automation/members.js +31 -22
  5. package/dist/automation/variant.d.ts +2 -0
  6. package/dist/automation/variant.js +38 -1
  7. package/dist/cli.js +7 -2
  8. package/dist/client/best.d.ts +6 -0
  9. package/dist/client/best.js +89 -45
  10. package/dist/client/constants.js +2 -2
  11. package/dist/client/dual.d.ts +14 -0
  12. package/dist/client/dual.js +122 -0
  13. package/dist/client/dynamic.d.ts +21 -9
  14. package/dist/client/dynamic.js +123 -18
  15. package/dist/client/events.js +11 -11
  16. package/dist/client/index.d.ts +39 -19
  17. package/dist/client/index.js +124 -17
  18. package/dist/commethod.js +67 -18
  19. package/dist/dispmethod.js +26 -5
  20. package/dist/executor/apartment.d.ts +32 -0
  21. package/dist/executor/apartment.js +226 -0
  22. package/dist/executor/classes.d.ts +10 -0
  23. package/dist/executor/classes.js +18 -0
  24. package/dist/executor/executor.d.ts +76 -0
  25. package/dist/executor/executor.js +208 -0
  26. package/dist/executor/operations.d.ts +29 -0
  27. package/dist/executor/operations.js +95 -0
  28. package/dist/index.d.ts +6 -2
  29. package/dist/index.js +3 -1
  30. package/dist/interface.d.ts +43 -3
  31. package/dist/interface.js +28 -8
  32. package/dist/interfaces/servprov.js +2 -2
  33. package/dist/low-level/index.d.ts +2 -0
  34. package/dist/low-level/index.js +1 -0
  35. package/dist/low-level/native.d.ts +6 -0
  36. package/dist/low-level/native.js +13 -1
  37. package/dist/pointer.d.ts +57 -6
  38. package/dist/pointer.js +233 -9
  39. package/dist/server/comobject.js +9 -3
  40. package/dist/server/errorinfo.js +6 -6
  41. package/dist/server/register.js +5 -0
  42. package/dist/threads.js +4 -4
  43. package/dist/tracking.d.ts +2 -0
  44. package/dist/tracking.js +4 -0
  45. package/dist/typelib/build.d.ts +5 -0
  46. package/dist/typelib/build.js +8 -1
  47. package/dist/typelib/generate.js +14 -11
  48. package/dist/typelib/getmodule.d.ts +14 -3
  49. package/dist/typelib/getmodule.js +61 -19
  50. package/dist/typelib/index.d.ts +1 -1
  51. package/dist/typelib/index.js +1 -1
  52. package/dist/typelib/load.js +32 -8
  53. package/dist/typelib/model.d.ts +3 -0
  54. package/dist/typelib/model.js +87 -66
  55. package/dist/typelib/steps.d.ts +12 -0
  56. package/dist/typelib/steps.js +51 -0
  57. package/package.json +2 -2
@@ -28,7 +28,7 @@ class Writer {
28
28
  /** Definition (interface, record class, coclass) -> export name. */
29
29
  names = new Map();
30
30
  /** node-comtypes names imported as types (aliased with `$`). */
31
- imports = new Set(["InterfaceDef", "InterfaceMethods", "InterfacePointer", "ComObject"]);
31
+ imports = new Set(["InterfaceDef", "InterfaceMethods", "InterfacePointer", "SyncInterfaceMethods", "ComObject"]);
32
32
  constructor(model) {
33
33
  this.model = model;
34
34
  this.module = buildModule(model);
@@ -151,20 +151,22 @@ class Writer {
151
151
  return spec.restype === HRESULT ? "number" : spec.restype === null ? "undefined" : this.simple(spec.restype, "out");
152
152
  return outputs.length === 1 ? outputs[0] : `[${outputs.join(", ")}]`;
153
153
  }
154
- signature(spec, self) {
154
+ /** Signature of a member; methods (kind `method`) return promises unless `synchronous`. */
155
+ signature(spec, self, synchronous = true) {
155
156
  const params = spec.params;
156
- if (!params)
157
- return "(...args: unknown[]): number";
158
- return `(${this.parameters(params, self)}): ${this.result(spec, self)}`;
157
+ const result = params ? this.result(spec, self) : "number";
158
+ const returned = synchronous || spec.kind !== "method" ? result : `Promise<${result}>`;
159
+ return params ? `(${this.parameters(params, self)}): ${returned}` : `(...args: unknown[]): ${returned}`;
159
160
  }
160
- interfaceBody(definition) {
161
+ /** Members as installed on pointers (`synchronous`: on the `sync()` views). */
162
+ interfaceBody(definition, synchronous) {
161
163
  const ownDisp = definition.dispMethods.slice(definition.base?.dispMethods.length ?? 0);
162
164
  const members = [...definition.methods, ...ownDisp];
163
165
  const lines = [];
164
166
  const memberNames = new Set();
165
167
  for (const spec of members) {
166
168
  memberNames.add(spec.name);
167
- lines.push(` ${key(spec.name)}${this.signature(spec, definition)};`);
169
+ lines.push(` ${key(spec.name)}${this.signature(spec, definition, synchronous)};`);
168
170
  if (spec.dispatch && spec.kind === "propget" && spec.writable) {
169
171
  memberNames.add(`_set_${spec.property}`);
170
172
  lines.push(` ${key(`_set_${spec.property}`)}(value: ${this.valueType(spec.valueType, "in", definition)}): undefined;`);
@@ -257,10 +259,11 @@ class Writer {
257
259
  body.push(`export const ${name} = module$[${JSON.stringify(type.name)}] as typeof ${this.use(builtin.name)};`, "");
258
260
  break;
259
261
  }
260
- const lines = this.interfaceBody(definition);
261
262
  const own = [...new Set([...definition.methods, ...definition.dispMethods].map((spec) => [spec.name, spec.property]).flat())];
262
- const base = definition.base ? `Omit<InterfaceMethods$<${this.interfaceType(definition.base)}>, ${own.length ? own.map((member) => JSON.stringify(member)).join(" | ") : "never"}>` : "{}";
263
- body.push(`/** ${type.doc ?? `${type.kind === "dispinterface" ? "Dispinterface" : "Interface"} ${type.name}`} (${definition.iid}) */`, `export interface ${name}Methods extends ${base} {`, ...lines, `}`, `export const ${name} = module$[${JSON.stringify(type.name)}] as InterfaceDef$<${name}Methods>;`, "");
263
+ const omitted = own.length ? own.map((member) => JSON.stringify(member)).join(" | ") : "never";
264
+ const base = definition.base ? `Omit<InterfaceMethods$<${this.interfaceType(definition.base)}>, ${omitted}>` : "{}";
265
+ const syncBase = definition.base ? `Omit<SyncInterfaceMethods$<${this.interfaceType(definition.base)}>, ${omitted}>` : "{}";
266
+ body.push(`/** ${type.doc ?? `${type.kind === "dispinterface" ? "Dispinterface" : "Interface"} ${type.name}`} (${definition.iid}) */`, `export interface ${name}Methods extends ${base} {`, ...this.interfaceBody(definition, false), `}`, `/** ${type.name} members on the \`sync()\` views: every method synchronous. */`, `export interface ${name}SyncMethods extends ${syncBase} {`, ...this.interfaceBody(definition, true), `}`, `export const ${name} = module$[${JSON.stringify(type.name)}] as InterfaceDef$<${name}Methods, ${name}SyncMethods>;`, "");
264
267
  break;
265
268
  }
266
269
  case "coclass": {
@@ -299,7 +302,7 @@ class Writer {
299
302
  if (!name)
300
303
  continue;
301
304
  const isInterface = typeof value === "object" && value !== null && "Pointer" in value;
302
- body.push(`export const ${name} = ${target};`, isInterface ? `export type ${name}Methods = ${target}Methods;` : `export type ${name} = ${target};`, "");
305
+ body.push(`export const ${name} = ${target};`, ...(isInterface ? [`export type ${name}Methods = ${target}Methods;`, `export type ${name}SyncMethods = ${target}SyncMethods;`] : [`export type ${name} = ${target};`]), "");
303
306
  }
304
307
  const typeImports = [...this.imports, "TypeLibModel", "TypeLibModule"].sort().map((name) => `${name} as ${name}$`);
305
308
  const header = [
@@ -14,11 +14,22 @@ export interface GetModuleOptions {
14
14
  * and LCID). Python equivalent: `comtypes.client.GetModule`.
15
15
  *
16
16
  * ```ts
17
- * const Scripting = GetModule("scrrun.dll");
18
- * using dict = CreateObject(Scripting.Dictionary); // typed IDictionary
17
+ * const Scripting = await GetModule("scrrun.dll");
18
+ * using dict = await CreateObject(Scripting.Dictionary); // typed IDictionary
19
19
  * ```
20
20
  *
21
+ * The library is read and built in slices of a few milliseconds, yielding to
22
+ * the event loop between them: a large library (e.g. mshtml) does not freeze
23
+ * timers, I/O or an Electron UI. Concurrent calls for the same library share
24
+ * one build. {@link getModuleSync} does the same work at once.
25
+ *
21
26
  * The result is untyped (`Record<string, unknown>`); generate a module
22
27
  * (`node-comtypes generate`) for static types.
23
28
  */
24
- export declare function GetModule(source: TypeLibSource | TypeLibModel, options?: GetModuleOptions): TypeLibModule;
29
+ export declare function GetModule(source: TypeLibSource | TypeLibModel, options?: GetModuleOptions): Promise<TypeLibModule>;
30
+ /**
31
+ * {@link GetModule} synchronously: the library is read and built at once, on
32
+ * the calling thread (the cache is shared). For code that cannot wait, such as
33
+ * the results of synchronous members.
34
+ */
35
+ export declare function getModuleSync(source: TypeLibSource | TypeLibModel, options?: GetModuleOptions): TypeLibModule;
@@ -50,31 +50,27 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
50
50
  var e = new Error(message);
51
51
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
52
  });
53
- import { buildModule } from "./build.js";
53
+ import { buildModuleSteps } from "./build.js";
54
54
  import { writeModule } from "./generate.js";
55
55
  import { loadTypeLib, withLibAttr } from "./load.js";
56
- import { readTypeLib } from "./model.js";
56
+ import { readTypeLibSteps } from "./model.js";
57
+ import { runSliced, runSync } from "./steps.js";
57
58
  const modules = new Map();
58
59
  /** `key|directory` pairs already written to a cache directory. */
59
60
  const written = new Set();
61
+ /** Asynchronous loads in progress, by library: concurrent calls share one build. */
62
+ const loading = new Map();
60
63
  const moduleKey = (libid, major, minor, lcid) => `${libid}:${major}.${minor}:${lcid}`;
61
64
  function isModel(value) {
62
65
  return typeof value === "object" && value !== null && "types" in value && "libid" in value && !("address" in value);
63
66
  }
64
- /**
65
- * Load a type library and build its definitions (cached per LIBID, version
66
- * and LCID). Python equivalent: `comtypes.client.GetModule`.
67
- *
68
- * ```ts
69
- * const Scripting = GetModule("scrrun.dll");
70
- * using dict = CreateObject(Scripting.Dictionary); // typed IDictionary
71
- * ```
72
- *
73
- * The result is untyped (`Record<string, unknown>`); generate a module
74
- * (`node-comtypes generate`) for static types.
75
- */
76
- export function GetModule(source, options = {}) {
67
+ /** Load, read and build a module, yielding after each type; the module cache is shared by both drivers. */
68
+ function* moduleSteps(source, options, sharing) {
77
69
  const cacheDir = options.cacheDir === undefined ? process.env.NODE_COMTYPES_CACHE : options.cacheDir;
70
+ const fresh = (key) => {
71
+ const cached = modules.get(key);
72
+ return cached && (!cacheDir || written.has(`${key}|${cacheDir}`)) ? cached : undefined;
73
+ };
78
74
  let model;
79
75
  let path;
80
76
  if (isModel(source)) {
@@ -86,10 +82,14 @@ export function GetModule(source, options = {}) {
86
82
  const library = __addDisposableResource(env_1, loadTypeLib(source), false);
87
83
  // Look up the cache before reading the whole library.
88
84
  const libraryKey = withLibAttr(library, (attr) => moduleKey(attr.guid.toString(), attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid));
89
- const cached = modules.get(libraryKey);
90
- if (cached && (!cacheDir || written.has(`${libraryKey}|${cacheDir}`)))
85
+ const cached = fresh(libraryKey);
86
+ if (cached)
91
87
  return cached;
92
- model = readTypeLib(library);
88
+ const pending = sharing?.pending(libraryKey);
89
+ if (pending)
90
+ return (yield pending);
91
+ sharing?.started(libraryKey);
92
+ model = yield* readTypeLibSteps(library);
93
93
  if (typeof source === "string" && /\.(dll|tlb|olb|ocx|exe)(\\\d+)?$/i.test(source))
94
94
  path = source;
95
95
  }
@@ -104,7 +104,9 @@ export function GetModule(source, options = {}) {
104
104
  const key = moduleKey(model.libid, model.major, model.minor, model.lcid);
105
105
  let module = modules.get(key);
106
106
  if (!module) {
107
- module = buildModule(model, { path });
107
+ const built = yield* buildModuleSteps(model, { path });
108
+ // A synchronous load may have built it meanwhile: keep the first.
109
+ module = modules.get(key) ?? built;
108
110
  modules.set(key, module);
109
111
  }
110
112
  if (cacheDir && !written.has(`${key}|${cacheDir}`)) {
@@ -113,3 +115,43 @@ export function GetModule(source, options = {}) {
113
115
  }
114
116
  return module;
115
117
  }
118
+ /**
119
+ * Load a type library and build its definitions (cached per LIBID, version
120
+ * and LCID). Python equivalent: `comtypes.client.GetModule`.
121
+ *
122
+ * ```ts
123
+ * const Scripting = await GetModule("scrrun.dll");
124
+ * using dict = await CreateObject(Scripting.Dictionary); // typed IDictionary
125
+ * ```
126
+ *
127
+ * The library is read and built in slices of a few milliseconds, yielding to
128
+ * the event loop between them: a large library (e.g. mshtml) does not freeze
129
+ * timers, I/O or an Electron UI. Concurrent calls for the same library share
130
+ * one build. {@link getModuleSync} does the same work at once.
131
+ *
132
+ * The result is untyped (`Record<string, unknown>`); generate a module
133
+ * (`node-comtypes generate`) for static types.
134
+ */
135
+ export function GetModule(source, options = {}) {
136
+ let key = null;
137
+ // runSliced starts after this function returns: `result` is set by then.
138
+ const result = runSliced(moduleSteps(source, options, {
139
+ pending: (libraryKey) => loading.get(libraryKey),
140
+ started: (libraryKey) => {
141
+ key = libraryKey;
142
+ loading.set(libraryKey, result);
143
+ },
144
+ })).finally(() => {
145
+ if (key !== null && loading.get(key) === result)
146
+ loading.delete(key);
147
+ });
148
+ return result;
149
+ }
150
+ /**
151
+ * {@link GetModule} synchronously: the library is read and built at once, on
152
+ * the calling thread (the cache is shared). For code that cannot wait, such as
153
+ * the results of synchronous members.
154
+ */
155
+ export function getModuleSync(source, options = {}) {
156
+ return runSync(moduleSteps(source, options));
157
+ }
@@ -6,7 +6,7 @@ export { buildModule, builtinInterfaceDefs, decodeDefault } from "./build.ts";
6
6
  export type { TypeLibModule } from "./build.ts";
7
7
  export { isCoClass, typeLibLocationOf } from "./coclass.ts";
8
8
  export type { CoClass, TypeLibLocation } from "./coclass.ts";
9
- export { GetModule } from "./getmodule.ts";
9
+ export { GetModule, getModuleSync } from "./getmodule.ts";
10
10
  export type { GetModuleOptions } from "./getmodule.ts";
11
11
  export { generateModule, writeModule, moduleFileName, identifier } from "./generate.ts";
12
12
  export type { GenerateOptions } from "./generate.ts";
@@ -2,5 +2,5 @@ export { loadTypeLib, loadRegisteredTypeLib, registeredTypeLibPath, registeredVe
2
2
  export { readTypeLib } from "./model.js";
3
3
  export { buildModule, builtinInterfaceDefs, decodeDefault } from "./build.js";
4
4
  export { isCoClass, typeLibLocationOf } from "./coclass.js";
5
- export { GetModule } from "./getmodule.js";
5
+ export { GetModule, getModuleSync } from "./getmodule.js";
6
6
  export { generateModule, writeModule, moduleFileName, identifier } from "./generate.js";
@@ -59,11 +59,12 @@ import { GUID, toGUID } from "../guid.js";
59
59
  import { TYPE_E_CANTLOADLIBRARY } from "../hresult.js";
60
60
  import { IDispatch } from "../interfaces/dispatch.js";
61
61
  import { ICreateTypeLib2, IProvideClassInfo, ITypeInfo, ITypeLib, TLIBATTR } from "../interfaces/typeinfo.js";
62
- import { ole32, oleaut32, takeBSTR } from "../low-level/native.js";
62
+ import { copyStruct, ole32, oleaut32, takeBSTR } from "../low-level/native.js";
63
63
  import { HKEY_CLASSES_ROOT, readString, subkeys } from "../low-level/registry.js";
64
64
  import { SYS_WIN32, SYS_WIN64 } from "../automation/constants.js";
65
65
  import { POINTER_SIZE } from "../low-level/native.js";
66
- import { COMPointer } from "../pointer.js";
66
+ import { COMPointer, sync } from "../pointer.js";
67
+ import { isProxy } from "../executor/apartment.js";
67
68
  const REGKIND_NONE = 2;
68
69
  /** Registered versions of a type library (`HKCR\TypeLib\{libid}`), highest first. */
69
70
  export function registeredVersions(libid) {
@@ -121,7 +122,7 @@ export function typeLibOf(object) {
121
122
  try {
122
123
  const owned = __addDisposableResource(env_2, provider, false);
123
124
  try {
124
- typeInfo = owned.GetClassInfo();
125
+ typeInfo = sync(owned).GetClassInfo();
125
126
  }
126
127
  catch {
127
128
  typeInfo = null;
@@ -157,7 +158,7 @@ export function typeLibOf(object) {
157
158
  const info = __addDisposableResource(env_1, typeInfo, false);
158
159
  const out = new ctypes.c_void_p();
159
160
  const index = new ctypes.c_uint32();
160
- info.GetContainingTypeLib(ctypes.byref(out), ctypes.byref(index));
161
+ sync(info).GetContainingTypeLib(ctypes.byref(out), ctypes.byref(index));
161
162
  return COMPointer.fromAddress(out.value, ITypeLib);
162
163
  }
163
164
  catch (e_3) {
@@ -178,7 +179,7 @@ const FILE_EXTENSION = /\.(dll|tlb|olb|ocx|exe)$/i;
178
179
  */
179
180
  export function loadTypeLib(source) {
180
181
  if (source instanceof COMPointer)
181
- return source.QueryInterface(ITypeLib);
182
+ return inProcess(source.QueryInterface(ITypeLib));
182
183
  if (typeof source === "object")
183
184
  return loadRegisteredTypeLib(source);
184
185
  if (GUID.isGUIDString(source))
@@ -192,15 +193,38 @@ export function loadTypeLib(source) {
192
193
  checkHRESULT(oleaut32().LoadTypeLibEx(source, REGKIND_NONE, ctypes.byref(out)), `LoadTypeLibEx(${source})`);
193
194
  return COMPointer.fromAddress(out.value, ITypeLib);
194
195
  }
196
+ /**
197
+ * `library` itself, or, when it is a proxy (the library of an object in
198
+ * another apartment or process), the same registered library loaded in this
199
+ * apartment: reading a library makes many calls, direct instead of
200
+ * cross-apartment. Takes over `library`.
201
+ */
202
+ function inProcess(library) {
203
+ if (!isProxy(library.address))
204
+ return library;
205
+ try {
206
+ const identity = withLibAttr(library, (attr) => ({ libid: attr.guid.toString(), major: attr.wMajorVerNum, minor: attr.wMinorVerNum, lcid: attr.lcid }));
207
+ const local = loadRegisteredTypeLib(identity);
208
+ library.Release();
209
+ return local;
210
+ }
211
+ catch (error) {
212
+ // Not registered (e.g. built in memory): read it through the proxy.
213
+ if (error instanceof COMError)
214
+ return library;
215
+ library.Release();
216
+ throw error;
217
+ }
218
+ }
195
219
  /** Read the `TLIBATTR` of a library. */
196
220
  export function withLibAttr(library, use) {
197
221
  const out = new ctypes.c_void_p();
198
- library.GetLibAttr(ctypes.byref(out));
222
+ sync(library).GetLibAttr(ctypes.byref(out));
199
223
  try {
200
- return use(TLIBATTR.from_address(out.value));
224
+ return use(copyStruct(TLIBATTR, out.value));
201
225
  }
202
226
  finally {
203
- library.ReleaseTLibAttr(out.value);
227
+ sync(library).ReleaseTLibAttr(out.value);
204
228
  }
205
229
  }
206
230
  /** `SYSKIND` of this process: `SYS_WIN64` on 64-bit Windows (x64 and ARM64), else `SYS_WIN32`. */
@@ -1,5 +1,6 @@
1
1
  import type { MethodKind } from "../interface.ts";
2
2
  import type { TypeLibPointer } from "./load.ts";
3
+ import type { Steps } from "./steps.ts";
3
4
  /** A type in a signature, a field or an alias. */
4
5
  export type TypeRef = {
5
6
  readonly kind: "vt";
@@ -138,4 +139,6 @@ export interface TypeLibModel {
138
139
  }
139
140
  /** Describe a loaded type library. */
140
141
  export declare function readTypeLib(library: TypeLibPointer): TypeLibModel;
142
+ /** {@link readTypeLib} in steps: yields after each type. */
143
+ export declare function readTypeLibSteps(library: TypeLibPointer): Steps<TypeLibModel>;
141
144
  export {};
@@ -56,9 +56,10 @@ import { dateToOADate } from "../automation/date.js";
56
56
  import { documentation, withFuncDesc, withTypeAttr, withVarDesc } from "../automation/members.js";
57
57
  import { ErrorValue, readVariant } from "../automation/variant.js";
58
58
  import { ELEMDESC, ITypeInfo, ITypeLib, PARAMDESCEX, TYPEDESC } from "../interfaces/typeinfo.js";
59
- import { POINTER_SIZE, readMemory, takeBSTR } from "../low-level/native.js";
60
- import { COMPointer } from "../pointer.js";
59
+ import { copyStruct, POINTER_SIZE, readMemory, takeBSTR } from "../low-level/native.js";
60
+ import { COMPointer, sync } from "../pointer.js";
61
61
  import { withLibAttr } from "./load.js";
62
+ import { runSync } from "./steps.js";
62
63
  // ── reading ───────────────────────────────────────────────────────────
63
64
  const VARFLAG_FREADONLY = 0x1;
64
65
  const SIZEOF_TYPEDESC = ctypes.sizeof(TYPEDESC);
@@ -80,7 +81,7 @@ function containingLibrary(info, context) {
80
81
  try {
81
82
  const out = new ctypes.c_void_p();
82
83
  const index = new ctypes.c_uint32();
83
- info.GetContainingTypeLib(ctypes.byref(out), ctypes.byref(index));
84
+ sync(info).GetContainingTypeLib(ctypes.byref(out), ctypes.byref(index));
84
85
  const library = __addDisposableResource(env_1, COMPointer.fromAddress(out.value, ITypeLib), false);
85
86
  const libid = withLibAttr(library, (attr) => attr.guid.toString());
86
87
  let name = context.libraries.get(libid);
@@ -103,25 +104,25 @@ function libraryDocumentation(library) {
103
104
  const doc = new ctypes.c_void_p();
104
105
  const context = new ctypes.c_uint32();
105
106
  const file = new ctypes.c_void_p();
106
- library.GetDocumentation(MEMBERID_NIL, ctypes.byref(name), ctypes.byref(doc), ctypes.byref(context), ctypes.byref(file));
107
+ sync(library).GetDocumentation(MEMBERID_NIL, ctypes.byref(name), ctypes.byref(doc), ctypes.byref(context), ctypes.byref(file));
107
108
  takeBSTR(file.value);
108
109
  return { name: takeBSTR(name.value), doc: takeBSTR(doc.value) };
109
110
  }
110
111
  function refTypeInfo(info, hreftype) {
111
112
  const out = new ctypes.c_void_p();
112
- info.GetRefTypeInfo(hreftype, ctypes.byref(out));
113
+ sync(info).GetRefTypeInfo(hreftype, ctypes.byref(out));
113
114
  return COMPointer.fromAddress(out.value, ITypeInfo);
114
115
  }
115
116
  function readTypeDesc(info, desc, context) {
116
117
  switch (desc.vt) {
117
118
  case VT_PTR:
118
- return { kind: "ptr", to: readTypeDesc(info, TYPEDESC.from_address(desc.lptdesc), context) };
119
+ return { kind: "ptr", to: readTypeDesc(info, copyStruct(TYPEDESC, desc.lptdesc), context) };
119
120
  case VT_SAFEARRAY:
120
- return { kind: "safearray", of: readTypeDesc(info, TYPEDESC.from_address(desc.lptdesc), context) };
121
+ return { kind: "safearray", of: readTypeDesc(info, copyStruct(TYPEDESC, desc.lptdesc), context) };
121
122
  case VT_CARRAY: {
122
123
  // ARRAYDESC { TYPEDESC tdescElem; USHORT cDims; SAFEARRAYBOUND rgbounds[cDims]; }
123
124
  const address = desc.lptdesc;
124
- const element = TYPEDESC.from_address(address);
125
+ const element = copyStruct(TYPEDESC, address);
125
126
  const count = ctypes.readValue(address + BigInt(SIZEOF_TYPEDESC), ctypes.c_uint16);
126
127
  const bounds = SIZEOF_TYPEDESC + 4;
127
128
  const dims = Array.from({ length: count }, (_, index) => ctypes.readValue(address + BigInt(bounds + index * 8), ctypes.c_uint32));
@@ -134,38 +135,45 @@ function readTypeDesc(info, desc, context) {
134
135
  }
135
136
  }
136
137
  function userType(info, hreftype, context) {
137
- const env_2 = { stack: [], error: void 0, hasError: false };
138
- try {
139
- const referenced = __addDisposableResource(env_2, refTypeInfo(info, hreftype), false);
140
- const name = documentation(referenced).name ?? `Type${hreftype}`;
141
- const library = containingLibrary(referenced, context);
142
- const external = library.libid !== context.libid;
143
- return withTypeAttr(referenced, (attr) => {
144
- // External aliases are replaced by their definition: no other module is needed.
145
- if (external && attr.typekind === TKIND_ALIAS)
146
- return readTypeDesc(referenced, attr.tdescAlias, context);
147
- return {
148
- kind: "user",
149
- name,
150
- typekind: attr.typekind,
151
- guid: attr.guid.isNull() ? null : attr.guid.toString(),
152
- library: external ? library.name : null,
153
- ...(external && (attr.typekind === TKIND_INTERFACE || attr.typekind === TKIND_DISPATCH) ? { dispatchable: attr.typekind === TKIND_DISPATCH || (attr.wTypeFlags & (TYPEFLAG_FDUAL | TYPEFLAG_FDISPATCHABLE)) !== 0 } : {}),
154
- };
155
- });
138
+ const referenced = refTypeInfo(info, hreftype);
139
+ const cached = context.userTypes.get(referenced.address);
140
+ if (cached) {
141
+ referenced.Release();
142
+ return cached.type;
156
143
  }
157
- catch (e_2) {
158
- env_2.error = e_2;
159
- env_2.hasError = true;
144
+ let type;
145
+ try {
146
+ type = describeUserType(referenced, hreftype, context);
160
147
  }
161
- finally {
162
- __disposeResources(env_2);
148
+ catch (error) {
149
+ referenced.Release();
150
+ throw error;
163
151
  }
152
+ context.userTypes.set(referenced.address, { pointer: referenced, type });
153
+ return type;
154
+ }
155
+ function describeUserType(referenced, hreftype, context) {
156
+ const name = documentation(referenced).name ?? `Type${hreftype}`;
157
+ const library = containingLibrary(referenced, context);
158
+ const external = library.libid !== context.libid;
159
+ return withTypeAttr(referenced, (attr) => {
160
+ // External aliases are replaced by their definition: no other module is needed.
161
+ if (external && attr.typekind === TKIND_ALIAS)
162
+ return readTypeDesc(referenced, attr.tdescAlias, context);
163
+ return {
164
+ kind: "user",
165
+ name,
166
+ typekind: attr.typekind,
167
+ guid: attr.guid.isNull() ? null : attr.guid.toString(),
168
+ library: external ? library.name : null,
169
+ ...(external && (attr.typekind === TKIND_INTERFACE || attr.typekind === TKIND_DISPATCH) ? { dispatchable: attr.typekind === TKIND_DISPATCH || (attr.wTypeFlags & (TYPEFLAG_FDUAL | TYPEFLAG_FDISPATCHABLE)) !== 0 } : {}),
170
+ };
171
+ });
164
172
  }
165
173
  function memberNames(info, memid, count) {
166
174
  const names = Buffer.alloc(POINTER_SIZE * count);
167
175
  const found = new ctypes.c_uint32();
168
- info.GetNames(memid, names, count, ctypes.byref(found));
176
+ sync(info).GetNames(memid, names, count, ctypes.byref(found));
169
177
  return Array.from({ length: found.value }, (_, index) => takeBSTR(ctypes.readValue(names, ctypes.c_void_p, index * POINTER_SIZE)) ?? "");
170
178
  }
171
179
  const INVOKE_KINDS = { 1: "method", [INVOKE_PROPERTYGET]: "propget", [INVOKE_PROPERTYPUT]: "propput", [INVOKE_PROPERTYPUTREF]: "propputref" };
@@ -176,11 +184,11 @@ function readFunctions(info, count, context) {
176
184
  const names = memberNames(info, desc.memid, desc.cParams + 1);
177
185
  const elementSize = ctypes.sizeof(ELEMDESC);
178
186
  const params = Array.from({ length: desc.cParams }, (_, position) => {
179
- const element = ELEMDESC.from_address(desc.lprgelemdescParam + BigInt(position * elementSize));
187
+ const element = copyStruct(ELEMDESC, desc.lprgelemdescParam + BigInt(position * elementSize));
180
188
  const flags = element.paramdesc.wParamFlags;
181
189
  const param = { name: names[position + 1] || (position === desc.cParams - 1 && desc.invkind & (INVOKE_PROPERTYPUT | INVOKE_PROPERTYPUTREF) ? "value" : `arg${position}`), type: readTypeDesc(info, element.tdesc, context), flags };
182
190
  if (flags & PARAMFLAG_FHASDEFAULT && element.paramdesc.pparamdescex) {
183
- const value = encodeDefault(readVariant(PARAMDESCEX.from_address(element.paramdesc.pparamdescex).varDefaultValue._buffer));
191
+ const value = encodeDefault(readVariant(copyStruct(PARAMDESCEX, element.paramdesc.pparamdescex).varDefaultValue._buffer));
184
192
  if (value !== undefined)
185
193
  return { ...param, default: value };
186
194
  }
@@ -207,8 +215,8 @@ function implementedTypes(info, count, context) {
207
215
  return Array.from({ length: count }, (_, index) => {
208
216
  const reference = new ctypes.c_uint32();
209
217
  const flags = new ctypes.c_int32();
210
- info.GetRefTypeOfImplType(index, ctypes.byref(reference));
211
- info.GetImplTypeFlags(index, ctypes.byref(flags));
218
+ sync(info).GetRefTypeOfImplType(index, ctypes.byref(reference));
219
+ sync(info).GetImplTypeFlags(index, ctypes.byref(flags));
212
220
  return { type: userType(info, reference.value, context), flags: flags.value };
213
221
  });
214
222
  }
@@ -254,21 +262,21 @@ function readType(info, context) {
254
262
  }
255
263
  case TKIND_DISPATCH: {
256
264
  if (attr.flags & TYPEFLAG_FDUAL) {
257
- const env_3 = { stack: [], error: void 0, hasError: false };
265
+ const env_2 = { stack: [], error: void 0, hasError: false };
258
266
  try {
259
267
  // Dual: describe the vtable interface (implemented type -1).
260
268
  const reference = new ctypes.c_uint32();
261
- info.GetRefTypeOfImplType(-1 >>> 0, ctypes.byref(reference));
262
- const vtable = __addDisposableResource(env_3, refTypeInfo(info, reference.value), false);
269
+ sync(info).GetRefTypeOfImplType(-1 >>> 0, ctypes.byref(reference));
270
+ const vtable = __addDisposableResource(env_2, refTypeInfo(info, reference.value), false);
263
271
  const model = readType(vtable, context);
264
272
  return model && model.kind === "interface" ? { ...model, dual: true, doc: model.doc ?? docString } : model;
265
273
  }
266
- catch (e_3) {
267
- env_3.error = e_3;
268
- env_3.hasError = true;
274
+ catch (e_2) {
275
+ env_2.error = e_2;
276
+ env_2.hasError = true;
269
277
  }
270
278
  finally {
271
- __disposeResources(env_3);
279
+ __disposeResources(env_2);
272
280
  }
273
281
  }
274
282
  const methods = readFunctions(info, attr.functions, context).filter((func) => !isInheritedDispatchMember(func));
@@ -296,34 +304,47 @@ function readType(info, context) {
296
304
  }
297
305
  /** Describe a loaded type library. */
298
306
  export function readTypeLib(library) {
307
+ return runSync(readTypeLibSteps(library));
308
+ }
309
+ /** {@link readTypeLib} in steps: yields after each type. */
310
+ export function* readTypeLibSteps(library) {
299
311
  const attributes = withLibAttr(library, (attr) => ({ libid: attr.guid.toString(), major: attr.wMajorVerNum, minor: attr.wMinorVerNum, lcid: attr.lcid, syskind: attr.syskind }));
300
312
  const { name, doc } = libraryDocumentation(library);
301
- const context = { libid: attributes.libid, libraries: new Map([[attributes.libid, name ?? attributes.libid]]) };
313
+ const context = { libid: attributes.libid, libraries: new Map([[attributes.libid, name ?? attributes.libid]]), userTypes: new Map() };
302
314
  const types = [];
303
315
  const seen = new Set();
304
- const count = library.GetTypeInfoCount();
305
- for (let index = 0; index < count; index++) {
306
- const env_4 = { stack: [], error: void 0, hasError: false };
307
- try {
316
+ try {
317
+ const count = sync(library).GetTypeInfoCount();
318
+ for (let index = 0; index < count; index++) {
308
319
  const out = new ctypes.c_void_p();
309
- library.GetTypeInfo(index, ctypes.byref(out));
310
- const info = __addDisposableResource(env_4, COMPointer.fromAddress(out.value, ITypeInfo), false);
311
- const type = readType(info, context);
312
- if (!type)
313
- continue;
314
- const key = "iid" in type ? `${type.kind === "dispinterface" ? "D" : "I"}${type.iid}` : `${type.kind}:${type.name}`;
315
- if (seen.has(key) || ("iid" in type && seen.has(`I${type.iid}`)))
316
- continue;
317
- seen.add(key);
318
- types.push(type);
319
- }
320
- catch (e_4) {
321
- env_4.error = e_4;
322
- env_4.hasError = true;
323
- }
324
- finally {
325
- __disposeResources(env_4);
320
+ sync(library).GetTypeInfo(index, ctypes.byref(out));
321
+ {
322
+ const env_3 = { stack: [], error: void 0, hasError: false };
323
+ try {
324
+ const info = __addDisposableResource(env_3, COMPointer.fromAddress(out.value, ITypeInfo), false);
325
+ const type = readType(info, context);
326
+ if (type) {
327
+ const key = "iid" in type ? `${type.kind === "dispinterface" ? "D" : "I"}${type.iid}` : `${type.kind}:${type.name}`;
328
+ if (!seen.has(key) && !("iid" in type && seen.has(`I${type.iid}`))) {
329
+ seen.add(key);
330
+ types.push(type);
331
+ }
332
+ }
333
+ }
334
+ catch (e_3) {
335
+ env_3.error = e_3;
336
+ env_3.hasError = true;
337
+ }
338
+ finally {
339
+ __disposeResources(env_3);
340
+ }
341
+ }
342
+ yield;
326
343
  }
327
344
  }
345
+ finally {
346
+ for (const { pointer } of context.userTypes.values())
347
+ pointer.Release();
348
+ }
328
349
  return { name: name ?? attributes.libid, doc, ...attributes, types };
329
350
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Work that yields between its units; it may also yield a promise to wait for
3
+ * (only when run with {@link runSliced}), and receives its value back.
4
+ */
5
+ export type Steps<T> = Generator<Promise<unknown> | void, T, unknown>;
6
+ /** Run `steps` to completion on the current thread. */
7
+ export declare function runSync<T>(steps: Steps<T>): T;
8
+ /**
9
+ * Run `steps` in slices of a few milliseconds, yielding to the event loop
10
+ * between them. Starts after the current synchronous code, like any promise.
11
+ */
12
+ export declare function runSliced<T>(steps: Steps<T>): Promise<T>;
@@ -0,0 +1,51 @@
1
+ // Work done in steps: a generator that yields between units of work (one type
2
+ // of a type library). It runs to completion synchronously, or in time slices
3
+ // that leave the event loop free in between (timers, I/O, an Electron UI).
4
+ /** Run `steps` to completion on the current thread. */
5
+ export function runSync(steps) {
6
+ for (;;) {
7
+ const step = steps.next();
8
+ if (step.done)
9
+ return step.value;
10
+ if (step.value instanceof Promise) {
11
+ steps.return(undefined);
12
+ throw new Error("work that waits for a promise cannot run synchronously");
13
+ }
14
+ }
15
+ }
16
+ /** Milliseconds of work between two turns of the event loop. */
17
+ const SLICE_MS = 8;
18
+ const nextTurn = () => new Promise((resolve) => setImmediate(resolve));
19
+ /**
20
+ * Run `steps` in slices of a few milliseconds, yielding to the event loop
21
+ * between them. Starts after the current synchronous code, like any promise.
22
+ */
23
+ export async function runSliced(steps) {
24
+ await null;
25
+ let deadline = performance.now() + SLICE_MS;
26
+ let step = steps.next();
27
+ for (;;) {
28
+ if (step.done)
29
+ return step.value;
30
+ if (step.value instanceof Promise) {
31
+ let value;
32
+ try {
33
+ value = await step.value;
34
+ }
35
+ catch (error) {
36
+ // Delivered as an exception at the yield point.
37
+ step = steps.throw(error);
38
+ deadline = performance.now() + SLICE_MS;
39
+ continue;
40
+ }
41
+ step = steps.next(value);
42
+ deadline = performance.now() + SLICE_MS;
43
+ continue;
44
+ }
45
+ if (performance.now() >= deadline) {
46
+ await nextTurn();
47
+ deadline = performance.now() + SLICE_MS;
48
+ }
49
+ step = steps.next();
50
+ }
51
+ }