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
23 changes: 23 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,29 @@ converting a raw value to a generated runtime class. A failed QueryInterface is
reported as an error. Internal generated `_fromNative()` paths consume native
return values; application code should use `projectAs()` instead.

### Explicit boxed-value unboxing

Generic WinRT `Object`/`IInspectable` results remain raw `DynWinRtValue`
instances. Use `unboxObject()` only where the application expects a boxed
`Windows.Foundation.IPropertyValue`, such as values from
`DeviceInformation.properties`:

```js
import { unboxObject } from '@microsoft/dynwinrt'

const raw = deviceInformation.properties.get('System.Devices.DeviceInstanceId')
const instanceId = unboxObject(raw)
```

The helper borrows its argument. It maps supported numeric, Boolean, string,
character, GUID, and corresponding array property types to JavaScript values;
`Int64` and `UInt64` use `bigint`, GUIDs use strings, and `UInt8Array` uses
`Uint8Array`. `null` stays `null`. If the object does not implement
`IPropertyValue`, the exact same JavaScript object is returned, so identity and
later projection remain intact. Unsupported property types (including
`DateTime`, `TimeSpan`, geometry, inspectable, and other types) and native getter
failures throw.

Generated WinUI `IElementFactory` bindings expose `IElementFactory.create()`.
It creates a synchronous, UI-thread factory backed by JavaScript
`getElement`/`recycleElement` callbacks. Call `releaseCallbacks()` on the
Expand Down
112 changes: 112 additions & 0 deletions bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
getWindowsDirectory,
hasPackageIdentity,
roInitialize,
unboxObject,
} from '../dist/winrt.js'
import * as winrtRuntime from '../dist/winrt.js'
import * as comRuntime from '../dist/com.js'
Expand Down Expand Up @@ -748,6 +749,117 @@ test('invoke WinRT through dynamic metadata', (t) => {
t.is(uriType.methodByName('get_AbsoluteUri').invoke(uri, []).toString(), expected)
})

test('explicitly unbox WinRT property values without changing raw objects', (t) => {
roInitialize(1)
const staticsIid = WinGuid.parse('629bdbc8-d932-4ff4-96b9-8d96c5c1e858')
const objectType = DynWinRtType.object()
const methods: Array<[string, InstanceType<typeof DynWinRtMethodSig>]> = [
['CreateEmpty', new DynWinRtMethodSig().addOut(objectType)],
['CreateUInt8', new DynWinRtMethodSig().addIn(DynWinRtType.u8()).addOut(objectType)],
['CreateInt16', new DynWinRtMethodSig().addIn(DynWinRtType.i16()).addOut(objectType)],
['CreateUInt16', new DynWinRtMethodSig().addIn(DynWinRtType.u16()).addOut(objectType)],
['CreateInt32', new DynWinRtMethodSig().addIn(DynWinRtType.i32()).addOut(objectType)],
['CreateUInt32', new DynWinRtMethodSig().addIn(DynWinRtType.u32()).addOut(objectType)],
['CreateInt64', new DynWinRtMethodSig().addIn(DynWinRtType.i64()).addOut(objectType)],
['CreateUInt64', new DynWinRtMethodSig().addIn(DynWinRtType.u64()).addOut(objectType)],
['CreateSingle', new DynWinRtMethodSig().addIn(DynWinRtType.f32()).addOut(objectType)],
['CreateDouble', new DynWinRtMethodSig().addIn(DynWinRtType.f64()).addOut(objectType)],
['CreateChar16', new DynWinRtMethodSig().addIn(DynWinRtType.char16()).addOut(objectType)],
['CreateBoolean', new DynWinRtMethodSig().addIn(DynWinRtType.boolType()).addOut(objectType)],
['CreateString', new DynWinRtMethodSig().addIn(DynWinRtType.hstring()).addOut(objectType)],
['CreateInspectable', new DynWinRtMethodSig().addIn(objectType).addOut(objectType)],
['SkippedCreateGuid', new DynWinRtMethodSig()],
[
'CreateDateTime',
new DynWinRtMethodSig()
.addIn(DynWinRtType.structType('Windows.Foundation.DateTime', [DynWinRtType.i64()]))
.addOut(objectType),
],
['SkippedCreateTimeSpan', new DynWinRtMethodSig()],
['SkippedCreatePoint', new DynWinRtMethodSig()],
['SkippedCreateSize', new DynWinRtMethodSig()],
['SkippedCreateRect', new DynWinRtMethodSig()],
['CreateUInt8Array', new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.u8())).addOut(objectType)],
['SkippedCreateInt16Array', new DynWinRtMethodSig()],
['SkippedCreateUInt16Array', new DynWinRtMethodSig()],
['CreateInt32Array', new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.i32())).addOut(objectType)],
['SkippedCreateUInt32Array', new DynWinRtMethodSig()],
['SkippedCreateInt64Array', new DynWinRtMethodSig()],
['SkippedCreateUInt64Array', new DynWinRtMethodSig()],
['SkippedCreateSingleArray', new DynWinRtMethodSig()],
['SkippedCreateDoubleArray', new DynWinRtMethodSig()],
[
'CreateChar16Array',
new DynWinRtMethodSig().addIn(DynWinRtType.arrayType(DynWinRtType.char16())).addOut(objectType),
],
]
let staticsType = DynWinRtType.registerInterface('IPropertyValueStaticsUnboxTest', staticsIid)
for (const [name, signature] of methods) {
staticsType = staticsType.addMethod(name, signature)
}
const factory = DynWinRtValue.activationFactory('Windows.Foundation.PropertyValue').cast(staticsIid)

