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
14 changes: 6 additions & 8 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,17 +91,15 @@ jobs:
run: |
npm install --prefix target/tsc --no-save --ignore-scripts --no-package-lock typescript@5.9.3
$tsc = (Resolve-Path target/tsc/node_modules/typescript/bin/tsc).Path
$windowsWinmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' `
-Filter Windows.winmd -File -Recurse |
Sort-Object FullName -Descending |
Select-Object -First 1
if (-not $windowsWinmd) {
throw 'Windows SDK metadata is required for declaration tests'
}
"DYNWINRT_TSC=$tsc" >> $env:GITHUB_ENV
"DYNWINRT_WINDOWS_WINMD=$($windowsWinmd.FullName)" >> $env:GITHUB_ENV
"DYNWINRT_REQUIRE_TSC=1" >> $env:GITHUB_ENV
- uses: NuGet/setup-nuget@v2
- name: Restore pinned Windows SDK corpus
shell: pwsh
run: |
$winmd = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus')
"DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV
- name: Install Win32 metadata
shell: pwsh
run: |
Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ on:
- 'crates/dynwinrt/**'
- 'crates/dynwinrt-com-contracts/**'
- 'eng/coverage/**'
- 'eng/ci/restore-windows-metadata.ps1'
- 'tests/e2e/**'
- 'tools/dynwinrt-codegen/**'
push:
Expand Down Expand Up @@ -57,6 +58,13 @@ jobs:

- uses: NuGet/setup-nuget@v2

- name: Restore pinned Windows SDK corpus
shell: pwsh
run: |
$winmd = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus')
"DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV

- name: Install cargo-llvm-cov
shell: pwsh
run: cargo install cargo-llvm-cov --version 0.8.7 --locked
Expand Down
14 changes: 14 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ cargo build -p dynwinrt-codegen

### Running Tests

The codegen's exhaustive Windows SDK corpus assertions use the immutable
`Microsoft.Windows.SDK.CPP` package pinned in
`tools/dynwinrt-codegen/tests/windows_sdk_corpus.json`, not whichever SDK servicing
update is installed on the machine. Restore and verify that metadata before
running codegen library tests or the coverage pipeline (requires `nuget` on PATH):

```powershell
$env:DYNWINRT_WINDOWS_WINMD = .\eng\ci\restore-windows-metadata.ps1 `
-OutputDirectory .\target\windows-sdk-corpus
```

CI uses the same helper and SHA-256 pin. A missing or different corpus fails with
restore instructions rather than skipping the exact member/count assertions.

```bash
# Core library tests
cargo test -p dynwinrt
Expand Down
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bindings/js/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pollster = "0.4.0"
serde_json = "1"
serde = { version = "1", features = ["derive"] }
libffi = "5.1.0"
sha2 = "0.10"

