Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,9 @@ jobs:
npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
npm run build:entrypoints --silent
- name: Check production native imports
working-directory: bindings/js
run: npm run test:imports
- uses: actions/upload-artifact@v4
with:
name: dynwinrt
Expand Down
13 changes: 13 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ metadata revisions without rebuilding a native addon.

The runtime primarily targets **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …). It also supports WinUI `Application + Window` hosting through the generated `Application.create()` helper when the caller supplies an STA UI thread, an initialized Windows App SDK runtime, and application lifecycle. Unpackaged callers can initialize the runtime with `initWinappsdk()`; the helper resolves the framework resources from that package graph. It also enables Per-Monitor V2 DPI awareness on the UI thread.

### System DispatcherQueue loading

The system DispatcherQueue helper resolves
`CoreMessaging.dll!CreateDispatcherQueueController` only when it needs to create
a current-thread queue, loading the DLL from the Windows system directory.
Capturing an existing queue skips that resolution. A successful resolution
retains the module for the process lifetime so controllers and callbacks remain
valid; DLL or export failures are reported at queue creation and can be retried.
Importing the root or `/com` entrypoint does not load CoreMessaging for this
helper. Apartment, message-pumping, and shutdown requirements are unchanged.
This is not a general older-Windows compatibility or addon feature-isolation
guarantee.

## Quick start