const boxedString = staticsType.methodByName('CreateString').invoke(factory, [DynWinRtValue.hstring('BLE Device')])
const boxedInt64 = staticsType.methodByName('CreateInt64').invoke(factory, [DynWinRtValue.i64(-(2n ** 63n))])
const boxedChar = staticsType.methodByName('CreateChar16').invoke(factory, [DynWinRtValue.u16(0xd800)])
const boxedBytes = staticsType
.methodByName('CreateUInt8Array')
.invoke(factory, [DynWinRtArray.fromU8Values([0, 1, 127, 255]).toValue()])
const boxedInts = staticsType
.methodByName('CreateInt32Array')
.invoke(factory, [DynWinRtArray.fromI32Values([-1, 0, 42]).toValue()])
const boxedChars = staticsType
.methodByName('CreateChar16Array')
.invoke(factory, [DynWinRtArray.fromU16Values([0xd800, 0x61]).toValue()])

t.is(unboxObject(boxedString), 'BLE Device')
t.is(unboxObject(boxedInt64), -(2n ** 63n))
t.is((unboxObject(boxedChar) as string).charCodeAt(0), 0xd800)
t.deepEqual([...(unboxObject(boxedBytes) as Uint8Array)], [0, 1, 127, 255])
t.deepEqual(unboxObject(boxedInts), [-1, 0, 42])
t.deepEqual(
(unboxObject(boxedChars) as string[]).map((value) => value.charCodeAt(0)),
[0xd800, 0x61],
)
t.is(unboxObject(null), null)
t.is(unboxObject(DynWinRtValue.nullValue()), null)

const uriFactory = DynWinRtValue.activationFactory('Windows.Foundation.Uri')
const identity = uriFactory.identityRaw()
t.is(unboxObject(uriFactory), uriFactory)
t.is(uriFactory.identityRaw(), identity)

const dateTime = DynWinRtStruct.create(DynWinRtType.structType('Windows.Foundation.DateTime', [DynWinRtType.i64()]))
dateTime.setI64(0, 0n)
const unsupported = staticsType.methodByName('CreateDateTime').invoke(factory, [dateTime.toValue()])
t.throws(() => unboxObject(unsupported), { message: /Unsupported WinRT IPropertyValue type/ })

const keyType = DynWinRtType.hstring()
const propertyMap = DynWinRtValue.createMap(
[DynWinRtValue.hstring('System.Devices.DeviceInstanceId')],
[boxedString],
keyType,
objectType,
)
const mapType = DynWinRtType.parameterized(WinGuid.parse('3c2925fe-8519-45c1-aa79-197b6718c1c1'), [
keyType,
objectType,
])
const mapInterface = DynWinRtType.registerInterface('IMap_String_Object_UnboxTest', mapType.iid()).addMethod(
'Lookup',
new DynWinRtMethodSig().addIn(keyType).addOut(objectType),
)
const deviceProperty = mapInterface
.methodByName('Lookup')
.invoke(propertyMap.cast(mapType.iid()), [DynWinRtValue.hstring('System.Devices.DeviceInstanceId')])
const generatedObjectResult: unknown = deviceProperty
t.is(unboxObject(generatedObjectResult), 'BLE Device')
t.is(unboxObject(boxedString), 'BLE Device')
t.throws(() => unboxObject('not a DynWinRtValue'), {
message: /Failed to recover `DynWinRTValue` type from napi value/,
})
})

