From 01149ecafd922478ccf8a2a957b4e5a6ab26a8e4 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sat, 19 Sep 2026 21:54:32 +0800 Subject: [PATCH 1/3] Fix JavaScript collection factory value projection Use the existing metadata-directed argument conversion for vector and observable-vector elements and both map key/value roles. Cover generated SDK native roundtrips without changing native admission checks or public declarations. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- .../js/__test__/collection-factories.e2e.mjs | 173 ++++++++++++++++ bindings/js/package.json | 1 + .../javascript-binding-internals.md | 12 ++ .../winrt/javascript/project/collections.rs | 10 +- .../tests/collection_factory_test.rs | 186 ++++++++++++++++++ 5 files changed, 379 insertions(+), 3 deletions(-) create mode 100644 bindings/js/__test__/collection-factories.e2e.mjs create mode 100644 tools/dynwinrt-codegen/tests/collection_factory_test.rs diff --git a/bindings/js/__test__/collection-factories.e2e.mjs b/bindings/js/__test__/collection-factories.e2e.mjs new file mode 100644 index 00000000..e1cd7119 --- /dev/null +++ b/bindings/js/__test__/collection-factories.e2e.mjs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import { mkdtempSync, mkdirSync, rmSync, statSync, symlinkSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { basename, dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { runCodegen } from '../scripts/run-codegen.mjs' + +const require = createRequire(import.meta.url) +const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const runtimeRoot = resolve(process.env.DYNWINRT_JS_PACKAGE ?? packageRoot) +const winmd = + process.env.DYNWINRT_WINDOWS_WINMD ?? + String.raw`C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd` +let output +let generated + +before(() => { + assert.ok(statSync(winmd).isFile(), 'Windows SDK metadata is required') + require(runtimeRoot).roInitialize(1) + output = mkdtempSync(join(tmpdir(), 'dynwinrt-collection-factories-')) + const generation = runCodegen( + [ + 'generate', + '--winmd', + winmd, + '--class-name', + 'Windows.Storage.StorageFile,Windows.UI.Notifications.NotificationData,Windows.ApplicationModel.Contacts.ContactPicker,Windows.UI.Xaml.Data.ICollectionView', + '--output', + output, + ], + { cwd: resolve(packageRoot, '..', '..'), encoding: 'utf8', windowsHide: true, timeout: 120_000 }, + ) + assert.equal(generation.status, 0, `${generation.error ?? ''}\n${generation.stderr}`) + const scope = join(output, 'node_modules', '@microsoft') + mkdirSync(scope, { recursive: true }) + symlinkSync(runtimeRoot, join(scope, 'dynwinrt'), 'junction') + generated = require(output) +}) + +after(() => { + if (output) { + rmSync(output, { recursive: true, force: true }) + for (const suffix of ['dynwinrt-generation.lock', 'dynwinrt-lock']) { + rmSync(join(dirname(output), `.${basename(output)}.${suffix}`), { force: true }) + } + } +}) + +function own(t) { + const values = new Set() + const release = (value) => { + if ('_obj' in value) generated.releaseProjected(value) + else value.release() + values.delete(value) + } + t.after(() => { + for (const value of [...values].reverse()) release(value) + }) + const keep = (value) => { + if (value !== null) values.add(value) + return value + } + keep.release = release + return keep +} + +function collection(prefix) { + const names = Object.keys(generated).filter((name) => name.startsWith(prefix)) + assert.equal(names.length, 1, `Expected one metadata projection for ${prefix}: ${names}`) + assert.equal(typeof generated[names[0]].create, 'function') + return generated[names[0]] +} + +test('generated string vector factory accepts nonempty Unicode strings', (t) => { + const keep = own(t) + const items = ['alpha', '\u03bb', '\ud83d\ude00', '', 'embedded\0nul'] + const vector = keep(generated.IVector_String.create(items)) + assert.deepEqual(vector.toArray(), items) + assert.equal(vector.indexOf('\u03bb'), 1) + const view = keep(vector.getView()) + keep.release(vector) + assert.deepEqual(view.toArray(), items) +}) + +test('generated string map factory converts both keys and values', (t) => { + const keep = own(t) + const keys = ['first', '\u03bb', '\ud83d\ude00'] + const values = ['alpha', '\ud83d\ude00', '\u03bb'] + const map = keep(generated.IMap_String_String.create(keys, values)) + assert.equal(map.size, keys.length) + keys.forEach((key, index) => assert.equal(map.lookup(key), values[index])) + assert.throws(() => generated.IMap_String_String.create(['mismatch'], []), /same length/) +}) + +test('typed empty factories still support append and insert', (t) => { + const keep = own(t) + const vector = keep(generated.IVector_String.create([])) + const map = keep(generated.IMap_String_String.create([], [])) + assert.equal(vector.size, 0) + assert.equal(map.size, 0) + vector.append('alpha') + vector.append('\u03bb') + map.insert('first', 'alpha') + map.insert('second', '\u03bb') + assert.deepEqual(vector.toArray(), ['alpha', '\u03bb']) + assert.equal(map.lookup('first'), 'alpha') + assert.equal(map.lookup('second'), '\u03bb') +}) + +test('generated enum vector factory uses the declared scalar projection', (t) => { + const keep = own(t) + const Vector = collection('IVector_WindowsApplicationModelContactsContactFieldType_') + const items = [generated.ContactFieldType.Email, generated.ContactFieldType.PhoneNumber] + const vector = keep(Vector.create(items)) + assert.deepEqual(vector.toArray(), items) +}) + +test('mixed map and observable vector factories preserve wrappers and null references', (t) => { + const keep = own(t) + const uri = keep(generated.Uri.createUri('https://example.invalid/collection')) + const map = keep(generated.IMap_String_Object.create(['uri', 'null'], [uri, null])) + const vector = keep(generated.IObservableVector_Object.create([uri, null])) + const fromMap = keep(map.lookup('uri')) + const fromVector = keep(vector.getAt(0)) + assert.equal(keep(generated.projectAs(fromMap, generated.Uri)).host, 'example.invalid') + assert.equal(keep(generated.projectAs(fromVector, generated.Uri)).host, 'example.invalid') + assert.equal(map.lookup('null'), null) + assert.equal(vector.getAt(1), null) + assert.equal(vector.size, 2) +}) + +test('runtime-class vector factories retain projected and managed inputs', (t) => { + const keep = own(t) + const Vector = collection('IVector_WindowsApplicationModelContactsContactDate_') + const date = keep(generated.ContactDate.create()) + date.month = 3 + const vector = keep(Vector.create([date, date._obj])) + keep.release(date) + assert.equal(keep(vector.getAt(0)).month, 3) + assert.equal(keep(vector.getAt(1)).month, 3) +}) + +test('nested collection arguments use supported small-struct packing', (t) => { + const keep = own(t) + const Map = collection('IMap_String_WindowsFoundationCollectionsIVectorView_WindowsDataTextTextSegment_') + const segments = [ + { startPosition: 1, length: 2 }, + { startPosition: 5, length: 3 }, + ] + if (process.arch === 'ia32') { + assert.throws(() => Map.create(['ranges'], [segments]), /struct|ABI/i) + } else { + const map = keep(Map.create(['ranges'], [segments])) + const view = keep(map.lookup('ranges')) + assert.deepEqual(view.toArray(), segments) + const copied = keep(Map.create(['ranges'], [view])) + assert.deepEqual(keep(copied.lookup('ranges')).toArray(), segments) + } +}) + +test('generated factories keep rejecting unsupported owned structs', () => { + const Vector = collection('IVector_WindowsStorageSearchSortEntry_') + assert.throws(() => Vector.create([]), /struct|ownership|HSTRING/i) + assert.throws( + () => Vector.create([{ propertyName: 'System.ItemNameDisplay', ascendingOrder: true }]), + /struct|ownership|HSTRING/i, + ) +}) diff --git a/bindings/js/package.json b/bindings/js/package.json index f38953fc..cd6afd75 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -110,6 +110,7 @@ "lint": "oxlint", "test": "npm run test:types && ava", "test:imports": "ava __test__/native-imports.spec.ts", + "test:collection-factories": "node --test __test__/collection-factories.e2e.mjs", "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", diff --git a/docs/architecture/javascript-binding-internals.md b/docs/architecture/javascript-binding-internals.md index be08d99f..85ccc711 100644 --- a/docs/architecture/javascript-binding-internals.md +++ b/docs/architecture/javascript-binding-internals.md @@ -38,6 +38,18 @@ moved into a core native operation. ## Value carriers +Generated WinRT collection factories convert each element (and both map keys +and values) using the same metadata-directed argument projection as ordinary +methods. Native `createVector`/`createMap` receive managed `DynWinRtValue` +carriers, not unconverted JavaScript primitives. Conversion does not expand +the native producer's supported ABI or ownership boundary. + +With the JS addon built, run `npm run test:collection-factories` from +`bindings/js` for generated SDK factory roundtrips. `DYNWINRT_CODEGEN` selects +a prebuilt generator, `DYNWINRT_JS_PACKAGE` selects a built runtime package, +and `DYNWINRT_WINDOWS_WINMD` overrides the SDK metadata path. Missing inputs +fail explicitly. + `value.rs` defines `DynWinRTValue` with named WinRT data, independent call storage, and the private `com_value.rs` sidecar. Callers use constructors and accessors, not positional tuple fields. diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs index 915442ff..d70de55d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/collections.rs @@ -530,6 +530,7 @@ pub(super) fn project_collection_create( if piid == PIID_IVECTOR && iface.generic_args.len() == 1 { let elem_type = ts_dynwinrt_type(context, &iface.generic_args[0]); let elem_ts = ts_param_type_safe(context, &iface.generic_args[0], known_types); + let item_wrap = wrap_arg(context, "i", &iface.generic_args[0]); members.push(ProjectedMember::Method(ProjectedMethod { name: "create".into(), doc: Some(DocInfo { @@ -550,7 +551,7 @@ pub(super) fn project_collection_create( is_static: true, invoke_expr: String::new(), sync_return_expr: Some(format!( - "new {}(DynWinRtValue.createVector(items.map(i => _unwrap(i)), {}))", + "new {}(DynWinRtValue.createVector(items.map(i => {item_wrap}), {}))", iface.name, elem_type )), async_convert_v: None, @@ -564,6 +565,7 @@ pub(super) fn project_collection_create( } else if piid == PIID_IOBSERVABLE_VECTOR && iface.generic_args.len() == 1 { let elem_type = ts_dynwinrt_type(context, &iface.generic_args[0]); let elem_ts = ts_param_type_safe(context, &iface.generic_args[0], known_types); + let item_wrap = wrap_arg(context, "i", &iface.generic_args[0]); let vector_name = context.projected_parameterized_name( crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, "IVector", @@ -631,7 +633,7 @@ pub(super) fn project_collection_create( is_static: true, invoke_expr: String::new(), sync_return_expr: Some(format!( - "(() => {{ const value = DynWinRtValue.createVector(items.map(i => _unwrap(i)), {elem_type}); const observable = new {observable}(value); const vector = new {vector}(value); Object.defineProperties(vector, {{ asVector: {{ value: observable.asVector.bind(observable) }}, onVectorChanged: {{ value: observable.onVectorChanged.bind(observable) }}, onceVectorChanged: {{ value: observable.onceVectorChanged.bind(observable) }}, offVectorChanged: {{ value: observable.offVectorChanged.bind(observable) }} }}); return vector; }})()", + "(() => {{ const value = DynWinRtValue.createVector(items.map(i => {item_wrap}), {elem_type}); const observable = new {observable}(value); const vector = new {vector}(value); Object.defineProperties(vector, {{ asVector: {{ value: observable.asVector.bind(observable) }}, onVectorChanged: {{ value: observable.onVectorChanged.bind(observable) }}, onceVectorChanged: {{ value: observable.onceVectorChanged.bind(observable) }}, offVectorChanged: {{ value: observable.offVectorChanged.bind(observable) }} }}); return vector; }})()", observable = iface.name, vector = ref_marker(&vector_name), )), @@ -646,6 +648,8 @@ pub(super) fn project_collection_create( } else if piid == PIID_IMAP && iface.generic_args.len() == 2 { let key_type = ts_dynwinrt_type(context, &iface.generic_args[0]); let val_type = ts_dynwinrt_type(context, &iface.generic_args[1]); + let key_wrap = wrap_arg(context, "k", &iface.generic_args[0]); + let val_wrap = wrap_arg(context, "v", &iface.generic_args[1]); let key_ts = ts_param_type_safe(context, &iface.generic_args[0], known_types); let key_ts = if key_ts == "DynWinRtValue" { "unknown".to_string() @@ -674,7 +678,7 @@ pub(super) fn project_collection_create( is_static: true, invoke_expr: String::new(), sync_return_expr: Some(format!( - "new {}(DynWinRtValue.createMap(keys.map(k => _unwrap(k)), values.map(v => _unwrap(v)), {}, {}))", + "new {}(DynWinRtValue.createMap(keys.map(k => {key_wrap}), values.map(v => {val_wrap}), {}, {}))", iface.name, key_type, val_type )), async_convert_v: None, diff --git a/tools/dynwinrt-codegen/tests/collection_factory_test.rs b/tools/dynwinrt-codegen/tests/collection_factory_test.rs new file mode 100644 index 00000000..c1d7d78e --- /dev/null +++ b/tools/dynwinrt-codegen/tests/collection_factory_test.rs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::{HashMap, HashSet}; + +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; +use dynwinrt_codegen::meta::{InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; +use dynwinrt_codegen::types::{FieldMeta, TypeMeta}; + +const VECTOR: &str = "913337e9-11a1-4345-a3a2-4e7f956e222d"; +const OBSERVABLE_VECTOR: &str = "5917eb53-50b4-4a0d-b309-65862b3f1dbc"; +const MAP: &str = "3c2925fe-8519-45c1-aa79-197b6718c1c1"; + +fn project_factory(piid: &str, args: Vec) -> (String, String) { + let interface = InterfaceMeta { + name: "Collection".into(), + namespace: "Windows.Foundation.Collections".into(), + generic_piid: Some(piid.into()), + // Include ordinary typed inputs so struct helpers and class IIDs are + // collected exactly as they are for real Append/Insert methods. + methods: vec![MethodMeta { + name: "Insert".into(), + raw_name: "Insert".into(), + vtable_index: 6, + params: args + .iter() + .enumerate() + .map(|(i, typ)| ParamMeta { + name: format!("arg{i}"), + typ: typ.clone(), + direction: ParamDirection::In, + }) + .collect(), + ..Default::default() + }], + generic_args: args, + ..Default::default() + }; + let projected = project::project_interface( + &Default::default(), + &interface, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + ( + render_js::render(&projected), + render_dts::render(&projected), + ) +} + +#[test] +fn collection_factories_wrap_declared_scalar_types_in_every_role() { + for (typ, constructor) in [ + (TypeMeta::String, "hstring"), + (TypeMeta::Bool, "boolValue"), + (TypeMeta::I8, "i32"), + (TypeMeta::U8, "i32"), + (TypeMeta::Char16, "i32"), + (TypeMeta::I16, "i16"), + (TypeMeta::U16, "u16"), + (TypeMeta::I32, "i32"), + (TypeMeta::U32, "u32"), + (TypeMeta::I64, "i64"), + (TypeMeta::U64, "u64"), + // Conversion does not imply admission by the native producer. + (TypeMeta::F32, "f32"), + (TypeMeta::F64, "f64"), + ] { + for piid in [VECTOR, OBSERVABLE_VECTOR] { + let (js, _) = project_factory(piid, vec![typ.clone()]); + assert!( + js.contains(&format!("items.map(i => DynWinRtValue.{constructor}(i))")), + "{typ:?}: {js}" + ); + } + let (js, _) = project_factory(MAP, vec![typ.clone(), TypeMeta::String]); + assert!(js.contains(&format!("keys.map(k => DynWinRtValue.{constructor}(k))"))); + assert!(js.contains("values.map(v => DynWinRtValue.hstring(v))")); + let (js, _) = project_factory(MAP, vec![TypeMeta::String, typ]); + assert!(js.contains("keys.map(k => DynWinRtValue.hstring(k))")); + assert!(js.contains(&format!("values.map(v => DynWinRtValue.{constructor}(v))"))); + } +} + +#[test] +fn collection_factories_preserve_projected_references_and_struct_packing() { + let interface = TypeMeta::Interface { + namespace: "Windows.Foundation".into(), + name: "IStringable".into(), + iid: "96369f54-8eb6-48f0-abce-c1b211e627c3".into(), + }; + let reference = TypeMeta::Parameterized { + namespace: "Windows.Foundation".into(), + name: "IReference`1".into(), + piid: "61c17706-2d65-11e0-9ae8-d48564015472".into(), + args: vec![TypeMeta::U32], + }; + for typ in [TypeMeta::Object, interface] { + let (js, _) = project_factory(VECTOR, vec![typ.clone()]); + assert!( + js.contains("items.map(i => (i == null ? DynWinRtValue.nullValue() : _unwrap(i)))") + ); + let (js, _) = project_factory(MAP, vec![TypeMeta::String, typ]); + assert!( + js.contains("values.map(v => (v == null ? DynWinRtValue.nullValue() : _unwrap(v)))") + ); + } + for (piid, args) in [ + (VECTOR, vec![reference.clone()]), + (OBSERVABLE_VECTOR, vec![reference.clone()]), + (MAP, vec![reference.clone(), reference]), + ] { + let (js, _) = project_factory(piid, args); + let factory = js.split("static create(").nth(1).unwrap(); + assert!(factory.contains("value == null ? DynWinRtValue.nullValue()")); + assert!(factory.contains("value instanceof DynWinRtValue ? value : value?._obj")); + assert!( + factory.contains( + "DynWinRtValue.boxReference(DynWinRtValue.u32(value), DynWinRtType.u32())" + ) + ); + } + + for (typ, expression) in [ + ( + TypeMeta::Enum { + namespace: "Windows.Foundation".into(), + name: "PropertyType".into(), + underlying: Box::new(TypeMeta::I32), + members: vec![], + is_flags: false, + doc: None, + deprecated: None, + }, + "DynWinRtValue.i32(i)", + ), + ( + TypeMeta::Struct { + namespace: "Windows.Foundation".into(), + name: "DateTime".into(), + fields: vec![FieldMeta { + name: "UniversalTime".into(), + typ: TypeMeta::I64, + }], + }, + "_packDateTime(i).toValue()", + ), + ( + TypeMeta::Struct { + namespace: "Windows.Foundation".into(), + name: "HResult".into(), + fields: vec![], + }, + "DynWinRtValue.hresult(i)", + ), + (TypeMeta::Guid, "DynWinRtValue.guid(WinGuid.parse(i))"), + ] { + for piid in [VECTOR, OBSERVABLE_VECTOR] { + let (js, _) = project_factory(piid, vec![typ.clone()]); + assert!( + js.contains(&format!("items.map(i => {expression})")), + "{js}" + ); + } + let (js, _) = project_factory(MAP, vec![typ.clone(), typ]); + assert!(js.contains(&format!( + "keys.map(k => {})", + expression.replace("(i)", "(k)") + ))); + assert!(js.contains(&format!( + "values.map(v => {})", + expression.replace("(i)", "(v)") + ))); + } +} + +#[test] +fn string_collection_factory_declarations_remain_native_js_arrays() { + let (_, dts) = project_factory(VECTOR, vec![TypeMeta::String]); + assert!(dts.contains("static create(items: string[]): Collection;")); + let (_, dts) = project_factory(MAP, vec![TypeMeta::String, TypeMeta::String]); + assert!(dts.contains("static create(keys: string[], values: string[]): Collection;")); +} From dc38fd8acfd925204347ec0c00756505cb97e61c Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sat, 19 Sep 2026 22:01:51 +0800 Subject: [PATCH 2/3] Run generated JS collection factory regressions in CI Run the standalone native factory suite after JS binding tests using the already verified production addon and DYNWINRT_CODEGEN artifact. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 21c0f5be..892557c1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -512,6 +512,9 @@ jobs: - name: Test JS binding working-directory: bindings/js run: npm test + - name: Test generated JS collection factories + working-directory: bindings/js + run: npm run test:collection-factories - name: Install prebuilt Python binding shell: pwsh run: | From a4d850410927e106ecf4835a937f5a92d33ac94a Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sun, 20 Sep 2026 08:40:06 +0800 Subject: [PATCH 3/3] Preserve managed nulls in projected reference casts Reuse a single-evaluation nullable reference conversion for runtime classes and collection reference arguments. Keep expected-IID queries for non-null values and extend generated native regressions for managed nulls, invalid inputs, and recovery. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- .../js/__test__/collection-factories.e2e.mjs | 76 +++++++++++++++++++ .../javascript-binding-internals.md | 3 + tools/dynwinrt-codegen/src/codegen/common.rs | 6 +- .../src/codegen/winrt/javascript/signature.rs | 14 +++- .../tests/collection_factory_test.rs | 47 ++++++++++++ tools/dynwinrt-codegen/tests/snapshot_test.rs | 4 +- .../snapshots/uri/windows/foundation/Uri.js | 2 +- 7 files changed, 144 insertions(+), 8 deletions(-) diff --git a/bindings/js/__test__/collection-factories.e2e.mjs b/bindings/js/__test__/collection-factories.e2e.mjs index e1cd7119..0566e1d3 100644 --- a/bindings/js/__test__/collection-factories.e2e.mjs +++ b/bindings/js/__test__/collection-factories.e2e.mjs @@ -145,6 +145,82 @@ test('runtime-class vector factories retain projected and managed inputs', (t) = assert.equal(keep(vector.getAt(1)).month, 3) }) +test('runtime-class vector factory preserves a managed null carrier', (t) => { + const keep = own(t) + const Vector = collection('IVector_WindowsApplicationModelContactsContactDate_') + const value = keep(require(runtimeRoot).DynWinRtValue.nullValue()) + const vector = keep(Vector.create([value])) + assert.equal(vector.size, 1) + assert.equal(vector.getAt(0), null) + assert.equal(value.isNull(), true) +}) + +test('runtime-class conversion preserves nulls and still rejects invalid non-null inputs', (t) => { + const keep = own(t) + const Vector = collection('IVector_WindowsApplicationModelContactsContactDate_') + const { DynWinRtValue } = require(runtimeRoot) + const nil = keep(DynWinRtValue.nullValue()) + const uri = keep(generated.Uri.createUri('https://example.invalid/wrong-interface')) + const scalar = keep(DynWinRtValue.i32(7)) + for (const invalid of [uri, uri._obj, scalar, {}, { isNull: () => true }]) { + assert.throws(() => Vector.create([invalid]), /QueryInterface|cast/) + } + let reads = 0 + const wrappedNull = { + get _obj() { + reads++ + return nil + }, + } + const date = keep(generated.ContactDate.create()) + date.month = 4 + const vector = keep(Vector.create([nil, wrappedNull, null, undefined, date, date._obj])) + assert.equal(reads, 1) + keep.release(date) + assert.equal(vector.size, 6) + for (let index = 0; index < 4; index++) assert.equal(vector.getAt(index), null) + assert.equal(keep(vector.getAt(4)).month, 4) + assert.equal(keep(vector.getAt(5)).month, 4) + vector.append(nil) + assert.equal(vector.size, 7) + assert.equal(vector.getAt(6), null) + assert.throws(() => vector.append(uri), /QueryInterface/) + vector.append(nil) + assert.equal(vector.size, 8) + assert.equal(vector.getAt(7), null) + const retained = keep(vector.getAt(4)) + vector.replaceAll([nil, retained]) + assert.equal(vector.size, 2) + assert.equal(vector.getAt(0), null) + assert.equal(keep(vector.getAt(1)).month, 4) +}) + +test('collection-valued map factories preserve managed nulls without weakening non-null QI', (t) => { + const keep = own(t) + const Map = collection('IMap_String_WindowsFoundationCollectionsIVectorView_WindowsDataTextTextSegment_') + const nil = keep(require(runtimeRoot).DynWinRtValue.nullValue()) + const uri = keep(generated.Uri.createUri('https://example.invalid/wrong-collection')) + for (const invalid of [uri, uri._obj, {}, { isNull: () => true }, null, undefined]) { + assert.throws(() => Map.create(['invalid'], [invalid]), /QueryInterface|cast/) + } + let reads = 0 + const wrappedNull = { + get _obj() { + reads++ + return nil + }, + } + const map = keep(Map.create(['managed', 'wrapped'], [nil, wrappedNull])) + assert.equal(reads, 1) + assert.equal(map.size, 2) + assert.equal(map.lookup('managed'), null) + assert.equal(map.lookup('wrapped'), null) + assert.throws(() => map.insert('wrong', uri), /QueryInterface/) + map.insert('later', nil) + assert.equal(map.size, 3) + assert.equal(map.lookup('later'), null) +}) + test('nested collection arguments use supported small-struct packing', (t) => { const keep = own(t) const Map = collection('IMap_String_WindowsFoundationCollectionsIVectorView_WindowsDataTextTextSegment_') diff --git a/docs/architecture/javascript-binding-internals.md b/docs/architecture/javascript-binding-internals.md index 85ccc711..0ea1498f 100644 --- a/docs/architecture/javascript-binding-internals.md +++ b/docs/architecture/javascript-binding-internals.md @@ -43,6 +43,9 @@ and values) using the same metadata-directed argument projection as ordinary methods. Native `createVector`/`createMap` receive managed `DynWinRtValue` carriers, not unconverted JavaScript primitives. Conversion does not expand the native producer's supported ABI or ownership boundary. +Runtime-class and collection-reference conversions preserve managed null +carriers without querying an interface; non-null carriers still query the +declared interface before being passed to native code. With the JS addon built, run `npm run test:collection-factories` from `bindings/js` for generated SDK factory roundtrips. `DYNWINRT_CODEGEN` selects diff --git a/tools/dynwinrt-codegen/src/codegen/common.rs b/tools/dynwinrt-codegen/src/codegen/common.rs index e7130eff..58c93126 100644 --- a/tools/dynwinrt-codegen/src/codegen/common.rs +++ b/tools/dynwinrt-codegen/src/codegen/common.rs @@ -320,7 +320,7 @@ mod tests { iid: "dc102dcc-3be2-5414-8599-94b6e76ef39b".into(), })), }; - let expected_cast = "_unwrap(value).cast(IID_ARG_Microsoft_UI_Xaml_Media_Geometry)"; + let expected_cast = "((value) => value instanceof DynWinRtValue && value.isNull() ? value : value.cast(IID_ARG_Microsoft_UI_Xaml_Media_Geometry))(_unwrap(value))"; assert_eq!( wrap_arg("value", &geometry), @@ -335,13 +335,13 @@ mod tests { }; assert!(wrap_arg("values", &vector).contains(&format!( "map(_i => {})", - expected_cast.replace("value", "_i") + expected_cast.replace("_unwrap(value)", "_unwrap(_i)") ))); let array = TypeMeta::Array(Box::new(geometry)); assert!(wrap_arg("values", &array).contains(&format!( "map(_i => {})", - expected_cast.replace("value", "_i") + expected_cast.replace("_unwrap(value)", "_unwrap(_i)") ))); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs index c92095f8..4909c08f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs @@ -391,8 +391,9 @@ pub(crate) fn wrap_arg( let elem_type = ts_dynwinrt_type(context, elem); let item_wrap = vector_item_wrap_expr(context, "_i", elem); let target_iid_expr = format!("{}.iid()", ts_dynwinrt_type(context, typ)); + let reference = nullable_reference_cast_expr(name, &target_iid_expr); return format!( - "(Array.isArray({name}) ? DynWinRtValue.createVector({name}.map(_i => {item_wrap}), {elem_type}).cast({target_iid_expr}) : _unwrap({name}).cast({target_iid_expr}))" + "(Array.isArray({name}) ? DynWinRtValue.createVector({name}.map(_i => {item_wrap}), {elem_type}).cast({target_iid_expr}) : {reference})" ); } } @@ -408,8 +409,9 @@ pub(crate) fn wrap_arg( let k_wrap = vector_item_wrap_expr(context, "_k", &args[0]); let v_wrap = vector_item_wrap_expr(context, "_v", &args[1]); let target_iid_expr = format!("{}.iid()", ts_dynwinrt_type(context, typ)); + let reference = nullable_reference_cast_expr(name, &target_iid_expr); return format!( - "({name} instanceof Map ? DynWinRtValue.createMap([...{name}.keys()].map(_k => {k_wrap}), [...{name}.values()].map(_v => {v_wrap}), {key_type}, {val_type}).cast({target_iid_expr}) : _unwrap({name}).cast({target_iid_expr}))" + "({name} instanceof Map ? DynWinRtValue.createMap([...{name}.keys()].map(_k => {k_wrap}), [...{name}.values()].map(_v => {v_wrap}), {key_type}, {val_type}).cast({target_iid_expr}) : {reference})" ); } } @@ -525,13 +527,19 @@ fn is_map_like(piid: &str, name: &str) -> bool { piid == PIID_IMAP || piid == PIID_IMAP_VIEW || name == "IMap" || name == "IMapView" } +fn nullable_reference_cast_expr(name: &str, iid: &str) -> String { + format!( + "((value) => value instanceof DynWinRtValue && value.isNull() ? value : value.cast({iid}))(_unwrap({name}))" + ) +} + fn runtime_class_wrap_expr( context: &JavaScriptProjectionContext, name: &str, typ: &TypeMeta, ) -> String { runtime_class_iid_const(context, typ) - .map(|(iid, _)| format!("_unwrap({}).cast({})", name, iid)) + .map(|(iid, _)| nullable_reference_cast_expr(name, &iid)) .unwrap_or_else(|| format!("_unwrap({})", name)) } diff --git a/tools/dynwinrt-codegen/tests/collection_factory_test.rs b/tools/dynwinrt-codegen/tests/collection_factory_test.rs index c1d7d78e..97de96df 100644 --- a/tools/dynwinrt-codegen/tests/collection_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/collection_factory_test.rs @@ -184,3 +184,50 @@ fn string_collection_factory_declarations_remain_native_js_arrays() { let (_, dts) = project_factory(MAP, vec![TypeMeta::String, TypeMeta::String]); assert!(dts.contains("static create(keys: string[], values: string[]): Collection;")); } + +#[test] +fn reference_factories_preserve_managed_nulls_before_querying_every_role() { + let class = TypeMeta::RuntimeClass { + namespace: "Windows.ApplicationModel.Contacts".into(), + name: "ContactDate".into(), + default_interface: Some(Box::new(TypeMeta::Interface { + namespace: "Windows.ApplicationModel.Contacts".into(), + name: "IContactDate".into(), + iid: "fe98ae66-b205-4934-9174-0ff2b0565707".into(), + })), + }; + let collection_type = |name: &str, piid: &str, args| TypeMeta::Parameterized { + namespace: "Windows.Foundation.Collections".into(), + name: name.into(), + piid: piid.into(), + args, + }; + for typ in [ + class.clone(), + collection_type("IVector", VECTOR, vec![class.clone()]), + collection_type("IMap", MAP, vec![class.clone(), class]), + ] { + for (piid, args, variables) in [ + (VECTOR, vec![typ.clone()], vec!["i"]), + (OBSERVABLE_VECTOR, vec![typ.clone()], vec!["i"]), + (MAP, vec![typ.clone(), typ.clone()], vec!["k", "v"]), + ] { + let (js, _) = project_factory(piid, args); + let factory = js.split("static create(").nth(1).unwrap(); + let guard = "value instanceof DynWinRtValue && value.isNull() ? value : value.cast("; + assert!(factory.contains(guard), "{factory}"); + for var in variables { + let unwrap = format!("_unwrap({var})"); + assert_eq!(factory.matches(&unwrap).count(), 1, "{factory}"); + assert!(factory.contains(&format!("))({unwrap})")), "{factory}"); + } + // Class elements in automatically converted arrays/maps must use + // the same null-preserving expected-IID query as direct inputs. + if matches!(typ, TypeMeta::Parameterized { .. }) { + assert!(factory.contains(&format!( + "{guard}IID_ARG_Windows_ApplicationModel_Contacts_ContactDate)" + ))); + } + } + } +} diff --git a/tools/dynwinrt-codegen/tests/snapshot_test.rs b/tools/dynwinrt-codegen/tests/snapshot_test.rs index 345fba9e..b9404fc4 100644 --- a/tools/dynwinrt-codegen/tests/snapshot_test.rs +++ b/tools/dynwinrt-codegen/tests/snapshot_test.rs @@ -185,7 +185,9 @@ fn snapshot_uri_class() { assert!(uri_js.contains( "const IID_ARG_Windows_Foundation_Uri = WinGuid.parse('9e365e57-48b2-4160-956f-c7385120bbfc');" )); - assert!(uri_js.contains("_unwrap(pUri).cast(IID_ARG_Windows_Foundation_Uri)")); + assert!(uri_js.contains( + "value instanceof DynWinRtValue && value.isNull() ? value : value.cast(IID_ARG_Windows_Foundation_Uri))(_unwrap(pUri))" + )); assert!( !uri_js.contains("_unwrap(pUri).cast(DynWinRtType.runtimeClass('Windows.Foundation.Uri'") ); diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js index 2245305f..73c68170 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/Uri.js @@ -181,7 +181,7 @@ class Uri { return (() => { const _m = _IUriRuntimeClass.method(20); return typeof _m.getBool === 'function' ? _m.getBool(this._obj) : _IUriRuntimeClass.method(20).invoke(this._obj, []).toBool(); })(); } equals(pUri) { - return _IUriRuntimeClass.method(21).invoke(this._obj, [(pUri == null ? DynWinRtValue.nullValue() : _unwrap(pUri).cast(IID_ARG_Windows_Foundation_Uri))]).toBool(); + return _IUriRuntimeClass.method(21).invoke(this._obj, [(pUri == null ? DynWinRtValue.nullValue() : ((value) => value instanceof DynWinRtValue && value.isNull() ? value : value.cast(IID_ARG_Windows_Foundation_Uri))(_unwrap(pUri)))]).toBool(); } combineUri(relativeUri) { return ((v) => v.isNull() ? null : Uri._fromNative(v))(_IUriRuntimeClass.method(22).invoke(this._obj, [DynWinRtValue.hstring(relativeUri)]));