`@microsoft/dynwinrt` is the **runtime**. You generate the typed bindings ahead of time with [`@microsoft/dynwinrt-codegen`](https://www.npmjs.com/package/@microsoft/dynwinrt-codegen), then import them at runtime:
Expand Down
82 changes: 82 additions & 0 deletions bindings/js/__test__/native-imports.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import test from 'ava'
import { spawnSync } from 'node:child_process'
import { existsSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'

const packageDir = fileURLToPath(new URL('..', import.meta.url))
const distDir = join(packageDir, 'dist')

function findDumpbin(): string {
const vswhere = join(
process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)',
'Microsoft Visual Studio',
'Installer',
'vswhere.exe',
)
const installation = spawnSync(vswhere, ['-latest', '-products', '*', '-property', 'installationPath'], {
encoding: 'utf8',
timeout: 10_000,
windowsHide: true,
})
if (installation.status !== 0 || !installation.stdout.trim()) {
throw new Error(`MSVC dumpbin is required to check native imports: ${installation.error ?? installation.stderr}`)
}
const toolsDir = join(installation.stdout.trim(), 'VC', 'Tools', 'MSVC')
const versions = readdirSync(toolsDir).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
const hosts = process.arch === 'arm64' ? ['Hostarm64\\arm64', 'Hostx64\\x64'] : ['Hostx64\\x64']
for (const version of versions) {
for (const host of hosts) {
const candidate = join(toolsDir, version, 'bin', host, 'dumpbin.exe')
if (existsSync(candidate)) return candidate
}
}
throw new Error(`MSVC dumpbin was not found under ${toolsDir}`)
}

test('native addons do not statically import CoreMessaging or CreateDispatcherQueueController', (t) => {
const artifacts = readdirSync(distDir).filter((name) => /^dynwinrt\.win32-.*\.node$/.test(name))
t.true(artifacts.length > 0, 'Build the production JS addon before checking imports')
const dumpbin = findDumpbin()
for (const artifact of artifacts) {
const imports = spawnSync(dumpbin, ['/nologo', '/imports', join(distDir, artifact)], {
encoding: 'utf8',
timeout: 30_000,
windowsHide: true,
})
t.is(imports.status, 0, `${artifact}: ${imports.error ?? imports.stderr}`)
t.notRegex(imports.stdout, /coremessaging\.dll|CreateDispatcherQueueController/i, artifact)
}
})

for (const entrypoint of ['@microsoft/dynwinrt', '@microsoft/dynwinrt/com']) {
test(`fresh ${entrypoint} import does not load CoreMessaging for DispatcherQueue`, (t) => {
const child = spawnSync(
process.execPath,
[
'--eval',
`
const assert = require('node:assert/strict');
const { basename } = require('node:path');
const modules = () => process.report.getReport().sharedObjects.map(p => basename(p).toLowerCase());
const before = modules();
const runtime = require(${JSON.stringify(entrypoint)});
assert.equal(typeof runtime.DynWinRtValue, 'function');
const after = modules();
assert(after.some(p => /^dynwinrt\\.win32-.*\\.node$/.test(p)), 'native addon was not loaded');
assert(
before.includes('coremessaging.dll') || !after.includes('coremessaging.dll'),
'ordinary import introduced CoreMessaging.dll'
);
console.log('lazy-coremessaging-import-ok');
`,
],
{ cwd: packageDir, encoding: 'utf8', timeout: 10_000, windowsHide: true },
)
t.is(child.status, 0, `${child.error ?? child.stderr}`)
t.regex(child.stdout, /lazy-coremessaging-import-ok/)
})
}
3 changes: 2 additions & 1 deletion bindings/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,13 @@
"format:rs": "cargo fmt",
"lint": "oxlint",
"test": "npm run test:types && ava",
"test:imports": "ava __test__/native-imports.spec.ts",
"test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts",
"test:winrt-implementation": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/winrt-implementation.spec.ts",
"test:native-completion": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/native-completion.e2e.ts",
"test:borrowed-copy": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/borrowed-copy.e2e.ts",
"test:types": "npm run test:types:index && npm run test:types:raw",
"test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts __test__/winrt-marshalling.spec.ts __test__/winrt-implementation.spec.ts",
"test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts __test__/winrt-marshalling.spec.ts __test__/winrt-implementation.spec.ts __test__/native-imports.spec.ts",
"test:types:raw": "tsc --noEmit --project __test__/types/tsconfig.json",
"test:tsfn": "npm run build:test-hooks && ava __test__/tsfn.spec.ts",
"version": "napi version"
Expand Down
25 changes: 20 additions & 5 deletions crates/dynwinrt/src/dispatcher_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ use windows::System::{
DispatcherQueue, DispatcherQueueController, DispatcherQueueHandler,
DispatcherQueueShutdownStartingEventArgs,
};
use windows::Win32::System::WinRT::{
CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions,
};
use windows::Win32::System::WinRT::{DQTAT_COM_STA, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions};

mod core_messaging;

#[cfg(test)]
mod tests;

/// A cloneable handle that can enqueue work from any thread onto a captured
/// Windows system dispatcher queue.
Expand Down Expand Up @@ -39,7 +42,19 @@ pub struct SystemDispatcherQueue {

impl SystemDispatcherQueue {
pub fn ensure_for_current_thread() -> windows_core::Result<Self> {
match DispatcherQueue::GetForCurrentThread() {
Self::ensure_for_current_thread_with(
DispatcherQueue::GetForCurrentThread,
core_messaging::create_controller,
)
}

fn ensure_for_current_thread_with(
get_queue: impl FnOnce() -> windows_core::Result<DispatcherQueue>,
create_controller: impl FnOnce(
DispatcherQueueOptions,
) -> windows_core::Result<DispatcherQueueController>,
) -> windows_core::Result<Self> {
match get_queue() {
Ok(queue) => return Ok(Self::new(queue, None)),
// A successful ABI call with a null queue becomes Error::empty().
Err(error) if error.code().is_ok() => {}
Expand All @@ -51,7 +66,7 @@ impl SystemDispatcherQueue {
threadType: DQTYPE_THREAD_CURRENT,
apartmentType: DQTAT_COM_STA,
};
let controller = unsafe { CreateDispatcherQueueController(options)? };
let controller = create_controller(options)?;
let queue = controller.DispatcherQueue()?;
Ok(Self::new(queue, Some(controller)))
}
Expand Down
Loading
Loading