test('resolve WinRT async operations through the Node event loop', async (t) => {
roInitialize(1)
const staticsIid = WinGuid.parse('5984c710-daf2-43c8-8bb4-a4d3eacfd03f')
Expand Down
18 changes: 18 additions & 0 deletions bindings/js/package-lock.json

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

2 changes: 2 additions & 0 deletions bindings/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"format:rs": "cargo fmt",
"lint": "oxlint",
"test": "ava",
"test:types": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts",
"test:tsfn": "npm run build:test-hooks && ava __test__/tsfn.spec.ts",
"version": "napi version"
},
Expand All @@ -93,6 +94,7 @@
"@oxc-node/core": "^0.0.35",
"@taplo/cli": "^0.7.0",
"@tybys/wasm-util": "^0.10.0",
"@types/node": "^24.13.3",
"ava": "^6.4.1",
"c8": "12.0.0",
"chalk": "^5.6.2",
Expand Down
128 changes: 127 additions & 1 deletion bindings/js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::{
};

use dynwinrt;
use napi::bindgen_prelude::{BigInt, Either, PromiseRaw};
use napi::bindgen_prelude::{BigInt, Either, FromNapiValue, PromiseRaw, ToNapiValue, Unknown};
use napi::Env;
use napi_derive::napi;
use windows::core::{IUnknown, Interface, HSTRING};
Expand Down Expand Up @@ -172,6 +172,132 @@ fn js_safe_i64(value: i64, context: &str) -> napi::Result<i64> {
"{context}: value is outside the JavaScript safe-integer range; use the bigint conversion instead",
)));
}

fn property_value_guid(value: windows::core::GUID) -> String {
format!("{value:?}")
}

fn to_unknown<'env, T: ToNapiValue>(env: Env, value: T) -> napi::Result<Unknown<'env>> {
let value = unsafe { T::to_napi_value(env.raw(), value) }?;
unsafe { Unknown::from_napi_value(env.raw(), value) }
}

fn utf16_unknown<'env>(env: Env, value: &[u16]) -> napi::Result<Unknown<'env>> {
let length = isize::try_from(value.len())
.map_err(|_| napi::Error::from_reason("WinRT Char16 string is too large for JavaScript"))?;
let mut result = std::ptr::null_mut();
napi::check_status!(
unsafe {
napi::sys::napi_create_string_utf16(env.raw(), value.as_ptr(), length, &mut result)
},
"Failed to create JavaScript UTF-16 string"
)?;
unsafe { Unknown::from_napi_value(env.raw(), result) }
}

fn utf16_array_unknown<'env>(env: Env, values: Vec<u16>) -> napi::Result<Unknown<'env>> {
let mut result = std::ptr::null_mut();
napi::check_status!(
unsafe { napi::sys::napi_create_array_with_length(env.raw(), values.len(), &mut result) },
"Failed to create JavaScript Char16 array"
)?;
for (index, value) in values.into_iter().enumerate() {
let value = utf16_unknown(env, &[value])?;
napi::check_status!(
unsafe {
napi::sys::napi_set_element(env.raw(), result, index as u32, napi::JsValue::raw(&value))
},
"Failed to populate JavaScript Char16 array"
)?;
}
unsafe { Unknown::from_napi_value(env.raw(), result) }
}

fn null_unknown<'env>(env: Env) -> napi::Result<Unknown<'env>> {
let mut value = std::ptr::null_mut();
napi::check_status!(
unsafe { napi::sys::napi_get_null(env.raw(), &mut value) },
"Failed to create JavaScript null"
)?;
unsafe { Unknown::from_napi_value(env.raw(), value) }
}

fn property_value_to_javascript<'env>(
env: Env,
value: dynwinrt::PropertyValueData,
) -> napi::Result<Unknown<'env>> {
use dynwinrt::PropertyValueData;

