From 3b31a7ace2f1445d9d7bd528317b485a30effa49 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 3 Sep 2026 17:56:50 +0800 Subject: [PATCH 1/3] Adopt canonical Classic COM module layout Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- README.md | 4 +- .../generated-unsafe-companion.e2e.ts | 10 +- .../classic-com-generated-unsafe.md | 44 +- docs/architecture/classic-com-support.md | 16 +- docs/guides/windows/classic-com-usage.md | 12 +- docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 9 +- .../js/electron-share-ui/src/main/index.ts | 2 +- samples/js/electron-smtc/media-controls.js | 2 +- samples/js/windows-hello/main.js | 2 +- tests/e2e/runners/com/automation-dispatch.mjs | 6 +- tests/e2e/runners/com/drop-target.mjs | 4 +- tests/e2e/runners/com/dtm.mjs | 2 +- .../e2e/runners/com/electron-hwnd-buffer.mjs | 4 +- tests/e2e/runners/com/file-open-dialog.mjs | 8 +- tests/e2e/runners/com/file-operation.mjs | 4 +- tests/e2e/runners/com/module-commonjs.cjs | 2 +- tests/e2e/runners/com/persist-file.mjs | 2 +- tests/e2e/runners/com/property-store.mjs | 2 +- .../runners/com/sequential-stream-buffer.mjs | 4 +- tests/e2e/runners/com/shell-link-pod.mjs | 2 +- tests/e2e/runners/com/smtc.mjs | 2 +- tests/e2e/runners/com/wic-imaging-factory.mjs | 2 +- .../src/codegen/com/generated_unsafe.rs | 55 +-- .../src/codegen/com/javascript/render.rs | 122 ++++-- .../codegen/com/javascript/render_tests.rs | 22 +- tools/dynwinrt-codegen/src/codegen/com/mod.rs | 96 ++++- .../src/codegen/javascript_layout.rs | 53 +++ tools/dynwinrt-codegen/src/codegen/mod.rs | 1 + tools/dynwinrt-codegen/src/codegen/package.rs | 13 +- .../src/codegen/winrt/javascript/mod.rs | 37 +- tools/dynwinrt-codegen/src/main.rs | 355 ++++++++++++---- .../tests/com_sink_tsc_check_test.rs | 8 +- .../snapshots/ishelllinkw/IShellLinkW.d.ts | 2 +- .../snapshots/ishelllinkw/IShellLinkW.js | 2 +- .../dynwinrt-codegen/tests/win32_com_test.rs | 400 ++++++++++++++---- 35 files changed, 980 insertions(+), 331 deletions(-) create mode 100644 tools/dynwinrt-codegen/src/codegen/javascript_layout.rs diff --git a/README.md b/README.md index 17edd114..8a295945 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,9 @@ BYREF/InOut, and output-ownership shapes. Classic COM generation currently emits JavaScript and TypeScript only. It uses the separate `@microsoft/dynwinrt/com` public surface; generated wrappers call `@microsoft/dynwinrt/com/unsafe` internally after codegen validates the ABI. -The `@microsoft/dynwinrt` package root remains WinRT-only. +Generated COM modules use the same lowercase/kebab namespace layout as WinRT +under `com/`, while the COM barrel keeps globally unique short exports. The +`@microsoft/dynwinrt` package root remains WinRT-only. - [Classic COM JavaScript usage guide](docs/guides/windows/classic-com-usage.md) - [Supported ABI, coverage, limitations, and ownership model](docs/architecture/classic-com-support.md) diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 98d7a7b1..cf520d77 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -87,8 +87,8 @@ test.serial('actual generated IWbemServices and IAudioClient companions use hard t.true(lstatSync(externalJunction).isSymbolicLink()) t.is(readFileSync(sentinel, 'utf8'), 'outside-target-must-survive') - const deepBase = join(output, 'com', 'unsafe', 'Windows', 'Win32', 'System', 'Wmi', 'IWbemServicesUnsafe') - const audioBase = join(output, 'com', 'unsafe', 'Windows', 'Win32', 'Media', 'Audio', 'IAudioClientUnsafe') + const deepBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'system', 'wmi', 'IWbemServicesUnsafe') + const audioBase = join(output, 'com', 'unsafe', 'windows', 'win32', 'media', 'audio', 'IAudioClientUnsafe') const runner = join(output, 'generated-companion-runner.cjs') writeFileSync( runner, @@ -121,7 +121,7 @@ test.serial('actual generated IWbemServices and IAudioClient companions use hard ` const esmBarrel = await import(pathToFileURL(${JSON.stringify(join(output, 'com', 'unsafe', 'index.mjs'))}).href)`, " assert.equal(typeof cjs.IWbemServicesUnsafe, 'function')", " assert.equal(typeof audio.IAudioClientUnsafe, 'function')", - ' assert.equal(cjs.IWbemServicesUnsafe.support.schemaVersion, 10)', + ' assert.equal(cjs.IWbemServicesUnsafe.support.schemaVersion, 11)', " const openNamespaceSupport = cjs.IWbemServicesUnsafe.support.methods.find(method => method.name === 'OpenNamespace')", " assert.equal(openNamespaceSupport.status, 'raw_metadata_complete')", " assert.deepEqual(openNamespaceSupport.reasons, [])", @@ -655,8 +655,8 @@ test.serial('actual generated IWbemServices and IAudioClient companions use hard writeFileSync( consumer, [ - "import { IWbemServicesUnsafe } from './com/unsafe/Windows/Win32/System/Wmi/IWbemServicesUnsafe.js'", - "import { IAudioClientUnsafe } from './com/unsafe/Windows/Win32/Media/Audio/IAudioClientUnsafe.js'", + "import { IWbemServicesUnsafe } from './com/unsafe/windows/win32/system/wmi/IWbemServicesUnsafe.js'", + "import { IAudioClientUnsafe } from './com/unsafe/windows/win32/media/audio/IAudioClientUnsafe.js'", "import { IWbemServicesUnsafe as FromBarrel } from './com/unsafe/index.js'", "import { UnsafePointee, UnsafePointerOutput } from './com/unsafe/runtime.js'", "import type { UnsafeOwnedPointer } from './com/unsafe/runtime.js'", diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index 16c369ac..b9e57254 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -44,11 +44,12 @@ metadata does not contain. ```text generated/ └── com/ - ├── IFoo.js - ├── IFoo.d.ts ├── index.js + ├── windows/win32/ui/shell/ + │ ├── ITaskbarList3.js + │ └── ITaskbarList3.d.ts └── unsafe/ - ├── Windows/Win32/System/Wmi/ + ├── windows/win32/system/wmi/ │ ├── IWbemServicesUnsafe.js │ └── IWbemServicesUnsafe.d.ts ├── index.js @@ -70,8 +71,12 @@ Rules: - the npm package root and `@microsoft/dynwinrt/com` remain unchanged. - a safe-complete interface does not need a duplicate unsafe companion unless a future explicit diagnostic feature requests one. -- unsafe module paths include every namespace segment. The class inside remains - the ergonomic short `Unsafe` name. +- safe and unsafe module paths use the same lowercase/kebab namespace mapping + as canonical WinRT JavaScript output. Class names preserve their metadata + spelling. +- generated imports are relative between canonical modules. The safe root + barrel omits ambiguous short exports while both deep modules remain + available. ## Class and method naming @@ -94,8 +99,8 @@ same class; the preferred design keeps them in separate companion classes. `Contoso.A.IFoo` and `Contoso.B.IFoo` therefore generate: ```text -com/unsafe/Contoso/A/IFooUnsafe.js -com/unsafe/Contoso/B/IFooUnsafe.js +com/unsafe/contoso/a/IFooUnsafe.js +com/unsafe/contoso/b/IFooUnsafe.js ``` If an unsafe class short name is globally unique in `support.json`, the unsafe @@ -450,10 +455,10 @@ Generation emits `generated/com/unsafe/support.json`: ```json { - "schemaVersion": 10, + "schemaVersion": 11, "interfaces": [ { - "schemaVersion": 10, + "schemaVersion": 11, "metadata": { "setSha256": "...", "files": [ @@ -557,6 +562,10 @@ dynwinrt-codegen generate ` --output generated ``` +Package import names remain unchanged. A relative `--import-name` is interpreted +from `generated/com/` and rebased for each canonical safe module, unsafe +companion, and shared unsafe runtime file. + Possible outcomes: | Result | Exit behavior | @@ -649,12 +658,18 @@ trailing dots/spaces, and Windows device names (`CON`, `PRN`, `AUX`, `NUL`, `CLOCK$`, `CONIN$`, `CONOUT$`, `COM1`-`COM9`, and `LPT1`-`LPT9`), including device names with extensions. -Retained schema-9 `modulePath` is never trusted. Codegen rederives it from the +Retained schema-11 `modulePath` is never trusted. Codegen rederives it from the validated qualified interface identity and exact `Unsafe` class name, requires an exact match, and then checks the case-insensitive path key. Case-only namespaces or type names therefore fail instead of aliasing on Windows. +Manifest v2 records canonical safe and unsafe paths. The first COM generation +against manifest v1 reprojects every retained root from the configured +metadata, migrates support schema 10 to 11, removes manifest-owned flat/Pascal +paths, prunes their empty directories, and publishes the complete canonical +tree in the same output transaction. + Before overwriting a staged path owned by any manifest root outside the current update set, codegen requires the retained and planned path identities to match, requires the staged file to exist, and byte-compares its contents. Shared @@ -670,8 +685,11 @@ remain allowed. ## Compatibility invariants -- Existing safe-complete generated output is byte-for-byte unchanged. -- Existing safe output paths and package exports are unchanged. +- Existing generated COM classes, declarations, and root barrel symbols retain + their public names; their deep module paths intentionally move to canonical + namespace directories. +- Manifest v1 output migrates atomically instead of retaining mixed flat and + canonical layouts. - Unsafe symbols never appear in a safe barrel or safe declaration file. - Existing WinRT generation is unchanged. - Existing Classic COM safe generation never changes a class into an unsafe @@ -745,7 +763,7 @@ Stage 2 is implemented: arguments; - parameter requirements come from the same per-target classifier analysis; - runtime-blocked methods remain omitted; -- support schema 9 records every parameter index/name, strategy type, exact +- support schema 11 records every parameter index/name, strategy type, exact reason, native direction/nullability, and known target pointee layouts; and - a raw pointer is never substituted for missing ownership. diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 12c89b3c..25a0596c 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -508,14 +508,15 @@ bindings/ ├── index.js ├── index.mjs ├── index.d.ts -├── Uri.js +├── windows/foundation/Uri.js ├── com/ │ ├── package.json │ ├── index.js │ ├── index.mjs │ ├── index.d.ts -│ ├── TaskbarList.js -│ └── ITaskbarList4.js +│ └── windows/win32/ui/shell/ +│ ├── TaskbarList.js +│ └── ITaskbarList4.js └── package.json ``` @@ -548,10 +549,11 @@ without adding COM exports to the WinRT root. Legacy COM-only output is relocated automatically when it is reused with the new generator. winappCli project aliases use `#winapp/bindings/com` for the COM barrel and -`#winapp/bindings/com/InterfaceName` for deep imports. Existing source that -used `#winapp/bindings/InterfaceName` for COM should switch to the `com/` -path. Standalone COM-only packages continue to expose their legacy -package-name deep imports. +canonical deep imports such as +`#winapp/bindings/com/windows/win32/ui/shell/ITaskbarList3`. Existing source +that used a flat COM deep import should switch to the canonical namespace path. +Standalone COM-only packages expose the same canonical path with and without +the explicit `com/` prefix. ### Explicit unsafe/raw opt-in diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 9fe9ae44..b87c8394 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -144,9 +144,9 @@ remain intact. The ordinary command has no unsafe opt-in flag. If complete safe projection fails but one or more methods are `raw_metadata_complete`, codegen writes an isolated namespace-qualified companion such as -`generated/com/unsafe/Windows/Win32/System/Wmi/IWbemServicesUnsafe.js` and -records every method in `support.json`. Safe-complete interfaces keep their -existing output unchanged. +`generated/com/unsafe/windows/win32/system/wmi/IWbemServicesUnsafe.js` and +records every method in `support.json`. Safe-complete interfaces use matching +canonical namespace directories under `generated/com/`. ```powershell npx dynwinrt-codegen generate ` @@ -194,8 +194,8 @@ The short barrel export is available only while `IWbemServicesUnsafe` is globally unique. If two namespaces contain `IFoo`, import their deep modules: ```js -import { IFooUnsafe as FooA } from "./generated/com/unsafe/Contoso/A/IFooUnsafe.js"; -import { IFooUnsafe as FooB } from "./generated/com/unsafe/Contoso/B/IFooUnsafe.js"; +import { IFooUnsafe as FooA } from "./generated/com/unsafe/contoso/a/IFooUnsafe.js"; +import { IFooUnsafe as FooB } from "./generated/com/unsafe/contoso/b/IFooUnsafe.js"; ``` The ambiguous `IFooUnsafe` short export is omitted until one root is removed. @@ -485,7 +485,7 @@ creates a safe `create()` method: ```js import { initializeCom } from "@microsoft/dynwinrt/com"; -import { IDataTransferManagerInterop } from "./generated/com/IDataTransferManagerInterop.js"; +import { IDataTransferManagerInterop } from "./generated/com/windows/win32/ui/shell/IDataTransferManagerInterop.js"; initializeCom(1); diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 02cfa836..88265d13 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -255,7 +255,7 @@ non-addressable identities block every method before companion selection. `MFASYNCRESULT` therefore produces no callable class. When an interface has no executable method, generation transactionally commits -a schema-9 report containing every blocked/manual method and exact reasons, +a schema-11 report containing every blocked/manual method and exact reasons, emits no class `.js`/`.d.ts`, and then exits nonzero. The metadata record is a sorted, deduplicated set of every loaded emission/reference/sibling winmd, with per-file hashes, a set hash, and an optional exact defining file; it contains no @@ -277,8 +277,9 @@ pre-publication rollback. No-follow residue cleanup removes only the links, never an external target. Case aliases, managed/staged/manifest ownership conflicts, transaction-residue names, and unsupported reparse tags fail closed. -Unsafe modules include their stable namespace path, for example -`com/unsafe/Windows/Win32/System/Wmi/IWbemServicesUnsafe.js`. The short class +Safe and unsafe modules use the canonical lowercase/kebab namespace layout, for +example `com/windows/win32/ui/shell/ITaskbarList3.js` and +`com/unsafe/windows/win32/system/wmi/IWbemServicesUnsafe.js`. The short class name remains `IWbemServicesUnsafe`. A short barrel export is emitted only when globally unique; ambiguous names are available only through deep modules, and incremental order does not affect the resulting barrel. @@ -304,7 +305,7 @@ generated `runtime.js`/`.d.ts` provides closed pointee, pointer-output, handle, interface-replacement, counted-buffer, owned-pointer, and raw-fallback strategies. Generated methods validate strategy types before dispatch, clean dirty HRESULT failure outputs according to the selected strategy, and report -exact per-parameter requirements in support schema 9. +exact per-parameter requirements in support schema 11. Strategy capabilities are unforgeable frozen objects backed by private WeakMaps. Private generated helpers perform prepare, writable-span overlap diff --git a/samples/js/electron-share-ui/src/main/index.ts b/samples/js/electron-share-ui/src/main/index.ts index 60125d61..e07b5d97 100644 --- a/samples/js/electron-share-ui/src/main/index.ts +++ b/samples/js/electron-share-ui/src/main/index.ts @@ -8,7 +8,7 @@ import { initializeCom } from '@microsoft/dynwinrt/com' import { roInitialize } from '@microsoft/dynwinrt' import { DataTransferManager } from '../../generated/windows/application-model/data-transfer/DataTransferManager.js' import { projectAs, releaseProjected } from '../../generated/lifetime.js' -import { IDataTransferManagerInterop } from '../../generated/com/IDataTransferManagerInterop.js' +import { IDataTransferManagerInterop } from '../../generated/com/windows/win32/ui/shell/IDataTransferManagerInterop.js' interface ShareContent { title: string diff --git a/samples/js/electron-smtc/media-controls.js b/samples/js/electron-smtc/media-controls.js index 2e433554..7460d711 100644 --- a/samples/js/electron-smtc/media-controls.js +++ b/samples/js/electron-smtc/media-controls.js @@ -15,7 +15,7 @@ const { } = require("./generated/index.js"); const { ISystemMediaTransportControlsInterop, -} = require("./generated/com/ISystemMediaTransportControlsInterop.js"); +} = require("./generated/com/windows/win32/system/win-rt/ISystemMediaTransportControlsInterop.js"); const { releaseProjected } = require("./generated/lifetime.js"); const TICKS_PER_SECOND = 10_000_000n; diff --git a/samples/js/windows-hello/main.js b/samples/js/windows-hello/main.js index 0b9414d6..69b24f77 100644 --- a/samples/js/windows-hello/main.js +++ b/samples/js/windows-hello/main.js @@ -15,7 +15,7 @@ const { } = require('./generated/index.js') const { IUserConsentVerifierInterop, -} = require('./generated/com/IUserConsentVerifierInterop.js') +} = require('./generated/com/windows/win32/system/win-rt/IUserConsentVerifierInterop.js') const resultType = DynWinRtType.enumType( 'Windows.Security.Credentials.UI.UserConsentVerificationResult', diff --git a/tests/e2e/runners/com/automation-dispatch.mjs b/tests/e2e/runners/com/automation-dispatch.mjs index 963da5e6..05ecc2cc 100644 --- a/tests/e2e/runners/com/automation-dispatch.mjs +++ b/tests/e2e/runners/com/automation-dispatch.mjs @@ -10,9 +10,9 @@ import { DynComUnsafe } from "../../../../bindings/js/dist/com-unsafe.js"; import { IDispatch, IID_IDispatch, -} from "../../e2e_generated/com/automation/com/IDispatch.js"; -import { IEnumVARIANT } from "../../e2e_generated/com/automation/com/IEnumVARIANT.js"; -import { IStream } from "../../e2e_generated/com/stream/com/IStream.js"; +} from "../../e2e_generated/com/automation/com/windows/win32/system/com/IDispatch.js"; +import { IEnumVARIANT } from "../../e2e_generated/com/automation/com/windows/win32/system/ole/IEnumVARIANT.js"; +import { IStream } from "../../e2e_generated/com/stream/com/windows/win32/system/com/IStream.js"; const CLSID_SHELL_APPLICATION = "13709620-c279-11ce-a49e-444553540000"; const DISPATCH_PROPERTYGET = 2; diff --git a/tests/e2e/runners/com/drop-target.mjs b/tests/e2e/runners/com/drop-target.mjs index c0350487..d8799056 100644 --- a/tests/e2e/runners/com/drop-target.mjs +++ b/tests/e2e/runners/com/drop-target.mjs @@ -7,8 +7,8 @@ import { DynCom } from "../../../../bindings/js/dist/com-unsafe.js"; import { createPOINTL, IDropTarget, -} from "../../e2e_generated/com/shell/com/IDropTarget.js"; -import { IFileDialogEvents } from "../../e2e_generated/com/shell/com/IFileDialogEvents.js"; +} from "../../e2e_generated/com/shell/com/windows/win32/system/ole/IDropTarget.js"; +import { IFileDialogEvents } from "../../e2e_generated/com/shell/com/windows/win32/ui/shell/IFileDialogEvents.js"; DynCom.initialize(0); diff --git a/tests/e2e/runners/com/dtm.mjs b/tests/e2e/runners/com/dtm.mjs index eb68d36b..f160db6e 100644 --- a/tests/e2e/runners/com/dtm.mjs +++ b/tests/e2e/runners/com/dtm.mjs @@ -7,7 +7,7 @@ // Run: .\tests\e2e\e2e_test.ps1 -SkipBuild -Lang com import { DynCom, DynComMethodSig, WinGuid } from '../../../../bindings/js/dist/com-unsafe.js'; -import { IDataTransferManagerInterop } from '../../e2e_generated/com/shell/com/IDataTransferManagerInterop.js'; +import { IDataTransferManagerInterop } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/IDataTransferManagerInterop.js'; import { acquireHwndBigInt } from './hwnd.mjs'; function fail(msg) { diff --git a/tests/e2e/runners/com/electron-hwnd-buffer.mjs b/tests/e2e/runners/com/electron-hwnd-buffer.mjs index 22a12242..933e9359 100644 --- a/tests/e2e/runners/com/electron-hwnd-buffer.mjs +++ b/tests/e2e/runners/com/electron-hwnd-buffer.mjs @@ -6,8 +6,8 @@ // contents as the handle value. Other Buffer-backed pointers retain address // semantics. -import { TaskbarList } from '../../e2e_generated/com/shell/com/TaskbarList.js'; -import { TBPFLAG } from '../../e2e_generated/com/shell/com/TBPFLAG.js'; +import { TaskbarList } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/TaskbarList.js'; +import { TBPFLAG } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/TBPFLAG.js'; import { acquireHwndBigInt } from './hwnd.mjs'; function fail(msg) { diff --git a/tests/e2e/runners/com/file-open-dialog.mjs b/tests/e2e/runners/com/file-open-dialog.mjs index c4266885..154cfa62 100644 --- a/tests/e2e/runners/com/file-open-dialog.mjs +++ b/tests/e2e/runners/com/file-open-dialog.mjs @@ -3,10 +3,10 @@ import assert from 'node:assert/strict'; import { DynCom } from '../../../../bindings/js/dist/com-unsafe.js'; -import { FDE_OVERWRITE_RESPONSE } from '../../e2e_generated/com/shell/com/FDE_OVERWRITE_RESPONSE.js'; -import { FDE_SHAREVIOLATION_RESPONSE } from '../../e2e_generated/com/shell/com/FDE_SHAREVIOLATION_RESPONSE.js'; -import { FileOpenDialog } from '../../e2e_generated/com/shell/com/FileOpenDialog.js'; -import { IFileDialogEvents } from '../../e2e_generated/com/shell/com/IFileDialogEvents.js'; +import { FDE_OVERWRITE_RESPONSE } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/FDE_OVERWRITE_RESPONSE.js'; +import { FDE_SHAREVIOLATION_RESPONSE } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/FDE_SHAREVIOLATION_RESPONSE.js'; +import { FileOpenDialog } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/FileOpenDialog.js'; +import { IFileDialogEvents } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/IFileDialogEvents.js'; DynCom.initialize(0); diff --git a/tests/e2e/runners/com/file-operation.mjs b/tests/e2e/runners/com/file-operation.mjs index 79d749d0..ac88f6f3 100644 --- a/tests/e2e/runners/com/file-operation.mjs +++ b/tests/e2e/runners/com/file-operation.mjs @@ -3,8 +3,8 @@ import assert from 'node:assert/strict'; import { DynCom } from '../../../../bindings/js/dist/com-unsafe.js'; -import { FILEOPERATION_FLAGS } from '../../e2e_generated/com/shell/com/FILEOPERATION_FLAGS.js'; -import { FileOperation } from '../../e2e_generated/com/shell/com/FileOperation.js'; +import { FILEOPERATION_FLAGS } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/FILEOPERATION_FLAGS.js'; +import { FileOperation } from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/FileOperation.js'; DynCom.initialize(1); diff --git a/tests/e2e/runners/com/module-commonjs.cjs b/tests/e2e/runners/com/module-commonjs.cjs index abd81c29..b2db9492 100644 --- a/tests/e2e/runners/com/module-commonjs.cjs +++ b/tests/e2e/runners/com/module-commonjs.cjs @@ -4,7 +4,7 @@ const assert = require('node:assert/strict'); const { DynCom } = require('../../../../bindings/js/dist/com-unsafe.js'); const barrel = require('../../e2e_generated/com/shell/com/index.js'); -const deep = require('../../e2e_generated/com/shell/com/TaskbarList.js'); +const deep = require('../../e2e_generated/com/shell/com/windows/win32/ui/shell/TaskbarList.js'); assert.equal(typeof barrel.TaskbarList, 'function'); assert.equal(typeof barrel.ITaskbarList3, 'function'); diff --git a/tests/e2e/runners/com/persist-file.mjs b/tests/e2e/runners/com/persist-file.mjs index 52476807..df67451d 100644 --- a/tests/e2e/runners/com/persist-file.mjs +++ b/tests/e2e/runners/com/persist-file.mjs @@ -6,7 +6,7 @@ import { DynCom } from '../../../../bindings/js/dist/com-unsafe.js'; import { IID_IPersistFile, IPersistFile, -} from '../../e2e_generated/com/shell/com/IPersistFile.js'; +} from '../../e2e_generated/com/shell/com/windows/win32/system/com/IPersistFile.js'; const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; DynCom.initialize(1); diff --git a/tests/e2e/runners/com/property-store.mjs b/tests/e2e/runners/com/property-store.mjs index a85a67b7..c2c4024c 100644 --- a/tests/e2e/runners/com/property-store.mjs +++ b/tests/e2e/runners/com/property-store.mjs @@ -10,7 +10,7 @@ import { createPROPERTYKEY, IID_IPropertyStore, IPropertyStore, -} from '../../e2e_generated/com/shell/com/IPropertyStore.js'; +} from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/properties-system/IPropertyStore.js'; const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; const VT_LPWSTR = 31; diff --git a/tests/e2e/runners/com/sequential-stream-buffer.mjs b/tests/e2e/runners/com/sequential-stream-buffer.mjs index b5742000..ac94dc01 100644 --- a/tests/e2e/runners/com/sequential-stream-buffer.mjs +++ b/tests/e2e/runners/com/sequential-stream-buffer.mjs @@ -6,11 +6,11 @@ import { DynCom, DynComMethodSig, WinGuid } from '../../../../bindings/js/dist/c import { IID_IStream, IStream, -} from '../../e2e_generated/com/stream/com/IStream.js'; +} from '../../e2e_generated/com/stream/com/windows/win32/system/com/IStream.js'; import { IID_IWICImagingFactory, IWICImagingFactory, -} from '../../e2e_generated/com/wic/com/IWICImagingFactory.js'; +} from '../../e2e_generated/com/wic/com/windows/win32/graphics/imaging/IWICImagingFactory.js'; const CLSID_WIC_IMAGING_FACTORY = 'cacaf262-9370-4615-a13b-9f5539da4c0a'; const IID_IWIC_STREAM = WinGuid.parse('135ff860-22b7-4ddf-b0f6-218f4f299a43'); diff --git a/tests/e2e/runners/com/shell-link-pod.mjs b/tests/e2e/runners/com/shell-link-pod.mjs index 9b1c510e..a1a983cf 100644 --- a/tests/e2e/runners/com/shell-link-pod.mjs +++ b/tests/e2e/runners/com/shell-link-pod.mjs @@ -7,7 +7,7 @@ import { createWIN32_FIND_DATAW, IID_IShellLinkW, IShellLinkW, -} from '../../e2e_generated/com/shell/com/IShellLinkW.js'; +} from '../../e2e_generated/com/shell/com/windows/win32/ui/shell/IShellLinkW.js'; const CLSID_SHELL_LINK = '00021401-0000-0000-c000-000000000046'; const SLGP_RAWPATH = 4; diff --git a/tests/e2e/runners/com/smtc.mjs b/tests/e2e/runners/com/smtc.mjs index 2155d44d..c2a78bea 100644 --- a/tests/e2e/runners/com/smtc.mjs +++ b/tests/e2e/runners/com/smtc.mjs @@ -17,7 +17,7 @@ import { DynCom, DynComMethodSig, WinGuid } from '../../../../bindings/js/dist/com-unsafe.js'; // Classic-COM interop wrapper: gets the SMTC pointer from an HWND. -import { ISystemMediaTransportControlsInterop } from '../../e2e_generated/com/interop/com/ISystemMediaTransportControlsInterop.js'; +import { ISystemMediaTransportControlsInterop } from '../../e2e_generated/com/interop/com/windows/win32/system/win-rt/ISystemMediaTransportControlsInterop.js'; import { acquireHwndBigInt } from './hwnd.mjs'; // Full WinRT natural projection generated by the unified E2E orchestrator. diff --git a/tests/e2e/runners/com/wic-imaging-factory.mjs b/tests/e2e/runners/com/wic-imaging-factory.mjs index 7e3677ec..2d34766c 100644 --- a/tests/e2e/runners/com/wic-imaging-factory.mjs +++ b/tests/e2e/runners/com/wic-imaging-factory.mjs @@ -6,7 +6,7 @@ import { DynCom } from '../../../../bindings/js/dist/com-unsafe.js'; import { IID_IWICImagingFactory, IWICImagingFactory, -} from '../../e2e_generated/com/wic/com/IWICImagingFactory.js'; +} from '../../e2e_generated/com/wic/com/windows/win32/graphics/imaging/IWICImagingFactory.js'; const CLSID_WIC_IMAGING_FACTORY = 'cacaf262-9370-4615-a13b-9f5539da4c0a'; diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 94415753..21b65aca 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -17,6 +17,9 @@ use super::capability::{ }; use super::javascript::naming::camel_case; +pub const LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 10; +pub const UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 11; + #[derive(Debug, Clone)] pub struct UnsafeGeneratedOutput { pub class_name: String, @@ -137,32 +140,13 @@ fn is_windows_reserved_name(segment: &str) -> bool { } fn unsafe_module_path(namespace: &str, class_name: &str) -> Result { - let valid_segment = |segment: &str| { - !segment.is_empty() - && !segment.as_bytes()[0].is_ascii_digit() - && segment - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') - }; - let mut segments = namespace.split('.').collect::>(); - if segments.is_empty() - || segments.iter().any(|segment| !valid_segment(segment)) - || !valid_segment(class_name) - { - return Err(format!( - "Unsafe COM namespace `{namespace}` cannot form a safe module path" - )); - } - segments.push(class_name); - let path = segments.join("/"); - windows_relative_path_key(&path)?; - Ok(path) + super::canonical_module_path(namespace, class_name) } pub fn validate_unsafe_supports(supports: &[UnsafeInterfaceSupport]) -> Result<(), String> { let mut identities = BTreeMap::::new(); for support in supports { - if support.schema_version != 10 { + if support.schema_version != UNSAFE_SUPPORT_SCHEMA_VERSION { return Err(format!( "Unsupported generated unsafe interface schema {} for {}", support.schema_version, support.interface_name @@ -429,7 +413,7 @@ pub fn generate_unsafe_interface_files_with_metadata( }); } let support = UnsafeInterfaceSupport { - schema_version: 10, + schema_version: UNSAFE_SUPPORT_SCHEMA_VERSION, metadata: UnsafeMetadataSupport { set_sha256: metadata.set_sha256.clone(), files: metadata.files.clone(), @@ -684,9 +668,12 @@ fn render_unsafe_class( support: &UnsafeInterfaceSupport, methods: &[(&RawComMethod, MethodCapability)], ) -> Result<(String, String), String> { - let raw_runtime_import = - serde_json::to_string(&super::javascript::render::com_raw_runtime_import_name()) - .map_err(|error| error.to_string())?; + let raw_runtime_import = serde_json::to_string( + &super::javascript::render::com_raw_runtime_import_name_for_depth( + super::canonical_namespace_depth(&meta.interface.namespace) + 1, + ), + ) + .map_err(|error| error.to_string())?; let mut layouts = LayoutRegistry::new(); let has_manual = methods .iter() @@ -785,7 +772,7 @@ fn render_unsafe_class( dts.push_str("export interface UnsafeMethodSupport { readonly name: string; readonly projectedName: string; readonly declaringIid: string; readonly absoluteSlot: number; readonly signatureFingerprint: string; readonly status: UnsafeMethodStatus; readonly reasons: readonly string[]; readonly strategyRequirements: readonly UnsafeStrategyRequirement[]; readonly exactInterfaceOutputs: readonly UnsafeExactInterfaceOutput[]; readonly exactInterfaceOutputCall: UnsafeExactInterfaceOutputCall | null; readonly targets: Readonly>; }\n"); dts.push_str("export interface UnsafeMetadataFile { readonly file: string; readonly package: string; readonly version: string; readonly sha256: string; }\n"); dts.push_str("export interface UnsafeMetadataSupport { readonly setSha256: string; readonly files: readonly UnsafeMetadataFile[]; readonly definingFile: UnsafeMetadataFile | null; }\n"); - dts.push_str("export interface UnsafeInterfaceSupport { readonly schemaVersion: 10; readonly metadata: UnsafeMetadataSupport; readonly interfaceName: string; readonly interfaceIid: string; readonly root: 'IUnknown' | 'IInspectable' | 'Unknown'; readonly baseIids: readonly string[]; readonly unsafeClass: string; readonly modulePath: string; readonly methods: readonly UnsafeMethodSupport[]; }\n\n"); + dts.push_str(&format!("export interface UnsafeInterfaceSupport {{ readonly schemaVersion: {UNSAFE_SUPPORT_SCHEMA_VERSION}; readonly metadata: UnsafeMetadataSupport; readonly interfaceName: string; readonly interfaceIid: string; readonly root: 'IUnknown' | 'IInspectable' | 'Unknown'; readonly baseIids: readonly string[]; readonly unsafeClass: string; readonly modulePath: string; readonly methods: readonly UnsafeMethodSupport[]; }}\n\n")); dts.push_str(&format!("export declare class {class_name} {{\n")); dts.push_str(" private constructor();\n"); dts.push_str(&format!( @@ -1857,11 +1844,11 @@ mod tests { crate::codegen::project::set_import_name(&previous); for content in [output.js.unwrap(), output.dts.unwrap()] { - assert!(content.contains("\"../dist/com-unsafe-raw.js\"")); + assert!(content.contains("\"../../../dist/com-unsafe-raw.js\"")); assert!(!content.contains("@microsoft/dynwinrt/com/unsafe/raw")); } for (_, content) in runtime { - assert!(content.contains("\"../dist/com-unsafe-raw.js\"")); + assert!(content.contains("\"../../dist/com-unsafe-raw.js\"")); assert!(!content.contains("@microsoft/dynwinrt/com/unsafe/raw")); } } @@ -2189,8 +2176,8 @@ mod tests { let second = build("Contoso.B", "20000000-0000-0000-c000-000000000046"); assert_eq!(first.class_name, "IFooUnsafe"); assert_eq!(second.class_name, "IFooUnsafe"); - assert_eq!(first.module_path, "Contoso/A/IFooUnsafe"); - assert_eq!(second.module_path, "Contoso/B/IFooUnsafe"); + assert_eq!(first.module_path, "contoso/a/IFooUnsafe"); + assert_eq!(second.module_path, "contoso/b/IFooUnsafe"); assert!(first.js.as_deref().unwrap().contains("class IFooUnsafe")); assert!( first @@ -2234,8 +2221,8 @@ mod tests { .find(|(path, _)| path == "unsafe/index.d.ts") .unwrap() .1; - assert!(cjs.contains("require('./Contoso/A/IFooUnsafe.js').IFooUnsafe")); - assert!(esm.contains("export { IFooUnsafe } from './Contoso/A/IFooUnsafe.js'")); + assert!(cjs.contains("require('./contoso/a/IFooUnsafe.js').IFooUnsafe")); + assert!(esm.contains("export { IFooUnsafe } from './contoso/a/IFooUnsafe.js'")); assert_eq!(esm, dts); } @@ -2627,7 +2614,7 @@ pub fn render_unsafe_package_files( ); let dts = esm.clone(); let support = serde_json::to_string_pretty(&serde_json::json!({ - "schemaVersion": 10, + "schemaVersion": UNSAFE_SUPPORT_SCHEMA_VERSION, "interfaces": supports, })) .map_err(|error| format!("Failed to serialize generated unsafe support: {error}"))?; @@ -2647,7 +2634,7 @@ pub fn render_unsafe_package_files( fn render_unsafe_runtime_files() -> Vec<(String, String)> { let raw_runtime_import = - serde_json::to_string(&super::javascript::render::com_raw_runtime_import_name()) + serde_json::to_string(&super::javascript::render::com_raw_runtime_import_name_for_depth(1)) .expect("serializing the runtime import name cannot fail"); let mut js = r#"// Generated by dynwinrt-codegen — do not edit 'use strict'; diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index 50822235..ac79bd07 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -23,6 +23,7 @@ use super::types::{ native_union_descriptor_js, native_union_layout_js, result_type_dts, safe_array_abi_type_js, scalar_type_dts, unwrap_callback_arg_js, unwrap_result_js, wrap_arg_js, }; +use crate::codegen::com::{canonical_module_file_path, relative_module_specifier}; use crate::codegen::winrt::javascript::render::javascript::commonjs::convert_to_cjs_with_eager; #[derive(Debug, Clone, PartialEq, Eq)] @@ -39,13 +40,21 @@ pub(in crate::codegen::com) fn render_com_interface( } fn render_projected_interface(meta: &ProjectedComInterface) -> ComGeneratedOutput { - let js = com_esm_to_cjs(&render_js(meta)); + let js = com_esm_to_cjs(&render_js(meta), &meta.namespace); let dts = render_dts(meta); let mut extra_files = BTreeMap::new(); for en in &meta.referenced_enums { let (enum_js, enum_dts) = render_enum_files(en); - extra_files.insert(format!("{}.js", en.name), enum_js); - extra_files.insert(format!("{}.d.ts", en.name), enum_dts); + extra_files.insert( + canonical_module_file_path(&en.namespace, &en.name, "js") + .expect("projected COM enum has a safe module identity"), + enum_js, + ); + extra_files.insert( + canonical_module_file_path(&en.namespace, &en.name, "d.ts") + .expect("projected COM enum has a safe module identity"), + enum_dts, + ); } ComGeneratedOutput { js, @@ -57,12 +66,25 @@ fn render_projected_interface(meta: &ProjectedComInterface) -> ComGeneratedOutpu pub(in crate::codegen::com) fn render_com_coclass( meta: &ProjectedComCoclass, ) -> ComGeneratedOutput { - let (js, dts) = render_coclass_files(&meta.name, &meta.clsid, &meta.primary_interface); + let (js, dts) = render_coclass_files( + &meta.namespace, + &meta.name, + &meta.clsid, + &meta.primary_interface, + ); let mut extra_files = BTreeMap::new(); for interface in &meta.associated_interfaces { let output = render_projected_interface(interface); - extra_files.insert(format!("{}.js", interface.name), output.js); - extra_files.insert(format!("{}.d.ts", interface.name), output.dts); + extra_files.insert( + canonical_module_file_path(&interface.namespace, &interface.name, "js") + .expect("projected COM interface has a safe module identity"), + output.js, + ); + extra_files.insert( + canonical_module_file_path(&interface.namespace, &interface.name, "d.ts") + .expect("projected COM interface has a safe module identity"), + output.dts, + ); for (name, content) in output.extra_files { if let Some(existing) = extra_files.insert(name.clone(), content.clone()) && existing != content @@ -79,19 +101,26 @@ pub(in crate::codegen::com) fn render_com_coclass( } fn render_coclass_files( + namespace: &str, name: &str, clsid: &str, primary_interface: &ProjectedComInterface, ) -> (String, String) { + let primary_import = relative_module_specifier( + namespace, + name, + &primary_interface.namespace, + &primary_interface.name, + ); let mut js = String::new(); js.push_str("// Generated by dynwinrt-codegen — do not edit\n"); js.push_str(&format!( "import {{ DynCom }} from '{}';\n", - com_runtime_import_name() + com_runtime_import_name_for_module(namespace) )); js.push_str(&format!( - "import {{ {}, IID_{} }} from './{}.js';\n\n", - primary_interface.name, primary_interface.name, primary_interface.name + "import {{ {}, IID_{} }} from '{}';\n\n", + primary_interface.name, primary_interface.name, primary_import )); js.push_str(&format!("export const CLSID_{name} = '{clsid}';\n\n")); js.push_str(&format!( @@ -117,8 +146,8 @@ fn render_coclass_files( let mut dts = String::new(); dts.push_str("// Generated by dynwinrt-codegen — do not edit\n"); dts.push_str(&format!( - "import {{ {} }} from './{}.js';\n\n", - primary_interface.name, primary_interface.name + "import {{ {} }} from '{}';\n\n", + primary_interface.name, primary_import )); dts.push_str(&format!("export declare const CLSID_{name}: string;\n\n")); dts.push_str(&format!( @@ -135,11 +164,12 @@ fn render_coclass_files( " supports(InterfaceClass: {descriptor}): boolean;\n" )); dts.push_str("}\n"); - (com_esm_to_cjs(&js), dts) + (com_esm_to_cjs(&js, namespace), dts) } -fn com_esm_to_cjs(esm: &str) -> String { - let runtime_sources = std::collections::HashSet::from([com_runtime_import_name()]); +fn com_esm_to_cjs(esm: &str, namespace: &str) -> String { + let runtime_sources = + std::collections::HashSet::from([com_runtime_import_name_for_module(namespace)]); convert_to_cjs_with_eager(esm, &runtime_sources) } @@ -153,19 +183,24 @@ fn render_js(meta: &ProjectedComInterface) -> String { }; out.push_str(&format!( "import {{ {runtime_imports} }} from '{}';\n", - com_runtime_import_name() + com_runtime_import_name_for_module(&meta.namespace) )); for en in &meta.referenced_enums { - out.push_str(&format!( - "import {{ {} }} from './{}.js';\n", - en.name, en.name - )); + let import = + relative_module_specifier(&meta.namespace, &meta.name, &en.namespace, &en.name); + out.push_str(&format!("import {{ {} }} from '{}';\n", en.name, import)); } for interface in collect_enumerator_interfaces(meta) { if interface.name != meta.name || interface.namespace != meta.namespace { + let import = relative_module_specifier( + &meta.namespace, + &meta.name, + &interface.namespace, + &interface.name, + ); out.push_str(&format!( - "import {{ {} }} from './{}.js';\n", - interface.name, interface.name + "import {{ {} }} from '{}';\n", + interface.name, import )); } } @@ -1812,26 +1847,31 @@ fn render_dts(meta: &ProjectedComInterface) -> String { }; out.push_str(&format!( "import type {{ {public_types} }} from '{}';\n", - com_public_import_name() + com_public_import_name_for_module(&meta.namespace) )); for en in &meta.referenced_enums { - out.push_str(&format!( - "import {{ {} }} from './{}.js';\n", - en.name, en.name - )); + let import = + relative_module_specifier(&meta.namespace, &meta.name, &en.namespace, &en.name); + out.push_str(&format!("import {{ {} }} from '{}';\n", en.name, import)); } for interface in collect_enumerator_interfaces(meta) { if interface.name != meta.name || interface.namespace != meta.namespace { + let import = relative_module_specifier( + &meta.namespace, + &meta.name, + &interface.namespace, + &interface.name, + ); out.push_str(&format!( - "import type {{ {} }} from './{}.js';\n", - interface.name, interface.name + "import type {{ {} }} from '{}';\n", + interface.name, import )); } } if meta.sink.is_some() || needs_bridge_import(meta) { out.push_str(&format!( "import type {{ DynWinRtValue }} from '{}';\n", - com_public_import_name() + com_public_import_name_for_module(&meta.namespace) )); } if !collect_native_pods(meta).is_empty() { @@ -1842,7 +1882,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { }; out.push_str(&format!( "import type {{ {types} }} from '{}';\n", - com_public_import_name() + com_public_import_name_for_module(&meta.namespace) )); } let runtime_types = collect_runtime_types(meta); @@ -1850,7 +1890,7 @@ fn render_dts(meta: &ProjectedComInterface) -> String { out.push_str(&format!( "import type {{ {} }} from '{}';\n", runtime_types.join(", "), - com_public_import_name() + com_public_import_name_for_module(&meta.namespace) )); } out.push('\n'); @@ -2543,6 +2583,13 @@ fn com_runtime_import_name() -> String { } } +fn com_runtime_import_name_for_module(namespace: &str) -> String { + super::super::rebase_runtime_import( + com_runtime_import_name(), + super::super::canonical_namespace_depth(namespace), + ) +} + fn com_public_import_name() -> String { let import_name = crate::codegen::project::get_import_name(); if import_name == "@microsoft/dynwinrt" { @@ -2558,6 +2605,13 @@ fn com_public_import_name() -> String { } } +fn com_public_import_name_for_module(namespace: &str) -> String { + super::super::rebase_runtime_import( + com_public_import_name(), + super::super::canonical_namespace_depth(namespace), + ) +} + pub(crate) fn com_raw_runtime_import_name() -> String { let import_name = crate::codegen::project::get_import_name(); match import_name.as_str() { @@ -2573,6 +2627,10 @@ pub(crate) fn com_raw_runtime_import_name() -> String { } } +pub(crate) fn com_raw_runtime_import_name_for_depth(parent_depth: usize) -> String { + super::super::rebase_runtime_import(com_raw_runtime_import_name(), parent_depth) +} + fn replace_exact_module_basename(value: &str, from: &str, to: &str) -> Option { let (prefix, basename) = value .rfind(|character| character == '/' || character == '\\') @@ -2605,7 +2663,7 @@ fn render_enum_files(en: &ProjectedComEnum) -> (String, String) { )); } dts.push_str("};\n"); - (com_esm_to_cjs(&js), dts) + (com_esm_to_cjs(&js, &en.namespace), dts) } fn render_enum_value(value: &ProjectedEnumValue, underlying: ComEnumUnderlying) -> String { diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index da9c794b..2187319a 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -1247,7 +1247,7 @@ fn coclass_renderer_uses_new_and_runtime_query_interface_views() { output .extra_files .iter() - .any(|(name, _)| name == "ITest4.js") + .any(|(name, _)| name == "tests/ITest4.js") ); } @@ -1473,10 +1473,26 @@ fn default_runtime_import_uses_com_subpath() { assert_eq!(com_runtime_import_name(), "../dist/com-unsafe.js"); assert_eq!(com_public_import_name(), "../dist/com.js"); assert_eq!(com_raw_runtime_import_name(), "../dist/com-unsafe-raw.js"); + assert_eq!( + com_runtime_import_name_for_module("Windows.Win32.System.Com"), + "../../../../../dist/com-unsafe.js" + ); + assert_eq!( + com_public_import_name_for_module("Windows.Win32.System.Com"), + "../../../../../dist/com.js" + ); + assert_eq!( + com_raw_runtime_import_name_for_depth(5), + "../../../../../../dist/com-unsafe-raw.js" + ); crate::codegen::project::set_import_name("./mycom.js"); assert_eq!(com_runtime_import_name(), "./mycom.js"); assert_eq!(com_public_import_name(), "./mycom.js"); assert_eq!(com_raw_runtime_import_name(), "./mycom.js"); + assert_eq!( + com_runtime_import_name_for_module("Windows.Win32.System.Com"), + "../../../../mycom.js" + ); crate::codegen::project::set_import_name(&previous); } @@ -2535,13 +2551,13 @@ fn return_only_enum_emits_import_and_sibling_files() { assert!( output .dts - .contains("import { THING_KIND } from './THING_KIND.js';") + .contains("import { THING_KIND } from '../../example/THING_KIND.js';") ); assert!( output .extra_files .iter() - .any(|(name, _)| name == "THING_KIND.d.ts") + .any(|(name, _)| name == "windows/win32/example/THING_KIND.d.ts") ); } diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index b91c4417..5a27fee1 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -14,12 +14,94 @@ mod typedef_inventory; use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; pub use generated_unsafe::{ - Stage2Coverage, UnsafeGeneratedOutput, UnsafeInterfaceSupport, generate_unsafe_interface_files, + LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, Stage2Coverage, UNSAFE_SUPPORT_SCHEMA_VERSION, + UnsafeGeneratedOutput, UnsafeInterfaceSupport, generate_unsafe_interface_files, generate_unsafe_interface_files_with_metadata, measure_stage2_coverage, render_unsafe_package_files, validate_unsafe_supports, windows_relative_path_key, }; pub use javascript::render::ComGeneratedOutput; +fn module_path(namespace: &str, name: &str) -> String { + let namespace = crate::codegen::javascript_layout::canonical_namespace_path(namespace); + if namespace.is_empty() { + name.to_string() + } else { + format!("{namespace}/{name}") + } +} + +pub fn canonical_module_path(namespace: &str, name: &str) -> Result { + let path = module_path(namespace, name); + windows_relative_path_key(&path)?; + if path.split('/').next() == Some("unsafe") { + return Err(format!( + "Classic-COM module `{namespace}.{name}` collides with the reserved unsafe package" + )); + } + Ok(path) +} + +pub fn canonical_module_file_path( + namespace: &str, + name: &str, + extension: &str, +) -> Result { + let module = canonical_module_path(namespace, name)?; + let path = format!("{module}.{extension}"); + windows_relative_path_key(&path)?; + Ok(path) +} + +pub(in crate::codegen::com) fn relative_module_specifier( + from_namespace: &str, + from_name: &str, + to_namespace: &str, + to_name: &str, +) -> String { + let from = module_path(from_namespace, from_name); + let to = module_path(to_namespace, to_name); + let mut from_segments = from.split('/').collect::>(); + from_segments.pop(); + let to_segments = to.split('/').collect::>(); + let common = from_segments + .iter() + .zip(&to_segments) + .take_while(|(left, right)| left == right) + .count(); + let mut segments = vec![".."; from_segments.len() - common]; + segments.extend(to_segments[common..].iter().copied()); + let path = segments.join("/"); + if path.starts_with("../") { + format!("{path}.js") + } else { + format!("./{path}.js") + } +} + +pub(in crate::codegen::com) fn canonical_namespace_depth(namespace: &str) -> usize { + let path = crate::codegen::javascript_layout::canonical_namespace_path(namespace); + if path.is_empty() { + 0 + } else { + path.split('/').count() + } +} + +pub(in crate::codegen::com) fn rebase_runtime_import( + import_name: String, + parent_depth: usize, +) -> String { + if !import_name.starts_with('.') || parent_depth == 0 { + return import_name; + } + let prefix = "../".repeat(parent_depth); + if let Some(import_name) = import_name.strip_prefix("./") { + format!("{prefix}{import_name}") + } else { + format!("{prefix}{import_name}") + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SafeCleanupAvailability { NoneRequired, @@ -78,8 +160,16 @@ pub fn generate_com_interface_files( .or_else(|_| project::project_com_reference_interface(&referenced))?; pending.extend(enumerator_interface_refs(&projected)); let rendered = javascript::render::render_com_interface(&projected); - insert_extra(&mut extras, format!("{name}.js"), rendered.js)?; - insert_extra(&mut extras, format!("{name}.d.ts"), rendered.dts)?; + insert_extra( + &mut extras, + canonical_module_file_path(&namespace, &name, "js")?, + rendered.js, + )?; + insert_extra( + &mut extras, + canonical_module_file_path(&namespace, &name, "d.ts")?, + rendered.dts, + )?; for (file, content) in rendered.extra_files { insert_extra(&mut extras, file, content)?; } diff --git a/tools/dynwinrt-codegen/src/codegen/javascript_layout.rs b/tools/dynwinrt-codegen/src/codegen/javascript_layout.rs new file mode 100644 index 00000000..c0e0c660 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/javascript_layout.rs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +pub(crate) fn canonical_namespace_path(namespace: &str) -> String { + namespace + .split('.') + .filter(|segment| !segment.is_empty()) + .map(|segment| { + let mut result = String::new(); + let chars = segment.chars().collect::>(); + for (index, character) in chars.iter().copied().enumerate() { + if !character.is_ascii_alphanumeric() { + if !result.ends_with('-') { + result.push('-'); + } + continue; + } + let previous_is_lower_or_digit = index > 0 + && (chars[index - 1].is_ascii_lowercase() || chars[index - 1].is_ascii_digit()); + let next_is_lower = chars + .get(index + 1) + .is_some_and(|next| next.is_ascii_lowercase()); + if character.is_ascii_uppercase() + && !result.is_empty() + && (previous_is_lower_or_digit || next_is_lower) + && !result.ends_with('-') + { + result.push('-'); + } + result.push(character.to_ascii_lowercase()); + } + result.trim_matches('-').to_string() + }) + .collect::>() + .join("/") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn namespaces_use_lowercase_kebab_segments() { + assert_eq!( + canonical_namespace_path("Microsoft.UI.DragDrop"), + "microsoft/ui/drag-drop" + ); + assert_eq!( + canonical_namespace_path("Windows.Win32.Graphics.Direct2D"), + "windows/win32/graphics/direct2-d" + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/mod.rs b/tools/dynwinrt-codegen/src/codegen/mod.rs index 23ec598c..402aa120 100644 --- a/tools/dynwinrt-codegen/src/codegen/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/mod.rs @@ -3,6 +3,7 @@ pub mod com; pub mod common; +mod javascript_layout; pub mod package; pub mod winrt; diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index e3ecc0cc..5b988087 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -261,8 +261,9 @@ mod tests { } #[test] - fn com_only_package_preserves_legacy_root_subpaths() { - let com = BTreeSet::from(["ITaskbarList3".to_string()]); + fn com_only_package_exposes_canonical_root_subpaths() { + let module = "windows/win32/ui/shell/ITaskbarList3"; + let com = BTreeSet::from([module.to_string()]); let winrt = BTreeSet::new(); let out = render_bindings_package_json(&BindingsPackageManifestInput { has_winrt_root: false, @@ -271,10 +272,10 @@ mod tests { }); assert!(out.contains("\"type\": \"commonjs\"")); - assert!(out.contains("\"./ITaskbarList3\"")); - assert!(out.contains("\"types\": \"./com/ITaskbarList3.d.ts\"")); - assert!(out.contains("\"import\": \"./com/ITaskbarList3.js\"")); - assert!(out.contains("\"require\": \"./com/ITaskbarList3.js\"")); + assert!(out.contains(&format!("\"./{module}\""))); + assert!(out.contains(&format!("\"types\": \"./com/{module}.d.ts\""))); + assert!(out.contains(&format!("\"import\": \"./com/{module}.js\""))); + assert!(out.contains(&format!("\"require\": \"./com/{module}.js\""))); assert!(out.contains("\"import\": \"./com/index.mjs\"")); assert!(out.contains("\"require\": \"./com/index.js\"")); assert!(out.contains("\"./com/*\"")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs index 69f4fa18..20ffc3fe 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs @@ -980,40 +980,6 @@ pub fn projected_parameterized_name( context.projected_parameterized_name(namespace, generic_name, piid, args) } -fn namespace_path(namespace: &str) -> String { - namespace - .split('.') - .filter(|segment| !segment.is_empty()) - .map(|segment| { - let mut result = String::new(); - let chars = segment.chars().collect::>(); - for (index, character) in chars.iter().copied().enumerate() { - if !character.is_ascii_alphanumeric() { - if !result.ends_with('-') { - result.push('-'); - } - continue; - } - let previous_is_lower_or_digit = index > 0 - && (chars[index - 1].is_ascii_lowercase() || chars[index - 1].is_ascii_digit()); - let next_is_lower = chars - .get(index + 1) - .is_some_and(|next| next.is_ascii_lowercase()); - if character.is_ascii_uppercase() - && !result.is_empty() - && (previous_is_lower_or_digit || next_is_lower) - && !result.ends_with('-') - { - result.push('-'); - } - result.push(character.to_ascii_lowercase()); - } - result.trim_matches('-').to_string() - }) - .collect::>() - .join("/") -} - fn qualified_projected_name(identity: &JavaScriptTypeIdentity) -> String { let qualifier = namespace_qualifier(&identity.namespace); let candidate = if qualifier.is_empty() { @@ -1150,7 +1116,8 @@ pub fn create_javascript_projection_context_with_records( let mut module_owners = HashMap::::new(); for identity in identities { let projected_name = projected_names[&identity].clone(); - let namespace = namespace_path(&identity.namespace); + let namespace = + crate::codegen::javascript_layout::canonical_namespace_path(&identity.namespace); let canonical_module = if namespace.is_empty() { identity.name.clone() } else { diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 5449b167..4a2ba5dd 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -176,6 +176,8 @@ enum Commands { } const COM_MANIFEST_FILE: &str = ".dynwinrt-com-manifest.json"; +const COM_MANIFEST_VERSION: u32 = 2; +const LEGACY_COM_MANIFEST_VERSION: u32 = 1; #[derive(Debug, Default, Deserialize, Serialize)] struct ComGenerationManifest { @@ -580,6 +582,17 @@ fn run() -> Result<(), String> { } } } + if lang == "js" + && !dry_run + && (!com_interfaces.is_empty() || !com_coclasses.is_empty()) + { + include_legacy_com_manifest_roots( + &output_dir.join("com"), + &winmd, + &mut com_interfaces, + &mut com_coclasses, + )?; + } // Fail loud: classic-COM codegen only emits `.js` + `.d.ts` // today. If the user asked for a different language @@ -638,9 +651,13 @@ fn run() -> Result<(), String> { let name = com_iface.interface.name.clone(); match com::generate_com_interface_files(com_iface, &winmd) { Ok(out) => { + let module = com::canonical_module_path( + &com_iface.interface.namespace, + &name, + )?; let mut files = vec![ - (format!("{name}.js"), out.js), - (format!("{name}.d.ts"), out.dts), + (format!("{module}.js"), out.js), + (format!("{module}.d.ts"), out.dts), ]; files.extend(out.extra_files); generated.push(PlannedComRoot { @@ -728,9 +745,10 @@ fn run() -> Result<(), String> { coclass.name, e ) })?; + let module = com::canonical_module_path(&coclass.namespace, &coclass.name)?; let mut files = vec![ - (format!("{}.js", coclass.name), out.js), - (format!("{}.d.ts", coclass.name), out.dts), + (format!("{module}.js"), out.js), + (format!("{module}.d.ts"), out.dts), ]; files.extend(out.extra_files); generated.push(PlannedComRoot { @@ -769,13 +787,13 @@ fn run() -> Result<(), String> { &root_files, &planned_files, )?; + apply_com_generation_manifest(&com_output_dir, manifest_update)?; for (file_name, content) in &planned_files { let path = com_output_dir.join(file_name); ensure_safe_generated_destination(output_dir, &path)?; fs::write(&path, content) .map_err(|e| format!("Failed to write {}: {}", file_name, e))?; } - apply_com_generation_manifest(&com_output_dir, manifest_update)?; if unsafe_package.remove_existing { remove_generated_unsafe_package_files(&com_output_dir)?; } @@ -3010,28 +3028,36 @@ fn prepare_com_generation_manifest( planned_files: &BTreeMap, ) -> Result { let path = com_output_dir.join(COM_MANIFEST_FILE); - let mut manifest = if path.exists() { - let content = fs::read_to_string(&path) - .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - serde_json::from_str::(&content).map_err(|error| { - format!( - "Invalid COM generation manifest {}: {error}", - path.display() - ) - })? - } else { - ComGenerationManifest { - version: 1, + let mut manifest = + read_com_generation_manifest(com_output_dir)?.unwrap_or_else(|| ComGenerationManifest { + version: COM_MANIFEST_VERSION, roots: BTreeMap::new(), - } - }; - if manifest.version != 1 { + }); + if !matches!( + manifest.version, + LEGACY_COM_MANIFEST_VERSION | COM_MANIFEST_VERSION + ) { return Err(format!( "Unsupported COM generation manifest version {} in {}", manifest.version, path.display() )); } + if manifest.version == LEGACY_COM_MANIFEST_VERSION { + let missing = manifest + .roots + .keys() + .filter(|root| !updated_roots.contains_key(*root)) + .cloned() + .collect::>(); + if !missing.is_empty() { + return Err(format!( + "Classic-COM canonical layout migration did not reproject retained roots: {}", + missing.join(", ") + )); + } + manifest.version = COM_MANIFEST_VERSION; + } let mut retained_paths = BTreeMap::)>::new(); for (root, files) in &manifest.roots { @@ -3127,10 +3153,7 @@ fn prepare_com_generation_manifest( let all_normal = components .iter() .all(|component| matches!(component, std::path::Component::Normal(_))); - let safe_location = all_normal - && (components.len() == 1 - || (components.len() >= 2 - && components[0].as_os_str() == std::ffi::OsStr::new("unsafe"))); + let safe_location = all_normal && !components.is_empty(); if !safe_location || !(stale.ends_with(".js") || stale.ends_with(".d.ts")) { return Err(format!( "Refusing unsafe path `{stale}` in COM generation manifest {}", @@ -3156,8 +3179,10 @@ fn apply_com_generation_manifest( if stale_path.exists() { fs::remove_file(&stale_path) .map_err(|error| format!("Failed to remove {}: {error}", stale_path.display()))?; + remove_empty_com_parents(stale_path.parent(), com_output_dir)?; } } + let content = serde_json::to_string_pretty(&update.manifest) .map_err(|error| format!("Failed to serialize COM generation manifest: {error}"))?; ensure_safe_generated_destination(output_dir, &path)?; @@ -3165,6 +3190,98 @@ fn apply_com_generation_manifest( .map_err(|error| format!("Failed to write {}: {error}", path.display())) } +fn read_com_generation_manifest( + com_output_dir: &Path, +) -> Result, String> { + let path = com_output_dir.join(COM_MANIFEST_FILE); + if !path.exists() { + return Ok(None); + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + serde_json::from_str::(&content) + .map(Some) + .map_err(|error| { + format!( + "Invalid COM generation manifest {}: {error}", + path.display() + ) + }) +} + +fn include_legacy_com_manifest_roots( + com_output_dir: &Path, + winmd: &str, + interfaces: &mut Vec, + coclasses: &mut Vec, +) -> Result<(), String> { + let Some(manifest) = read_com_generation_manifest(com_output_dir)? else { + return Ok(()); + }; + if manifest.version != LEGACY_COM_MANIFEST_VERSION { + return Ok(()); + } + let mut included = interfaces + .iter() + .map(|interface| { + format!( + "{}.{}", + interface.interface.namespace, interface.interface.name + ) + }) + .chain( + coclasses + .iter() + .map(|coclass| format!("{}.{}", coclass.namespace, coclass.name)), + ) + .collect::>(); + for root in manifest.roots.keys() { + if !included.insert(root.clone()) { + continue; + } + let (namespace, name) = root + .rsplit_once('.') + .ok_or_else(|| format!("Legacy COM manifest root is not qualified: `{root}`"))?; + if let Some(interface) = com_metadata::parse_com_interface(winmd, namespace, name) { + interfaces.push(interface); + continue; + } + if let Some(coclass) = com_metadata::parse_com_coclass(winmd, namespace, name)? { + coclasses.push(coclass); + continue; + } + return Err(format!( + "Legacy COM manifest root `{root}` could not be reprojected from the configured metadata" + )); + } + Ok(()) +} + +fn remove_empty_com_parents( + mut current: Option<&Path>, + com_output_dir: &Path, +) -> Result<(), String> { + while let Some(directory) = current { + if directory == com_output_dir { + break; + } + match fs::remove_dir(directory) { + Ok(()) => current = directory.parent(), + Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + current = directory.parent(); + } + Err(error) => { + return Err(format!( + "Failed to remove empty COM output directory {}: {error}", + directory.display() + )); + } + } + } + Ok(()) +} + const GENERATED_UNSAFE_PACKAGE_FILES: [&str; 7] = [ "unsafe/index.js", "unsafe/index.mjs", @@ -3209,10 +3326,15 @@ fn prepare_generated_unsafe_package( .map_err(|error| format!("Failed to read {}: {error}", support_path.display()))?; let existing: ExistingSupport = serde_json::from_str(&content) .map_err(|error| format!("Invalid {}: {error}", support_path.display()))?; - if existing.schema_version != 10 { + if !matches!( + existing.schema_version, + com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION | com::UNSAFE_SUPPORT_SCHEMA_VERSION + ) { return Err(format!( - "Unsupported generated unsafe support schema {} (expected 9)", - existing.schema_version + "Unsupported generated unsafe support schema {} (expected {} or {})", + existing.schema_version, + com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, + com::UNSAFE_SUPPORT_SCHEMA_VERSION )); } existing.interfaces @@ -3229,6 +3351,14 @@ fn prepare_generated_unsafe_package( .iter() .filter_map(|output| output.unsafe_support.clone()), ); + if supports + .iter() + .any(|support| support.schema_version != com::UNSAFE_SUPPORT_SCHEMA_VERSION) + { + return Err( + "Legacy generated unsafe support remained after canonical layout migration".into(), + ); + } supports.sort_by(|left, right| left.interface_name.cmp(&right.interface_name)); if supports.is_empty() { return Ok(GeneratedUnsafePackagePlan { @@ -3247,32 +3377,9 @@ fn write_com_js_barrel(com_output_dir: &Path) -> Result<(), String> { ensure_safe_generated_parent(output_dir, &com_output_dir.join(".dynwinrt-write-check"))?; let mut modules: BTreeMap> = BTreeMap::new(); let mut contents: BTreeMap = BTreeMap::new(); - let entries = fs::read_dir(com_output_dir).map_err(|error| { - format!( - "Failed to read COM output directory {}: {error}", - com_output_dir.display() - ) - })?; - for entry in entries.flatten() { - let path = entry.path(); - let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else { - continue; - }; - let Some(module) = file_name.strip_suffix(".js") else { - continue; - }; - if module == "index" { - continue; - } - let content = fs::read_to_string(&path) - .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - let exports = collect_com_cjs_exports(&content); - if !exports.is_empty() { - modules.insert(module.to_string(), exports); - contents.insert(module.to_string(), content); - } - } + collect_com_barrel_modules(com_output_dir, com_output_dir, &mut modules, &mut contents)?; deduplicate_com_barrel_exports(&mut modules, &contents)?; + modules.retain(|_, exports| !exports.is_empty()); let mut index = String::from("// Generated by dynwinrt-codegen - do not edit\n"); for (module, exports) in &modules { @@ -3307,23 +3414,92 @@ fn deduplicate_com_barrel_exports( modules: &mut BTreeMap>, contents: &BTreeMap, ) -> Result<(), String> { - let mut owners = BTreeMap::)>::new(); - for (module, exports) in modules.iter_mut() { + let mut owners = BTreeMap::)>>::new(); + for (module, exports) in modules.iter() { let content = &contents[module]; - let names = exports.iter().cloned().collect::>(); - for name in names { - let signature = native_pod_factory_signature(content, &name); - if let Some((owner, owner_signature)) = owners.get(&name) { - if signature.is_some() && signature.as_ref() == owner_signature.as_ref() { - exports.remove(&name); - } else { - return Err(format!( - "COM barrel export `{name}` is ambiguous between `{owner}.js` and `{module}.js`" - )); - } - } else { - owners.insert(name, (module.clone(), signature)); + for name in exports { + owners + .entry(name.clone()) + .or_default() + .push((module.clone(), native_pod_factory_signature(content, name))); + } + } + for (name, owners) in owners { + if owners.len() < 2 { + continue; + } + let shared_factory = owners[0].1.is_some() + && owners + .iter() + .all(|(_, signature)| signature == &owners[0].1); + for (index, (module, _)) in owners.into_iter().enumerate() { + if !shared_factory || index > 0 { + modules + .get_mut(&module) + .expect("barrel module exists") + .remove(&name); + } + } + } + Ok(()) +} + +fn collect_com_barrel_modules( + com_output_dir: &Path, + current: &Path, + modules: &mut BTreeMap>, + contents: &mut BTreeMap, +) -> Result<(), String> { + let mut entries = fs::read_dir(current) + .map_err(|error| { + format!( + "Failed to read COM output directory {}: {error}", + current.display() + ) + })? + .collect::, _>>() + .map_err(|error| { + format!( + "Failed to read COM output directory {}: {error}", + current.display() + ) + })?; + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + let path = entry.path(); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?; + if is_link_or_reparse_point(&metadata) { + continue; + } + if metadata.is_dir() { + if current == com_output_dir && entry.file_name() == std::ffi::OsStr::new("unsafe") { + continue; } + collect_com_barrel_modules(com_output_dir, &path, modules, contents)?; + continue; + } + let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if file_name == "index.js" || !file_name.ends_with(".js") { + continue; + } + let relative = path + .strip_prefix(com_output_dir) + .expect("recursive COM path remains under output root"); + let module = relative + .to_string_lossy() + .replace('\\', "/") + .strip_suffix(".js") + .expect("JavaScript suffix checked") + .to_string(); + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let exports = collect_com_cjs_exports(&content); + if !exports.is_empty() { + modules.insert(module.clone(), exports); + contents.insert(module, content); } } Ok(()) @@ -3400,7 +3576,10 @@ fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { return Ok(()); } - let modules = collect_com_index_modules(&index); + let modules = collect_com_index_modules(&index) + .into_iter() + .filter(|module| !module.starts_with("com/")) + .collect::>(); if modules.is_empty() { return Ok(()); } @@ -3442,7 +3621,7 @@ fn collect_com_index_modules(index: &str) -> BTreeSet { .filter_map(|line| { let (_, module) = line.split_once(" from './")?; let module = module.strip_suffix(".js';")?; - (!module.is_empty() && !module.contains(['/', '\\'])).then(|| module.to_string()) + (!module.is_empty() && !module.contains('\\')).then(|| module.to_string()) }) .collect() } @@ -3518,6 +3697,26 @@ fn write_bindings_manifest_with_plan( } fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { + if let Some(manifest) = read_com_generation_manifest(com_output_dir)? { + if !matches!( + manifest.version, + LEGACY_COM_MANIFEST_VERSION | COM_MANIFEST_VERSION + ) { + return Err(format!( + "Unsupported COM generation manifest version {} in {}", + manifest.version, + com_output_dir.join(COM_MANIFEST_FILE).display() + )); + } + return Ok(manifest + .roots + .values() + .flatten() + .filter(|path| !path.starts_with("unsafe/")) + .filter_map(|path| path.strip_suffix(".js")) + .map(str::to_string) + .collect()); + } let index_path = com_output_dir.join("index.d.ts"); if !index_path.is_file() { return Ok(BTreeSet::new()); @@ -6674,10 +6873,9 @@ mod tests { "ISecond".into(), "const _nativeLayout_RECT = 'different';\nexports.createRECT = createRECT;\n".into(), ); - assert!( - deduplicate_com_barrel_exports(&mut conflicting_modules, &conflicting_contents) - .is_err() - ); + deduplicate_com_barrel_exports(&mut conflicting_modules, &conflicting_contents).unwrap(); + assert!(!conflicting_modules["IFirst"].contains("createRECT")); + assert!(!conflicting_modules["ISecond"].contains("createRECT")); let union_descriptor = "const _nativeUnionLayout_VALUE = '{\"name\":\"Contoso.VALUE\"}';"; let mut union_modules = BTreeMap::from([ @@ -8787,7 +8985,10 @@ mod tests { fs::write(com_dir.join(shared), "same").unwrap(); let write_manifest = |roots: BTreeMap>| { - let manifest = ComGenerationManifest { version: 1, roots }; + let manifest = ComGenerationManifest { + version: COM_MANIFEST_VERSION, + roots, + }; fs::write( com_dir.join(COM_MANIFEST_FILE), format!("{}\n", serde_json::to_string_pretty(&manifest).unwrap()), @@ -8859,9 +9060,9 @@ mod tests { fn unsafe_support_sequential_orders_converge_and_stale_removal_restores_export() { fn support(namespace: &str) -> com::UnsafeInterfaceSupport { let interface_name = format!("{namespace}.IFoo"); - let module_path = format!("{}/IFooUnsafe", namespace.replace('.', "/")); + let module_path = com::canonical_module_path(namespace, "IFooUnsafe").unwrap(); serde_json::from_value(serde_json::json!({ - "schemaVersion": 10, + "schemaVersion": com::UNSAFE_SUPPORT_SCHEMA_VERSION, "metadata": { "setSha256": "00", "files": [], @@ -8961,7 +9162,7 @@ mod tests { .unwrap() .1 .as_str(); - assert!(restored_index.contains("require('./Contoso/A/IFooUnsafe.js').IFooUnsafe")); + assert!(restored_index.contains("require('./contoso/a/IFooUnsafe.js').IFooUnsafe")); apply(&forward, restored); let removed = diff --git a/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs b/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs index 7e90f36b..3f6a469b 100644 --- a/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/com_sink_tsc_check_test.rs @@ -67,7 +67,7 @@ fn generated_com_sink_dts_passes_tsc_no_emit() { let com_dir = tmp.join("com"); fs::write( com_dir.join("sink-usage.ts"), - r#"import { FileOpenDialog } from "./FileOpenDialog.js"; + r#"import { FileOpenDialog } from "./windows/win32/ui/shell/FileOpenDialog.js"; import { DROPEFFECT, FDE_OVERWRITE_RESPONSE, @@ -75,13 +75,13 @@ import { IFileDialogEvents, MODIFIERKEYS_FLAGS, } from "./index.js"; -import type { IFileDialogEventsImplementation } from "./IFileDialogEvents.js"; +import type { IFileDialogEventsImplementation } from "./windows/win32/ui/shell/IFileDialogEvents.js"; import { createPOINTL, IDropTarget, type IDropTargetImplementation, type POINTL, -} from "./IDropTarget.js"; +} from "./windows/win32/system/ole/IDropTarget.js"; const dialog = new FileOpenDialog(); const eventHandlers: IFileDialogEventsImplementation = { @@ -161,7 +161,7 @@ composed.release(); "skipLibCheck": false, "types": [] }, - "include": ["globals.d.ts", "com/*.d.ts", "com/*.ts"] + "include": ["globals.d.ts", "com/**/*.d.ts", "com/*.ts"] }"#, ) .expect("write COM sink tsconfig"); diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts index 5211ee2b..29d5e914 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.d.ts @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit import type { WinGuid } from '@microsoft/dynwinrt/com'; -import { SHOW_WINDOW_CMD } from './SHOW_WINDOW_CMD.js'; +import { SHOW_WINDOW_CMD } from '../windows-and-messaging/SHOW_WINDOW_CMD.js'; import type { DynWinRtValue } from '@microsoft/dynwinrt/com'; import type { DynComNativeStruct } from '@microsoft/dynwinrt/com'; diff --git a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js index 434c382d..acea0c00 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js +++ b/tools/dynwinrt-codegen/tests/snapshots/ishelllinkw/IShellLinkW.js @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit const { DynCom, DynComMethodSig, WinGuid } = require('@microsoft/dynwinrt/com/unsafe'); -const { SHOW_WINDOW_CMD } = require('./SHOW_WINDOW_CMD.js'); +const { SHOW_WINDOW_CMD } = require('../windows-and-messaging/SHOW_WINDOW_CMD.js'); const _nativeLayout_WIN32_FIND_DATAW = '{"name":"Windows.Win32.Storage.FileSystem.WIN32_FIND_DATAW","x86":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"x64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]},"arm64":{"size":592,"alignment":4,"fields":[{"name":"dwFileAttributes","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"ftCreationTime","offset":4,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastAccessTime","offset":12,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"ftLastWriteTime","offset":20,"count":1,"type":{"kind":"struct","name":"Windows.Win32.Foundation.FILETIME","layout":{"size":8,"alignment":4,"fields":[{"name":"dwLowDateTime","offset":0,"count":1,"type":{"kind":"u32"}},{"name":"dwHighDateTime","offset":4,"count":1,"type":{"kind":"u32"}}]}}},{"name":"nFileSizeHigh","offset":28,"count":1,"type":{"kind":"u32"}},{"name":"nFileSizeLow","offset":32,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved0","offset":36,"count":1,"type":{"kind":"u32"}},{"name":"dwReserved1","offset":40,"count":1,"type":{"kind":"u32"}},{"name":"cFileName","offset":44,"count":260,"type":{"kind":"u16"}},{"name":"cAlternateFileName","offset":564,"count":14,"type":{"kind":"u16"}}]}}'; function createWIN32_FIND_DATAW(bytes) { return DynCom.createNativeStruct(_nativeLayout_WIN32_FIND_DATAW, bytes); } diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index aa040a29..ae103987 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -12,6 +12,7 @@ //! Tests are skipped (with an `eprintln!` note) when the Win32 winmd is not //! present at the well-known path. +use std::collections::BTreeSet; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -1008,10 +1009,36 @@ fn run_codegen_command( ); } +fn generated_com_module( + output_dir: &Path, + namespace: &str, + name: &str, + extension: &str, +) -> PathBuf { + output_dir.join("com").join( + com::canonical_module_file_path(namespace, name, extension) + .expect("test metadata has a canonical COM module identity"), + ) +} + +fn generated_unsafe_module( + output_dir: &Path, + namespace: &str, + name: &str, + extension: &str, +) -> PathBuf { + output_dir.join("com").join("unsafe").join( + com::canonical_module_file_path(namespace, &format!("{name}Unsafe"), extension) + .expect("test metadata has a canonical unsafe COM module identity"), + ) +} + fn assert_mixed_package_shape(output_dir: &Path) { assert!(output_dir.join("windows/foundation/Uri.js").is_file()); assert!(!output_dir.join("Uri.js").exists()); - assert!(output_dir.join("com").join("ITaskbarList3.js").is_file()); + assert!( + generated_com_module(output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js").is_file() + ); assert!(output_dir.join("com").join("package.json").is_file()); let root_index = fs::read_to_string(output_dir.join("index.d.ts")).unwrap(); @@ -1222,8 +1249,9 @@ fn taskbarlist_coclass_generates_newable_class_and_interface_views() { "ITaskbarList3.js", "ITaskbarList4.js", ] { + let expected = format!("windows/win32/ui/shell/{interface}"); assert!( - out.extra_files.iter().any(|(name, _)| name == interface), + out.extra_files.iter().any(|(name, _)| name == &expected), "missing {interface}" ); } @@ -1418,7 +1446,9 @@ fn partial_generation_only_emits_target_interface() { ); // Should include TBPFLAG (a direct dep) - let has_tbpflag = file_names.iter().any(|n| n.starts_with("TBPFLAG")); + let has_tbpflag = file_names + .iter() + .any(|name| name.ends_with("/TBPFLAG.js") || name.ends_with("/TBPFLAG.d.ts")); assert!( has_tbpflag, "TBPFLAG (direct enum dep) must be included: {:?}", @@ -1819,7 +1849,14 @@ fn snapshot_itaskbarlist3() { generated.push(("TaskbarList.js".into(), out.js.clone())); generated.push(("TaskbarList.d.ts".into(), out.dts.clone())); for (name, content) in &out.extra_files { - generated.push((name.clone(), content.clone())); + generated.push(( + Path::new(name) + .file_name() + .expect("generated snapshot file has a basename") + .to_string_lossy() + .into_owned(), + content.clone(), + )); } let mut mismatches = Vec::new(); @@ -1927,8 +1964,9 @@ fn import_name_flag_is_honored_by_com_path() { // Custom import must appear on the runtime import line... assert!( - out.js.contains("require('../dist/com-unsafe.js')"), - "classic-COM .js must honor --import-name (expected `require('../dist/com-unsafe.js')`):\n{}", + out.js + .contains("require('../../../../../dist/com-unsafe.js')"), + "classic-COM .js must rebase --import-name from the canonical module:\n{}", out.js ); // ...and the hardcoded default must NOT be present in the generated body. @@ -1991,7 +2029,8 @@ fn import_name_flag_is_honored_by_interop_wrapper() { // The interop .js itself must honor the flag. assert!( - out.js.contains("require('../dist/com-unsafe.js')"), + out.js + .contains("require('../../../../../dist/com-unsafe.js')"), "interop .js must honor --import-name:\n{}", out.js ); @@ -2002,7 +2041,7 @@ fn import_name_flag_is_honored_by_interop_wrapper() { ); assert!( - out.dts.contains("from '../dist/com.js'"), + out.dts.contains("from '../../../../../dist/com.js'"), "interop .d.ts must honor --import-name:\n{}", out.dts ); @@ -2740,11 +2779,11 @@ fn standard_enumerator_next_projects_partial_arrays_and_exact_interface_ownershi && output .extra_files .iter() - .any(|(name, _)| name == "IConnectionPoint.js") + .any(|(name, _)| name == "windows/win32/system/com/IConnectionPoint.js") && output .extra_files .iter() - .any(|(name, _)| name == "IConnectionPoint.d.ts"), + .any(|(name, _)| name == "windows/win32/system/com/IConnectionPoint.d.ts"), "owned interface elements must use managed wrappers and emit their complete dependency:\n{}", output.js ); @@ -3042,7 +3081,7 @@ fn real_owning_counted_arrays_project_natural_inputs_and_outputs() { let wrapper = sink .extra_files .iter() - .find(|(name, _)| name == "IWbemClassObject.js") + .find(|(name, _)| name == "windows/win32/system/wmi/IWbemClassObject.js") .expect("nominal element wrapper dependency"); assert!( wrapper.1.contains("class IWbemClassObject"), @@ -4625,25 +4664,36 @@ fn com_only_generation_emits_an_importable_package_shape() { "COM-only compatibility output must include {name}" ); } - for name in [ - "index.js", - "index.mjs", - "index.d.ts", - "package.json", - "ITaskbarList3.js", - "ITaskbarList3.d.ts", - ] { + for name in ["index.js", "index.mjs", "index.d.ts", "package.json"] { assert!( output_dir.join("com").join(name).is_file(), "COM subpackage must include {name}" ); } + assert!( + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") + .is_file() + ); + assert!( + generated_com_module( + &output_dir, + "Windows.Win32.UI.Shell", + "ITaskbarList3", + "d.ts" + ) + .is_file() + ); assert!(!output_dir.join("ITaskbarList3.js").exists()); let index = fs::read_to_string(output_dir.join("index.js")).unwrap(); assert!(index.contains("ITaskbarList3") && index.contains("TBPFLAG")); - assert!(index.contains("__exportLazy('ITaskbarList3', './com/ITaskbarList3.js')")); + assert!(index.contains( + "__exportLazy('ITaskbarList3', './com/windows/win32/ui/shell/ITaskbarList3.js')" + )); let com_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); - assert!(com_index.contains("__exportLazy('ITaskbarList3', './ITaskbarList3.js')")); + assert!( + com_index + .contains("__exportLazy('ITaskbarList3', './windows/win32/ui/shell/ITaskbarList3.js')") + ); assert!( !index.contains("Unsafe") && !com_index.contains("Unsafe"), "safe-complete generation must not leak generated unsafe companions" @@ -4656,7 +4706,7 @@ fn com_only_generation_emits_an_importable_package_shape() { assert!(com_esm_index.contains("import * as __m")); let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!(package.contains("\"type\": \"commonjs\"")); - assert!(package.contains("\"./ITaskbarList3\"")); + assert!(package.contains("\"./windows/win32/ui/shell/ITaskbarList3\"")); assert!(package.contains("\"./com\"")); assert!(package.contains("\"./com/*\"")); assert!(package.contains("\"import\": \"./com/index.mjs\"")); @@ -4690,8 +4740,8 @@ fn com_only_generation_emits_an_importable_package_shape() { ); let incremental_package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!( - incremental_package.contains("\"./ITaskbarList3\"") - && incremental_package.contains("\"./IShellLinkW\""), + incremental_package.contains("\"./windows/win32/ui/shell/ITaskbarList3\"") + && incremental_package.contains("\"./windows/win32/ui/shell/IShellLinkW\""), "incremental generation must preserve earlier package subpaths:\n{incremental_package}" ); @@ -4812,10 +4862,10 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { ); let unsafe_dir = output_dir.join("com").join("unsafe"); - let class_module = "Windows/Win32/System/Wmi/IWbemServicesUnsafe"; + let class_module = "windows/win32/system/wmi/IWbemServicesUnsafe"; let retained = [ - "Windows/Win32/System/Wmi/IWbemServicesUnsafe.js", - "Windows/Win32/System/Wmi/IWbemServicesUnsafe.d.ts", + "windows/win32/system/wmi/IWbemServicesUnsafe.js", + "windows/win32/system/wmi/IWbemServicesUnsafe.d.ts", "index.js", "index.mjs", "index.d.ts", @@ -4858,7 +4908,7 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { let support: serde_json::Value = serde_json::from_str(&fs::read_to_string(unsafe_dir.join("support.json")).unwrap()) .unwrap(); - assert_eq!(support["schemaVersion"], 10); + assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); assert_eq!(support["interfaces"][0]["modulePath"], class_module); let methods = support["interfaces"][0]["methods"] .as_array() @@ -4963,37 +5013,37 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { ( "Windows.Win32.Media.Audio", "IAudioClient", - "Windows/Win32/Media/Audio/IAudioClientUnsafe", + "windows/win32/media/audio/IAudioClientUnsafe", "isFormatSupported(ShareMode: number, pFormat: UnsafePointee, ppClosestMatch: UnsafePointerOutput): readonly [number, T0]", ), ( "Windows.Win32.Graphics.Dxgi", "IDXGIObject", - "Windows/Win32/Graphics/Dxgi/IDXGIObjectUnsafe", + "windows/win32/graphics/dxgi/IDXGIObjectUnsafe", "setPrivateData(Name: DynComRawMemory | DynComRawPointer, DataSize: number, pData: UnsafePointee): void", ), ( "Windows.Win32.System.ClrHosting", "IHostMalloc", - "Windows/Win32/System/ClrHosting/IHostMallocUnsafe", + "windows/win32/system/clr-hosting/IHostMallocUnsafe", "alloc(cbSize: bigint, eCriticalLevel: number, ppMem: UnsafePointerOutput): T0", ), ( "Windows.Win32.Devices.Fax", "IStiDeviceControl", - "Windows/Win32/Devices/Fax/IStiDeviceControlUnsafe", + "windows/win32/devices/fax/IStiDeviceControlUnsafe", "getMyDeviceHandle(", ), ( "Windows.Win32.Devices.Fax", "IStillImageW", - "Windows/Win32/Devices/Fax/IStillImageWUnsafe", + "windows/win32/devices/fax/IStillImageWUnsafe", "getSTILaunchInformation(pwszDeviceName: UnsafeCountedBuffer, pdwEventCode: DynComRawMemory, pwszEventName: UnsafeCountedBuffer): void", ), ( "Windows.Win32.System.Wmi", "IWbemServices", - "Windows/Win32/System/Wmi/IWbemServicesUnsafe", + "windows/win32/system/wmi/IWbemServicesUnsafe", "openNamespace(strNamespace: string, options: { readonly lFlags: 0; readonly workingNamespace: DynComRawMemory; readonly result?: null }): DynComRawOwnedComPointer", ), ]; @@ -5026,7 +5076,7 @@ fn stage2_official_manual_interfaces_emit_exact_strategy_requirements() { &fs::read_to_string(output.join("com").join("unsafe").join("support.json")).unwrap(), ) .unwrap(); - assert_eq!(support["schemaVersion"], 10); + assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); let audio = support["interfaces"] .as_array() .unwrap() @@ -5245,15 +5295,15 @@ fn report_only_interface_persists_support_and_removes_only_owned_stale_files() { "{stderr}" ); let unsafe_dir = output_dir.join("com").join("unsafe"); - let mf_module = "Windows/Win32/Media/MediaFoundation/MFASYNCRESULTUnsafe"; - let iwbem_module = "Windows/Win32/System/Wmi/IWbemServicesUnsafe"; + let mf_module = "windows/win32/media/media-foundation/MFASYNCRESULTUnsafe"; + let iwbem_module = "windows/win32/system/wmi/IWbemServicesUnsafe"; assert!(unsafe_dir.join("support.json").is_file()); assert!(!unsafe_dir.join(format!("{mf_module}.js")).exists()); assert!(!unsafe_dir.join(format!("{mf_module}.d.ts")).exists()); let support: serde_json::Value = serde_json::from_str(&fs::read_to_string(unsafe_dir.join("support.json")).unwrap()) .unwrap(); - assert_eq!(support["schemaVersion"], 10); + assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); let mf = &support["interfaces"][0]; assert_eq!( mf["interfaceName"], @@ -5415,8 +5465,11 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { let com_dir = output_dir.join("com"); let unsafe_dir = com_dir.join("unsafe"); - let iwbem_module = "Windows/Win32/System/Wmi/IWbemServicesUnsafe.js"; - assert!(com_dir.join("ITaskbarList3.js").is_file()); + let iwbem_module = "windows/win32/system/wmi/IWbemServicesUnsafe.js"; + assert!( + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") + .is_file() + ); assert!(unsafe_dir.join(iwbem_module).is_file()); let safe_barrel = fs::read_to_string(com_dir.join("index.js")).unwrap(); let unsafe_barrel = fs::read_to_string(unsafe_dir.join("index.js")).unwrap(); @@ -5440,8 +5493,13 @@ fn concurrent_incremental_com_generation_preserves_all_roots_and_reports() { String::from_utf8_lossy(&safe_second.stderr) ); assert!(!report_only.status.success()); - assert!(com_dir.join("ITaskbarList3.js").is_file()); - assert!(com_dir.join("IShellLinkW.js").is_file()); + assert!( + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") + .is_file() + ); + assert!( + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "IShellLinkW", "js").is_file() + ); assert!(unsafe_dir.join(iwbem_module).is_file()); let support: serde_json::Value = serde_json::from_str(&fs::read_to_string(unsafe_dir.join("support.json")).unwrap()) @@ -5644,16 +5702,9 @@ fn concurrent_com_and_winrt_writers_share_one_output_lock_in_both_orders() { .join("Calendar.js") .exists() ); - assert!(output.join("com").join("IShellLinkW.js").is_file()); + assert!(generated_com_module(&output, "Windows.Win32.UI.Shell", "IShellLinkW", "js").is_file()); assert!( - output - .join("com") - .join("unsafe") - .join("Windows") - .join("Win32") - .join("System") - .join("Wmi") - .join("IWbemServicesUnsafe.js") + generated_unsafe_module(&output, "Windows.Win32.System.Wmi", "IWbemServices", "js") .is_file() ); let manifest: serde_json::Value = serde_json::from_str( @@ -5890,18 +5941,19 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { .join("Uri.js") .is_file() ); - assert!(output_dir.join("com").join("ITaskbarList3.js").is_file()); assert!( - output_dir - .join("com") - .join("unsafe") - .join("Windows") - .join("Win32") - .join("System") - .join("Wmi") - .join("IWbemServicesUnsafe.js") + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "ITaskbarList3", "js") .is_file() ); + assert!( + generated_unsafe_module( + &output_dir, + "Windows.Win32.System.Wmi", + "IWbemServices", + "js" + ) + .is_file() + ); let backup_prefix = format!( ".{}.dynwinrt-backup-", output_dir.file_name().unwrap().to_string_lossy() @@ -5929,12 +5981,196 @@ fn unified_output_transaction_rolls_back_first_and_incremental_failures() { !backup.exists(), "next locked generation did not remove backup residue" ); - assert!(output_dir.join("com").join("IShellLinkW.js").is_file()); + assert!( + generated_com_module(&output_dir, "Windows.Win32.UI.Shell", "IShellLinkW", "js").is_file() + ); fs::remove_dir_all(&output_dir).unwrap(); remove_com_generation_lock(&output_dir); } +#[test] +fn canonical_com_layout_separates_real_short_name_collisions() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let output = std::env::temp_dir().join(format!( + "dynwinrt-codegen-canonical-collision-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&output); + remove_com_generation_lock(&output); + + run_codegen_command( + &win32_winmd(), + None, + "Windows.Win32.Media.DirectShow.IResourceManager,Windows.Win32.System.DistributedTransactionCoordinator.IResourceManager", + &output, + ); + + for namespace in [ + "Windows.Win32.Media.DirectShow", + "Windows.Win32.System.DistributedTransactionCoordinator", + ] { + assert!(generated_com_module(&output, namespace, "IResourceManager", "js").is_file()); + assert!(generated_com_module(&output, namespace, "IResourceManager", "d.ts").is_file()); + } + let index = fs::read_to_string(output.join("com").join("index.js")).unwrap(); + assert!( + !index.contains("__exportLazy('IResourceManager'"), + "ambiguous short exports must be omitted from the root COM barrel:\n{index}" + ); + assert!( + !fs::read_to_string(output.join("com").join("index.d.ts")) + .unwrap() + .contains("export { }") + ); + let package = fs::read_to_string(output.join("package.json")).unwrap(); + assert!(package.contains("\"./windows/win32/media/direct-show/IResourceManager\"")); + assert!(package.contains( + "\"./windows/win32/system/distributed-transaction-coordinator/IResourceManager\"" + )); + + fs::remove_dir_all(&output).unwrap(); + remove_com_generation_lock(&output); +} + +#[test] +fn version_one_com_output_migrates_all_roots_to_canonical_layout() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let output = std::env::temp_dir().join(format!( + "dynwinrt-codegen-canonical-migration-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&output); + remove_com_generation_lock(&output); + let com_dir = output.join("com"); + let unsafe_dir = com_dir.join("unsafe"); + fs::create_dir_all(&unsafe_dir).unwrap(); + + let taskbar = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.UI.Shell", + "ITaskbarList3", + ) + .unwrap(); + let taskbar_output = com::generate_com_interface_files(&taskbar, &win32_winmd()).unwrap(); + let mut taskbar_files = BTreeSet::new(); + for (name, content) in std::iter::once(("ITaskbarList3.js".into(), taskbar_output.js)) + .chain(std::iter::once(( + "ITaskbarList3.d.ts".into(), + taskbar_output.dts, + ))) + .chain(taskbar_output.extra_files) + { + let basename = Path::new(&name) + .file_name() + .expect("legacy COM file has a basename") + .to_string_lossy() + .into_owned(); + fs::write(com_dir.join(&basename), content).unwrap(); + taskbar_files.insert(basename); + } + + let wbem = com_metadata::parse_com_interface( + &win32_winmd(), + "Windows.Win32.System.Wmi", + "IWbemServices", + ) + .unwrap(); + let mut wbem_output = com::generate_unsafe_interface_files(&wbem, &win32_winmd()).unwrap(); + let legacy_module = "Windows/Win32/System/Wmi/IWbemServicesUnsafe"; + let legacy_js = format!("{legacy_module}.js"); + let legacy_dts = format!("{legacy_module}.d.ts"); + for (relative, content) in [ + (legacy_js.clone(), wbem_output.js.take().unwrap()), + (legacy_dts.clone(), wbem_output.dts.take().unwrap()), + ] { + let path = unsafe_dir.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } + let mut legacy_support = serde_json::to_value(wbem_output.support).unwrap(); + legacy_support["schemaVersion"] = serde_json::json!(com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION); + legacy_support["modulePath"] = serde_json::json!(legacy_module); + fs::write( + unsafe_dir.join("support.json"), + format!( + "{}\n", + serde_json::to_string_pretty(&serde_json::json!({ + "schemaVersion": com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, + "interfaces": [legacy_support], + })) + .unwrap() + ), + ) + .unwrap(); + + let manifest = serde_json::json!({ + "version": 1, + "roots": { + "Windows.Win32.UI.Shell.ITaskbarList3": taskbar_files, + "Windows.Win32.System.Wmi.IWbemServices": [ + format!("unsafe/{legacy_js}"), + format!("unsafe/{legacy_dts}"), + "unsafe/runtime.js", + "unsafe/runtime.d.ts", + ], + }, + }); + fs::write( + com_dir.join(".dynwinrt-com-manifest.json"), + format!("{}\n", serde_json::to_string_pretty(&manifest).unwrap()), + ) + .unwrap(); + + run_codegen_command( + &win32_winmd(), + Some("Windows.Win32.UI.Shell"), + "IShellLinkW", + &output, + ); + + for (namespace, name) in [ + ("Windows.Win32.UI.Shell", "ITaskbarList3"), + ("Windows.Win32.UI.Shell", "IShellLinkW"), + ] { + assert!(generated_com_module(&output, namespace, name, "js").is_file()); + assert!(!com_dir.join(format!("{name}.js")).exists()); + } + assert!( + generated_unsafe_module(&output, "Windows.Win32.System.Wmi", "IWbemServices", "js") + .is_file() + ); + let manifest: serde_json::Value = serde_json::from_str( + &fs::read_to_string(com_dir.join(".dynwinrt-com-manifest.json")).unwrap(), + ) + .unwrap(); + assert_eq!(manifest["version"], 2); + assert_eq!(manifest["roots"].as_object().unwrap().len(), 3); + let support: serde_json::Value = + serde_json::from_str(&fs::read_to_string(unsafe_dir.join("support.json")).unwrap()) + .unwrap(); + assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); + assert_eq!( + support["interfaces"][0]["modulePath"], + "windows/win32/system/wmi/IWbemServicesUnsafe" + ); + let unsafe_roots = fs::read_dir(&unsafe_dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect::>(); + assert!(unsafe_roots.contains("windows")); + assert!(!unsafe_roots.contains("Windows")); + + fs::remove_dir_all(&output).unwrap(); + remove_com_generation_lock(&output); +} + #[test] fn mixed_generation_supports_one_command_and_both_incremental_orders() { if !win32_available() { @@ -6037,19 +6273,29 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { &legacy_com_first, ); let com_dir = legacy_com_first.join("com"); - let legacy_index = fs::read_to_string(com_dir.join("index.js")).unwrap(); - let legacy_dts = fs::read_to_string(com_dir.join("index.d.ts")).unwrap(); - for entry in fs::read_dir(&com_dir).unwrap() { - let entry = entry.unwrap(); - let name = entry.file_name(); - let name = name.to_string_lossy(); - if name != "index.js" - && name != "index.mjs" - && name != "index.d.ts" - && name != "package.json" - { - fs::copy(entry.path(), legacy_com_first.join(name.as_ref())).unwrap(); + let mut legacy_index = fs::read_to_string(com_dir.join("index.js")).unwrap(); + let mut legacy_dts = fs::read_to_string(com_dir.join("index.d.ts")).unwrap(); + let modules = legacy_dts + .lines() + .filter_map(|line| { + let (_, module) = line.split_once(" from './")?; + module.strip_suffix(".js';").map(str::to_string) + }) + .collect::>(); + for module in modules { + let basename = Path::new(&module) + .file_name() + .expect("canonical COM module has a basename") + .to_string_lossy(); + for suffix in [".js", ".d.ts"] { + fs::copy( + com_dir.join(format!("{module}{suffix}")), + legacy_com_first.join(format!("{basename}{suffix}")), + ) + .unwrap(); } + legacy_index = legacy_index.replace(&format!("./{module}.js"), &format!("./{basename}.js")); + legacy_dts = legacy_dts.replace(&format!("./{module}.js"), &format!("./{basename}.js")); } fs::write(legacy_com_first.join("index.js"), &legacy_index).unwrap(); fs::write(legacy_com_first.join("index.d.ts"), legacy_dts).unwrap(); @@ -6061,7 +6307,13 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { "Windows.Foundation.Uri,Windows.Graphics.DirectX.Direct3D11.IDirect3DSurface", &legacy_com_first, ); - assert_mixed_package_shape(&legacy_com_first); + assert!(legacy_com_first.join("windows/foundation/Uri.js").is_file()); + assert!( + legacy_com_first + .join("com") + .join("ITaskbarList3.js") + .is_file() + ); assert!(!legacy_com_first.join("ITaskbarList3.js").exists()); assert!(!legacy_com_first.join("TBPFLAG.js").exists()); From 9b0d8e04be1750463f6c6dded67f2336dcc03b3e Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 3 Sep 2026 21:04:09 +0800 Subject: [PATCH 2/3] Remove COM-only root compatibility entrypoint Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- README.md | 6 +- .../classic-com-generated-unsafe.md | 14 +- docs/architecture/classic-com-support.md | 11 +- .../src/codegen/com/generated_unsafe.rs | 1 - tools/dynwinrt-codegen/src/codegen/com/mod.rs | 8 +- tools/dynwinrt-codegen/src/codegen/package.rs | 47 +-- tools/dynwinrt-codegen/src/main.rs | 304 ++++-------------- .../dynwinrt-codegen/tests/win32_com_test.rs | 239 +++----------- 8 files changed, 148 insertions(+), 482 deletions(-) diff --git a/README.md b/README.md index 8a295945..b29d4ac1 100644 --- a/README.md +++ b/README.md @@ -161,8 +161,10 @@ Classic COM generation currently emits JavaScript and TypeScript only. It uses the separate `@microsoft/dynwinrt/com` public surface; generated wrappers call `@microsoft/dynwinrt/com/unsafe` internally after codegen validates the ABI. Generated COM modules use the same lowercase/kebab namespace layout as WinRT -under `com/`, while the COM barrel keeps globally unique short exports. The -`@microsoft/dynwinrt` package root remains WinRT-only. +under `com/`, while the COM barrel keeps globally unique short exports. +COM-only generated packages also require the explicit `com/` entrypoint; the +generated package root and `@microsoft/dynwinrt` runtime root remain +WinRT-only. - [Classic COM JavaScript usage guide](docs/guides/windows/classic-com-usage.md) - [Supported ABI, coverage, limitations, and ownership model](docs/architecture/classic-com-support.md) diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index b9e57254..8ef81577 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -664,11 +664,9 @@ name, requires an exact match, and then checks the case-insensitive path key. Case-only namespaces or type names therefore fail instead of aliasing on Windows. -Manifest v2 records canonical safe and unsafe paths. The first COM generation -against manifest v1 reprojects every retained root from the configured -metadata, migrates support schema 10 to 11, removes manifest-owned flat/Pascal -paths, prunes their empty directories, and publishes the complete canonical -tree in the same output transaction. +Manifest v2 records canonical safe and unsafe paths. Manifest or support schema +mismatches fail closed; version upgrades require deleting and regenerating the +complete bindings output rather than migrating files in place. Before overwriting a staged path owned by any manifest root outside the current update set, codegen requires the retained and planned path identities to match, @@ -688,8 +686,8 @@ remain allowed. - Existing generated COM classes, declarations, and root barrel symbols retain their public names; their deep module paths intentionally move to canonical namespace directories. -- Manifest v1 output migrates atomically instead of retaining mixed flat and - canonical layouts. +- Version-mismatched output is rejected instead of producing a mixed flat and + canonical layout. - Unsafe symbols never appear in a safe barrel or safe declaration file. - Existing WinRT generation is unchanged. - Existing Classic COM safe generation never changes a class into an unsafe @@ -700,7 +698,7 @@ remain allowed. - Concurrent processes targeting the same output serialize the complete incremental merge, including successful classes and report-only entries. - The entire output root is replaced transactionally. COM is never published - before root compatibility barrels and package metadata are ready. + before COM barrels and package metadata are ready. ## Validation diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 25a0596c..4f3b5ad6 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -471,7 +471,7 @@ not be described as solving every problem in the map above. | Explicit COM initialization | Activation no longer silently chooses MTA; callers select STA or MTA with `initializeCom()`. Generated implementation files use the isolated unsafe runtime internally. | | Dynamic JavaScript COM implementations | Any `IUnknown`-rooted interface whose complete contiguous vtable maps to the validated callback subset receives `static implement()` and `static implementation()`. Static fast-path thunks cover common signatures; cached libffi closures cover arbitrary supported parameter counts, scalar widths, POD layouts, outputs, and native return conventions using the platform COM calling convention. Objects support derived/base IID aliases, multiple interface views, canonical IUnknown identity, shared atomic AddRef/Release, synchronous owner-thread JS dispatch, required Out initialization/validation, allocator-correct transfer, and panic/exception containment. Count/capacity values are read according to their In/InOut ABI direction, fixed outputs without an actual-length slot require exact size, and typed interface outputs are queried to the declared IID. QI references, BSTR/HSTRING values, and CoTaskMem buffers remain RAII-owned until every output is prepared; only then are all native output slots committed, so preparation failure leaves owned outputs null and releases every temporary owner. Wrong-thread HRESULT methods return `RPC_E_WRONG_THREAD`; direct returns are zeroed and void methods do nothing because those native ABIs have no error channel. `IFileDialogEvents` is live-tested with `Advise`/`Unadvise`; `IDropTarget` exercises libffi, POD/InOut, generated multi-interface composition, and QueryInterface. | | Fail-closed generation | Unknown/unsafe layouts, untagged/by-value/output unions, bitfields, flexible arrays, nested owned fields, unsupported VARTYPE/BYREF/SAFEARRAY/PROPVARIANT combinations, unsupported arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | -| Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. Mixed and incremental generation preserve the WinRT-only root barrel; COM-only output retains its legacy root entrypoint. | +| Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. The generated package root is always WinRT-only; COM-only output deliberately has no root entrypoint. | | Explicit vtable registration | Every generated method is registered with `.addMethodAt(vtableIndex, name, signature)`, keyed by its actual metadata-derived vtable slot. Methods are never deduplicated by name, so same-name overloads at different slots both register correctly. | | Same-name overload projection | Overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) are grouped once during projection (not by renderer heuristics). A single public JS method dispatches to a private per-slot implementation using only a validated, mutually-distinguishable arity/shape key (`typeof`-based: boolean/number/bigint/string/object); ambiguous groups fail generation closed with a diagnostic naming the interface, method, and reason. The `.d.ts` emits one TypeScript overload signature per branch, contiguously. | | Lifecycle ergonomics | Generated interface wrappers declare a protected constructor (`protected constructor(obj: unknown);`) so only generated coclasses can subclass them. Coclasses expose a public zero-argument constructor, and every wrapper provides an idempotent `release()` that delegates to the managed native value. Factory-activated interop wrappers retain `static create()` with JSDoc reminding callers to initialize COM first. | @@ -545,15 +545,16 @@ taskbar.release(); Separate WinRT and COM invocations may target the same output directory in either order. The generated package manifest is rebuilt from both domains -without adding COM exports to the WinRT root. Legacy COM-only output is -relocated automatically when it is reused with the new generator. +without adding COM exports to the WinRT root. Generated layout/schema version +changes require deleting and regenerating the complete bindings directory; +in-place cross-version migration is intentionally unsupported. winappCli project aliases use `#winapp/bindings/com` for the COM barrel and canonical deep imports such as `#winapp/bindings/com/windows/win32/ui/shell/ITaskbarList3`. Existing source that used a flat COM deep import should switch to the canonical namespace path. -Standalone COM-only packages expose the same canonical path with and without -the explicit `com/` prefix. +Standalone COM-only packages also require the explicit `com/` prefix; package +root imports do not expose COM symbols. ### Explicit unsafe/raw opt-in diff --git a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs index 21b65aca..15964194 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/generated_unsafe.rs @@ -17,7 +17,6 @@ use super::capability::{ }; use super::javascript::naming::camel_case; -pub const LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 10; pub const UNSAFE_SUPPORT_SCHEMA_VERSION: u32 = 11; #[derive(Debug, Clone)] diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index 5a27fee1..3db8491b 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -14,10 +14,10 @@ mod typedef_inventory; use crate::com_metadata::{ComCoclassMeta, ComInterfaceMeta}; pub use generated_unsafe::{ - LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, Stage2Coverage, UNSAFE_SUPPORT_SCHEMA_VERSION, - UnsafeGeneratedOutput, UnsafeInterfaceSupport, generate_unsafe_interface_files, - generate_unsafe_interface_files_with_metadata, measure_stage2_coverage, - render_unsafe_package_files, validate_unsafe_supports, windows_relative_path_key, + Stage2Coverage, UNSAFE_SUPPORT_SCHEMA_VERSION, UnsafeGeneratedOutput, UnsafeInterfaceSupport, + generate_unsafe_interface_files, generate_unsafe_interface_files_with_metadata, + measure_stage2_coverage, render_unsafe_package_files, validate_unsafe_supports, + windows_relative_path_key, }; pub use javascript::render::ComGeneratedOutput; diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index 5b988087..9e167154 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -38,7 +38,7 @@ pub fn render_bindings_package_json(input: &BindingsPackageManifestInput<'_>) -> if input.has_winrt_root { render_winrt_package(input) } else { - render_com_only_package(input.com_subpath_names) + render_com_only_package() } } @@ -123,52 +123,33 @@ fn render_winrt_package(input: &BindingsPackageManifestInput<'_>) -> String { out.push_str(" }"); } - append_com_exports(&mut out, input.com_subpath_names); + append_com_exports(&mut out, !input.com_subpath_names.is_empty(), true); out.push_str("\n }\n"); out.push_str("}\n"); out } -fn render_com_only_package(com_subpath_names: &BTreeSet) -> String { +fn render_com_only_package() -> String { let mut out = String::new(); out.push_str("{\n"); out.push_str(" \"name\": \"@winapp/bindings\",\n"); out.push_str(" \"type\": \"commonjs\",\n"); out.push_str(" \"sideEffects\": false,\n"); - out.push_str(" \"main\": \"./index.js\",\n"); - out.push_str(" \"types\": \"./index.d.ts\",\n"); out.push_str(" \"exports\": {\n"); - out.push_str(" \".\": {\n"); - out.push_str(" \"types\": \"./com/index.d.ts\",\n"); - out.push_str(" \"import\": \"./com/index.mjs\",\n"); - out.push_str(" \"require\": \"./com/index.js\",\n"); - out.push_str(" \"default\": \"./com/index.js\"\n"); - out.push_str(" }"); - - // Preserve the original COM-only deep-import paths while storing all COM - // implementation files under the domain-specific `com/` directory. - for name in com_subpath_names { - out.push_str(",\n"); - out.push_str(&format!(" \"./{}\": {{\n", name)); - out.push_str(&format!(" \"types\": \"./com/{}.d.ts\",\n", name)); - out.push_str(&format!(" \"import\": \"./com/{}.js\",\n", name)); - out.push_str(&format!(" \"require\": \"./com/{}.js\",\n", name)); - out.push_str(&format!(" \"default\": \"./com/{}.js\"\n", name)); - out.push_str(" }"); - } - - append_com_exports(&mut out, com_subpath_names); + append_com_exports(&mut out, true, false); out.push_str("\n }\n"); out.push_str("}\n"); out } -fn append_com_exports(out: &mut String, com_subpath_names: &BTreeSet) { - if com_subpath_names.is_empty() { +fn append_com_exports(out: &mut String, include_com: bool, has_previous: bool) { + if !include_com { return; } - out.push_str(",\n"); + if has_previous { + out.push_str(",\n"); + } out.push_str(" \"./com\": {\n"); out.push_str(" \"types\": \"./com/index.d.ts\",\n"); out.push_str(" \"import\": \"./com/index.mjs\",\n"); @@ -261,7 +242,7 @@ mod tests { } #[test] - fn com_only_package_exposes_canonical_root_subpaths() { + fn com_only_package_exposes_only_explicit_com_subpaths() { let module = "windows/win32/ui/shell/ITaskbarList3"; let com = BTreeSet::from([module.to_string()]); let winrt = BTreeSet::new(); @@ -272,10 +253,10 @@ mod tests { }); assert!(out.contains("\"type\": \"commonjs\"")); - assert!(out.contains(&format!("\"./{module}\""))); - assert!(out.contains(&format!("\"types\": \"./com/{module}.d.ts\""))); - assert!(out.contains(&format!("\"import\": \"./com/{module}.js\""))); - assert!(out.contains(&format!("\"require\": \"./com/{module}.js\""))); + assert!(!out.contains("\"main\"")); + assert!(!out.contains("\n \"types\":")); + assert!(!out.contains("\".\":")); + assert!(!out.contains(&format!("\"./{module}\""))); assert!(out.contains("\"import\": \"./com/index.mjs\"")); assert!(out.contains("\"require\": \"./com/index.js\"")); assert!(out.contains("\"./com/*\"")); diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 4a2ba5dd..4b1c34fd 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -177,7 +177,6 @@ enum Commands { const COM_MANIFEST_FILE: &str = ".dynwinrt-com-manifest.json"; const COM_MANIFEST_VERSION: u32 = 2; -const LEGACY_COM_MANIFEST_VERSION: u32 = 1; #[derive(Debug, Default, Deserialize, Serialize)] struct ComGenerationManifest { @@ -513,9 +512,6 @@ fn run() -> Result<(), String> { fs::create_dir_all(output_dir).map_err(|e| { format!("Failed to create output directory '{}': {}", output, e) })?; - if lang == "js" { - migrate_legacy_com_only_package(output_dir)?; - } } if lang == "py" && !dry_run && !pyi && class_name.is_some() { remove_all_generated_python_stubs(output_dir)?; @@ -582,18 +578,6 @@ fn run() -> Result<(), String> { } } } - if lang == "js" - && !dry_run - && (!com_interfaces.is_empty() || !com_coclasses.is_empty()) - { - include_legacy_com_manifest_roots( - &output_dir.join("com"), - &winmd, - &mut com_interfaces, - &mut com_coclasses, - )?; - } - // Fail loud: classic-COM codegen only emits `.js` + `.d.ts` // today. If the user asked for a different language // (e.g. `--lang py`) but any of the requested `--class-name` @@ -2323,8 +2307,6 @@ fn load_effective_generation_plan( index_path.display() ) })?; - // A COM-only package temporarily uses the root barrel as a - // compatibility forwarder. WinRT generation replaces that barrel; // COM subpaths are planned independently from the `com/` manifest. if module.starts_with("com/") && !plan.modules.contains_key(&module) { continue; @@ -3028,36 +3010,25 @@ fn prepare_com_generation_manifest( planned_files: &BTreeMap, ) -> Result { let path = com_output_dir.join(COM_MANIFEST_FILE); - let mut manifest = - read_com_generation_manifest(com_output_dir)?.unwrap_or_else(|| ComGenerationManifest { - version: COM_MANIFEST_VERSION, - roots: BTreeMap::new(), - }); - if !matches!( - manifest.version, - LEGACY_COM_MANIFEST_VERSION | COM_MANIFEST_VERSION - ) { + let existing_manifest = read_com_generation_manifest(com_output_dir)?; + if existing_manifest.is_none() && com_output_dir.join("index.d.ts").is_file() { return Err(format!( - "Unsupported COM generation manifest version {} in {}", + "Existing COM bindings in '{}' have no version {} generation manifest; delete and regenerate the complete bindings directory", + com_output_dir.display(), + COM_MANIFEST_VERSION + )); + } + let mut manifest = existing_manifest.unwrap_or_else(|| ComGenerationManifest { + version: COM_MANIFEST_VERSION, + roots: BTreeMap::new(), + }); + if manifest.version != COM_MANIFEST_VERSION { + return Err(format!( + "Unsupported COM generation manifest version {} in {}; delete and regenerate the complete bindings directory", manifest.version, path.display() )); } - if manifest.version == LEGACY_COM_MANIFEST_VERSION { - let missing = manifest - .roots - .keys() - .filter(|root| !updated_roots.contains_key(*root)) - .cloned() - .collect::>(); - if !missing.is_empty() { - return Err(format!( - "Classic-COM canonical layout migration did not reproject retained roots: {}", - missing.join(", ") - )); - } - manifest.version = COM_MANIFEST_VERSION; - } let mut retained_paths = BTreeMap::)>::new(); for (root, files) in &manifest.roots { @@ -3209,54 +3180,6 @@ fn read_com_generation_manifest( }) } -fn include_legacy_com_manifest_roots( - com_output_dir: &Path, - winmd: &str, - interfaces: &mut Vec, - coclasses: &mut Vec, -) -> Result<(), String> { - let Some(manifest) = read_com_generation_manifest(com_output_dir)? else { - return Ok(()); - }; - if manifest.version != LEGACY_COM_MANIFEST_VERSION { - return Ok(()); - } - let mut included = interfaces - .iter() - .map(|interface| { - format!( - "{}.{}", - interface.interface.namespace, interface.interface.name - ) - }) - .chain( - coclasses - .iter() - .map(|coclass| format!("{}.{}", coclass.namespace, coclass.name)), - ) - .collect::>(); - for root in manifest.roots.keys() { - if !included.insert(root.clone()) { - continue; - } - let (namespace, name) = root - .rsplit_once('.') - .ok_or_else(|| format!("Legacy COM manifest root is not qualified: `{root}`"))?; - if let Some(interface) = com_metadata::parse_com_interface(winmd, namespace, name) { - interfaces.push(interface); - continue; - } - if let Some(coclass) = com_metadata::parse_com_coclass(winmd, namespace, name)? { - coclasses.push(coclass); - continue; - } - return Err(format!( - "Legacy COM manifest root `{root}` could not be reprojected from the configured metadata" - )); - } - Ok(()) -} - fn remove_empty_com_parents( mut current: Option<&Path>, com_output_dir: &Path, @@ -3326,14 +3249,10 @@ fn prepare_generated_unsafe_package( .map_err(|error| format!("Failed to read {}: {error}", support_path.display()))?; let existing: ExistingSupport = serde_json::from_str(&content) .map_err(|error| format!("Invalid {}: {error}", support_path.display()))?; - if !matches!( - existing.schema_version, - com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION | com::UNSAFE_SUPPORT_SCHEMA_VERSION - ) { + if existing.schema_version != com::UNSAFE_SUPPORT_SCHEMA_VERSION { return Err(format!( - "Unsupported generated unsafe support schema {} (expected {} or {})", + "Unsupported generated unsafe support schema {} (expected {}); delete and regenerate the complete bindings directory", existing.schema_version, - com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, com::UNSAFE_SUPPORT_SCHEMA_VERSION )); } @@ -3351,14 +3270,6 @@ fn prepare_generated_unsafe_package( .iter() .filter_map(|output| output.unsafe_support.clone()), ); - if supports - .iter() - .any(|support| support.schema_version != com::UNSAFE_SUPPORT_SCHEMA_VERSION) - { - return Err( - "Legacy generated unsafe support remained after canonical layout migration".into(), - ); - } supports.sort_by(|left, right| left.interface_name.cmp(&right.interface_name)); if supports.is_empty() { return Ok(GeneratedUnsafePackagePlan { @@ -3525,96 +3436,9 @@ fn native_pod_factory_signature(content: &str, export_name: &str) -> Option Result<(), String> { - if !has_winrt_root(output_dir) { - write_com_root_compatibility_barrels(output_dir)?; - } write_bindings_manifest(output_dir) } -fn write_com_root_compatibility_barrels(output_dir: &Path) -> Result<(), String> { - let com_dir = output_dir.join("com"); - let com_js_path = com_dir.join("index.js"); - let com_dts_path = com_dir.join("index.d.ts"); - ensure_safe_generated_destination(output_dir, &com_js_path)?; - ensure_safe_generated_destination(output_dir, &com_dts_path)?; - let com_js = fs::read_to_string(&com_js_path) - .map_err(|error| format!("Failed to read {}: {error}", com_js_path.display()))?; - let com_dts = fs::read_to_string(&com_dts_path) - .map_err(|error| format!("Failed to read {}: {error}", com_dts_path.display()))?; - let root_js = com_js.replace(", './", ", './com/"); - let root_dts = com_dts.replace("from './", "from './com/"); - let index_js = output_dir.join("index.js"); - let index_dts = output_dir.join("index.d.ts"); - ensure_safe_generated_destination(output_dir, &index_js)?; - ensure_safe_generated_destination(output_dir, &index_dts)?; - fs::write(&index_js, &root_js) - .map_err(|error| format!("Failed to write COM compatibility index.js: {error}"))?; - fs::write(&index_dts, root_dts) - .map_err(|error| format!("Failed to write COM compatibility index.d.ts: {error}"))?; - Ok(()) -} - -fn migrate_legacy_com_only_package(output_dir: &Path) -> Result<(), String> { - if has_winrt_root(output_dir) { - return Ok(()); - } - - let package_path = output_dir.join("package.json"); - let index_path = output_dir.join("index.js"); - let index_dts_path = output_dir.join("index.d.ts"); - if !package_path.is_file() || !index_path.is_file() || !index_dts_path.is_file() { - return Ok(()); - } - let package = fs::read_to_string(&package_path) - .map_err(|error| format!("Failed to read {}: {error}", package_path.display()))?; - let index = fs::read_to_string(&index_dts_path) - .map_err(|error| format!("Failed to read {}: {error}", index_dts_path.display()))?; - if !package.contains("\"name\": \"@winapp/bindings\"") - || !(package.contains("\"type\": \"module\"") || package.contains("\"type\": \"commonjs\"")) - || !index.starts_with("// Generated by dynwinrt-codegen") - { - return Ok(()); - } - - let modules = collect_com_index_modules(&index) - .into_iter() - .filter(|module| !module.starts_with("com/")) - .collect::>(); - if modules.is_empty() { - return Ok(()); - } - - let com_output_dir = output_dir.join("com"); - ensure_safe_generated_parent( - output_dir, - &com_output_dir.join(".dynwinrt-migration-check"), - )?; - for module in modules { - for suffix in [".js", ".d.ts"] { - move_legacy_com_file( - output_dir, - &output_dir.join(format!("{module}{suffix}")), - &com_output_dir.join(format!("{module}{suffix}")), - )?; - } - } - - for path in [ - output_dir.join("index.js"), - output_dir.join("index.mjs"), - output_dir.join("index.d.ts"), - package_path, - ] { - if path.exists() { - ensure_safe_generated_destination(output_dir, &path)?; - fs::remove_file(&path) - .map_err(|error| format!("Failed to remove {}: {error}", path.display()))?; - } - } - write_com_js_barrel(&com_output_dir)?; - finalize_com_generation(output_dir) -} - fn collect_com_index_modules(index: &str) -> BTreeSet { index .lines() @@ -3626,42 +3450,6 @@ fn collect_com_index_modules(index: &str) -> BTreeSet { .collect() } -fn move_legacy_com_file( - output_dir: &Path, - source: &Path, - destination: &Path, -) -> Result<(), String> { - if !source.exists() { - return Ok(()); - } - ensure_safe_generated_destination(output_dir, source)?; - ensure_safe_generated_destination(output_dir, destination)?; - if destination.exists() { - let source_content = fs::read(source) - .map_err(|error| format!("Failed to read {}: {error}", source.display()))?; - let destination_content = fs::read(destination) - .map_err(|error| format!("Failed to read {}: {error}", destination.display()))?; - if source_content != destination_content { - return Err(format!( - "Cannot migrate legacy COM file {} because {} already exists with different content", - source.display(), - destination.display() - )); - } - fs::remove_file(source) - .map_err(|error| format!("Failed to remove {}: {error}", source.display()))?; - return Ok(()); - } - - fs::rename(source, destination).map_err(|error| { - format!( - "Failed to migrate legacy COM file {} to {}: {error}", - source.display(), - destination.display() - ) - }) -} - fn has_winrt_root(output_dir: &Path) -> bool { ["index.mjs", "index.proxy.js", "lifetime.js"] .iter() @@ -3698,12 +3486,9 @@ fn write_bindings_manifest_with_plan( fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { if let Some(manifest) = read_com_generation_manifest(com_output_dir)? { - if !matches!( - manifest.version, - LEGACY_COM_MANIFEST_VERSION | COM_MANIFEST_VERSION - ) { + if manifest.version != COM_MANIFEST_VERSION { return Err(format!( - "Unsupported COM generation manifest version {} in {}", + "Unsupported COM generation manifest version {} in {}; delete and regenerate the complete bindings directory", manifest.version, com_output_dir.join(COM_MANIFEST_FILE).display() )); @@ -3718,12 +3503,14 @@ fn collect_com_subpath_names(com_output_dir: &Path) -> Result, .collect()); } let index_path = com_output_dir.join("index.d.ts"); - if !index_path.is_file() { - return Ok(BTreeSet::new()); + if index_path.is_file() { + return Err(format!( + "Existing COM bindings in '{}' have no version {} generation manifest; delete and regenerate the complete bindings directory", + com_output_dir.display(), + COM_MANIFEST_VERSION + )); } - let index = fs::read_to_string(&index_path) - .map_err(|error| format!("Failed to read {}: {error}", index_path.display()))?; - Ok(collect_com_index_modules(&index)) + Ok(BTreeSet::new()) } fn collect_com_cjs_exports(content: &str) -> BTreeSet { @@ -9181,6 +8968,47 @@ mod tests { fs::remove_dir_all(reverse.parent().unwrap()).unwrap(); } + #[test] + fn unsafe_support_schema_mismatch_requires_clean_regeneration() { + let output = test_directory("unsafe-schema-mismatch").join("com"); + let unsafe_dir = output.join("unsafe"); + fs::create_dir_all(&unsafe_dir).unwrap(); + fs::write( + unsafe_dir.join("support.json"), + "{\"schemaVersion\":10,\"interfaces\":[]}\n", + ) + .unwrap(); + + let error = prepare_generated_unsafe_package(&output, &[]).unwrap_err(); + assert!( + error.contains("Unsupported generated unsafe support schema 10") + && error.contains("expected 11"), + "{error}" + ); + + fs::remove_dir_all(output.parent().unwrap()).unwrap(); + } + + #[test] + fn unversioned_com_output_requires_clean_regeneration() { + let output = test_directory("unversioned-com-output").join("com"); + fs::create_dir_all(&output).unwrap(); + fs::write( + output.join("index.d.ts"), + "// Generated by dynwinrt-codegen - do not edit\n", + ) + .unwrap(); + + let error = collect_com_subpath_names(&output).unwrap_err(); + assert!( + error.contains("have no version 2 generation manifest") + && error.contains("delete and regenerate"), + "{error}" + ); + + fs::remove_dir_all(output.parent().unwrap()).unwrap(); + } + #[test] fn output_transaction_commits_complete_tree() { let output = test_directory("transaction-commit"); diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index ae103987..983c05f4 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -12,7 +12,6 @@ //! Tests are skipped (with an `eprintln!` note) when the Win32 winmd is not //! present at the well-known path. -use std::collections::BTreeSet; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -4627,7 +4626,7 @@ fn by_value_guid_is_not_treated_as_a_dynamic_iid_pointer() { } #[test] -fn com_only_generation_emits_an_importable_package_shape() { +fn com_only_generation_emits_only_an_explicit_com_subpackage() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; @@ -4658,12 +4657,9 @@ fn com_only_generation_emits_an_importable_package_shape() { let stderr = String::from_utf8_lossy(&output.stderr); assert!(output.status.success(), "COM generation failed:\n{stderr}"); - for name in ["index.js", "index.d.ts", "package.json"] { - assert!( - output_dir.join(name).is_file(), - "COM-only compatibility output must include {name}" - ); - } + assert!(output_dir.join("package.json").is_file()); + assert!(!output_dir.join("index.js").exists()); + assert!(!output_dir.join("index.d.ts").exists()); for name in ["index.js", "index.mjs", "index.d.ts", "package.json"] { assert!( output_dir.join("com").join(name).is_file(), @@ -4684,18 +4680,13 @@ fn com_only_generation_emits_an_importable_package_shape() { .is_file() ); assert!(!output_dir.join("ITaskbarList3.js").exists()); - let index = fs::read_to_string(output_dir.join("index.js")).unwrap(); - assert!(index.contains("ITaskbarList3") && index.contains("TBPFLAG")); - assert!(index.contains( - "__exportLazy('ITaskbarList3', './com/windows/win32/ui/shell/ITaskbarList3.js')" - )); let com_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); assert!( com_index .contains("__exportLazy('ITaskbarList3', './windows/win32/ui/shell/ITaskbarList3.js')") ); assert!( - !index.contains("Unsafe") && !com_index.contains("Unsafe"), + !com_index.contains("Unsafe"), "safe-complete generation must not leak generated unsafe companions" ); assert!( @@ -4706,7 +4697,8 @@ fn com_only_generation_emits_an_importable_package_shape() { assert!(com_esm_index.contains("import * as __m")); let package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!(package.contains("\"type\": \"commonjs\"")); - assert!(package.contains("\"./windows/win32/ui/shell/ITaskbarList3\"")); + assert!(!package.contains("\".\":")); + assert!(!package.contains("\"./windows/win32/ui/shell/ITaskbarList3\"")); assert!(package.contains("\"./com\"")); assert!(package.contains("\"./com/*\"")); assert!(package.contains("\"import\": \"./com/index.mjs\"")); @@ -4731,6 +4723,8 @@ fn com_only_generation_emits_an_importable_package_shape() { incremental.status.success(), "incremental COM generation failed:\n{incremental_stderr}" ); + assert!(!output_dir.join("index.js").exists()); + assert!(!output_dir.join("index.d.ts").exists()); let incremental_index = fs::read_to_string(output_dir.join("com").join("index.js")).unwrap(); assert!( incremental_index.contains("ITaskbarList3") @@ -4740,9 +4734,10 @@ fn com_only_generation_emits_an_importable_package_shape() { ); let incremental_package = fs::read_to_string(output_dir.join("package.json")).unwrap(); assert!( - incremental_package.contains("\"./windows/win32/ui/shell/ITaskbarList3\"") - && incremental_package.contains("\"./windows/win32/ui/shell/IShellLinkW\""), - "incremental generation must preserve earlier package subpaths:\n{incremental_package}" + incremental_package.contains("\"./com\"") + && incremental_package.contains("\"./com/*\"") + && !incremental_package.contains("\".\":"), + "incremental generation must preserve only explicit COM package subpaths:\n{incremental_package}" ); let manifest_path = output_dir.join("com").join(".dynwinrt-com-manifest.json"); @@ -4945,9 +4940,9 @@ fn safe_incomplete_interface_generates_an_isolated_unsafe_companion() { true ); + assert!(!output_dir.join("index.js").exists()); + assert!(!output_dir.join("index.d.ts").exists()); for path in [ - output_dir.join("index.js"), - output_dir.join("index.d.ts"), output_dir.join("com").join("index.js"), output_dir.join("com").join("index.mjs"), output_dir.join("com").join("index.d.ts"), @@ -6027,145 +6022,61 @@ fn canonical_com_layout_separates_real_short_name_collisions() { .contains("export { }") ); let package = fs::read_to_string(output.join("package.json")).unwrap(); - assert!(package.contains("\"./windows/win32/media/direct-show/IResourceManager\"")); - assert!(package.contains( - "\"./windows/win32/system/distributed-transaction-coordinator/IResourceManager\"" - )); + assert!(!package.contains("\".\":")); + assert!(package.contains("\"./com\"")); + assert!(package.contains("\"./com/*\"")); fs::remove_dir_all(&output).unwrap(); remove_com_generation_lock(&output); } #[test] -fn version_one_com_output_migrates_all_roots_to_canonical_layout() { +fn version_one_com_output_requires_clean_regeneration() { if !win32_available() { eprintln!("Skipping: Win32 winmd not available"); return; } let output = std::env::temp_dir().join(format!( - "dynwinrt-codegen-canonical-migration-{}", + "dynwinrt-codegen-canonical-version-mismatch-{}", std::process::id() )); let _ = fs::remove_dir_all(&output); remove_com_generation_lock(&output); let com_dir = output.join("com"); - let unsafe_dir = com_dir.join("unsafe"); - fs::create_dir_all(&unsafe_dir).unwrap(); - - let taskbar = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.UI.Shell", - "ITaskbarList3", - ) - .unwrap(); - let taskbar_output = com::generate_com_interface_files(&taskbar, &win32_winmd()).unwrap(); - let mut taskbar_files = BTreeSet::new(); - for (name, content) in std::iter::once(("ITaskbarList3.js".into(), taskbar_output.js)) - .chain(std::iter::once(( - "ITaskbarList3.d.ts".into(), - taskbar_output.dts, - ))) - .chain(taskbar_output.extra_files) - { - let basename = Path::new(&name) - .file_name() - .expect("legacy COM file has a basename") - .to_string_lossy() - .into_owned(); - fs::write(com_dir.join(&basename), content).unwrap(); - taskbar_files.insert(basename); - } - - let wbem = com_metadata::parse_com_interface( - &win32_winmd(), - "Windows.Win32.System.Wmi", - "IWbemServices", - ) - .unwrap(); - let mut wbem_output = com::generate_unsafe_interface_files(&wbem, &win32_winmd()).unwrap(); - let legacy_module = "Windows/Win32/System/Wmi/IWbemServicesUnsafe"; - let legacy_js = format!("{legacy_module}.js"); - let legacy_dts = format!("{legacy_module}.d.ts"); - for (relative, content) in [ - (legacy_js.clone(), wbem_output.js.take().unwrap()), - (legacy_dts.clone(), wbem_output.dts.take().unwrap()), - ] { - let path = unsafe_dir.join(relative); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, content).unwrap(); - } - let mut legacy_support = serde_json::to_value(wbem_output.support).unwrap(); - legacy_support["schemaVersion"] = serde_json::json!(com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION); - legacy_support["modulePath"] = serde_json::json!(legacy_module); - fs::write( - unsafe_dir.join("support.json"), - format!( - "{}\n", - serde_json::to_string_pretty(&serde_json::json!({ - "schemaVersion": com::LEGACY_UNSAFE_SUPPORT_SCHEMA_VERSION, - "interfaces": [legacy_support], - })) - .unwrap() - ), - ) - .unwrap(); - - let manifest = serde_json::json!({ - "version": 1, - "roots": { - "Windows.Win32.UI.Shell.ITaskbarList3": taskbar_files, - "Windows.Win32.System.Wmi.IWbemServices": [ - format!("unsafe/{legacy_js}"), - format!("unsafe/{legacy_dts}"), - "unsafe/runtime.js", - "unsafe/runtime.d.ts", - ], - }, - }); + fs::create_dir_all(&com_dir).unwrap(); + let manifest = serde_json::json!({"version": 1, "roots": {}}); fs::write( com_dir.join(".dynwinrt-com-manifest.json"), format!("{}\n", serde_json::to_string_pretty(&manifest).unwrap()), ) .unwrap(); - run_codegen_command( - &win32_winmd(), - Some("Windows.Win32.UI.Shell"), - "IShellLinkW", - &output, - ); - - for (namespace, name) in [ - ("Windows.Win32.UI.Shell", "ITaskbarList3"), - ("Windows.Win32.UI.Shell", "IShellLinkW"), - ] { - assert!(generated_com_module(&output, namespace, name, "js").is_file()); - assert!(!com_dir.join(format!("{name}.js")).exists()); - } + let result = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args([ + "generate", + "--winmd", + &win32_winmd(), + "--namespace", + "Windows.Win32.UI.Shell", + "--class-name", + "IShellLinkW", + "--output", + output.to_str().unwrap(), + ]) + .output() + .unwrap(); + assert!(!result.status.success()); assert!( - generated_unsafe_module(&output, "Windows.Win32.System.Wmi", "IWbemServices", "js") - .is_file() + String::from_utf8_lossy(&result.stderr) + .contains("Unsupported COM generation manifest version 1") ); - let manifest: serde_json::Value = serde_json::from_str( - &fs::read_to_string(com_dir.join(".dynwinrt-com-manifest.json")).unwrap(), - ) - .unwrap(); - assert_eq!(manifest["version"], 2); - assert_eq!(manifest["roots"].as_object().unwrap().len(), 3); - let support: serde_json::Value = - serde_json::from_str(&fs::read_to_string(unsafe_dir.join("support.json")).unwrap()) - .unwrap(); - assert_eq!(support["schemaVersion"], com::UNSAFE_SUPPORT_SCHEMA_VERSION); assert_eq!( - support["interfaces"][0]["modulePath"], - "windows/win32/system/wmi/IWbemServicesUnsafe" + serde_json::from_str::( + &fs::read_to_string(com_dir.join(".dynwinrt-com-manifest.json")).unwrap() + ) + .unwrap()["version"], + 1 ); - let unsafe_roots = fs::read_dir(&unsafe_dir) - .unwrap() - .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) - .collect::>(); - assert!(unsafe_roots.contains("windows")); - assert!(!unsafe_roots.contains("Windows")); fs::remove_dir_all(&output).unwrap(); remove_com_generation_lock(&output); @@ -6195,11 +6106,7 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { "dynwinrt-codegen-mixed-com-first-{}", std::process::id() )); - let legacy_com_first = temp.join(format!( - "dynwinrt-codegen-mixed-legacy-com-first-{}", - std::process::id() - )); - for output_dir in [&mixed, &winrt_first, &com_first, &legacy_com_first] { + for output_dir in [&mixed, &winrt_first, &com_first] { if output_dir.exists() { fs::remove_dir_all(output_dir).expect("remove stale mixed package test directory"); } @@ -6242,8 +6149,9 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { ); let com_only_package = fs::read_to_string(com_first.join("package.json")).unwrap(); assert!(com_only_package.contains("\"type\": \"commonjs\"")); + assert!(!com_first.join("index.d.ts").exists()); assert!( - fs::read_to_string(com_first.join("index.d.ts")) + fs::read_to_string(com_first.join("com").join("index.d.ts")) .unwrap() .contains("ITaskbarList3") ); @@ -6266,58 +6174,7 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { "one-batch and COM-first output must be byte-identical" ); - run_codegen_command( - &metadata, - Some("Windows.Win32.UI.Shell"), - "ITaskbarList3", - &legacy_com_first, - ); - let com_dir = legacy_com_first.join("com"); - let mut legacy_index = fs::read_to_string(com_dir.join("index.js")).unwrap(); - let mut legacy_dts = fs::read_to_string(com_dir.join("index.d.ts")).unwrap(); - let modules = legacy_dts - .lines() - .filter_map(|line| { - let (_, module) = line.split_once(" from './")?; - module.strip_suffix(".js';").map(str::to_string) - }) - .collect::>(); - for module in modules { - let basename = Path::new(&module) - .file_name() - .expect("canonical COM module has a basename") - .to_string_lossy(); - for suffix in [".js", ".d.ts"] { - fs::copy( - com_dir.join(format!("{module}{suffix}")), - legacy_com_first.join(format!("{basename}{suffix}")), - ) - .unwrap(); - } - legacy_index = legacy_index.replace(&format!("./{module}.js"), &format!("./{basename}.js")); - legacy_dts = legacy_dts.replace(&format!("./{module}.js"), &format!("./{basename}.js")); - } - fs::write(legacy_com_first.join("index.js"), &legacy_index).unwrap(); - fs::write(legacy_com_first.join("index.d.ts"), legacy_dts).unwrap(); - fs::remove_dir_all(com_dir).unwrap(); - - run_codegen_command( - &metadata, - None, - "Windows.Foundation.Uri,Windows.Graphics.DirectX.Direct3D11.IDirect3DSurface", - &legacy_com_first, - ); - assert!(legacy_com_first.join("windows/foundation/Uri.js").is_file()); - assert!( - legacy_com_first - .join("com") - .join("ITaskbarList3.js") - .is_file() - ); - assert!(!legacy_com_first.join("ITaskbarList3.js").exists()); - assert!(!legacy_com_first.join("TBPFLAG.js").exists()); - - for output_dir in [&mixed, &winrt_first, &com_first, &legacy_com_first] { + for output_dir in [&mixed, &winrt_first, &com_first] { fs::remove_dir_all(output_dir).expect("remove mixed package test directory"); remove_com_generation_lock(output_dir); } From 3475eceb74bc4af850d59d3caf64d083efce4827 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 3 Sep 2026 21:55:36 +0800 Subject: [PATCH 3/3] Fix canonical COM review findings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .../src/codegen/com/javascript/render.rs | 89 +++++++++++++------ .../codegen/com/javascript/render_tests.rs | 88 ++++++++++++++---- tools/dynwinrt-codegen/src/codegen/com/mod.rs | 6 +- tools/dynwinrt-codegen/src/codegen/package.rs | 19 ++-- tools/dynwinrt-codegen/src/main.rs | 19 ++-- .../dynwinrt-codegen/tests/win32_com_test.rs | 43 +++++++++ 6 files changed, 193 insertions(+), 71 deletions(-) diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs index ac79bd07..10239172 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render.rs @@ -35,37 +35,39 @@ pub struct ComGeneratedOutput { pub(in crate::codegen::com) fn render_com_interface( meta: &ProjectedComInterface, -) -> ComGeneratedOutput { +) -> Result { render_projected_interface(meta) } -fn render_projected_interface(meta: &ProjectedComInterface) -> ComGeneratedOutput { +fn render_projected_interface(meta: &ProjectedComInterface) -> Result { let js = com_esm_to_cjs(&render_js(meta), &meta.namespace); let dts = render_dts(meta); let mut extra_files = BTreeMap::new(); for en in &meta.referenced_enums { let (enum_js, enum_dts) = render_enum_files(en); - extra_files.insert( - canonical_module_file_path(&en.namespace, &en.name, "js") - .expect("projected COM enum has a safe module identity"), + insert_unique_extra_file( + &mut extra_files, + canonical_module_file_path(&en.namespace, &en.name, "js")?, enum_js, - ); - extra_files.insert( - canonical_module_file_path(&en.namespace, &en.name, "d.ts") - .expect("projected COM enum has a safe module identity"), + &format!("enum {}.{}", en.namespace, en.name), + )?; + insert_unique_extra_file( + &mut extra_files, + canonical_module_file_path(&en.namespace, &en.name, "d.ts")?, enum_dts, - ); + &format!("enum {}.{}", en.namespace, en.name), + )?; } - ComGeneratedOutput { + Ok(ComGeneratedOutput { js, dts, extra_files: extra_files.into_iter().collect(), - } + }) } pub(in crate::codegen::com) fn render_com_coclass( meta: &ProjectedComCoclass, -) -> ComGeneratedOutput { +) -> Result { let (js, dts) = render_coclass_files( &meta.namespace, &meta.name, @@ -74,30 +76,61 @@ pub(in crate::codegen::com) fn render_com_coclass( ); let mut extra_files = BTreeMap::new(); for interface in &meta.associated_interfaces { - let output = render_projected_interface(interface); - extra_files.insert( - canonical_module_file_path(&interface.namespace, &interface.name, "js") - .expect("projected COM interface has a safe module identity"), + let output = render_projected_interface(interface)?; + let identity = format!("interface {}.{}", interface.namespace, interface.name); + insert_unique_extra_file( + &mut extra_files, + canonical_module_file_path(&interface.namespace, &interface.name, "js")?, output.js, - ); - extra_files.insert( - canonical_module_file_path(&interface.namespace, &interface.name, "d.ts") - .expect("projected COM interface has a safe module identity"), + &identity, + )?; + insert_unique_extra_file( + &mut extra_files, + canonical_module_file_path(&interface.namespace, &interface.name, "d.ts")?, output.dts, - ); + &identity, + )?; for (name, content) in output.extra_files { - if let Some(existing) = extra_files.insert(name.clone(), content.clone()) - && existing != content - { - panic!("validated coclass emitted conflicting `{name}` files"); - } + insert_shared_extra_file(&mut extra_files, name, content)?; } } - ComGeneratedOutput { + Ok(ComGeneratedOutput { js, dts, extra_files: extra_files.into_iter().collect(), + }) +} + +fn insert_unique_extra_file( + files: &mut BTreeMap, + path: String, + content: String, + identity: &str, +) -> Result<(), String> { + if files.contains_key(&path) { + return Err(format!( + "Classic-COM canonical path collision for {identity}: `{path}` is already emitted" + )); + } + files.insert(path, content); + Ok(()) +} + +fn insert_shared_extra_file( + files: &mut BTreeMap, + path: String, + content: String, +) -> Result<(), String> { + if let Some(existing) = files.get(&path) { + if existing != &content { + return Err(format!( + "Classic-COM coclass emitted conflicting canonical output `{path}`" + )); + } + return Ok(()); } + files.insert(path, content); + Ok(()) } fn render_coclass_files( diff --git a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs index 2187319a..9f455aba 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/javascript/render_tests.rs @@ -21,7 +21,7 @@ fn generate_com_interface_files( winmd_paths: &str, ) -> Result { let projected = project_com_interface(meta, winmd_paths)?; - Ok(render_com_interface(&projected)) + render_com_interface(&projected) } #[test] @@ -38,7 +38,7 @@ fn renderer_api_accepts_only_projected_ir() { sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("registerIUnknownInterface")); assert!(output.dts.contains("export declare class ITest")); assert!( @@ -159,7 +159,7 @@ fn renderer_serializes_validated_com_sink_plan() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("static implementation(handlers)")); assert!( output @@ -264,7 +264,7 @@ fn renderer_serializes_direct_and_void_com_sink_returns() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("return DynCom.i32(result);")); assert!(output.js.contains("return undefined;")); assert!( @@ -368,7 +368,7 @@ fn renderer_projects_borrowed_hwnd_output_as_numeric_handle() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output .js @@ -436,7 +436,7 @@ fn canonical_iunknown_arrays_use_managed_values_without_nominal_wrappers() { sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output .dts @@ -482,7 +482,7 @@ fn renderer_projects_bstr_replacement_as_a_string_roundtrip() { sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output @@ -530,7 +530,7 @@ fn renderer_allows_null_only_for_nullable_bstr_inputs() { sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output @@ -566,7 +566,7 @@ fn real_automation_bstr_interfaces_render_natural_string_apis() { crate::com_metadata::parse_com_interface(&winmd, namespace, interface_name).unwrap(); let projected = crate::codegen::com::project::project_com_interface(&meta, &winmd) .unwrap_or_else(|error| panic!("{namespace}.{interface_name}: {error}")); - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("DynCom.bstrType()")); assert!(output.js.contains("DynCom.takeBstr(")); assert!(output.dts.contains("string")); @@ -649,7 +649,8 @@ fn renderer_keeps_dynamic_iid_native_order_and_all_results() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), - }); + }) + .unwrap(); assert!(output.js.contains( ".addIn(DynCom.u32Type()).addOut(DynCom.i32Type()).addIn(DynCom.pointerType()).addOut(DynCom.ownedComPointerType()).addIn(DynCom.u16Type()).addOut(DynCom.u64Type())" @@ -706,7 +707,7 @@ fn renderer_emits_distinct_by_value_variant_inputs() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains( ".addMethodAt(3, 'UseVariant', new DynComMethodSig().addIn(DynCom.variantByValueType()))" )); @@ -846,7 +847,7 @@ fn renderer_serializes_fixed_capacity_bytes_from_projected_ir() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output .js @@ -952,7 +953,7 @@ fn parallel_arrays_use_semantic_element_counts_and_guid_conversion() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!( output .js @@ -1081,7 +1082,7 @@ fn renderer_emits_tagged_unions_and_automation_runtime_transfers() { evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), }; - let output = render_com_interface(&projected); + let output = render_com_interface(&projected).unwrap(); assert!(output.js.contains("createTaggedValue(activeField, bytes)")); assert!(output.js.contains("DynCom.nativeUnion(")); assert!(output.js.contains("DynCom.variant(")); @@ -1160,7 +1161,8 @@ fn renderer_emits_explicit_idispatch_invoke_options_and_compound_types() { referenced_enums: Vec::new(), sink: None, evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), - }); + }) + .unwrap(); assert!(output.js.contains(".addIn(DynCom.dispatchParamsType())")); assert!( @@ -1220,7 +1222,7 @@ fn coclass_renderer_uses_new_and_runtime_query_interface_views() { associated_interfaces: vec![primary], }; - let output = render_com_coclass(&coclass); + let output = render_com_coclass(&coclass).unwrap(); assert!(output.js.contains("class Test extends ITest4")); assert!( @@ -1251,6 +1253,60 @@ fn coclass_renderer_uses_new_and_runtime_query_interface_views() { ); } +#[test] +fn coclass_renderer_rejects_exact_canonical_interface_path_collisions() { + let interface = |namespace: &str, iid: &str| ProjectedComInterface { + name: "ICollision".into(), + namespace: namespace.into(), + iid: iid.into(), + base_iids: Vec::new(), + is_iunknown_rooted: true, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + sink: None, + evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + }; + let first = interface("Tests.FooBar", "00000000-0000-0000-0000-000000000001"); + let second = interface("Tests.Foo-Bar", "00000000-0000-0000-0000-000000000002"); + let coclass = ProjectedComCoclass { + name: "CollisionClass".into(), + namespace: "Tests".into(), + clsid: "10000000-0000-0000-0000-000000000001".into(), + primary_interface: first.clone(), + associated_interfaces: vec![first, second], + }; + + let error = render_com_coclass(&coclass).unwrap_err(); + assert!(error.contains("canonical path collision"), "{error}"); + assert!(error.contains("tests/foo-bar/ICollision.js"), "{error}"); +} + +#[test] +fn renderer_returns_invalid_referenced_identity_errors() { + let projected = ProjectedComInterface { + name: "ITest".into(), + namespace: "Tests".into(), + iid: "00000000-0000-0000-0000-000000000001".into(), + base_iids: Vec::new(), + is_iunknown_rooted: true, + methods: Vec::new(), + activation: ActivationPlan::None, + referenced_enums: vec![ProjectedComEnum { + namespace: "Tests.CON".into(), + name: "FLAGS".into(), + underlying: ComEnumUnderlying::I32, + members: Vec::new(), + }], + sink: None, + evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + }; + + let error = render_com_interface(&projected).unwrap_err(); + assert!(error.contains("reserved"), "{error}"); + assert!(error.contains("con"), "{error}"); +} + #[test] fn allocator_contract_rejects_trailing_separator_and_whitespace() { for free_with in ["CoTaskMemFree:", " CoTaskMemFree", "CoTaskMemFree "] { diff --git a/tools/dynwinrt-codegen/src/codegen/com/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/mod.rs index 3db8491b..fee38fd7 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/mod.rs @@ -138,7 +138,7 @@ pub fn generate_com_interface_files( winmd_paths: &str, ) -> Result { let projected = project::project_com_interface(meta, winmd_paths)?; - let mut output = javascript::render::render_com_interface(&projected); + let mut output = javascript::render::render_com_interface(&projected)?; let mut pending = enumerator_interface_refs(&projected); let mut generated = std::collections::BTreeSet::from([( meta.interface.namespace.clone(), @@ -159,7 +159,7 @@ pub fn generate_com_interface_files( let projected = project::project_com_interface(&referenced, winmd_paths) .or_else(|_| project::project_com_reference_interface(&referenced))?; pending.extend(enumerator_interface_refs(&projected)); - let rendered = javascript::render::render_com_interface(&projected); + let rendered = javascript::render::render_com_interface(&projected)?; insert_extra( &mut extras, canonical_module_file_path(&namespace, &name, "js")?, @@ -228,5 +228,5 @@ pub fn generate_com_coclass_files( winmd_paths: &str, ) -> Result { let projected = project::project_com_coclass(meta, winmd_paths)?; - Ok(javascript::render::render_com_coclass(&projected)) + javascript::render::render_com_coclass(&projected) } diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index 9e167154..af79c4f5 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -12,8 +12,8 @@ pub struct PackageManifestInput<'a> { pub struct BindingsPackageManifestInput<'a> { pub has_winrt_root: bool, + pub has_com_output: bool, pub winrt_subpath_names: &'a BTreeSet, - pub com_subpath_names: &'a BTreeSet, } pub struct PythonPackageManifestInput<'a> { @@ -26,11 +26,10 @@ pub struct PythonPackageManifestInput<'a> { /// Preserve the existing WinRT-only renderer API and byte-for-byte output. pub fn render_package_json(input: &PackageManifestInput<'_>) -> String { - let com_subpath_names = BTreeSet::new(); render_bindings_package_json(&BindingsPackageManifestInput { has_winrt_root: true, + has_com_output: false, winrt_subpath_names: input.subpath_names, - com_subpath_names: &com_subpath_names, }) } @@ -38,7 +37,7 @@ pub fn render_bindings_package_json(input: &BindingsPackageManifestInput<'_>) -> if input.has_winrt_root { render_winrt_package(input) } else { - render_com_only_package() + render_com_only_package(input.has_com_output) } } @@ -123,20 +122,20 @@ fn render_winrt_package(input: &BindingsPackageManifestInput<'_>) -> String { out.push_str(" }"); } - append_com_exports(&mut out, !input.com_subpath_names.is_empty(), true); + append_com_exports(&mut out, input.has_com_output, true); out.push_str("\n }\n"); out.push_str("}\n"); out } -fn render_com_only_package() -> String { +fn render_com_only_package(has_com_output: bool) -> String { let mut out = String::new(); out.push_str("{\n"); out.push_str(" \"name\": \"@winapp/bindings\",\n"); out.push_str(" \"type\": \"commonjs\",\n"); out.push_str(" \"sideEffects\": false,\n"); out.push_str(" \"exports\": {\n"); - append_com_exports(&mut out, true, false); + append_com_exports(&mut out, has_com_output, false); out.push_str("\n }\n"); out.push_str("}\n"); out @@ -225,11 +224,10 @@ mod tests { #[test] fn mixed_package_keeps_duplicate_names_in_separate_domains() { let winrt = BTreeSet::from(["Uri".to_string()]); - let com = BTreeSet::from(["Uri".to_string()]); let out = render_bindings_package_json(&BindingsPackageManifestInput { has_winrt_root: true, + has_com_output: true, winrt_subpath_names: &winrt, - com_subpath_names: &com, }); assert!(out.contains("\"./Uri\"")); @@ -244,12 +242,11 @@ mod tests { #[test] fn com_only_package_exposes_only_explicit_com_subpaths() { let module = "windows/win32/ui/shell/ITaskbarList3"; - let com = BTreeSet::from([module.to_string()]); let winrt = BTreeSet::new(); let out = render_bindings_package_json(&BindingsPackageManifestInput { has_winrt_root: false, + has_com_output: true, winrt_subpath_names: &winrt, - com_subpath_names: &com, }); assert!(out.contains("\"type\": \"commonjs\"")); diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 4b1c34fd..07600635 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -3472,11 +3472,11 @@ fn write_bindings_manifest_with_plan( } else { BTreeSet::new() }; - let com_subpath_names = collect_com_subpath_names(&output_dir.join("com"))?; + let has_com_output = has_com_output(&output_dir.join("com"))?; let content = package::render_bindings_package_json(&package::BindingsPackageManifestInput { has_winrt_root, + has_com_output, winrt_subpath_names: &winrt_subpath_names, - com_subpath_names: &com_subpath_names, }); let path = output_dir.join("package.json"); ensure_safe_generated_destination(output_dir, &path)?; @@ -3484,7 +3484,7 @@ fn write_bindings_manifest_with_plan( .map_err(|error| format!("Failed to write {}: {error}", path.display())) } -fn collect_com_subpath_names(com_output_dir: &Path) -> Result, String> { +fn has_com_output(com_output_dir: &Path) -> Result { if let Some(manifest) = read_com_generation_manifest(com_output_dir)? { if manifest.version != COM_MANIFEST_VERSION { return Err(format!( @@ -3493,14 +3493,7 @@ fn collect_com_subpath_names(com_output_dir: &Path) -> Result, com_output_dir.join(COM_MANIFEST_FILE).display() )); } - return Ok(manifest - .roots - .values() - .flatten() - .filter(|path| !path.starts_with("unsafe/")) - .filter_map(|path| path.strip_suffix(".js")) - .map(str::to_string) - .collect()); + return Ok(!manifest.roots.is_empty()); } let index_path = com_output_dir.join("index.d.ts"); if index_path.is_file() { @@ -3510,7 +3503,7 @@ fn collect_com_subpath_names(com_output_dir: &Path) -> Result, COM_MANIFEST_VERSION )); } - Ok(BTreeSet::new()) + Ok(false) } fn collect_com_cjs_exports(content: &str) -> BTreeSet { @@ -8999,7 +8992,7 @@ mod tests { ) .unwrap(); - let error = collect_com_subpath_names(&output).unwrap_err(); + let error = has_com_output(&output).unwrap_err(); assert!( error.contains("have no version 2 generation manifest") && error.contains("delete and regenerate"), diff --git a/tools/dynwinrt-codegen/tests/win32_com_test.rs b/tools/dynwinrt-codegen/tests/win32_com_test.rs index 983c05f4..520fb5e0 100644 --- a/tools/dynwinrt-codegen/tests/win32_com_test.rs +++ b/tools/dynwinrt-codegen/tests/win32_com_test.rs @@ -6180,6 +6180,49 @@ fn mixed_generation_supports_one_command_and_both_incremental_orders() { } } +#[test] +fn mixed_unsafe_only_com_retains_com_package_exports() { + if !win32_available() { + eprintln!("Skipping: Win32 winmd not available"); + return; + } + let Some(windows_winmd) = discovered_windows_winmd() else { + eprintln!("Skipping: Windows.winmd not available"); + return; + }; + let output = std::env::temp_dir().join(format!( + "dynwinrt-codegen-mixed-unsafe-only-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&output); + remove_com_generation_lock(&output); + + run_codegen_command( + &win32_winmd(), + Some("Windows.Win32.System.Wmi"), + "IWbemServices", + &output, + ); + run_codegen_command( + &format!("{};{}", windows_winmd, win32_winmd()), + Some("Windows.Foundation"), + "Uri", + &output, + ); + + assert!( + generated_unsafe_module(&output, "Windows.Win32.System.Wmi", "IWbemServices", "js") + .is_file() + ); + let package = fs::read_to_string(output.join("package.json")).unwrap(); + assert!(package.contains("\".\":")); + assert!(package.contains("\"./com\":")); + assert!(package.contains("\"./com/*\":")); + + fs::remove_dir_all(&output).unwrap(); + remove_com_generation_lock(&output); +} + /// Requirement 8: multi-interface COM generation must be atomic enough that /// a later request's resolution/projection failure doesn't leave an earlier, /// successfully-projected interface's files (or the `com/` barrel) newly