[dependencies.windows]
version = ">=0.59, <=0.62"
Expand Down
78 changes: 77 additions & 1 deletion bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ dynamically at runtime. There is no native build step in the consuming Electron
or Node project. The same generated bindings can work across compatible
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.
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 initialize the runtime with explicit `initWinappsdk(major, minor)` arguments, or `initWinappsdk()` after importing a configured generated package; see [Windows App SDK initialization](#windows-app-sdk-initialization). 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

Expand Down Expand Up @@ -96,6 +96,82 @@ contains duplicate short names, each canonical module keeps its native symbol
name while the root barrel uses a namespace-qualified name, such as
`AIFoundationEmbeddingVector` or `SemanticSearchEmbeddingVector`.

### Windows App SDK initialization

The existing `initWinappsdk` API returns `void`. Explicit version calls keep their
native/environment behavior; the optional third argument supplies the DLL path
without setting a process environment variable:

```js
const { initWinappsdk } = require('@microsoft/dynwinrt');
initWinappsdk(2, 5, bootstrapDllPath);
```

Generate bindings with `--winappsdk-version 2.5` and
[`--winappsdk-bootstrap-path PATH`](../../tools/dynwinrt-codegen/README.md#packaged-windows-app-sdk-initialization),
accepting a DLL file or a directory such as `.winapp\bin`; repeat the option for
multiple inputs. Directories are searched recursively for the Bootstrap DLL
without following links or searching system/global package locations.
Architecture is read from each PE, and byte-identical duplicates are deduplicated.
Unsupported directory matches are reported and ignored; explicit unsupported
files, corrupt matches and directories with no supported DLL fail. Then the normal
generated package or type import registers configuration, without initializing anything:

```js
import { initWinappsdk, roInitialize } from '@microsoft/dynwinrt';
import { Application } from '@winapp/bindings';

roInitialize(0); // The application selects the UI apartment.
initWinappsdk();
// Create and run Application here.
```

CJS, ESM, proxy barrels and generated type subpaths share registration. Import the
generated module before calling the no-argument initializer; no extra setup
function, ROOT or config argument is required. Generated packages declare an
exact runtime peer dependency so the application and generated modules resolve
the same runtime installation. `npm pack` includes the DLLs, JSON configuration
and notices, and registration is marked as a side effect for bundlers. Runtime
paths are package-relative, independent of the working directory.

Bootstrap bundling requires `--import-name` to name an npm package exposing the
`/winappsdk` support entry point (the default is `@microsoft/dynwinrt`).
File imports and package subpaths are rejected, even when a later generation pass
omits the Bootstrap options. File-based runtime imports remain supported when
generating without Bootstrap bundling in a clean output directory.

Missing imported configuration, partial version arguments, conflicting product
versions or differing DLL payloads produce explicit errors. Identical bundles
can be registered by multiple generated packages. The codegen-support
`@microsoft/dynwinrt/winappsdk` subpath is internal to generated registration;
applications still call `initWinappsdk`, not a replacement initializer.

Explicit DLL paths take precedence over `WINAPPSDK_BOOTSTRAP_DLL_PATH`.
No-argument calls use the environment when set, otherwise the generated resource
for `process.arch`; invalid overrides fail rather than falling back. Existing
`initWinappsdk(major, minor)` calls do not consult registered packages.

The native process-lifetime cache remains: matching versions return after a
successful initialization; other versions fail. New explicit/generated DLL
selections additionally retain their first successful payload digest, accepting
byte-identical copies but rejecting a later different payload. A process first
initialized through the legacy two-version-argument path has no recorded DLL
digest; restart before switching it to explicit/generated DLL selection.
Initialization failures are not cached. `getWinappsdkResourcePriPath()` remains
available, and there is no automatic shutdown or Runtime installation.

Importing generated configuration does not initialize COM or Bootstrap, and
`initWinappsdk` does not choose an apartment. The example's apartment-first order
is a conservative use of the documented Bootstrap prerequisite, not a claim that
the existing init-first examples fail on modern Windows. Package identity alone
does not make initialization a successful no-op.

The Bootstrap DLL is not the complete Windows App Runtime and is governed by the
Microsoft Windows App SDK license, not dynwinrt's MIT license. Runtime deployment
and redistribution as part of a qualifying application remain the producer's
responsibility. Without the generation options, existing Windows SDK-only output
and calls remain unchanged.

### Standalone WinRT interface implementations

Metadata-generated standalone WinRT interfaces expose `implementation(handlers)`
Expand Down
167 changes: 167 additions & 0 deletions bindings/js/__test__/winappsdk-config.e2e.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

'use strict'

const assert = require('node:assert/strict')
const { createHash } = require('node:crypto')
const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = require('node:fs')
const { tmpdir } = require('node:os')
const { join } = require('node:path')
const { test } = require('node:test')

const environment = 'WINAPPSDK_BOOTSTRAP_DLL_PATH'
const dllName = 'Microsoft.WindowsAppRuntime.Bootstrap.dll'

function fixture(t, label = 'bundle') {
const root = mkdtempSync(join(tmpdir(), `dynwinrt-${label}-`))
t.after(() => rmSync(root, { recursive: true, force: true }))
const config = { schema_version: 1, major: 2, minor: 5, dlls: {} }
for (const arch of ['x64', 'arm64']) {
const dir = join(root, '_native', 'winappsdk', arch)
mkdirSync(dir, { recursive: true })
const content = Buffer.from(`test resource ${arch}`)
writeFileSync(join(dir, dllName), content)
config.dlls[arch] = createHash('sha256').update(content).digest('hex')
}
return { root, source: join(root, '_winappsdk.cjs'), config }
}

function runtime(t) {
const module = require.resolve('../runtime/winappsdk.cjs')
delete require.cache[module]
const helpers = require(module)
const previous = process.env[environment]
delete process.env[environment]
t.after(() => {
if (previous === undefined) delete process.env[environment]
else process.env[environment] = previous
})
const calls = []
const init = helpers.createInitializer((...args) => {
calls.push(args)
})
return { ...helpers, init, calls }
}

test('missing configuration and partial versions fail without initializing', (t) => {
const { init, calls } = runtime(t)
assert.throws(() => init(), /No generated Windows App SDK configuration/)
assert.throws(() => init(2), /both major and minor/)
assert.throws(() => init(undefined, 5), /both major and minor/)
assert.deepEqual(calls, [])
})

test('explicit versions retain native/environment behavior despite registered conflicts', (t) => {
const { init, calls, registerConfig } = runtime(t)
const first = fixture(t)
const second = fixture(t)
registerConfig(first.source, first.config)
registerConfig(second.source, { ...second.config, minor: 6 })
process.env[environment] = 'unchanged relative legacy.dll'
assert.equal(init(2, 5), undefined)
assert.deepEqual(calls, [[2, 5]])
assert.equal(process.env[environment], 'unchanged relative legacy.dll')
})

test('registration is inert and consistent providers merge independently of import order', (t) => {
const { init, calls, registerConfig } = runtime(t)
const first = fixture(t)
const second = fixture(t)
registerConfig(second.source, second.config)
registerConfig(first.source, first.config)
registerConfig(first.source, first.config)
assert.equal(calls.length, 0)
init()
const selected = [first, second].sort((a, b) => a.source.localeCompare(b.source))[0]
assert.deepEqual(calls, [[2, 5, join(selected.root, '_native', 'winappsdk', process.arch, dllName)]])
assert.equal(process.env[environment], undefined)
})

test('conflicting versions and payloads name both provider sources', (t) => {
const { init, calls, registerConfig } = runtime(t)
const first = fixture(t)
const second = fixture(t)
registerConfig(first.source, first.config)
registerConfig(second.source, { ...second.config, dlls: { ...second.config.dlls, x64: '0'.repeat(64) } })
assert.throws(init, (error) => {
assert.match(error.message, /Conflicting generated/)
assert.ok(error.message.includes(first.source) && error.message.includes(second.source))
return true
})
assert.equal(calls.length, 0)
})

test('explicit path wins over environment and environment wins over generated resources', (t) => {
const { init, calls, registerConfig } = runtime(t)
const { root, source, config } = fixture(t)
registerConfig(source, config)
const fromEnv = join(root, 'env.dll')
const explicit = join(root, 'explicit.dll')
writeFileSync(fromEnv, '')
writeFileSync(explicit, '')
process.env[environment] = fromEnv
init()
init(2, 5, explicit)
assert.deepEqual(calls, [
[2, 5, fromEnv],
[2, 5, explicit],
])
assert.equal(process.env[environment], fromEnv)
for (const invalid of ['', ' ', 'bad\0path', join(root, 'missing.dll')]) {
assert.throws(() => init(2, 5, invalid))
}
process.env[environment] = ''
assert.throws(init, /nonempty path/)
assert.equal(calls.length, 2)
})

test('modified resources fail before initialization', (t) => {
const { init, calls, registerConfig } = runtime(t)
const { root, source, config } = fixture(t)
registerConfig(source, config)
writeFileSync(join(root, '_native', 'winappsdk', process.arch, dllName), 'changed')
assert.throws(init, /digest mismatch/)
assert.equal(calls.length, 0)
})

test('missing generated resources report reinstallation', (t) => {
const { init, calls, registerConfig } = runtime(t)
const { root, source, config } = fixture(t)
registerConfig(source, config)
rmSync(join(root, '_native', 'winappsdk', process.arch, dllName))
assert.throws(init, /Reinstall the complete generated package/)
assert.equal(calls.length, 0)
})

test('invalid schema fields and changed registration fail closed', (t) => {
const { registerConfig } = runtime(t)
const { source, config } = fixture(t)
for (const invalid of [
{ ...config, schema_version: 2 },
{ ...config, major: -1 },
{ ...config, minor: 65536 },
{ ...config, minor: 1.5 },
{ ...config, extra: true },
{ ...config, dlls: {} },
{ ...config, dlls: { x86: '0'.repeat(64) } },
]) {
assert.throws(() => registerConfig(source, invalid), /Invalid Windows App SDK configuration/)
}
registerConfig(source, config)
assert.throws(() => registerConfig(source, { ...config, minor: 6 }), /configuration changed/)
})

test('native failures preserve the original exception and do not poison retries', (t) => {
const { createInitializer, registerConfig } = runtime(t)
const { source, config } = fixture(t)
registerConfig(source, config)
const error = new Error('native failure')
let calls = 0
const init = createInitializer(() => {
if (++calls === 1) throw error
})
assert.throws(init, (caught) => caught === error)
assert.equal(init(), undefined)
assert.equal(calls, 2)
})
12 changes: 11 additions & 1 deletion bindings/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
"require": "./dist/winrt.js",
"default": "./dist/winrt.js"
},
"./winappsdk": {
"types": "./dist/winappsdk-config.d.ts",
"import": "./dist/winappsdk-config.js",
"require": "./dist/winappsdk-config.js",
"default": "./dist/winappsdk-config.js"
},
"./com": {
"types": "./dist/com.d.ts",
"import": "./dist/com.js",
Expand Down Expand Up @@ -45,6 +51,9 @@
},
"typesVersions": {
"*": {
"winappsdk": [
"dist/winappsdk-config.d.ts"
],
"com": [
"dist/com.d.ts"
],
Expand Down Expand Up @@ -108,7 +117,8 @@
"format:toml": "taplo format",
"format:rs": "cargo fmt",
"lint": "oxlint",
"test": "npm run test:types && ava && npm run test:native-classes && npm run test:interface-inputs",
"test": "npm run test:types && ava && npm run test:native-classes && npm run test:interface-inputs && npm run test:winappsdk",
"test:winappsdk": "node --test __test__/winappsdk-config.e2e.cjs",
"test:interface-inputs": "node --test __test__/interface-inputs.e2e.mjs",
"test:native-classes": "node --test __test__/native-class-boundary.e2e.mjs",
"test:native-classes:hooks": "node --test __test__/native-class-boundary-hooks.e2e.mjs",
Expand Down
Loading
Loading