match value {
PropertyValueData::UInt8(value) => to_unknown(env, u32::from(value)),
PropertyValueData::Int16(value) => to_unknown(env, i32::from(value)),
PropertyValueData::UInt16(value) => to_unknown(env, u32::from(value)),
PropertyValueData::Int32(value) => to_unknown(env, value),
PropertyValueData::UInt32(value) => to_unknown(env, value),
PropertyValueData::Int64(value) => to_unknown(env, BigInt::from(value)),
PropertyValueData::UInt64(value) => to_unknown(env, BigInt::from(value)),
PropertyValueData::Single(value) => to_unknown(env, value),
PropertyValueData::Double(value) => to_unknown(env, value),
PropertyValueData::Char16(value) => utf16_unknown(env, &[value]),
PropertyValueData::Boolean(value) => to_unknown(env, value),
PropertyValueData::String(value) => to_unknown(env, value),
PropertyValueData::Guid(value) => to_unknown(env, property_value_guid(value)),
PropertyValueData::UInt8Array(value) => {
to_unknown(env, napi::bindgen_prelude::Buffer::from(value))
}
PropertyValueData::Int16Array(value) => {
to_unknown(env, value.into_iter().map(i32::from).collect::<Vec<_>>())
}
PropertyValueData::UInt16Array(value) => {
to_unknown(env, value.into_iter().map(u32::from).collect::<Vec<_>>())
}
PropertyValueData::Int32Array(value) => to_unknown(env, value),
PropertyValueData::UInt32Array(value) => to_unknown(env, value),
PropertyValueData::Int64Array(value) => {
to_unknown(env, value.into_iter().map(BigInt::from).collect::<Vec<_>>())
}
PropertyValueData::UInt64Array(value) => {
to_unknown(env, value.into_iter().map(BigInt::from).collect::<Vec<_>>())
}
PropertyValueData::SingleArray(value) => to_unknown(env, value),
PropertyValueData::DoubleArray(value) => to_unknown(env, value),
PropertyValueData::Char16Array(value) => utf16_array_unknown(env, value),
PropertyValueData::BooleanArray(value) => to_unknown(env, value),
PropertyValueData::StringArray(value) => to_unknown(env, value),
PropertyValueData::GuidArray(value) => to_unknown(
env,
value
.into_iter()
.map(property_value_guid)
.collect::<Vec<_>>(),
),
}
}

/// Explicitly unbox a supported WinRT `IPropertyValue`.
///
/// JavaScript `null` and WinRT null are returned as `null`. A non-`IPropertyValue`
/// `DynWinRtValue` is returned unchanged, preserving JavaScript and COM identity.
#[napi(
ts_args_type = "value: unknown",
ts_return_type = "boolean | number | bigint | string | Uint8Array | number[] | bigint[] | boolean[] | string[] | DynWinRtValue | null"
)]
pub fn unbox_object<'env>(env: Env, value: Unknown<'env>) -> napi::Result<Unknown<'env>> {
if value.get_type()? == napi::ValueType::Null {
return Ok(value);
}

let raw = unsafe {
<&DynWinRTValue as FromNapiValue>::from_napi_value(env.raw(), napi::JsValue::raw(&value))
}?;
match dynwinrt::unbox_property_value(&raw.0)
.map_err(|error| napi::Error::from_reason(error.message()))?
{
dynwinrt::PropertyValueUnboxResult::Null => null_unknown(env),
dynwinrt::PropertyValueUnboxResult::NotPropertyValue => Ok(value),
dynwinrt::PropertyValueUnboxResult::Value(value) => property_value_to_javascript(env, value),
}
}
Ok(value)
}

Expand Down
22 changes: 22 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,28 @@ produce a wrapper unless the input actually implements that default interface.
Incompatible types raise the ordinary WinRT `OSError`. Static-only metadata
classes with no instance surface are not projection targets.

### Explicit boxed-value unboxing

Generic WinRT `Object`/`IInspectable` results remain raw `DynWinRTValue`
instances. Use `unbox_object()` only where the application expects a boxed
`Windows.Foundation.IPropertyValue`, such as values from
`DeviceInformation.properties`:

```python
from dynwinrt import unbox_object

raw = device_information.properties["System.Devices.DeviceInstanceId"]
instance_id = unbox_object(raw)
```

The helper borrows its argument. It maps supported numeric, Boolean, string,
character, GUID, and corresponding array property types to Python values;
64-bit integers use `int`, GUIDs use `uuid.UUID`, and `UInt8Array` uses `bytes`.
`None` stays `None`. If the object does not implement `IPropertyValue`, the
exact same Python object is returned, so identity and later projection remain
intact. Unsupported property types (including `DateTime`, `TimeSpan`, geometry,
inspectable, and other types) and native getter failures raise an exception.

Use `wrapper.as_interface(InterfaceClass)` when converting an existing
wrapper to an interface view. Use `InterfaceClass.from_value(raw)` for a raw
`DynWinRTValue`. Do not call the internal `_from_native()` method from
Expand Down
Loading
Loading