A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
mobile-apps: use published npm templates and safe production upgrades (#664)
Shubham Agarwalb3a3fe0a7dbf
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.ymlindex 81533b452..aeebc3e03 100644--- a/.github/workflows/mobile-apps-script-tests.yml+++ b/.github/workflows/mobile-apps-script-tests.yml@@ -37,7 +37,13 @@ jobs:- name: syntax-check-mobile-templateshell: bash- run: node --check plugins/mobile-apps/template/metro.config.js+ run: |+ node --check plugins/mobile-apps/template/metro.config.js+ node --check plugins/mobile-apps/scripts/lib/mobile-release.js+ node --check plugins/mobile-apps/scripts/lib/mobile-published-packages.js+ node --check plugins/mobile-apps/scripts/lib/mobile-package-artifacts.js+ node --check plugins/mobile-apps/scripts/resolve-mobile-release.js+ node --check plugins/mobile-apps/scripts/mobile-template-lifecycle.js- name: run-mobile-apps-script-testsshell: bash@@ -45,7 +51,7 @@ jobs:run: node --test scripts/tests/*.test.jstest-mobile-apps-template:- name: test-mobile-apps-template (ubuntu, node 22)+ name: test-mobile-apps-legacy-preparation-fixture (ubuntu, node 22)runs-on: ubuntu-latestenv:POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: "1"diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.jsonindex 86ddbc3a7..7deccbd5f 100644--- a/plugins/mobile-apps/.claude-plugin/plugin.json+++ b/plugins/mobile-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.6.2",+ "version": "0.6.3","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.jsonindex 86ddbc3a7..7deccbd5f 100644--- a/plugins/mobile-apps/.plugin/plugin.json+++ b/plugins/mobile-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.6.2",+ "version": "0.6.3","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.mdindex 4c36a3b5f..eb5076138 100644--- a/plugins/mobile-apps/AGENTS.md+++ b/plugins/mobile-apps/AGENTS.md@@ -2,13 +2,13 @@This file provides guidance to AI Agents when working with the **mobile-app** plugin.-> **Status:** v0 — 24 skills + 5 agents authored. The latest Expo standalone template snapshot is bundled under `template/`. Read [README.md](./README.md) for the command list.+> **Status:** Preview. The bundled `template/` remains a legacy test fixture, not a release selector or an app-version-independent native allowlist. Read [README.md](./README.md) for the command list and release gate.## What This Plugin IsA plugin for building and deploying **Power Apps code apps that run as native mobile + web apps** using Expo + React Native + TypeScript. Connects to Power Platform via connectors using the standard `pa app add data-source` workflow.-The Expo template snapshot is distributed with this plugin under `template/` and published from [`plugins/mobile-apps/template`](https://github.com/microsoft/power-platform-skills/tree/main/plugins/mobile-apps/template). `/create-mobile-app` runs in fresh-template working-directory mode: the user starts in an installed template folder, then the skill validates and prepares it.+`/create-mobile-app` selects an exact published template package, acquires it only into a new/empty folder after approval, installs its lockfile after separate approval, then validates and prepares it. Existing fresh installed folders must match its package-owned host contract. See [mobile-release-lifecycle.md](shared/references/mobile-release-lifecycle.md); missing published compatibility metadata blocks native adoption.## Local Development@@ -32,7 +32,7 @@ hooks/ ← Telemetry start hooks plus validators invoked## Template source-The Expo template snapshot ships bundled inside this plugin at `template/`. It is synced from `microsoft/power-platform-skills` `main`, `plugins/mobile-apps/template/`. `/create-mobile-app` does not silently copy the bundled template over a user's folder; it expects a fresh installed template working directory and applies these preparation edits there:+The bundled `template/` is retained for existing preparation/source tests. Runtime selection comes from the published host's compatibility profile and the matching immutable template metadata/lock, not a plugin-owned release array, bundled snapshot or independently chosen npm `latest` dependencies. `/check-updates` keeps npm outdated discovery and delegates migration writes to the published target host. `/create-mobile-app` never copies the bundled snapshot over a user's folder. After immutable acquisition and package validation, preparation applies these bounded edits:| Edit | Purpose ||---|---|@@ -42,15 +42,30 @@ The Expo template snapshot ships bundled inside this plugin at `template/`. It i| Remove legacy example hooks and query-client files | Preserve every artifact under `src/generated/` || `app/_layout.tsx`: add `tamaguiConfig` + `defaultTheme` | Use host light/dark defaults until generated brand themes are explicitly wired || `app.json` + `app/_layout.tsx`: `appConfig` | Pass the complete generated app configuration once so the host can resolve opt-in Application Insights settings inside fixed Dev Player |-| `tsconfig.json`: verify the host base | Package shims and `@/` aliases remain centralized in the native host |+| `tsconfig.json`: verify the host base | Preserve both host inheritance and any version-specific project-rooted aliases |++Preparation preserves `app.json` compatibility metadata and customer extras byte-for-byte, together with scaffolded or customer-owned `AGENTS.md`, `CLAUDE.md`, and `.github/copilot-instructions.md`. Never synthesize runtime IDs from semver. Existing app instruction updates require a separately reviewed merge.++Only finalized published host/template packages authorize creation or native+upgrades. The former diagnostic artifact mode is retired; do not substitute a+local archive, a bundled template or a Git checkout for a missing publication.+Preserve normal approvals, telemetry checkpoints and app-owned offline profiles,+imports, settings and data.+The installed offline SDK must match the selected host's runtime family, peer+requirements and offline-contract version. Obtain its expected metadata and+complete declared native artifact inventory from the integrity-verified SDK+archive selected by the immutable template lock, never from mutable installed+hashes alone.+Metadata checks do not certify offline synchronization or database migration.+Never patch, fork or locally rewrite a first-party package to work around a defect.Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `src/playerConfig.ts`, `fingerprint.config.js`, or `native-runtime.json` unless those files exist in the synced main template.## Guiding Principles1. **Connector-first for data** — All Power Platform data access goes through connectors and generated services in `src/generated/`. No direct Graph / Azure REST calls.-2. **Native code is allowlist-bounded; pure JavaScript is app-scoped.** Expo modules and packages that ship native source, a podspec, codegen configuration, an Expo module/config plugin, or platform projects must already exist in `template/package.json`. The rewrap binary is built from a pre-built base, so adding those packages to an app cannot add their native code. Do not classify a package from its name alone: a `react-native-*` package can still be pure JavaScript. For an explicit library request or an approved use case that benefits from an established pure-JavaScript package, the planner may select a compatible version, pin it in the app's `package.json`, and install it before builders use it; no Android/iOS rebuild is required. Do not bundle optional libraries such as `react-native-calendars` in the base template. Follow [`shared/references/javascript-dependency-planning.md`](shared/references/javascript-dependency-planning.md). `expo-haptics` is template-shipped: add haptic behavior through `/add-native haptics`, keep native calls in `src/native/haptics.ts`, and pair tactile feedback with visible UI. When a template/base maintainer adds or changes a native dependency version, the Android and iOS base binaries must be rebuilt before release; generated apps based on that rebuilt template do not install or link it again. The native boundary and reconciliation rule are in [`skills/add-native/SKILL.md`](skills/add-native/SKILL.md).-3. **Fresh-template mode** — `/create-mobile-app` validates and prepares an existing fresh Expo standalone template working directory. Do not silently copy the bundled `template/` snapshot over the user's folder.+2. **Native code is version-bounded; pure JavaScript is app-scoped.** Use `scripts/resolve-mobile-release.js` to resolve the app's reviewed native inventory, including installed versions and transitive native code. The newest plugin template's names are not an old app's baseline. Adding packages cannot add native code to a fixed player/base; native changes require a coordinated reviewed release. Pure-JS additions retain explicit planning/approval and installed-closure validation. Follow [JavaScript dependency planning](shared/references/javascript-dependency-planning.md) and [the native boundary](skills/add-native/SKILL.md). Verify haptics/controls support in the resolved release before generating wrappers. Native binary changes require matching rebuilt Android/iOS bases and available players before policy promotion.+3. **Fresh-template mode** — acquire only an immutable verified package into a new/empty folder, or validate an existing fresh installed template. Never overwrite a customer project, use a mutable branch, or silently copy the bundled snapshot.4. **Safety guardrails** — Confirm before deploys, before global installs, before edits outside the project root.5. **Memory bank** — Persist `memory-bank.md` in the project root.6. **Plan mode** — Confirm requirements first. Gate 1 then presents native@@ -179,7 +194,7 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro- ✅ `/add-native` v0 scope: camera, location, push, biometrics, secure-store (already in template)- ✅ Build documentation: every run writes `docs/create-app-plan.html` - environment, requirements, architecture, a colour-coded Dataverse ER diagram, screen plan, design system, and live phase progress - in the Power Pages plan format. The page also carries a phone frame that advances from a building state to the generated screens to the device QR code. The folder survives the run so the app carries its own design record.- ✅ Cross-host Metro diagnostics: user-owned `npm run dev`, port-probe liveness and stale-PID protection, sanitized project-local logs, a durable debug cursor, and read-only `status` plus foreground-loop `stop` commands-- ✅ Template is supplied as a fresh `microsoft/power-platform-skills/plugins/mobile-apps/template#main` folder before `/create-mobile-app` runs; users materialize it with `degit`, run `npm install`, then invoke the skill from that folder. The skill validates/prepares the folder and runs `pa app init`.+- ✅ Template acquisition uses a verified exact package and lockfile; no default release is promoted until publication and both platforms' bases/players are verified.- ✅ `brand/` directory convention: `/design-system` (Step 6.75) writes `brand/design-system.md` (spec), `brand/tokens.ts` (importable Tamagui tokens), and `brand/design-system.html` (visual gallery). Screen-builders MUST read `brand/design-system.md` if present; `## Negatives` = HARD RULES. `/create-mobile-app` Step 9b imports `brand/tokens.ts` via `skills/design-system/references/tamagui-integration.md`. Projects without `brand/` fall back to `## Design Direction` only — no breakage.- ✅ Offline profile creation is **configuration-only in v0.1** —`/setup-offline-profile` and `/enable-tables-offline` POSTdiff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.mdindex 44882a4fc..4c05aa59e 100644--- a/plugins/mobile-apps/README.md+++ b/plugins/mobile-apps/README.md@@ -18,22 +18,10 @@ Start from the Power Platform mobile app template, then use the mobile-appskill to generate the app plan, data model, screens, native capabilities, andconnector wiring.-1. Create a new app from the template and install dependencies:+1. Install the mobile-app plugin before running its helper commands.- ```sh- npx degit microsoft/power-platform-skills/plugins/mobile-apps/template#main my-mobile-app- cd my-mobile-app- npm install- ```--2. Install the mobile-app plugin from the Power Platform Skills marketplace.-- 1. Open the Extensions pane.- 2. Enter `@agentPlugins mobile-app` in the search box.- 3. Select the **mobile-app** plugin and install it.- 4. Reload VS Code if prompted, then open Copilot Chat in Agent mode.-- Alternatively, install it from a terminal with GitHub Copilot CLI:+ In VS Code, open Extensions, search for `@agentPlugins mobile-app`, install+ **mobile-app**, and reload VS Code. Alternatively, use GitHub Copilot CLI:```shcopilot plugin marketplace add microsoft/power-platform-skills@@ -47,6 +35,53 @@ connector wiring.claude plugin install mobile-app@power-platform-skills --scope user```+ Restart the agent host after installation. Set `PLUGIN_ROOT` to the absolute+ installed plugin directory reported by that host; do not assume a cache layout:++ ```sh+ export PLUGIN_ROOT='/absolute/path/to/installed/mobile-app'+ ```++2. Discover published template versions:++ ```sh+ npm view @microsoft/power-apps-native-template dist-tags --json+ ```++ Select an exact version. After approving acquisition and dependency installation,+ run this guarded sequence from the intended parent directory:++ ```sh+ node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --template-version "<exact-template-version>" &&+ node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" acquire \+ --template-version "<exact-template-version>" --destination ./my-mobile-app &&+ cd -- ./my-mobile-app &&+ npm ci+ ```++ `${PLUGIN_ROOT}` is the installed mobile-app plugin directory. Acquisition+ and dependency installation require approval. The helper checks the exact+ package version, integrity, and compatibility manifest and never overwrites+ a non-empty target. A failed resolution, acquisition or directory change stops+ before installation. Use existing npm user/environment authentication; it+ does not provision registry credentials.++ **Package compatibility:** the helpers inspect published host/template metadata+ and the immutable template lock, not a manually populated skills release list.+ They check exact package integrity, native requirements and dependency+ inventory. Missing/unfinalized published contracts remain blockers. Player+ and Wrap availability are reported separately; npm publication does not+ establish either. Do not substitute a Git branch or bundled snapshot.+ See [the lifecycle contract](shared/references/mobile-release-lifecycle.md).++ The former local diagnostic artifact mode is retired. Missing published+ packages block creation/adoption; there is no Git, bundled-template or local+ archive fallback. Existing offline profiles and data remain app-owned.+ Versioned offline SDK contracts and native files are checked against the+ published host and the SDK archive's contract and artifact inventory, verified+ with the immutable template lock's integrity. This is not an offline+ synchronization or database-upgrade test.+3. Open the template folder in VS Code and run the skill from Copilot Chat:```text@@ -132,32 +167,38 @@ This template is provided under the license in `LICENSE`.The mobile-app plugin is stored in `plugins/mobile-apps` in the `power-platform-skills` marketplace. It works with GitHub Copilot in VS Code and Claude Code.-## Manual migration to a new template+## Updating an existing app-To migrate without `upgrade-template`, create a new app from the latest template-instead of modifying the old app in place. Commit or back up the old app first.+`/check-updates` **offers to update** a verified native release as a unit:+template migrations, host, Expo/React Native, native inventory, and matching+bases/players. It checks for stale templates even when the host was already+updated and supports same-template host repair. It previews every migration in+a disposable copy, then asks separately before applying the full reviewed+chain. Customer code, settings, local changes, and instruction files are preserved.-1. Create the new app and install its dependencies.-2. Copy the contents of `app/` and `src/` from the old app into the same- directories in the new app:+Managed/native packages are never offered as unrelated npm bumps. Pure-JS+dependencies retain individual approval, validation, rollback, and direct-advisory+auditing. Unsupported metadata, conflicts, unavailable releases, and incomplete+previews block changes rather than inventing state. See+[the lifecycle contract](shared/references/mobile-release-lifecycle.md).- ```bash- cp -R ../old-app/app/. app/- cp -R ../old-app/src/. src/- ```+When an old app has no supported migration, retain the original app and report+the missing route. Do not run the new-project CLI over it, replace its root+configuration wholesale, or rewrite its protected compatibility IDs.++## Existing native controls++When a verified release includes `@microsoft/power-apps-native-controls`,+`/add-native` routes PDF viewing, pen capture, and geolocation to its public+`/pdf`, `/pen`, and `/geolocation` subpaths. Older releases use only the leaf+APIs their binary actually ships; installing the aggregate is not a binary+upgrade. Barcode is not an aggregate subpath.-3. Copy app-owned assets and settings such as `assets/`, `auth.config.json`,- `power.config.json`, and `offline-profile.json` as needed. Review each file- before replacing the version supplied by the new template.-4. Keep the new template's `package.json`, root configuration files,- `android/`, and `ios/`. Reapply old customizations selectively rather than- copying these files wholesale.-5. Run `npm install`, `npm run type-check`, and the bundle command for each- target platform, such as `npm run bundle:android` or `npm run bundle:ios`.-6. Give the resulting errors to GitHub Copilot in Agent mode and ask it to- update the migrated `app/` and `src/` code for the new template APIs while- preserving the new template configuration. Review the changes and rerun the- failing command until the build succeeds.+The template owns the dependency; a compatible host owns plugin registration.+Merely adding the package does not grant runtime permissions or start tracking.+Existing Android library declarations can remain even for unused controls.+This workflow uses a fixed-capability base, not per-customer optional-permission+selection during wrapping. Different declarations require another verified base.## Hello world — your first run@@ -398,17 +439,17 @@ metadata alone never means the app is healthy.| Command | Status | Description || --- | --- | --- |-| `/create-mobile-app` | ✅ v0 | Orchestrator — starts from a fresh installed `expo-app-standalone` template folder, gates planning, runs `pa app init`, resolves the selected environment tenant, discovers tenant-visible app registrations and checks the complete required permission profile, lets the user select or create one (or skip auth), then applies data/native/connectors, builds screens, starts dev server |+| `/create-mobile-app` | ✅ v0 | Orchestrator — acquires an exact reviewed immutable template into a new/empty folder after approval, or validates an existing fresh installed app against its release. Separately approves installation, gates planning, runs the resolved `pa app init`, verifies environment/auth setup, then applies data/native/connectors, builds screens and starts the dev server. Missing release evidence blocks creation. || `/set-app-registration-native` | ✅ v0 | Auth helper — discovers tenant-visible app registrations, checks the applicable native runtime permission profile, opens the environment-specific Wrap page for creation or repair, and writes the selected client ID to `auth.config.json`. || `/add-dataverse` | ✅ v0 | Add Dataverse — connect to existing tables, or create / extend tables in Tier 0 → N order via the Dataverse Web API, then generate TS services. Accepts ER diagrams via image / Mermaid / text, or spawns the data-model-architect agent. || `/setup-datamodel` | ✅ v0 | Plan and approve a scoped Dataverse/connector change. Choose data-only work or full `/edit-app` integration; `--plan-only` returns a proposal without applying it. || `/add-connector` | ✅ v0 | Generic connector — runs `pa app add data-source` for any first-party or custom connector |-| `/add-native` | ✅ v0 | Add a supported native capability/control (camera, image-picker, barcode/QR scanner, document-picker, PDF viewer/report, pen/signature, secure-store, file-system, sharing, haptics, etc.) — verifies the module already ships in the template and writes typed wrappers under `src/native/` without installing native packages or editing `app.config.js` |+| `/add-native` | ✅ v0 | Add a supported native capability/control (camera, image-picker, barcode/QR scanner, document-picker, PDF viewer/report, pen/signature, secure-store, file-system, sharing, haptics, etc.) — resolves the app-matched reviewed native inventory and installed closure, then writes typed wrappers under `src/native/`. The newest bundled template is not the allowlist; missing native support requires a coordinated release, not an independent package install. || `/list-connections` | ✅ v0 | Finds or creates a Power Platform connection ID, or resolves a solution connection reference, for `pa app add data-source`. Use when adding non-Dataverse connectors or re-binding after a 401. || `/edit-app` | ✅ v0 | Post-generation app editor — updates affected sections of `native-app-plan.md`, applies Dataverse/native/design/connector changes, rebuilds affected screens, runs verification, updates `memory-bank.md`, and regenerates `preview.html` when UI changed. `--plan-only` preserves the old docs-only behavior. || `/debug-app` | ✅ v0 | Diagnoses install/startup/QR failures before an app is loaded, then monitors live sanitized `.powernative` logs for runtime or silent failures. Same-lock restoration and Metro restart require explicit approval; it does not upgrade dependencies. `startup` returns without the runtime monitor; `--no-fix` stays non-mutating. || `/setup-app-insights` | ✅ v0 | Configure optional customer-owned Application Insights telemetry — discover or accept an existing Azure resource and wire `app.json` → `expo.extra.appInsightsConfig` + `PowerAppsProvider`, change the resource, or disable it. Off by default; invoking it is the opt-in. Also delegated to by `/edit-app`. Never provisions Azure resources or stores the connection string. |-| `/check-updates` | ✅ v0 | Standalone dependency maintenance — checks for a plugin update and restart first, then presents, approves, updates, and validates direct packages one at a time in host, other `@microsoft/*`, and remaining npm package order. |+| `/check-updates` | ✅ v0 | Offers a coordinated verified native release/template upgrade or host repair, then individually approved JS-only updates and direct-advisory auditing. Full-chain preview, explicit application approval, validation, and rollback; never independent native bumps. || `/deploy` | ✅ v0 | Build + push — `npm run build` then `pa app push` to the env in `power.config.json`. **Does not** drive `expo run:ios` or `expo run:android` (out of scope for v0). || `/open-wrap-url` | ✅ v0 | Opens the Wrap URL in browser for an app ID using `https://make.powerapps.com/environments/<envID>/wrap?appID=<appID>`. Requires both `--app-id` and `--env-id`. || `/report-issue` | ✅ v0 | Read-only diagnostic — collects env / Expo / Node versions, project context, recent errors, and renders a copy-paste-ready GitHub issue body. Sanitizes secrets. |@@ -458,6 +499,6 @@ Control the per-user transmission preference with:## See also-- [`plugins/mobile-apps/template`](https://github.com/microsoft/power-platform-skills/tree/main/plugins/mobile-apps/template) — bundled Expo standalone template and fresh-template working directory source+- [`plugins/mobile-apps/template`](https://github.com/microsoft/power-platform-skills/tree/main/plugins/mobile-apps/template) — legacy preparation/test fixture and missing-guidance defaults; not an app-template acquisition source- [Expo docs](https://docs.expo.dev/)- [Power Apps developer docs](https://learn.microsoft.com/en-us/power-apps/developer/)diff --git a/plugins/mobile-apps/agents/data-model-architect.md b/plugins/mobile-apps/agents/data-model-architect.mdindex a23a6cb0a..4069184f1 100644--- a/plugins/mobile-apps/agents/data-model-architect.md+++ b/plugins/mobile-apps/agents/data-model-architect.md@@ -52,6 +52,15 @@ or standalone `/add-dataverse` with a prompt that includes:## Hard Rules+- **Preserve the app-matched release context.** Read+ [release lifecycle](../shared/references/mobile-release-lifecycle.md).+ Carry the orchestrator's sanitized resolved context with approved native+ capabilities; do not derive support from the newest bundled template.+ Unknown/missing release records do not prohibit read-only data/source+ planning, but native use remains blocked/unverified. One-shot location+ needs no tracking table or data source. Continuous geolocation target+ verification belongs to `/add-native geolocation`; do not invent an API or+ provision its package-owned table as an app-model workaround.- **Read-only.** You MUST NOT run `pa app add data-source --connector dataverse --org-url <env-url> --table <table>`, table-creation HTTP calls, or any mutating PowerShell. Mutation happens later in `/add-dataverse` after user approval.- **Scoped proposals preserve the owner.** For setup/edit/standalone changeplanning, use [dataverse-change-planning.md](../shared/references/dataverse-change-planning.md).diff --git a/plugins/mobile-apps/agents/native-app-planner.md b/plugins/mobile-apps/agents/native-app-planner.mdindex 60f9e7798..e04a7dcc2 100644--- a/plugins/mobile-apps/agents/native-app-planner.md+++ b/plugins/mobile-apps/agents/native-app-planner.md@@ -31,6 +31,9 @@ You will be invoked by `/create-mobile-app` with a prompt that includes:- Dataverse planning mode: `required` or `connector-only` in `complete` phase- Architecture phase: `gate-only` or `complete`- Approved architecture artifact path for `complete` phase+- Sanitized resolved release context for this app (template, host, Expo, React+ Native, native inventory, and verified player/base), or explicit unresolved+ status for existing source-only work## Hard Rules@@ -99,15 +102,24 @@ The orchestrator's Step 3 has a documented inline-gate fallback for exactly thisRead these references once before doing anything else:- `${PLUGIN_ROOT}/AGENTS.md` — plugin conventions-- `${PLUGIN_ROOT}/template/package.json` — **the native-code allowlist**. The set of modules with native code/config is fixed by the rewrap pipeline; you may NEVER propose a native capability whose module is not present here. Pure-JavaScript app dependencies are planned separately by `screen-planner` under `## Screens` and need not be bundled in this template.+- `${PLUGIN_ROOT}/shared/references/mobile-release-lifecycle.md` — the app-matched+ verified release policy. Use the orchestrator's sanitized resolved context;+ the newest bundled template is not the runtime allowlist.+- `${PLUGIN_ROOT}/skills/add-native/references/native-controls.md` — conditional+ controls subpaths, legacy leaf support, permissions, and location ownership.- `${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md` — ownshow offline and connectivity wording is handled during creation.-Do NOT attempt to read `app.config.js` from the working directory — scaffolding has not run yet. Reading `template/package.json` from `${PLUGIN_ROOT}` IS allowed and IS required.+Do not assume scaffolding has completed or infer a runtime from plugin files.+If the release context is missing, request it from the orchestrator or resolve+read-only with `node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'`.+Unknown/missing records block native capability approval for implementation.+Existing pure source/UI planning may continue explicitly unverified; do not+turn a plan-only proposal into a native-readiness claim.From the planner prompt extract:- **Target platforms** — always iOS + Android. The foreground does not ask the user to choose a subset; retain platform-specific fallback behavior for both.-- **Native capability hints** — words like "photo", "camera" -> `camera` with `expo-image-picker`; "scan", "barcode", "QR" -> `barcode-scanner` with `expo-camera`; "pick file", "upload PDF", "import document", "attach file" -> `expo-document-picker`; "generate PDF", "export report", "print report", "evidence packet" -> `pdf-report` (`expo-print` plus optional `expo-sharing`); "view PDF", "open PDF", "preview PDF" -> `native-pdf-viewer` for HTTPS URLs or local `file://` URIs with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+; "signature", "sign off", "approval", "pen", "ink", "draw" -> `pen-input` with `@microsoft/power-apps-native-pen-input`; "track location", "background location", "GPS tracking", "follow my route", "breadcrumb", "field worker location" -> `geolocation` with `@microsoft/power-apps-native-bglocation` (continuous/background tracking + Dataverse sync); "where am I", "current location", "one-shot location", "tag this with my coordinates" -> one-shot `location` with `expo-location`; "save token", "credentials" -> `expo-secure-store`; "share / send" -> `expo-sharing`; "save file / download" -> `expo-file-system`. **Capability hints that the template does NOT ship** (including PDF viewer, PDF report, sharing, pen, or geolocation packages when absent) are surfaced to the user as transparency notes per Step 3 - never silently promoted into the plan. If the request is generated-report-shaped and the Power Apps PDF viewer package is absent, fall back to `pdf-report` only when `expo-print` is present; otherwise drop the PDF capability.+- **Native capability hints** - photo/camera -> `camera` with `expo-image-picker`; scan/barcode/QR -> `barcode-scanner` with `expo-camera`; user-picked files -> document-picker or a Dataverse host picker; generated reports -> pdf-report; arbitrary HTTPS/local-file PDF viewing -> pdf-viewer; signature/ink -> pen-input; continuous route/worker tracking -> geolocation; a single coordinate -> location; secrets -> secure-store; local sharing -> sharing. Resolve these semantics against this app's native inventory and the version-conditional controls reference in Step 3, not a newest-template package list. Missing support is a transparency note, never a silently approved capability. PDF generation is not a substitute for arbitrary PDF viewing; generate reports only when the resolved runtime includes the required print/sharing APIs.- **Pure-JavaScript dependency hints** — pass any explicit JavaScript-library request, or any feature that may benefit from an established JS-only package instead of custom code, to `screen-planner`. These are app dependencies, not native capabilities. The screen planner reuses suitable installed packages first; otherwise it follows the canonical candidate-selection workflow and records the selected package with an exact version under `## Screens → ### JavaScript Dependencies`.- **Industry confirmed** — if the prompt contains a line `Industry confirmed: <slug>`, the orchestrator already ran the industry-confidence check (see Step 3c). Treat that slug as the locked industry for Step 3c — skip detection, skip the confidence check, jump straight to mapping the industry to aesthetic direction / palette / tone.@@ -133,25 +145,43 @@ external-system decisions can change schema and storage requirements.## Step 3 — Plan Native Capabilities Inline (Gate 1 input)**Print before starting:**-> "→ [2/4] Building native capabilities matrix from requirements (allowlist-bounded against template/package.json)…"+> "→ [2/4] Building native capabilities matrix from requirements and the app-matched verified release…"Build the native capabilities matrix yourself (this is a small enough surfaceto keep in-house). Screen planning has not run yet, so tie each capability tothe confirmed workflow or use case that requires it.-**Important:** the upstream template owns iOS Info.plist keys, Android permissions, and config plugins for every shipped module. Do NOT specify those here — the planner does not pick permission strings, and downstream `/add-native` helpers do not edit `app.config.js` or `package.json`. The matrix only records *which* capabilities the app uses and *why*.+**Important:** the verified fixed-capability base owns OS declarations and config+plugins. The matrix records usage, not permission selection. Keep package+inclusion, OS declarations, runtime grants, and app usage distinct. Omitting+controls does not remove default Android permissions. Different declarations+require another verified base; optional permission wrapping is deferred.-### Step 3.0 — Build the allowlist (MANDATORY, before any cap is proposed)+### Step 3.0 — Resolve the native inventory (MANDATORY, before native approval)-The set of modules with native code/config that the rewrap pipeline supports is FIXED by `${PLUGIN_ROOT}/template/package.json`. You may NEVER propose a native capability whose underlying module is not present there — the customer's binary is built from a pre-built base, not from their `package.json`. Adding a native module to the plan that's not shipped means a downstream `/add-native` call WILL stop, and the orchestrator's whole flow stalls at Step 9. This restriction does not apply to verified pure-JavaScript dependencies; do not infer native code from a package-name prefix.--Read the template's `package.json`:+Use the app-version-matched resolved inventory, not the newest template or npm+publication. A customer's manifest cannot add native code to its player/base.+This restriction does not apply to verified pure-JavaScript dependencies.+Do not infer native code from a package-name prefix.```bash-node -e "const p = require('${PLUGIN_ROOT}/template/package.json'); console.log(Object.keys({...p.dependencies, ...p.devDependencies}).sort().join('\n'));"+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'```-Map each shipped module to a user-facing capability slug. Use this known mapping table, but still gate every row against the live allowlist output; a listed capability is supported only when its exact package appears in `template/package.json` and is not runtime-banned.+Carry the sanitized resolved context unchanged to every architect, screen+planner, revision, and downstream builder. Missing published compatibility+metadata blocks native mutations; it is not evidence that every package is supported.+Inspect `nativePackages` for canonical `node_modules`-relative package paths+and exact reviewed versions, including nested native dependencies. Inspect+`managedDependencies` for published host dependency declarations. These are package+metadata, not absolute project paths, raw manifests, or lockfile download URLs.+Do not collapse distinct nested package versions into a name-only allowlist.+Planning-only `--requirements-only` output cannot authorize native mutation.+Map the resolved packages to capabilities using this table; every “present”+condition below also requires matching versions and native support.+This is capability-planning guidance, not a migration step: it does not install+the Controls bundle or rewrite existing imports. `/check-updates` owns any+separately approved release migration.| Capability | Module | Add via ||---|---|---|@@ -160,13 +190,13 @@ Map each shipped module to a user-facing capability slug. Use this known mapping| `barcode-scanner` | `expo-camera` | `/add-native barcode-scanner` || `document-picker` | `expo-document-picker` | `/add-native document-picker` || `pdf-report` | `expo-print` (+ `expo-sharing` when local share is needed and present) | `/add-native pdf-report` |-| `native-pdf-viewer` | `@microsoft/power-apps-native-pdf-viewer` | `/add-native pdf-viewer` |-| `pen-input` | `@microsoft/power-apps-native-pen-input` | `/add-native pen-input` |-| `geolocation` | `@microsoft/power-apps-native-bglocation` | `/add-native geolocation` |+| `native-pdf-viewer` | Resolved controls `/pdf` or matching legacy PDF leaf | `/add-native pdf-viewer` |+| `pen-input` | Resolved controls `/pen` or matching legacy pen leaf | `/add-native pen-input` |+| `geolocation` | Resolved controls `/geolocation` or matching background-location leaf | `/add-native geolocation` || `secure-store` | `expo-secure-store` | — || `file-system` | `expo-file-system` | — || `sharing` | `expo-sharing` | — |-| `location` | `expo-location` | `/add-native location` |+| `location` | Resolved controls `/geolocation` or matching leaf; independently verified `expo-location` | `/add-native location` (one-shot) || `biometrics` / `local-authentication` | `expo-local-authentication` | `/add-native biometrics` || `clipboard` | `expo-clipboard` | `/add-native clipboard` || `mail-composer` / `email-draft` | `expo-mail-composer` | `/add-native mail-composer` |@@ -179,10 +209,26 @@ Map each shipped module to a user-facing capability slug. Use this known mappingFor custom workflows outside Dataverse File/Image form fields, plan `image-picker` with `/add-native image-picker` for user-selected photos and videos, or `document-picker` with `/add-native document-picker` for documents and other files. For Dataverse-bound File/Image fields, plan host `<FilePicker>` / `<ImagePicker>` controls instead. Do not plan broad media-library access when either scoped picker path satisfies the workflow.-Do not propose `native-pdf-viewer` or `pen-input` unless the exact extension package is present in the template allowlist output (`@microsoft/power-apps-native-pdf-viewer` and `@microsoft/power-apps-native-pen-input`). Do not propose `geolocation` unless `@microsoft/power-apps-native-bglocation` is present, and only for continuous/background tracking or durable Dataverse upload — use one-shot `location` (`expo-location`) for a single foreground coordinate read. When proposing `geolocation`, record that its Dataverse target table must already exist and must be verified by `/add-native geolocation` (default entity set `msdyn_locationrecords`, or a custom `tableName` whose `fieldMap` columns exist). Do not propose `pdf-report` unless `expo-print` is present. Do not propose local sharing for generated PDFs unless `expo-sharing` is present. If neither package path is present, drop the PDF capability and add a transparency note.+Select aggregate subpaths only when the verified release includes controls;+retain legacy imports only when matching leaves are included. Controls 0.2.0+uses an Expo 55 / React Native 0.83.6 baseline, not Expo 57. Do not install the+aggregate to fix an older binary. Host `enableNativeControls` registration+requires a verified supporting host; published host 0.4.0 lacks it.++One-shot `location` via `new BgLocationClient().getCurrentLocation()` needs no+`app_id`, data source, table, or `startTracking`. Continuous `geolocation`+requires the existing `msdyn_locationrecords` table and mapped columns to be+verified by the helper. Background-location 0.2.3 `startTracking` uses background+permissions even with `trackInBackground: false`; tracking is shared and+`stopTracking()` / `isTracking()` have no `app_id`. Plan one coordinated owner.+Do not import the unrelated `configureSync` / `HttpSyncContract` API.++Do not propose `pdf-report` unless `expo-print` is in the resolved inventory;+local sharing additionally requires `expo-sharing`. Missing required support+must be addressed at Gate 1, not replaced with fake wrappers.PDF fallback order:-1. Existing HTTPS PDF URL or local `file://` URI + `@microsoft/power-apps-native-pdf-viewer` 0.2.9+ present -> `native-pdf-viewer`.+1. Existing HTTPS PDF URL or local `file://` URI + resolved PDF contract with 0.2.9+ file support -> `native-pdf-viewer`.2. App-generated PDF + `expo-print` present -> `pdf-report`.3. App-generated PDF + `expo-print` and `expo-sharing` present -> `pdf-report` plus `sharing` when sharing is required.4. User-selected/uploaded PDF -> `document-picker` or Dataverse host `<FilePicker>` when those packages/controls are present.@@ -198,13 +244,14 @@ Control planning gate:PDF/pen inference rules:- `document-picker` means user-selected local files only: pick/import/upload PDF/document/attachment.- `pdf-report` means app-generated PDFs. Local output is shared with `expo-sharing` only when that package is present. Retention uses an approved Dataverse File column or a supported connector-owned storage operation; do not force a Dataverse model for a connector-owned PDF.-- `native-pdf-viewer` means opening an HTTPS PDF URL or local `file://` URI with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+. It does not support `content://`, `blob:`, or `http://`.-- `pen-input` means signature/ink capture with `@microsoft/power-apps-native-pen-input`. It returns a PNG data URI. When retained, use an approved Dataverse Image/File/child-row target or a supported connector-owned storage operation with an explicit conversion/upload path; use on-device/share-only only when retention is not required.-- `geolocation` means continuous/background GPS tracking with durable storage and inline Dataverse sync via `@microsoft/power-apps-native-bglocation`. Auth is MSAL-only; native uploads each fix to an existing Dataverse table (default entity set `msdyn_locationrecords`). It is distinct from one-shot `location` (`expo-location`). Plan it only for continuous tracking or durable upload, require `/add-native geolocation` to verify the target table exists before use, and never propose the `GeolocationExtension`/HostingSDK path.+- `native-pdf-viewer` means opening HTTPS or local `file://` PDFs with the resolved `/pdf` or matching legacy contract. It does not support `content://`, `blob:`, or `http://`.+- `pen-input` means signature/ink capture with the resolved `/pen` or matching legacy contract. It returns a PNG data URI. When retained, use an approved Dataverse Image/File/child-row target or a supported connector-owned storage operation with an explicit conversion/upload path; use on-device/share-only only when retention is not required.+- `geolocation` means continuous tracking with native durable storage and Dataverse sync via the resolved `/geolocation` or matching leaf contract. Auth is MSAL-only. It is distinct from one-shot `location`; never require a target table for a single coordinate read, and never propose the `GeolocationExtension`/HostingSDK path.- `haptics` means supplemental tactile feedback through `expo-haptics`. Record the interaction and feedback kind in the screen spec: impact (`light`, `medium`, `heavy`, `soft`, or `rigid`) for deliberate actions, selection for changed selections, or notification (`success`, `warning`, or `error`) after a completed outcome. Every haptic must accompany visible UI feedback.-- The Power Apps extensions are use-case-specific, not generic replacements for Expo modules. For other native needs, choose the relevant Expo module or dependency already present in `template/package.json` and still enforce the allowlist.+- Native controls are use-case-specific. For other native needs, choose a package already in the app's resolved inventory and enforce its installed public contract.-**Capabilities not present** — do not propose anything with required native code/config whose exact package is absent, `expo-notifications` unless a future template ships it, or Bluetooth/NFC/BLE/AR without a shipped package.+**Capabilities not present** — do not approve anything with required native+code/config whose exact package/version is absent from the verified release.### Pure-JavaScript dependency handoff@@ -213,7 +260,7 @@ Do not put JS-only libraries in `## Native Capabilities` and do not route them tIf the requirements imply one of these, DROP the capability and add a transparency note to the `## Native Capabilities` section so the user sees what was excluded and why:```markdown-> Excluded — requirements suggested **push notifications**, but the template does not ship `expo-notifications`. The app cannot include native notifications until the upstream template adds it. File a request at the template repo if you need this.+> Excluded — the app's resolved release does not include the requested native notification capability. A verified release with matching player/base support is required; installing a package cannot add it.```One transparency line per excluded capability, capped at three lines. If more than three were dropped, list the top three and roll up the rest as `> Additionally excluded: <comma-separated list>.`@@ -861,7 +908,7 @@ Sections approved:Next steps for the orchestrator:1. Auth + environment selection- 2. Use the user-prepared fresh template folder materialized from `microsoft/power-platform-skills/plugins/mobile-apps/template#main` with `degit`+ 2. Use the orchestrator-approved fresh app from the exact stable published npm template and its verified package creation CLI; reuse the separately approved shipped-lock `npm ci` installation.3. $PA app init -t MobileApp --display-name <name> --environment-id <environment-id> --non-interactive4. If Dataverse was approved, apply data model via /add-dataverse using the plan5. Apply native capabilities via /add-native using the plandiff --git a/plugins/mobile-apps/agents/offline-profile-architect.md b/plugins/mobile-apps/agents/offline-profile-architect.mdindex 1dacadcf1..c49c011da 100644--- a/plugins/mobile-apps/agents/offline-profile-architect.md+++ b/plugins/mobile-apps/agents/offline-profile-architect.md@@ -46,6 +46,14 @@ Planning grants no mutation approval. Write only## Hard Rules+- **Preserve the app-matched release context.** Read+ [release lifecycle](../shared/references/mobile-release-lifecycle.md) and+ carry the orchestrator's sanitized resolved context or explicit unresolved+ status. The newest bundled template is not proof of native offline support.+ Profile scope planning remains read-only and may continue when native+ compatibility is unverified; do not claim the installed player/base has+ passed native validation. Missing release evidence blocks native mutations+ and deployment, not a read-only schema/profile proposal.- **Read-only.** You MUST NOT POST to `/mobileofflineprofiles`, PUT EntityMetadata, or call `pa app add data-source`. Mutation happens later in `/setup-offline-profile` after user approval through 3 gates.- **Reuse existing profiles.** Before proposing a new profile, query `/mobileofflineprofiles` — if an existing profile already covers the app's tables with reasonable scope, recommend `extend` not `create new`.- **Return a section, not a separate doc.** Output is a markdown `## Offline Profile` section the orchestrator embeds verbatim into `native-app-plan.md`.diff --git a/plugins/mobile-apps/agents/screen-builder.md b/plugins/mobile-apps/agents/screen-builder.mdindex 253adfe41..344f89a7a 100644--- a/plugins/mobile-apps/agents/screen-builder.md+++ b/plugins/mobile-apps/agents/screen-builder.md@@ -27,6 +27,18 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil## Hard Rules+- **App-matched release context.** Read+ [release lifecycle](../shared/references/mobile-release-lifecycle.md) and use+ the orchestrator's sanitized resolved context, not the newest bundled+ template. A missing context is `NEEDS_CONTEXT`; unknown/missing release+ records block new/changed native use. Existing pure source/UI work may+ continue against installed APIs with native compatibility explicitly+ unverified. Never install/upgrade a host, Expo package, controls aggregate,+ or leaf to make a screen compile, and never claim native validation from tsc.+ Preserve and forward the same context on any handoff.+ Release-matched installed APIs take precedence over illustrative samples in+ this file; do not adopt a newer host/Tamagui/Expo API merely because an example+ uses it. For an unavailable required API, return `NEEDS_CONTEXT`, not a shim.- **MANDATORY progress reporting.** Every step in the workflow has a `**Print before starting:**` block. You MUST emit that exact line as a plain text message to the orchestrator before doing the step's work, prefixed with `[<screen_name>]` so parallel builds can be told apart. Do not skip, do not paraphrase. Without these prints, the user sees nothing for 30–60 seconds while N screens build in parallel.- **Write exactly one screen file.** No new hooks, no new services beyond your assigned screen file. **`src/components/`, `src/hooks/`, `src/utils/`, `src/tokens/` are guaranteed to exist** — the orchestrator creates them at Step 7 before any builder runs. NEVER create or modify these shared files from a builder. If `src/components/index.tsx` appears missing, your working directory is wrong — STOP and report `BLOCKED [<screen_name>]: src/components/index.tsx is missing — orchestrator should have created it at Step 7`.- **Use shared code via path aliases — NEVER re-define inline.** The project has `@/components`, `@/hooks`, `@/utils`, `@/tokens` configured in tsconfig. Import from them:@@ -93,7 +105,7 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil| Tokens: `$4`, `$color12`, `$background`, `$sm` | Screen options: `<Stack.Screen options={{ presentation: 'modal' \| 'formSheet', headerSearchBarOptions, headerLargeTitle }}>` || Theme switching, breakpoints (`useMedia()`) | Scroll insets: `<ScrollView contentInsetAdjustmentBehavior="automatic">` || | Platform branching: `process.env.EXPO_OS`, `useWindowDimensions` |- | | Capabilities: `expo-camera`, `expo-document-picker`, `expo-print`, `expo-secure-store`, `expo-file-system`, `expo-sharing`, `@microsoft/power-apps-native-pdf-viewer`, `@microsoft/power-apps-native-pen-input`, `@microsoft/power-apps-native-bglocation` when allowlisted by the plan (see AGENTS.md §2) |+ | | Capabilities: only packages/versions in the app's resolved native inventory; controls use approved wrappers and release-conditional subpaths || | Animations: Reanimated |**Translation rule:** when the Expo `building-native-ui` skill shows `<View style={{ padding: 16, gap: 8 }}>`, write `<YStack p="$4" gap="$2">`. When it shows `<Stack.Screen options={{...}}>`, copy that **verbatim** — Tamagui never replaces navigation primitives.@@ -219,7 +231,27 @@ You will be invoked by `/create-mobile-app` Step 11 or `/edit-app` screen-rebuil- **Dataverse image rendering rule (detail/list screens).** If a screen displays a Dataverse Image column, include the real image/base64 field in `select` and render a `data:image/<mime>;base64,...` URI when base64 is present. Do not rely on guessed URL/display pseudo-fields alone.-- **Native capabilities use `src/native/` wrappers.** `/add-native` creates typed wrappers under `src/native/` (e.g., `camera.ts`, `cameraUpload.ts`, `secureStore.ts`, `documentPicker.ts`, `pdfReport.ts`, `pdfViewer.ts`, `penInput.ts`, `geolocation.ts`, `haptics.ts`). For non-Dataverse native workflows, screen files import these wrappers; the wrapper implementation owns imports from `expo-camera`, `expo-image-picker`, `expo-document-picker`, `expo-print`, `expo-secure-store`, `expo-file-system`, `expo-sharing`, `expo-haptics`, `@microsoft/power-apps-native-pdf-viewer`, `@microsoft/power-apps-native-pen-input`, or `@microsoft/power-apps-native-bglocation`. The wrappers handle permissions, iOS/Android platform differences, URL validation, and return discriminated-union results (`{ ok: true, ... } | { ok: false, reason }`). If a wrapper doesn't exist yet, write the screen with the expected import path and a `// TODO(native-not-yet-added): run /add-native <capability> to create src/native/<wrapper>.ts` comment. For `camera.ts`, use `/add-native camera`; for `barcodeScanner.tsx`, use `/add-native barcode-scanner`; for `pdfReport.ts`, use `/add-native pdf-report`; for `pdfViewer.ts`, use `/add-native pdf-viewer` or `/add-native @microsoft/power-apps-native-pdf-viewer`; for `penInput.ts`, use `/add-native pen-input` or `/add-native @microsoft/power-apps-native-pen-input`; for `geolocation.ts`, use `/add-native geolocation` or `/add-native @microsoft/power-apps-native-bglocation`; for `haptics.ts`, use `/add-native haptics`. `expo-notifications` remains unavailable. If the plan tells you to use an unavailable capability, return `NEEDS_CONTEXT`.+- **Native capabilities use existing `src/native/` wrappers.** `/add-native`+ owns `camera.ts`, `barcodeScanner.tsx`, `pdfReport.ts`, `pdfViewer.ts`,+ `penInput.ts`, `location.ts`, `geolocation.ts`, and `haptics.ts`. For+ non-Dataverse native workflows, import these wrappers only after they exist+ and their APIs match the approved spec. A missing wrapper is `BLOCKED`, never+ a TODO import or fake implementation. Wrappers guard the native platform+ before lazy imports and return discriminated results. Read the+ [conditional controls contract](../skills/add-native/references/native-controls.md):+ the aggregate root is metadata; runtime subpaths are `/pdf`, `/pen`, and+ `/geolocation`, with no barcode subpath. Legacy leaf imports require matching+ resolved inventory. Do not install the aggregate to fix older binaries.+- **Location mode is explicit.** One-shot `BgLocationClient.getCurrentLocation()`+ requires no `app_id`, data source, table, or `startTracking`. Continuous+ tracking has one coordinated owner; do not stop shared tracking when a+ screen unmounts. Background-location 0.2.3 uses background permissions even+ with `trackInBackground: false`; `stopTracking()` and `isTracking()` have no+ `app_id`. Do not introduce `configureSync` / `HttpSyncContract`.+- **Usage is not permission selection.** Keep package inclusion, OS declarations,+ runtime grants, and app use distinct. Disabling controls does not remove+ default Android permissions. A different declaration set requires another+ verified base; optional per-customer permission wrapping is deferred.- **Planned pure-JavaScript dependencies may be imported directly.** Follow `${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md`'s Builder Contract. Before importing any non-template package, verify it appears with an exact version in `## Screens → ### JavaScript Dependencies` and in the project's `package.json` `dependencies`, and that `require.resolve('<package>', { paths: [working_dir] })` succeeds. If the plan lists it but installation is missing, return `BLOCKED [<screen_name>]: approved JavaScript dependency <package>@<version> is not installed — orchestrator must install dependencies before builders run.` If it is not in the approved table, return `NEEDS_CONTEXT` instead of adding it yourself. Builders never select packages, edit `package.json`, or run installs. Import and use only the package APIs named by the approved per-screen spec.diff --git a/plugins/mobile-apps/agents/screen-planner.md b/plugins/mobile-apps/agents/screen-planner.mdindex 25ace9e71..78fdb8ccf 100644--- a/plugins/mobile-apps/agents/screen-planner.md+++ b/plugins/mobile-apps/agents/screen-planner.md@@ -34,6 +34,15 @@ You will be invoked by `native-app-planner` in parallel with `data-model-archite## Inputs You Can Rely OnThe planner gives you:+- Sanitized app-matched resolved release context, or explicit unresolved status+ for existing pure source/UI work. Read+ [release lifecycle](../shared/references/mobile-release-lifecycle.md); use the+ same context throughout planning and builder handoffs. Do not use the newest+ bundled template as a runtime allowlist. Unknown/missing release records+ block new/changed native use, not pure source/UI planning. Mark native+ compatibility unverified; approval and previews are not native validation.+ Treat sample APIs as illustrative: verify them against installed release+ docs/types before planning their use, rather than assuming newest-host APIs.- App requirements (`$ARGUMENTS`)- Target users + device class (phone/tablet, internal/external)- Target platforms (iOS / Android)@@ -55,12 +64,12 @@ The orchestrator uses separate graph and specs gates so the user can edit the sc**Hard rule — single-write in `phase: specs`.** Assemble the complete replacement, including the Step 6 markdown summary when requested, before one update to `plan_path`. A retry replaces the previous specs-owned output; it never adds a second copy. Do not write `_screens_section.md` or delete old sections in a separate operation before inserting their replacements.-**The scaffolded project IS available at `<working_dir>/`.** The orchestrator's Step 2d background pipeline finishes the full template scaffold (clone → fixes → npm install → `pa app init -t MobileApp --display-name <name> --environment-id <environment-id> --non-interactive` → schemas → tsc smoke) in parallel with your run. By the time you start, `<working_dir>/` is populated with the complete template tree. Safe to `Glob` and `Read`:+**The scaffolded project at `<working_dir>/` comes from the reviewed published npm template.** The orchestrator owns acquisition through the package's creation CLI and the separately approved shipped-lock `npm ci` installation under the fresh-template gate. Step 2d does not run a background scaffold pipeline. Template preparation and app initialization are later foreground-only steps; do not assume shared helpers, generated schemas or environment binding are already prepared. Do not create another scaffold or install dependencies during planning. Safe to `Glob` and `Read` existing files:- `<working_dir>/app/index.tsx`, `app/login.tsx`, `app/oauth-callback.tsx`, `app/(app)/_layout.tsx`, `app/(app)/home.tsx` — existing routes- `<working_dir>/tamagui.config.ts` — design tokens- `<working_dir>/package.json` — installed dependencies. Native modules must already be present; a verified pure-JavaScript library may instead be proposed with an exact version under `## Screens → ### JavaScript Dependencies` for the orchestrator to install before screen generation.-- `<working_dir>/src/components/`, `src/hooks/`, `src/utils/`, `src/tokens/` — shared code copied by the orchestrator+- `<working_dir>/src/components/`, `src/hooks/`, `src/utils/`, `src/tokens/` — shared code, if present; missing helpers are added by the orchestrator's foreground preparation, not by the planner**Hard rule — read-only on the scaffolded files.** You may NEVER write to anything outside this allow-list:@@ -69,9 +78,9 @@ The orchestrator uses separate graph and specs gates so the user can edit the sc- `<working_dir>/_plan_preview.html` (only when `skip_preview` is unset/false)- `<working_dir>/.tmp/*` (scratch)-If you discover a real issue in `app/`, `src/`, `package.json`, `tamagui.config.ts`, `tsconfig.json`, `power.config.json`, `node_modules/`, or `memory-bank.md`, return `DONE_WITH_CONCERNS: <issue>` — DO NOT silently edit. Those paths are owned by the orchestrator's bg pipeline and writing to them races `cp -R`, `pa app init`, or `npm install`.+If you discover a real issue in `app/`, `src/`, `package.json`, `tamagui.config.ts`, `tsconfig.json`, `power.config.json`, `node_modules/`, or `memory-bank.md`, return `DONE_WITH_CONCERNS: <issue>` — DO NOT silently edit. Those paths are owned by the orchestrator's approved foreground preparation and initialization; writing to them here bypasses that ownership and can overwrite app-owned changes.-Specifically — `memory-bank.md` is OFF-LIMITS during `phase: graph` and `phase: specs`. If a sub-agent (data-model architect, etc.) returns a concern that needs persisting, stash the line in `<working_dir>/.tmp/pending-memory-bank-appends.txt` (orchestrator's Step 6.7 flushes this after JOIN). Do not append to `memory-bank.md` directly.+Specifically — `memory-bank.md` is OFF-LIMITS during `phase: graph` and `phase: specs`. Return concerns through `DONE_WITH_CONCERNS` so the orchestrator queues them in `DEFERRED_CONCERNS[]` and persists them when Step 6.7 creates the memory bank. Do not append to `memory-bank.md` directly.## Workflow@@ -320,13 +329,28 @@ Pick a layout strategy per screen based on target platform:| Tokens: `$4`, `$color12`, `$background`, `$sm` | Screen options: `presentation`, `headerSearchBarOptions`, `headerLargeTitle` || Theme switching, breakpoints (`useMedia()`) | Scroll insets: `<ScrollView contentInsetAdjustmentBehavior="automatic">` || | Platform branching: `process.env.EXPO_OS`, `useWindowDimensions` |-| | Capabilities: `expo-camera`, `expo-document-picker`, `expo-print`, `expo-secure-store`, `expo-file-system`, `expo-sharing`, `@microsoft/power-apps-native-pdf-viewer`, `@microsoft/power-apps-native-pen-input`, `@microsoft/power-apps-native-bglocation` when allowlisted by the plan (see AGENTS.md §2) |+| | Capabilities: only packages/versions in the app's resolved native inventory; use release-conditional controls wrappers || | Calendar management views: `react-native-calendars` (`Calendar`, `CalendarList`, `Agenda`, `ExpandableCalendar`, `AgendaList`) when the approved `JavaScript Dependencies` table includes it |Reference `${PLUGIN_ROOT}/shared/samples/_layout.tsx` for existing navigation layout patterns (tab structure, safe-area, stack options).### Pure-JavaScript dependency planning+For native controls, read+[the conditional import and permission contract](../skills/add-native/references/native-controls.md).+Plan `/pdf`, `/pen`, or `/geolocation` only for a release containing those+subpaths; the root is metadata and there is no barcode subpath. Legacy leaves+require matching resolved inventory. Keep the installed APIs, not a newer+release's signatures. Do not install controls to repair an older binary.++One-shot location requires no `app_id`, data source, target table, or tracking.+Continuous tracking needs one coordinated owner; background-location 0.2.3+requests background permissions even with `trackInBackground: false`, and+`stopTracking()` / `isTracking()` have no `app_id`. Treat OS declarations,+runtime grants, package inclusion, and actual use as separate. Disabling a+control does not remove default Android permissions; another declaration set+requires another verified base. Optional permission wrapping is deferred.+Read and follow `${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md`. Apply it both when the user explicitly names a JavaScript library and when a screen use case has an established library that materially reduces implementation or accessibility risk. Inspect existing dependencies first; otherwise research at most three candidates with the reference's read-only npm commands, select one compatible JS-only package, and emit the exact-version evidence table in `phase: specs` or legacy mode. Do not install during planning.Calendar management is one example, not a special ownership path. Full month/week/agenda surfaces trigger candidate selection and normally evaluate `react-native-calendars` first; a lightweight `timeline-day-list` can stay on existing primitives. Other use cases follow the same candidate-selection workflow rather than requiring a hardcoded package map.@@ -440,7 +464,14 @@ For each screen the user adds, provide this compact shape:- **Audit** (omit for read-only / non-write screens) — one line per audit-bearing action: `<trigger>: event <code> (<event label>); payload: <field, field, field>`. Example: `On submit: event 100000006 (Inspection Submitted); payload: inspectionId, submittedAt, defectCount, openCriticalCount.` The screen-builder wraps the payload field list in `JSON.stringify({...})` and writes the full `cr3e9_audit_log_entriesService.create(...)` call from the Generated Services table — do NOT spell out the wrapper or service name.- **Lookup writes** — for form/edit screens that set a parent reference (Task → Project, Comment → Task, etc.), explicitly copy the exact quoted `@odata.bind` property from the generated target model and pair it with the entity set, e.g. `'[email protected]': '/cr3e9_projects(<guid>)'` when that exact key exists in `src/generated/models/<Entity>Model.ts`. Never derive casing from Dataverse schema-name conventions. Without the generated-model key, mark the spec `BLOCKED: lookup write key not verified`. Skip for read-only and no-lookup screens.- **Pagination** — `cursor` if the table has no natural record ceiling (visits, inspections, work orders, tickets, any user-created records over time); `none` if the table is a bounded lookup (status types, categories, job types). When `cursor`, include SDK `maxPageSize: 50`, deterministic `orderBy` with a unique key, `select`, `skipToken` continuation support, and server-side `filter` for search in the data spec. Do not imply that `top: 50` alone is pagination.-- **Native capabilities** — which native modules/wrappers it uses, and which iOS/Android platforms or permission states need fallback handling. For PDF/pen screens, be precise: `document-picker` (`expo-document-picker`) for user-picked files; `pdf-report` (`expo-print`, plus `expo-sharing` only when present and sharing is required) for generated local PDFs; `native-pdf-viewer` (`@microsoft/power-apps-native-pdf-viewer` 0.2.9+) for HTTPS PDF URLs and local `file://` URIs; `pen-input` (`@microsoft/power-apps-native-pen-input`) for signature/ink capture. For location screens, distinguish `geolocation` (`@microsoft/power-apps-native-bglocation`) — continuous/background tracking with native Dataverse sync, needs start/stop/tracking-status UI plus a permission-denied state — from one-shot `location` (`expo-location`) for a single foreground coordinate read. For haptics, name the exact interaction plus wrapper call: impact and strength for deliberate presses, selection for changed choices, or notification and outcome for completed operations; also name the visible feedback that accompanies it.+- **Native capabilities** — name the resolved package/version and wrapper, plus+ iOS/Android permission-denied and unsupported states. Preserve document+ picking vs PDF generation vs PDF viewing vs pen capture boundaries.+ Controls use the approved aggregate subpath or matching legacy leaf, never a+ newer contract. Distinguish continuous `geolocation` (coordinated+ start/stop/status UI and verified Dataverse target) from one-shot `location`+ (no data source or tracking startup). Haptics specify the interaction,+ feedback kind/strength, wrapper call, and accompanying visible feedback.- **Calendar library** — REQUIRED for screens with `Calendar pattern` unless the pattern is `timeline-day-list`. Write `react-native-calendars` and name the exact components expected, for example `CalendarProvider`, `ExpandableCalendar`, `AgendaList`, `Calendar`, `CalendarList`, or `Agenda`. The package must also appear in `### JavaScript Dependencies`; the screen-builder imports it directly after the orchestrator installs it. No `/add-native` wrapper or native rebuild is involved.- **Navigation** — what links to it / what it links to- **Navigation intent** — for each outgoing action, explicitly name `navigate`, `push`, or `replace` (must match Navigation Contracts `Intent`)diff --git a/plugins/mobile-apps/hooks/validate-package-deps.js b/plugins/mobile-apps/hooks/validate-package-deps.jsindex 40280e4c7..1be38a1f0 100644--- a/plugins/mobile-apps/hooks/validate-package-deps.js+++ b/plugins/mobile-apps/hooks/validate-package-deps.js@@ -1,31 +1,14 @@#!/usr/bin/env node+'use strict';-/**- * Explicit validator: forbid bad dependencies in package.json writes.- *- * Triggers on Write/Edit/MultiEdit of any package.json. Blocks when the- * resulting deps include known-bad packages, private vendor packages are- * referenced via the npm registry instead of `file:` paths to vendor *.tgz,- * OR native/runtime packages are added outside the current package baseline's- * native/runtime allowlist. A reviewed exact-version exception may admit an- * otherwise ambiguous `react-native-*` package that planning verified is JS-only.- *- * Allowed icon library: `@expo/vector-icons` only.- *- * Forbidden npm-registry packages:- * - lucide-react-native, lucide-react, @tamagui/lucide-icons, @tamagui/lucide-icons-2- * - react-native-vector-icons (use @expo/vector-icons)- * - axios, node-fetch (use generated services from src/generated/)- *- * Vendor-only packages (must use file: path):- * - expo-msal-intune- * - @microsoft/pa-client (and any @microsoft/pa-* family)- *- * Exit codes: 0 pass, 2 block + stderr message.- */--const fs = require('fs');-const path = require('path');+// Explicit workflows admit a version-matched reviewed release, never package+// names from the newest bundled template. Legacy edits retain a conservative+// before/lock comparison, but cannot silently change detected native versions.+const fs = require('node:fs');+const path = require('node:path');+const {+ resolveProjectReleaseWithInventory, dependencySections, inspectInstalledPackages, isRuntimePackage, resolveInstalledDependency, npmAliasTarget,+} = require('../scripts/lib/mobile-release');const FORBIDDEN_DEPS = {'lucide-react-native': 'Use `@expo/vector-icons` (Ionicons family).',@@ -36,251 +19,192 @@ const FORBIDDEN_DEPS = {axios: 'Use generated connector services from `src/generated/` (connector-first rule).','node-fetch': 'Use generated connector services from `src/generated/`. The runtime has global fetch.',};--// Names that MUST resolve to a vendor *.tgz file: path.const VENDOR_ONLY = [/^expo-msal-intune$/, /^@microsoft\/pa-/];+const EXACT_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;-// These patterns identify packages known to require native runtime support. The-// broad `react-native-*` namespace is handled separately because it also contains-// pure-JavaScript packages; those stay blocked unless planning passes an exact-// reviewed name/version exception to explicit validation.-const NATIVE_PACKAGE_PATTERNS = [- /^expo($|-)/,- /^@expo\//,- /^react-native$/,- /^@react-native\//,- /^@react-native-community\//,- /^@shopify\/react-native-/,- /^react-native-gesture-handler$/,- /^react-native-reanimated$/,- /^react-native-screens$/,- /^react-native-safe-area-context$/,- /^react-native-webview$/,- /^react-native-svg$/,- /^react-native-maps$/,- /^react-native-camera$/,- /^react-native-vision-camera$/,- /^react-native-document-picker$/,- /^react-native-fs$/,- /^react-native-permissions$/,- /^react-native-device-info$/,- /^react-native-keychain$/,- /^react-native-biometrics$/,- /^react-native-nfc-manager$/,- /^react-native-ble-/,- /^@config-plugins\//,- /^@sentry\/react-native$/,-];--const AMBIGUOUS_REACT_NATIVE_PACKAGE_PATTERN = /^react-native-/;--const BUNDLED_TEMPLATE_PACKAGE_PATH = path.resolve(__dirname, '..', 'template', 'package.json');--function packageDeps(pkg) {- return {- ...(pkg.dependencies || {}),- ...(pkg.devDependencies || {}),- ...(pkg.peerDependencies || {}),- ...(pkg.optionalDependencies || {}),- };+function fail(message) {+ const error = new Error(message);+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;}-function readPackageDepsFromContent(content) {+function parseJson(content, label) {try {- return packageDeps(JSON.parse(content));- } catch {- return null;- }-}--function readRequiredPackageDeps(packagePath) {- const deps = readPackageDepsFromContent(fs.readFileSync(packagePath, 'utf8'));- if (!deps) {- throw new Error('package manifest is not valid JSON');+ const result = JSON.parse(content);+ if (!result || typeof result !== 'object' || Array.isArray(result)) fail(`Invalid ${label}.`);+ return result;+ } catch (error) {+ if (error.code === 'MOBILE_RELEASE_BLOCKED') throw error;+ fail(`Cannot validate malformed ${label}. Correct the JSON before continuing.`);}- return deps;}-function readPackageLockDeps(packageJsonPath) {- if (typeof packageJsonPath !== 'string') return null;- const lockPath = path.join(path.dirname(packageJsonPath), 'package-lock.json');- if (!fs.existsSync(lockPath)) return null;- try {- const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));- const rootPackage = lock.packages && lock.packages[''];- if (rootPackage) {- return packageDeps(rootPackage);- }- if (lock.dependencies && typeof lock.dependencies === 'object') {- return Object.fromEntries(Object.keys(lock.dependencies).map((name) => [name, true]));- }- } catch {- return null;- }- return null;+function packageDeps(pkg) {+ return Object.assign({}, ...Object.values(dependencySections(pkg)));}-function reverseEdit(afterContent, newString, oldString) {- if (typeof newString !== 'string' || typeof oldString !== 'string') return null;- if (newString.length === 0) return null;- if (!afterContent.includes(newString)) return null;- return afterContent.replace(newString, oldString);+function reverseEdit(afterContent, edit) {+ if (typeof edit?.new_string !== 'string' || typeof edit?.old_string !== 'string'+ || !edit.new_string || !afterContent.includes(edit.new_string)) return null;+ return afterContent.replace(edit.new_string, edit.old_string);}-function reconstructBeforeContent(toolName, toolInput, afterContent) {- if (!afterContent) return null;- if (toolName === 'Edit') {- return reverseEdit(afterContent, toolInput.new_string, toolInput.old_string);- }+function reconstructBefore(toolName, toolInput, afterContent) {+ if (toolName === 'Edit') return reverseEdit(afterContent, toolInput);if (toolName === 'MultiEdit' && Array.isArray(toolInput.edits)) {- let beforeContent = afterContent;+ let before = afterContent;for (const edit of [...toolInput.edits].reverse()) {- beforeContent = reverseEdit(beforeContent, edit?.new_string, edit?.old_string);- if (beforeContent === null) return null;+ before = reverseEdit(before, edit);+ if (before === null) return null;}- return beforeContent;+ return before;}return null;}-function getNativeAllowlistDeps(toolName, toolInput, afterContent, packageJsonPath) {- if (toolInput.validation_mode === 'explicit-mobile-workflow') {- // Explicit mobile validation is the final native-runtime gate. If the bundled- // template is missing or malformed, allowing the write would silently turn a- // verification failure into permission to add arbitrary native dependencies.- return readRequiredPackageDeps(BUNDLED_TEMPLATE_PACKAGE_PATH);- }-- const beforeContent = reconstructBeforeContent(toolName, toolInput, afterContent);- const beforeDeps = beforeContent ? readPackageDepsFromContent(beforeContent) : null;- return beforeDeps || readPackageLockDeps(packageJsonPath);+function readResult(toolName, toolInput, filePath) {+ if (fs.existsSync(filePath)) return fs.readFileSync(filePath, 'utf8');+ if (toolName === 'Write' && typeof toolInput.content === 'string') return toolInput.content;+ fail('The resulting package.json must be available for validation.');}-function approvedJsDependencyVersions(toolInput) {+function approvedJsDependencies(input) {const approved = new Map();- if (!Array.isArray(toolInput.approved_js_dependencies)) return approved;- for (const entry of toolInput.approved_js_dependencies) {- if (typeof entry?.name === 'string' && typeof entry?.version === 'string') {+ if (!Array.isArray(input.approved_js_dependencies)) return approved;+ for (const entry of input.approved_js_dependencies) {+ if (typeof entry?.name === 'string' && typeof entry.version === 'string'+ && EXACT_VERSION.test(entry.version)) {approved.set(entry.name, entry.version);}}return approved;}-function isPackageJson(filePath) {- return typeof filePath === 'string' && path.basename(filePath) === 'package.json';+function hasNativeClosure(installed, installPath, unchangedPeers, seen = new Set()) {+ if (!installPath || seen.has(installPath)) return false;+ seen.add(installPath);+ const item = installed.get(installPath);+ if (!item) return false;+ if (item.native) return true;+ const dependencies = { ...item.pkg.dependencies, ...item.pkg.optionalDependencies };+ if (Object.keys(dependencies).some((name) => isRuntimePackage(name)+ || hasNativeClosure(installed, resolveInstalledDependency(installed, installPath, name), unchangedPeers, seen))) return true;+ return Object.keys(item.pkg.peerDependencies || {}).some((name) => {+ const peer = resolveInstalledDependency(installed, installPath, name);+ // A JS UI consuming the app's unchanged React/RN peer does not add native+ // code. Nested, new, changed, or uninstalled peers cannot use that exception.+ if (peer && unchangedPeers.has(peer)) return false;+ return isRuntimePackage(name) || hasNativeClosure(installed, peer, unchangedPeers, seen);+ });}-function isWriteTool(t) {- return t === 'Write' || t === 'Edit' || t === 'MultiEdit';-}--function readResult(toolName, toolInput) {- // Prefer the file on disk because explicit validation runs after the write.- const fp = toolInput.file_path || toolInput.filePath;- if (typeof fp === 'string' && fs.existsSync(fp)) {- try {- return fs.readFileSync(fp, 'utf8');- } catch {- /* fallthrough */+function legacyBaseline(toolName, toolInput, content, projectRoot, installed) {+ const before = reconstructBefore(toolName, toolInput, content);+ const lockPath = path.join(projectRoot, 'package-lock.json');+ const lock = fs.existsSync(lockPath) ? parseJson(fs.readFileSync(lockPath, 'utf8'), 'package-lock.json') : null;+ const baseline = before !== null ? packageDeps(parseJson(before, 'previous package.json'))+ : lock?.packages?.[''] ? packageDeps(lock.packages[''])+ : Object.fromEntries(Object.entries(lock?.dependencies || {}).map(([name, value]) => [name, value.version]));+ for (const [installPath, item] of installed) {+ if (!item.native) continue;+ const locked = lock?.packages?.[installPath]+ || (installPath === `node_modules/${item.name}` ? lock?.dependencies?.[item.name] : null);+ const direct = installPath === `node_modules/${item.name}`;+ const pinnedBefore = direct && EXACT_VERSION.test(baseline[item.name] || '');+ if (!locked || locked.version !== item.version || (pinnedBefore && baseline[item.name] !== item.version)) {+ fail('Detected native dependency drift between the installation and app lock. Restore the approved runtime and validate a verified release.');}}- if (toolName === 'Write' && typeof toolInput.content === 'string') return toolInput.content;- if (toolName === 'Edit' && typeof toolInput.new_string === 'string') return toolInput.new_string;- if (toolName === 'MultiEdit' && Array.isArray(toolInput.edits)) {- return toolInput.edits.map((e) => (e && e.new_string) || '').join('\n');- }- return '';+ return baseline;}-function findViolations(content, filePath, nativeAllowlistDeps, approvedJsDependencies) {- let pkg;- try {- pkg = JSON.parse(content);- } catch {- return []; // mid-edit; let it be — tsc / npm install will catch+function main(input) {+ const toolName = input.tool_name || input.toolName;+ const toolInput = input.tool_input || input.toolInput || {};+ if (!['Write', 'Edit', 'MultiEdit'].includes(toolName)) return;+ const filePath = toolInput.file_path || toolInput.filePath;+ if (typeof filePath !== 'string' || path.basename(filePath) !== 'package.json') return;++ const content = readResult(toolName, toolInput, filePath);+ const pkg = parseJson(content, 'package.json');+ const dependencies = packageDeps(pkg);+ const sections = dependencySections(pkg);+ // Inspect every section: a safe optional/dev declaration must not shadow a+ // forbidden or registry-only declaration in dependencies.+ for (const section of Object.values(sections)) {+ for (const [name, version] of Object.entries(section)) {+ if (Object.hasOwn(FORBIDDEN_DEPS, name)) fail(`Forbidden dependency \`${name}\`. ${FORBIDDEN_DEPS[name]}`);+ const canonical = npmAliasTarget(version);+ if (canonical && Object.hasOwn(FORBIDDEN_DEPS, canonical)) fail(`Forbidden dependency \`${canonical}\`. ${FORBIDDEN_DEPS[canonical]}`);+ if (canonical && VENDOR_ONLY.some((pattern) => pattern.test(canonical))) {+ fail(`Vendor-only dependency \`${canonical}\` cannot use an npm alias.`);+ }+ if (VENDOR_ONLY.some((pattern) => pattern.test(name))+ && !/^file:\.\/vendor\/[a-zA-Z0-9][a-zA-Z0-9._-]*\.tgz$/.test(version)) {+ fail(`Vendor-only dependency \`${name}\` must reference a file:./vendor package archive.`);+ }+ }}- const allDeps = packageDeps(pkg);- const violations = [];- const editingBundledTemplatePackage =- typeof filePath === 'string' && path.resolve(filePath) === BUNDLED_TEMPLATE_PACKAGE_PATH;-- for (const [name, version] of Object.entries(allDeps)) {- if (FORBIDDEN_DEPS[name]) {- violations.push({- name,- version,- reason: `Forbidden dependency \`${name}\`. ${FORBIDDEN_DEPS[name]}`,- });+ const projectRoot = path.dirname(path.resolve(filePath));+ if (toolInput.diagnostic_artifacts !== undefined) {+ fail('Diagnostic artifact mode is retired. Resolve the app against its published host and template packages.');+ }+ const explicit = toolInput.validation_mode === 'explicit-mobile-workflow';+ if (explicit && toolInput.validation_scope === 'upgrade-only') {+ // The host CLI owns installation; upgrades rely on Expo/Doctor/TypeScript,+ // not this separate app-lock and native-inventory admission policy.+ process.stderr.write('WARNING: Upgrade validation does not verify Dev Player/Wrap compatibility.\n');+ return;+ }+ let baseline;+ let installed;+ if (explicit) {+ const resolved = resolveProjectReleaseWithInventory(projectRoot);+ const { release } = resolved;+ installed = resolved.installed;+ baseline = packageDeps(release.managedDependencies);+ } else {+ installed = inspectInstalledPackages(projectRoot);+ baseline = legacyBaseline(toolName, toolInput, content, projectRoot, installed);+ }+ const approved = approvedJsDependencies(toolInput);+ const unchangedPeers = new Set(Object.entries(baseline).filter(([name, version]) => dependencies[name] === version+ && installed.has(`node_modules/${name}`)).map(([name]) => `node_modules/${name}`));+ for (const name of new Set([...Object.keys(baseline), ...Object.keys(dependencies)])) {+ const version = dependencies[name];+ const actual = installed.get(`node_modules/${name}`);+ if (version !== undefined && actual?.alias) {+ if (Object.hasOwn(FORBIDDEN_DEPS, actual.canonicalName)) fail(`Forbidden dependency \`${actual.canonicalName}\`. ${FORBIDDEN_DEPS[actual.canonicalName]}`);+ if (npmAliasTarget(version) !== actual.canonicalName) fail('Installed npm alias canonical identity does not match its dependency declaration.');}- if (VENDOR_ONLY.some((rx) => rx.test(name)) && !String(version).startsWith('file:')) {- violations.push({- name,- version,- reason: `\`${name}\` is a private vendor package. Reference must be a \`file:./vendor/<name>-<version>.tgz\` path, not \`${version}\`. Will 404 from npm registry.`,- });+ const native = isRuntimePackage(name)+ || hasNativeClosure(installed, `node_modules/${name}`, unchangedPeers);+ if (native && baseline[name] !== version) {+ fail(`Native/runtime dependency \`${name}\` differs from this app's reviewed baseline. Restore its declaration or select a verified release.`);}- if (!editingBundledTemplatePackage && nativeAllowlistDeps && !nativeAllowlistDeps[name]) {- if (NATIVE_PACKAGE_PATTERNS.some((rx) => rx.test(name))) {- violations.push({- name,- version,- reason: `Native/runtime dependency \`${name}\` was not present in this app/template package baseline. Start from a template/runtime that already ships it.`,- });- } else if (- AMBIGUOUS_REACT_NATIVE_PACKAGE_PATTERN.test(name) &&- approvedJsDependencies.get(name) !== String(version)- ) {- violations.push({- name,- version,- reason: `Dependency \`${name}@${version}\` uses the ambiguous \`react-native-*\` namespace and is absent from the app/template baseline. Explicit validation requires the same exact name/version from the user-approved JavaScript Dependencies plan.`,- });- }+ if (!native && !Object.hasOwn(baseline, name) && /^react-native-/.test(name)+ && approved.get(name) !== version) {+ fail(`Dependency \`${name}\` requires the same exact name/version from the user-approved JavaScript Dependencies plan.`);}}- return violations;}-let buf = '';-process.stdin.on('data', (c) => (buf += c));+let buffer = '';+process.stdin.on('data', (chunk) => { buffer += chunk; });process.stdin.on('end', () => {let input;try {- input = JSON.parse(buf || '{}');+ input = parseJson(buffer, 'validator input');} catch {- process.exit(0);+ return;}- const toolName = input.tool_name || input.toolName;- const toolInput = input.tool_input || input.toolInput || {};- if (!isWriteTool(toolName)) process.exit(0);- const fp = toolInput.file_path || toolInput.filePath;- if (!isPackageJson(fp)) process.exit(0);-- const content = readResult(toolName, toolInput);- if (!content) process.exit(0);-- let nativeAllowlistDeps;try {- nativeAllowlistDeps = getNativeAllowlistDeps(toolName, toolInput, content, fp);+ main(input);} catch (error) {- process.stderr.write(- `BLOCKED: unable to load native dependency allowlist from ${BUNDLED_TEMPLATE_PACKAGE_PATH}: ${error.message}\n`,- );- process.exit(2);- }- const approvedJsDependencies = approvedJsDependencyVersions(toolInput);- const violations = findViolations(content, fp, nativeAllowlistDeps, approvedJsDependencies);- if (violations.length === 0) process.exit(0);-- const rel = path.relative(process.cwd(), fp) || fp;- const lines = [`BLOCKED: forbidden dependencies in ${rel}`, ''];- for (const v of violations) {- lines.push(` - ${v.reason}`);+ const message = error.code === 'MOBILE_RELEASE_BLOCKED'+ ? error.message : 'Unable to verify package dependencies. Restore valid project files and the reviewed installation.';+ process.stderr.write(`BLOCKED: ${message}\n`);+ process.exitCode = 2;}- lines.push('');- lines.push('Re-issue the write with the dependency list corrected.');- process.stderr.write(lines.join('\n') + '\n');- process.exit(2);});diff --git a/plugins/mobile-apps/hooks/validate-protected-paths.js b/plugins/mobile-apps/hooks/validate-protected-paths.jsindex c4bcfb77f..4958af72c 100644--- a/plugins/mobile-apps/hooks/validate-protected-paths.js+++ b/plugins/mobile-apps/hooks/validate-protected-paths.js@@ -1,15 +1,15 @@#!/usr/bin/env node/**- * Explicit validator: protect agent-generated read-only paths.+ * Explicit validator: protect generated and release-owned paths.** Blocks writes to:* - any path under `src/generated/` (regenerated by `pa app add data-source`)* - any `power.config.json` (regenerated by `pa app init`)- * - any `vendor/<name>.tgz` (sourced from plugins/mobile-apps/template)+ * - any `vendor/<name>.tgz` (part of the reviewed published dependency set)*- * Manual edits to these files are silently lost on the next CLI run, so it's- * almost always wrong. Block with a clear message pointing to the right tool.+ * Generated files are CLI-owned; runtime archives belong to the reviewed release.+ * Block manual writes and point callers to the owning workflow.** Exit codes: 0 pass, 2 block.*/@@ -34,7 +34,7 @@ const PROTECTED = [{rx: /(^|\/)vendor\/[^/]+\.tgz$/,reason:- '`vendor/*.tgz` files are sourced from https://github.com/microsoft/power-platform-skills/tree/main/plugins/mobile-apps/template. Update them there, not by editing in-project.',+ '`vendor/*.tgz` files are part of the app\'s reviewed published npm template/dependency set. Use `/check-updates` to review a compatible published release. Do not edit archives in-project or replace them from the skills repository.',},];diff --git a/plugins/mobile-apps/scripts/lib/mobile-package-artifacts.js b/plugins/mobile-apps/scripts/lib/mobile-package-artifacts.jsnew file mode 100644index 000000000..7293fc279--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-package-artifacts.js@@ -0,0 +1,142 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { createHash } = require('node:crypto');+const { isDeepStrictEqual } = require('node:util');+const semver = require('../vendor/semver.cjs');++const HOST = '@microsoft/power-apps-native-host';+const OFFLINE = '@microsoft/power-apps-native-offline';+const SRI = /^sha512-[A-Za-z0-9+/]{86}==$/;++function requireValue(condition, message) {+ if (condition) return;+ const error = new Error(message);+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+}++function unpack(archive, destination, run) {+ // Keep archive inspection and extraction in one cwd for Windows drive safety.+ const archiveName = 'artifact.tgz';+ const stagedArchive = path.join(destination, archiveName);+ fs.copyFileSync(archive, stagedArchive, fs.constants.COPYFILE_EXCL);+ try {+ const names = run('tar', ['-tzf', archiveName], destination).trim().split(/\r?\n/);+ const types = run('tar', ['-tvzf', archiveName], destination).trim().split(/\r?\n/);+ requireValue(names.length > 0 && names.length === types.length+ && types.every((line) => /^[-d]/.test(line))+ && new Set(names).size === names.length+ && names.every((name) => /^package(?:\/|$)/.test(name)+ && !/[\\:\u0000-\u001f]/.test(name) && name.split('/').every((part) => part !== '..' && part !== '.')),+ 'Packed artifacts must contain only regular package files and directories; links and unsafe archive paths are rejected.');+ run('tar', ['-xzf', archiveName], destination);+ return path.join(destination, 'package');+ } finally {+ fs.unlinkSync(stagedArchive);+ }+}++function packageFile(root, relative, directory = false) {+ requireValue(typeof relative === 'string' && relative.length > 0 && !path.isAbsolute(relative)+ && !/[\\:\u0000-\u001f]/.test(relative)+ && relative.split('/').every((part) => part && part !== '.' && part !== '..'),+ 'Package artifacts must use contained relative paths.');+ let file = root;+ for (const part of relative.split('/')) {+ file = path.join(file, part);+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });+ requireValue(stat && !stat.isSymbolicLink(), 'Package artifacts must exist and must not traverse symbolic links.');+ }+ const stat = fs.lstatSync(file);+ requireValue(directory ? stat.isDirectory() : stat.isFile(), 'Package artifacts must be regular files or directories.');+ return file;+}++function readJson(file) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch {+ requireValue(false, 'Cannot read the offline SDK metadata; restore the verified package.');+ }+}++function hashFile(file, algorithm = 'sha256', encoding = 'hex') {+ const hash = createHash(algorithm);+ const fd = fs.openSync(file, 'r');+ try {+ const buffer = Buffer.alloc(1024 * 1024);+ let size;+ while ((size = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, size));+ return hash.digest(encoding);+ } finally {+ fs.closeSync(fd);+ }+}++function verifyOfflineArtifacts(root, contract) {+ requireValue(contract?.artifacts && typeof contract.artifacts === 'object'+ && !Array.isArray(contract.artifacts) && Object.keys(contract.artifacts).length > 0,+ 'Offline compatibility metadata is missing native artifact hashes.');+ for (const [file, hash] of Object.entries(contract.artifacts)) {+ requireValue(typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)+ && hashFile(packageFile(root, file)) === hash,+ 'Offline native artifact hash differs from the selected SDK contract.');+ }+}++function readOfflineContract(root) {+ const contract = readJson(packageFile(root, 'compatibility.json'));+ verifyOfflineArtifacts(root, contract);+ return contract;+}++function verifyInstalledOfflineSdk(projectRoot, profile, host, lock, referenceLock, readPackage) {+ // Historical hosts have no versioned offline contract; preserve their existing admission rules.+ if (profile.offlineContractVersion === undefined) return;+ const version = profile.managedDependencies?.[OFFLINE];+ const entry = `node_modules/${OFFLINE}`;+ const locked = lock.packages?.[entry];+ const expected = referenceLock.packages?.[entry];+ if (version === undefined && !locked) return;+ requireValue(semver.valid(version) && !semver.prerelease(version) && locked?.version === version+ && !locked.link && expected?.version === version && !expected.link+ && SRI.test(locked.integrity || '') && expected.integrity === locked.integrity,+ 'Offline SDK version and integrity must match the selected published template lock.');+ requireValue(typeof readPackage === 'function', 'Offline admission requires an integrity-verified published SDK archive.');+ const reference = readPackage(OFFLINE, version);+ requireValue(reference?.publication?.package === OFFLINE && reference.publication.version === version+ && reference.publication.integrity === expected.integrity+ && reference.pkg?.name === OFFLINE && reference.pkg.version === version,+ 'Published offline SDK archive does not match the immutable template lock integrity.');+ const root = packageFile(projectRoot, entry, true);+ const installed = readJson(packageFile(root, 'package.json'));+ const contract = reference.contract;+ const pkg = reference.pkg;+ requireValue(installed.name === pkg.name && installed.version === pkg.version+ && isDeepStrictEqual(installed.peerDependencies, pkg.peerDependencies)+ && isDeepStrictEqual(readJson(packageFile(root, 'compatibility.json')), contract),+ 'Installed offline SDK metadata differs from its integrity-verified published archive.');+ requireValue(pkg.name === OFFLINE && pkg.version === version+ && contract?.schemaVersion === 2 && contract.complete === true && contract.sourceDirty === false+ && contract.packageVersion === version && contract.reactNativeVersion === profile.managedDependencies['react-native']+ && Number(contract.expoSdkVersion) === profile.expoSdk+ && typeof contract.runtimeFamily === 'string' && contract.runtimeFamily.length > 0+ && contract.runtimeFamily === profile.runtimeFamily+ && Number.isSafeInteger(contract.offlineContractVersion) && contract.offlineContractVersion > 0+ && contract.offlineContractVersion === profile.offlineContractVersion && contract.engine === 'hermes'+ && ['android', 'ios'].every((platform) => Array.isArray(contract.platformArchitectures?.[platform])+ && contract.platformArchitectures[platform].includes('new'))+ && typeof pkg.peerDependencies?.[HOST] === 'string'+ && typeof pkg.peerDependencies?.['react-native'] === 'string'+ && typeof host.peerDependencies?.[OFFLINE] === 'string'+ && contract.hostPeerRange === pkg.peerDependencies[HOST]+ && semver.satisfies(host.version, contract.hostPeerRange)+ && semver.satisfies(contract.reactNativeVersion, pkg.peerDependencies['react-native'])+ && semver.satisfies(version, host.peerDependencies[OFFLINE]),+ 'Offline SDK, published host peers and native runtime contract disagree.');+ verifyOfflineArtifacts(root, contract);+}++module.exports = { unpack, hashFile, readOfflineContract, verifyInstalledOfflineSdk };diff --git a/plugins/mobile-apps/scripts/lib/mobile-published-packages.js b/plugins/mobile-apps/scripts/lib/mobile-published-packages.jsnew file mode 100644index 000000000..fb19ab460--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-published-packages.js@@ -0,0 +1,383 @@+'use strict';++const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { runCliSync, CliLaunchError } = require('./process-runner');+const { unpack, hashFile, readOfflineContract, verifyInstalledOfflineSdk } = require('./mobile-package-artifacts');+const {+ exactVersion, declarationSpec, dependencySections, isRuntimePackage, readProjectRequirements, validateRelease,+ summarizeRelease, validHostIntegrity,+} = require('./mobile-release');++const HOST = '@microsoft/power-apps-native-host';+const TEMPLATE = '@microsoft/power-apps-native-template';+const OFFLINE = '@microsoft/power-apps-native-offline';+const PLATFORMS = ['android', 'ios'];+const SRI = /^sha512-[A-Za-z0-9+/]{86}==$/;++function requireValue(condition, message) {+ if (condition) return;+ const error = new Error(message);+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+}++function readJson(file, label) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch {+ requireValue(false, `Cannot inspect ${label}; restore the published package or project installation.`);+ }+}++function same(left, right) {+ if (left === right) return true;+ return Boolean(left && right && typeof left === 'object' && typeof right === 'object'+ && Object.keys(left).length === Object.keys(right).length+ && Object.keys(left).every((key) => Object.hasOwn(right, key) && same(left[key], right[key])));+}++function compareVersions(left, right) {+ requireValue(exactVersion(left, true) && exactVersion(right, true), 'Select exact stable published package versions.');+ const a = left.split('+', 1)[0].split('.').map(BigInt);+ const b = right.split('+', 1)[0].split('.').map(BigInt);+ for (let index = 0; index < a.length; index += 1) {+ if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;+ }+ return 0;+}++function run(command, args, cwd) {+ try {+ return runCliSync(command, args, {+ cwd, encoding: 'utf8', timeout: 120000, maxBuffer: 32 * 1024 * 1024,+ env: { ...process.env, npm_config_ignore_scripts: 'true', npm_config_update_notifier: 'false' },+ });+ } catch (error) {+ if (!(error instanceof CliLaunchError) && !(Number.isInteger(error.status) && error.status > 0)) throw error;+ requireValue(false, command === 'npm'+ ? 'Published package lookup failed. Check the exact version, configured npm registry, authentication and network; no other version was substituted.'+ : 'Package inspection failed. Ensure tar is available; no package code was executed.');+ }+}++function parseOutput(output) {+ try {+ return JSON.parse(output);+ } catch {+ requireValue(false, 'npm returned invalid package metadata; inspect registry access locally (raw output withheld).');+ }+}++function createSource(options = {}) {+ const execute = options.run || run;+ const context = options.cwd || process.cwd();+ const cache = new Map();+ return {+ defaultVersion() {+ const version = parseOutput(execute('npm', ['view', HOST, 'version', '--json'], context));+ requireValue(exactVersion(version, true), 'The npm default host channel must resolve to one exact stable version.');+ return version;+ },+ versions() {+ if (options.versions) return options.versions();+ const versions = parseOutput(execute('npm', ['view', TEMPLATE, 'versions', '--json'], context));+ requireValue(Array.isArray(versions) && versions.every((version) => exactVersion(version)),+ 'The template registry response must contain published package versions.');+ return versions;+ },+ read(name, version) {+ requireValue([HOST, TEMPLATE, OFFLINE].includes(name) && exactVersion(version, true),+ 'Select an exact stable host or template package version, or its locked offline SDK version; not a release id, range, URL or tag.');+ const key = `${name}@${version}`;+ if (cache.has(key)) return cache.get(key);+ if (options.readPackage) {+ const result = options.readPackage(name, version);+ cache.set(key, result);+ return result;+ }+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-published-package-'));+ fs.chmodSync(directory, 0o700);+ try {+ const metadata = parseOutput(execute('npm', ['view', key, '--json'], context));+ // Older host publications use npm's registry shasum rather than+ // dist.integrity. Verify that original digest; never invent an attestation.+ const integrity = metadata.dist?.integrity ?? (name === HOST && /^[a-f0-9]{40}$/.test(metadata.dist?.shasum || '')+ ? `sha1-${Buffer.from(metadata.dist.shasum, 'hex').toString('base64')}` : null);+ requireValue(metadata?.name === name && metadata.version === version+ && (name === HOST ? validHostIntegrity(integrity) : SRI.test(integrity || '')),+ `Registry metadata for ${key} must identify the exact package and its published integrity.`);+ const packed = parseOutput(execute('npm', [+ 'pack', key, '--ignore-scripts', '--json', '--pack-destination', directory,+ ], context));+ requireValue(Array.isArray(packed) && packed.length === 1 && packed[0].name === name+ && packed[0].version === version && SRI.test(packed[0].integrity || '')+ && typeof packed[0].filename === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._+-]*\.tgz$/.test(packed[0].filename),+ 'Downloaded package identity or integrity differs from npm publication metadata.');+ const archive = path.join(directory, packed[0].filename);+ requireValue(fs.lstatSync(archive).isFile() && !fs.lstatSync(archive).isSymbolicLink(),+ 'Downloaded package must be a regular archive.');+ const algorithm = integrity.slice(0, integrity.indexOf('-'));+ const packedIntegrity = `sha512-${hashFile(archive, 'sha512', 'base64')}`;+ const registryIntegrity = algorithm === 'sha512' ? packedIntegrity : `${algorithm}-${hashFile(archive, algorithm, 'base64')}`;+ requireValue(registryIntegrity === integrity && packedIntegrity === packed[0].integrity,+ 'Downloaded package bytes do not match the published integrity.');+ const root = unpack(archive, directory, execute);+ const pkg = readJson(path.join(root, 'package.json'), 'packed package manifest');+ requireValue(pkg.name === name && pkg.version === version && pkg.private !== true && !pkg.powerAppsDiagnostic,+ 'Packed package identity must match the selected public production package.');+ const publication = { package: name, version, integrity };+ let result;+ if (name === HOST) {+ const profile = readJson(path.join(root, 'compatibility/current.json'), 'published host compatibility profile');+ const migrationIds = profile.migrations === undefined ? [] : profile.migrations;+ requireValue(Array.isArray(migrationIds), 'The published host migration list must be an array.');+ const migrations = migrationIds.map((id) => {+ requireValue(typeof id === 'string' && /^[a-z0-9][a-z0-9._-]*$/i.test(id), 'Invalid published migration identity.');+ return readJson(path.join(root, 'compatibility/migrations', `${id}.json`), 'published host migration');+ });+ result = { publication, pkg, profile, migrations };+ } else if (name === TEMPLATE) {+ result = {+ publication, pkg,+ app: readJson(path.join(root, 'template/app.json'), 'published template state'),+ manifest: readJson(path.join(root, 'template/package.json'), 'published template dependencies'),+ lock: readJson(path.join(root, 'template/package-lock.json'), 'published template lock'),+ };+ } else {+ result = { publication, pkg, contract: readOfflineContract(root) };+ }+ cache.set(key, result);+ return result;+ } finally {+ fs.rmSync(directory, { recursive: true, force: true });+ }+ },+ };+}++function validateHost(host) {+ const { profile, publication } = host;+ requireValue(publication?.package === HOST && exactVersion(publication.version, true)+ && validHostIntegrity(publication.integrity) && host.pkg?.name === HOST && host.pkg.version === publication.version,+ 'Invalid published host identity.');+ requireValue(!profile?.runtimePreparation,+ 'The host is still in diagnostic runtime preparation. Wait for a finalized published release.');+ requireValue(profile?.schemaVersion === 1 && Number.isSafeInteger(profile.targetTemplateVersion)+ && profile.targetTemplateVersion > 0 && exactVersion(profile.expoVersion, true)+ && PLATFORMS.every((platform) => Number.isSafeInteger(profile.nativeRuntime?.[platform]?.version)+ && profile.nativeRuntime[platform].version > 0 && /^[a-f0-9]{64}$/.test(profile.nativeRuntime[platform].fingerprint)),+ 'The published host lacks a supported template/native compatibility profile.');+ const managed = { dependencies: { ...profile.managedDependencies, expo: profile.expoVersion, [HOST]: publication.version } };+ if (profile.managedDevDependencies) managed.devDependencies = profile.managedDevDependencies;+ dependencySections(managed);+ requireValue(Object.values(managed).every((section) => Object.values(section).every(declarationSpec))+ && ['react', 'react-native'].every((name) => exactVersion(managed.dependencies[name], true)),+ 'The published host must declare the coordinated Expo, React and React Native dependency set.');+ requireValue(Array.isArray(host.migrations), 'The published host migration graph is unavailable.');+ for (const migration of host.migrations) {+ requireValue(Number.isSafeInteger(migration.fromTemplateVersion) && migration.fromTemplateVersion > 0+ && migration.toTemplateVersion === migration.fromTemplateVersion + 1+ && migration.toTemplateVersion <= profile.targetTemplateVersion+ && exactVersion(migration.targetProfile?.hostVersion, true),+ 'The host contains an invalid or unfinalized migration target. Wait for a finalized published release; do not replace version placeholders.');+ }+ return managed;+}++function templateState(template) {+ requireValue(template.publication?.package === TEMPLATE && exactVersion(template.publication.version, true)+ && SRI.test(template.publication.integrity || ''), 'Invalid published template identity.');+ const state = template.app?.expo?.extra?.powerappsNative;+ requireValue(state?.schemaVersion === 1 && Number.isSafeInteger(state.templateVersion) && state.templateVersion > 0+ && PLATFORMS.every((platform) => Number.isSafeInteger(state.nativeRuntimeVersions?.[platform])+ && state.nativeRuntimeVersions[platform] > 0), 'The published template lacks protected compatibility metadata.');+ return state;+}++function findTemplate(source, host, requestedVersion) {+ const versions = requestedVersion ? [requestedVersion]+ : source.versions().filter((version) => exactVersion(version, true)).sort((a, b) => compareVersions(b, a));+ for (const version of versions) {+ const template = source.read(TEMPLATE, version);+ const state = templateState(template);+ if (state.templateVersion !== host.profile.targetTemplateVersion+ || !PLATFORMS.every((platform) => state.nativeRuntimeVersions[platform] === host.profile.nativeRuntime[platform].version)) {+ if (requestedVersion) requireValue(false, 'Selected host and template require different native/template versions.');+ continue;+ }+ requireValue([2, 3].includes(template.lock?.lockfileVersion) && template.lock.packages?.[''],+ 'The published template must include its immutable npm lock.');+ requireValue(same(dependencySections(template.manifest), dependencySections(template.lock.packages[''])),+ 'Published template dependency declarations differ from its packaged lock.');+ const lockedHost = template.lock.packages[`node_modules/${HOST}`]?.version;+ requireValue(exactVersion(lockedHost, true), 'The published template must pin a production host in its lock.');+ if (compareVersions(lockedHost, host.publication.version) > 0) {+ if (requestedVersion) requireValue(false, 'The selected template requires a newer host; do not downgrade its published baseline.');+ continue;+ }+ const baseline = source.read(HOST, lockedHost);+ validateHost(baseline);+ requireValue(same(baseline.profile.nativeRuntime, host.profile.nativeRuntime),+ 'The selected host differs from the template native fingerprint. Select a compatible published template; counters alone are insufficient.');+ for (const [name, version] of Object.entries({+ expo: host.profile.expoVersion, react: host.profile.managedDependencies.react,+ 'react-native': host.profile.managedDependencies['react-native'],+ })) {+ requireValue(template.lock.packages[`node_modules/${name}`]?.version === version,+ 'The template lock does not match the selected host Expo/React/React Native requirements.');+ }+ return template;+ }+ requireValue(false, 'No published template matches this host compatibility profile. Finish publishing the matching template; do not use a bundled snapshot.');+}++function contractFromPackages(host, template, project) {+ const managed = validateHost(host);+ const state = templateState(template);+ const nativePackages = {};+ for (const [installPath, entry] of Object.entries(template.lock.packages)) {+ if (!installPath.startsWith('node_modules/')) continue;+ const name = installPath.split('/node_modules/').pop().replace(/^node_modules\//, '');+ if (isRuntimePackage(name) || project?.installed.get(installPath)?.native) {+ requireValue(exactVersion(entry.version), 'The published template has an invalid native lock entry.');+ nativePackages[installPath] = entry.version;+ }+ }+ nativePackages[`node_modules/${HOST}`] = host.publication.version;+ // The host CLI pins itself exactly; an untouched scaffold may retain the+ // template's published range. Neither permits a different installed version.+ const declaredHost = project?.declarations.dependencies?.[HOST];+ if (declaredHost === template.manifest.dependencies?.[HOST]) managed.dependencies[HOST] = declaredHost;+ return validateRelease({+ source: 'npm',+ id: `host-${host.publication.version}-template-${template.publication.version}`,+ host: { ...host.publication },+ template: { ...template.publication },+ templateVersion: state.templateVersion,+ nativeRuntimeVersions: { ...state.nativeRuntimeVersions },+ managedDependencies: managed,+ nativePackages,+ platforms: Object.fromEntries(PLATFORMS.map((platform) => [platform, {+ fingerprint: host.profile.nativeRuntime[platform].fingerprint,+ }])),+ });+}++function selectPublishedContract(hostVersion, options = {}) {+ const source = createSource(options);+ const host = source.read(HOST, hostVersion);+ validateHost(host);+ const template = findTemplate(source, host, options.templateVersion);+ return contractFromPackages(host, template, options.project);+}++function selectTemplateContract(templateVersion, options = {}) {+ const source = createSource(options);+ const template = source.read(TEMPLATE, templateVersion);+ templateState(template);+ const hostVersion = template.lock?.packages?.[`node_modules/${HOST}`]?.version;+ const host = source.read(HOST, hostVersion);+ validateHost(host);+ findTemplate(source, host, templateVersion);+ return contractFromPackages(host, template);+}++function readSourceRequirements(projectRoot) {+ const metadata = readProjectRequirements(projectRoot);+ const hostRoot = path.join(projectRoot, 'node_modules', HOST);+ for (const relative of ['node_modules', 'node_modules/@microsoft', `node_modules/${HOST}`]) {+ const stat = fs.lstatSync(path.join(projectRoot, relative), { throwIfNoEntry: false });+ requireValue(stat?.isDirectory() && !stat.isSymbolicLink(), 'Restore a regular installed host before planning an upgrade.');+ }+ const installed = readJson(path.join(hostRoot, 'package.json'), 'installed host manifest');+ requireValue(installed.name === HOST && exactVersion(installed.version, true), 'Upgrade planning requires an exact installed production host version.');+ return {+ templateVersion: metadata.templateVersion,+ nativeRuntimeVersions: metadata.nativeRuntimeVersions,+ hostVersion: installed.version,+ validationScope: 'requirements-only',+ };+}++function projectContract(projectRoot, project, options = {}) {+ const requirements = readSourceRequirements(projectRoot);+ const source = createSource({ ...options, cwd: projectRoot });+ const contract = selectPublishedContract(requirements.hostVersion, {+ ...options, project, readPackage: source.read, versions: source.versions,+ });+ requireValue(contract.templateVersion === requirements.templateVersion+ && same(contract.nativeRuntimeVersions, requirements.nativeRuntimeVersions),+ 'Installed host and recorded template/native state differ. Run check-updates to preview the host migration; do not rewrite the app metadata.');+ const host = source.read(HOST, requirements.hostVersion);+ assertInstalledProfile(projectRoot, host.profile, host.pkg, project.lock,+ source.read(TEMPLATE, contract.template.version).lock, source.read);+ return contract;+}++function assertInstalledProfile(projectRoot, profile, host, lock, referenceLock, readPackage) {+ const installed = readJson(path.join(projectRoot, 'node_modules', HOST, 'compatibility/current.json'), 'installed host compatibility profile');+ requireValue(same(installed, profile), 'Installed host compatibility metadata differs from its published package.');+ verifyInstalledOfflineSdk(projectRoot, profile, host, lock, referenceLock, readPackage);+}++function planPublishedUpdate(projectRoot, hostVersion, options = {}) {+ const sourceRequirements = readSourceRequirements(projectRoot);+ requireValue(compareVersions(sourceRequirements.hostVersion, hostVersion) <= 0,+ 'Selected published host would downgrade the app; choose a supported forward version.');+ const source = createSource({ ...options, cwd: projectRoot });+ const host = source.read(HOST, hostVersion);+ validateHost(host);+ const template = findTemplate(source, host, options.templateVersion);+ const target = contractFromPackages(host, template);+ requireValue(sourceRequirements.templateVersion <= target.templateVersion+ && PLATFORMS.every((platform) => sourceRequirements.nativeRuntimeVersions[platform] <= target.nativeRuntimeVersions[platform]),+ 'Selected published host would downgrade the app; choose a supported forward version.');+ const migrationRequired = sourceRequirements.templateVersion < target.templateVersion;+ const nativeChanged = PLATFORMS.some((platform) => sourceRequirements.nativeRuntimeVersions[platform] !== target.nativeRuntimeVersions[platform]);+ requireValue(!nativeChanged || migrationRequired, 'Native runtime changes require a host-owned template migration.');+ const installedProfilePath = path.join(projectRoot, 'node_modules', HOST, 'compatibility/current.json');+ const warnings = [];+ if (fs.existsSync(installedProfilePath)) {+ const installedProfile = readJson(installedProfilePath, 'installed host compatibility profile');+ for (const platform of PLATFORMS) {+ const previous = installedProfile.nativeRuntime?.[platform];+ if (previous?.version !== sourceRequirements.nativeRuntimeVersions[platform]) continue;+ if (previous.fingerprint !== target.platforms[platform].fingerprint) {+ warnings.push(`${platform} native fingerprints differ; verify Dev Player/Wrap compatibility separately.`);+ }+ }+ }+ const edges = [];+ for (let version = sourceRequirements.templateVersion; version < target.templateVersion; version += 1) {+ const matching = host.migrations.filter((migration) => migration.fromTemplateVersion === version);+ requireValue(matching.length === 1, 'The selected published host does not contain an unambiguous migration chain for this app.');+ edges.push(matching[0]);+ }+ if (nativeChanged) {+ const fromSpec = edges[0]?.packageTransitions?.dependencies?.[HOST]?.from;+ const fromVersion = typeof fromSpec === 'string' ? fromSpec.replace(/^[~^]/, '') : sourceRequirements.hostVersion;+ requireValue(exactVersion(fromVersion, true)+ && BigInt(hostVersion.split('.')[0]) > BigInt(fromVersion.split('.')[0]),+ 'A native runtime transition requires a new host major; the published migration must identify the source host requirement.');+ }+ const hostInstallRequired = sourceRequirements.hostVersion !== hostVersion;+ return {+ kind: migrationRequired ? 'template-upgrade' : hostInstallRequired ? 'host-repair' : 'current',+ installedHostVersion: sourceRequirements.hostVersion,+ source: sourceRequirements,+ target: summarizeRelease(target),+ hostInstallRequired,+ migrationRequired,+ fullChainPreviewRequired: migrationRequired,+ nativeChanged,+ warnings,+ binaryAvailability: 'not-checked; package publication does not prove Player or Wrap availability',+ };+}++module.exports = {+ HOST, TEMPLATE, createSource, compareVersions, selectPublishedContract, selectTemplateContract,+ readSourceRequirements, projectContract, planPublishedUpdate,+};diff --git a/plugins/mobile-apps/scripts/lib/mobile-release.js b/plugins/mobile-apps/scripts/lib/mobile-release.jsnew file mode 100644index 000000000..f22a4abb0--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-release.js@@ -0,0 +1,587 @@+'use strict';++// Package-owned compatibility is the default. Explicit contracts remain an+// injection seam for the validators' synthetic tests, not an app-authored policy.+const fs = require('node:fs');+const path = require('node:path');+const net = require('node:net');+const semver = require('../vendor/semver.cjs');++const HOST = '@microsoft/power-apps-native-host';+const SECTIONS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];+const CORE = [HOST, 'expo', 'react-native', 'react'];+const TOKEN = /^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,127}$/;+const PACKAGE_PART = '[a-z0-9][a-z0-9._-]*';+const PACKAGE_NAME = new RegExp(`^(?:@${PACKAGE_PART}/)?${PACKAGE_PART}$`);+const INSTALL_PATH = new RegExp(`^node_modules/(?:@${PACKAGE_PART}/)?${PACKAGE_PART}(?:/node_modules/(?:@${PACKAGE_PART}/)?${PACKAGE_PART})*$`);+const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;+const RUNTIME_NAMES = [+ /^expo($|-)/, /^@expo\//, /^react$/, /^react-native$/, /^@react-native\//,+ /^@react-native-community\//, /^@shopify\/react-native-/, /^@config-plugins\//,+ /^@sentry\/react-native$/, /^@microsoft\/power-apps-native-/,+ /^expo-msal-intune$/, /^@microsoft\/pa-/,+ /^react-native-(?:gesture-handler|reanimated|screens|safe-area-context|webview|svg|maps|camera|vision-camera|document-picker|fs|permissions|device-info|keychain|biometrics|nfc-manager|worklets)$/,+ /^react-native-ble-/,+];++function blocked(message) {+ const error = new Error(message);+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+}++function requireValue(condition, message) {+ if (!condition) blocked(message);+}++function object(value) {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function keys(value, allowed, required = allowed) {+ return object(value)+ && Object.keys(value).every((key) => allowed.includes(key))+ && required.every((key) => Object.hasOwn(value, key));+}++function positiveInteger(value) {+ return Number.isSafeInteger(value) && value > 0;+}++function exactVersion(value, stable = false) {+ if (typeof value !== 'string' || value.length > 128) return false;+ const match = VERSION.exec(value);+ return Boolean(match && (!stable || !match[4])+ && (!match[4] || match[4].split('.').every((part) => !/^\d+$/.test(part) || part === '0' || part[0] !== '0')));+}++function validHostIntegrity(value) {+ return typeof value === 'string'+ && /^(?:sha512-[A-Za-z0-9+/]{86}==|sha1-[A-Za-z0-9+/]{27}=)$/.test(value);+}++function safePackageName(name) {+ return typeof name === 'string' && name.length <= 214 && PACKAGE_NAME.test(name)+ && !name.split('/').some((part) => part === '.' || part === '..' || part === 'node_modules');+}++function safeInstallPath(value) {+ return typeof value === 'string' && value.length <= 4096 && INSTALL_PATH.test(value)+ && value.split('/node_modules/').every((part) => safePackageName(part.replace(/^node_modules\//, '')));+}++function declarationSpec(value) {+ if (typeof value !== 'string' || !value.trim() || value.length > 256 || /[\u0000-\u001f]/.test(value)) return false;+ if (/^file:\.\/vendor\/[a-zA-Z0-9][a-zA-Z0-9._-]*\.tgz$/.test(value)) return true;+ // Reviewed registry declarations may be ranges; the installed inventory is exact.+ return semver.validRange(value) !== null;+}++function publicEvidence(value) {+ if (typeof value !== 'string' || !value.startsWith('https://') || value.length > 2048 || /\s|\\/.test(value)) return false;+ try {+ const url = new URL(value);+ const host = url.hostname.toLowerCase();+ // No signed URLs, credentials, IP literals, intranet names, or private repo hosts.+ return url.protocol === 'https:' && !url.username && !url.password && !url.search+ && !url.hash && !url.port && !net.isIP(host) && !host.includes(':')+ && /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(host)+ && !host.split('.').some((label) => /^(?:localhost|local|localdomain|internal|intranet|corp|lan|home|private|invalid|test)$/.test(label))+ && host !== 'ghe.com' && !host.endsWith('.ghe.com')+ && !/(?:token|password|secret|signature|authorization)[=:]/i.test(decodeURIComponent(url.pathname));+ } catch {+ return false;+ }+}++function validateRelease(release) {+ const published = release?.source === 'npm';+ requireValue(keys(release, [+ 'id', 'template', 'templateVersion', 'nativeRuntimeVersions', 'managedDependencies',+ 'nativePackages', 'platforms', ...(published ? ['source', 'host'] : ['evidence']),+ ]), 'Invalid reviewed release schema; ask a maintainer to repair the release policy.');+ if (published) {+ requireValue(keys(release.host, ['package', 'version', 'integrity'])+ && release.host.package === HOST && exactVersion(release.host.version, true)+ && validHostIntegrity(release.host.integrity),+ 'Invalid published host identity or integrity.');+ }+ requireValue(typeof release.id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(release.id), 'Invalid reviewed release id.');+ requireValue(keys(release.template, ['package', 'version', 'integrity'])+ && release.template.package === '@microsoft/power-apps-native-template'+ && exactVersion(release.template.version, true), 'Reviewed template must have its public package name and exact stable version.');+ const integrity = release.template.integrity;+ requireValue(typeof integrity === 'string' && /^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)+ && Buffer.from(integrity.slice(7), 'base64').toString('base64') === integrity.slice(7), 'Reviewed template must have a sha512 SRI integrity.');+ requireValue(positiveInteger(release.templateVersion), 'Invalid reviewed templateVersion.');+ requireValue(keys(release.nativeRuntimeVersions, ['android', 'ios'])+ && Object.values(release.nativeRuntimeVersions).every(positiveInteger), 'Invalid reviewed nativeRuntimeVersions.');+ requireValue(keys(release.managedDependencies, SECTIONS, []), 'Invalid reviewed managedDependencies.');+ const managedNames = new Set();+ for (const section of SECTIONS) {+ if (!Object.hasOwn(release.managedDependencies, section)) continue;+ const dependencies = release.managedDependencies[section];+ requireValue(object(dependencies), 'Invalid reviewed dependency section.');+ for (const [name, spec] of Object.entries(dependencies)) {+ requireValue(safePackageName(name) && declarationSpec(spec) && !managedNames.has(name), 'Invalid or duplicate reviewed managed dependency.');+ managedNames.add(name);+ }+ }+ requireValue(CORE.every((name) => Object.hasOwn(release.managedDependencies.dependencies || {}, name)), 'Reviewed release must manage the host, expo, react-native and react runtime dependencies.');+ requireValue(object(release.nativePackages) && Object.keys(release.nativePackages).length > 0, 'Reviewed release needs an exact native package inventory.');+ for (const [installPath, version] of Object.entries(release.nativePackages)) {+ requireValue(safeInstallPath(installPath) && exactVersion(version), 'Invalid reviewed native package path or exact version.');+ }+ for (const dependencies of Object.values(release.managedDependencies)) {+ for (const [name, spec] of Object.entries(dependencies)) {+ const version = release.nativePackages[`node_modules/${name}`];+ if (version && !spec.startsWith('file:./vendor/')) {+ requireValue(semver.satisfies(version, spec),+ `Managed native dependency ${name} does not accept its reviewed exact version.`);+ }+ }+ }+ requireValue(CORE.every((name) => Object.hasOwn(release.nativePackages, `node_modules/${name}`)), 'Reviewed native inventory must include the host, expo, react-native and react.');+ requireValue(exactVersion(release.nativePackages[`node_modules/${HOST}`], true),+ 'Reviewed host must have an exact stable version; prerelease hosts require the separate diagnostic contract.');+ requireValue(!published || release.nativePackages[`node_modules/${HOST}`] === release.host.version,+ 'Published host identity differs from the native inventory.');+ for (const name of managedNames) {+ requireValue(!isRuntimePackage(name) || Object.hasOwn(release.nativePackages, `node_modules/${name}`), 'Reviewed native inventory is missing a managed runtime dependency.');+ }+ requireValue(keys(release.platforms, ['android', 'ios']), 'The host contract must describe Android and iOS requirements.');+ for (const platform of Object.values(release.platforms)) {+ requireValue(keys(platform, published ? ['fingerprint'] : ['fingerprint', 'base', 'player'])+ && typeof platform.fingerprint === 'string'+ && /^[a-zA-Z0-9][a-zA-Z0-9._:+-]{0,255}$/.test(platform.fingerprint), 'Invalid reviewed platform fingerprint.');+ for (const target of published ? [] : ['base', 'player']) {+ requireValue(keys(platform[target], ['version', 'evidence'])+ && typeof platform[target].version === 'string' && TOKEN.test(platform[target].version)+ && publicEvidence(platform[target].evidence), 'Reviewed base and player need versions and public HTTPS verification evidence.');+ }+ }+ if (!published) {+ requireValue(Array.isArray(release.evidence) && release.evidence.length > 0+ && release.evidence.every(publicEvidence), 'Reviewed release needs public HTTPS publication and device-validation evidence.');+ }+ return release;+}++function validateCatalog(catalog) {+ requireValue(keys(catalog, ['schemaVersion', 'defaultRelease', 'releases'])+ && catalog.schemaVersion === 1 && Array.isArray(catalog.releases), 'Invalid bundled mobile release policy; update or repair the plugin.');+ const ids = new Set();+ for (const release of catalog.releases) {+ validateRelease(release);+ requireValue(!ids.has(release.id), 'Duplicate reviewed release id.');+ ids.add(release.id);+ }+ requireValue(catalog.defaultRelease === null || (typeof catalog.defaultRelease === 'string' && ids.has(catalog.defaultRelease)), 'The default release must reference a reviewed policy entry, or be null.');+ return catalog;+}++function readJson(filePath, label) {+ try {+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));+ requireValue(object(parsed), `${label} must contain a JSON object.`);+ return parsed;+ } catch (error) {+ if (error.code === 'MOBILE_RELEASE_BLOCKED') throw error;+ // JSON parse and filesystem errors may contain application config or paths.+ blocked(`Cannot read valid ${label}. Restore the file before continuing.`);+ }+}++function selectRelease(id, catalog, options) {+ if (catalog === undefined) return require('./mobile-published-packages').selectPublishedContract(id, options);+ validateCatalog(catalog);+ requireValue(id === undefined || id === null || (typeof id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(id)), 'Use a valid reviewed release id.');+ const selected = catalog.releases.find((release) => release.id === (id ?? catalog.defaultRelease));+ requireValue(selected, 'No verified mobile release is available for this selection. Ask a maintainer to publish and review template, host, Android/iOS player and base evidence; do not use npm latest or bypass this gate.');+ return selected;+}++function isRuntimePackage(name) {+ return RUNTIME_NAMES.some((pattern) => pattern.test(name));+}++function npmAliasTarget(spec) {+ if (typeof spec !== 'string' || !spec.startsWith('npm:')) return null;+ const separator = spec.indexOf('@', spec[4] === '@' ? 5 : 4);+ const name = spec.slice(4, separator < 0 ? undefined : separator);+ return safePackageName(name) ? name : null;+}++function dependencySections(pkg) {+ const result = {};+ for (const section of SECTIONS) {+ if (pkg[section] === undefined) continue;+ requireValue(object(pkg[section]), 'Invalid package dependency section.');+ result[section] = pkg[section];+ for (const [name, spec] of Object.entries(pkg[section])) {+ requireValue(safePackageName(name) && typeof spec === 'string' && spec.length > 0, 'Invalid package dependency declaration.');+ }+ }+ return result;+}++function detectsNative(directory, pkg) {+ if (Object.hasOwn(pkg, 'codegenConfig') || pkg.expo?.plugins || pkg.expo?.autolinking) return true;+ function visit(current) {+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === '.git') continue;+ requireValue(!entry.isSymbolicLink(), 'Linked package contents cannot be verified against the reviewed runtime.');+ if (/\.podspec(?:\.json)?$|\.(?:java|kt|kts|gradle|swift|m|mm|h|hpp|c|cc|cpp|cxx|aar|so|a|dylib|dll|lib|vcxproj|csproj|sln)$/.test(entry.name)+ || /^(?:expo-module\.config\.json|app\.plugin\.[cm]?js|react-native\.config\.[cm]?js|Podfile|CMakeLists\.txt|AndroidManifest\.xml)$/.test(entry.name)+ || /\.(?:xcodeproj|xcworkspace|xcframework|framework)$/.test(entry.name)) return true;+ if (entry.isDirectory()+ && (entry.name === 'android' || entry.name === 'ios' || visit(path.join(current, entry.name)))) return true;+ }+ return false;+ }+ return visit(directory);+}++function inspectInstalledPackages(projectRoot, lock) {+ const installed = new Map();+ function visitModules(relativeDirectory) {+ const directory = path.join(projectRoot, relativeDirectory);+ if (!fs.existsSync(directory)) return;+ requireValue(!fs.lstatSync(directory).isSymbolicLink(), 'Linked node_modules cannot be verified against the reviewed runtime.');+ function visitPackage(relativePath) {+ requireValue(safeInstallPath(relativePath), 'Unsupported installed package path.');+ const absolutePath = path.join(projectRoot, relativePath);+ requireValue(!fs.lstatSync(absolutePath).isSymbolicLink(), 'Linked packages cannot be verified against the reviewed runtime.');+ const pkg = readJson(path.join(absolutePath, 'package.json'), 'installed package manifest');+ const name = relativePath.split('/node_modules/').pop().replace(/^node_modules\//, '');+ requireValue(safePackageName(pkg.name) && exactVersion(pkg.version), 'Installed package identity or version is invalid.');+ dependencySections(pkg);+ const native = isRuntimePackage(name) || isRuntimePackage(pkg.name) || detectsNative(absolutePath, pkg);+ const alias = pkg.name !== name;+ const locked = lock?.packages?.[relativePath];+ if (alias) {+ // npm aliases retain the canonical package name in package.json and the+ // v2/v3 lock entry, e.g. string-width-cjs -> string-width. The release+ // inventory cannot bind a separate canonical native identity safely.+ requireValue(!native, 'Native/runtime npm aliases cannot be admitted by the reviewed inventory schema.');+ requireValue([2, 3].includes(lock?.lockfileVersion) && object(locked) && !locked.link+ && locked.name === pkg.name && locked.version === pkg.version,+ 'Installed npm alias must match its canonical name and exact version in the app lock.');+ }+ requireValue(locked?.name === undefined || locked.name === pkg.name, 'Installed package canonical identity differs from the app lock.');+ installed.set(relativePath, {+ name, canonicalName: pkg.name, alias, version: pkg.version, pkg, native,+ });+ visitModules(`${relativePath}/node_modules`);+ }+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {+ if (entry.name.startsWith('.')) continue;+ if (entry.name.startsWith('@')) {+ requireValue(entry.isDirectory() && !entry.isSymbolicLink(), 'Invalid installed package scope.');+ for (const child of fs.readdirSync(path.join(directory, entry.name), { withFileTypes: true })) {+ requireValue(child.isDirectory() || child.isSymbolicLink(), 'Invalid installed scoped package.');+ visitPackage(`${relativeDirectory}/${entry.name}/${child.name}`);+ }+ } else if (entry.isDirectory() || entry.isSymbolicLink()) {+ visitPackage(`${relativeDirectory}/${entry.name}`);+ }+ }+ }+ try {+ const lockPath = path.join(projectRoot, 'package-lock.json');+ if (lock === undefined && fs.existsSync(lockPath)) lock = readJson(lockPath, 'package-lock.json');+ visitModules('node_modules');+ return installed;+ } catch (error) {+ if (error.code === 'MOBILE_RELEASE_BLOCKED') throw error;+ blocked('Cannot inspect installed dependencies. Restore a complete npm installation before continuing.');+ }+}++function readPlatformContext({ os = process.platform, cpu = process.arch, getReport = () => process.report?.getReport?.() } = {}) {+ let libc = null;+ if (os === 'linux') {+ try {+ // Inspect only in memory: diagnostic reports also contain environment+ // variables and paths and must never be logged or written by this gate.+ const report = getReport();+ if (typeof report?.header?.glibcVersionRuntime === 'string' && report.header.glibcVersionRuntime) {+ libc = 'glibc';+ } else if (Array.isArray(report?.sharedObjects) && report.sharedObjects.some((file) => typeof file === 'string'+ && /(?:^|\/)(?:ld-musl-[^/]+|libc\.musl-[^/]+)\.so(?:\.\d+)*$/.test(file))) {+ libc = 'musl';+ }+ } catch {+ // An unknown libc is not evidence that an optional package is ineligible.+ }+ }+ return { os, cpu, libc };+}++function optionalForOtherPlatform(entry, context) {+ const excludes = (value, current) => {+ if (value === undefined) return false;+ const values = typeof value === 'string' ? [value] : value;+ requireValue(Array.isArray(values) && values.every((item) => typeof item === 'string' && /^!?[a-zA-Z0-9_-]+$/.test(item)),+ 'Invalid platform constraints in the app lock.');+ if (!current || values.length === 0 || (values.length === 1 && values[0] === 'any')) return false;+ return values.includes(`!${current}`)+ || (values.some((item) => !item.startsWith('!')) && !values.includes(current));+ };+ return entry.optional === true && (excludes(entry.os, context.os) || excludes(entry.cpu, context.cpu)+ || (context.os === 'linux' && excludes(entry.libc, context.libc)));+}++function resolveInstalledDependency(inventory, from, name) {+ let parent = from;+ while (parent) {+ const candidate = `${parent}/node_modules/${name}`;+ if (inventory.has(candidate)) return candidate;+ const index = parent.lastIndexOf('/node_modules/');+ parent = index < 0 ? '' : parent.slice(0, index);+ }+ return inventory.has(`node_modules/${name}`) ? `node_modules/${name}` : null;+}++function dependencyEdges(pkg, includeDev = false) {+ dependencySections(pkg);+ const required = { ...pkg.dependencies, ...(includeDev ? pkg.devDependencies : {}) };+ const children = { ...required, ...pkg.optionalDependencies, ...pkg.peerDependencies };+ return new Map(Object.keys(children).map((name) => {+ const optionalDependency = Object.hasOwn(pkg.optionalDependencies || {}, name);+ const optionalPeer = !Object.hasOwn(required, name) && !optionalDependency+ && pkg.peerDependenciesMeta?.[name]?.optional === true;+ const spec = pkg.optionalDependencies?.[name] ?? required[name] ?? pkg.peerDependencies?.[name];+ return [name, { optional: optionalDependency || optionalPeer, optionalPeer, specs: [spec] }];+ }));+}++function validateDependencyReachability(lock, installed, context) {+ const inventory = new Map(Object.entries(lock.packages));+ const edgesFor = (installPath) => {+ const result = dependencyEdges(inventory.get(installPath), installPath === '');+ const actual = installed.get(installPath);+ if (actual) {+ // Installed manifests are inspected too: incomplete/stale lock metadata+ // must not conceal an ordinary JS wrapper's native dependency.+ for (const [name, edge] of dependencyEdges(actual.pkg)) {+ const previous = result.get(name);+ result.set(name, previous ? {+ optional: previous.optional && edge.optional,+ optionalPeer: previous.optionalPeer && edge.optionalPeer,+ specs: [...previous.specs, ...edge.specs],+ } : edge);+ }+ }+ return result;+ };++ const omitted = new Set();+ const pendingOmissions = [...inventory].filter(([installPath, entry]) => installPath !== ''+ && !installed.has(installPath) && optionalForOtherPlatform(entry, context)).map(([installPath]) => installPath);+ while (pendingOmissions.length > 0) {+ const installPath = pendingOmissions.pop();+ if (omitted.has(installPath)) continue;+ omitted.add(installPath);+ for (const name of dependencyEdges(inventory.get(installPath)).keys()) {+ const child = resolveInstalledDependency(inventory, installPath, name);+ if (child) pendingOmissions.push(child);+ }+ }++ // Every installed package stays in scope, even if its optional parent is+ // absent. Only missing, exclusively inactive optional branches may be omitted.+ for (const installPath of ['', ...installed.keys()]) {+ for (const [name, edge] of edgesFor(installPath)) {+ const child = resolveInstalledDependency(inventory, installPath, name);+ const actual = installed.get(child);+ if (actual) {+ requireValue(!actual.alias || edge.specs.every((spec) => npmAliasTarget(spec) === actual.canonicalName),+ 'Installed npm alias canonical identity does not match its dependency declaration.');+ continue;+ }+ if (edge.optionalPeer) continue;+ if (child && edge.optional && optionalForOtherPlatform(inventory.get(child), context)) continue;+ blocked(installPath === ''+ ? 'A declared dependency is not installed and cannot be checked for native code. Restore the app lock installation with npm ci.'+ : 'An installed dependency has an incomplete transitive dependency tree. Restore the app lock installation with npm ci before native verification.');+ }+ }+ for (const [installPath, entry] of inventory) {+ if (installPath !== '' && !installed.has(installPath)) {+ requireValue(entry.optional === true && omitted.has(installPath),+ 'A locked dependency is not installed. Restore the app lock installation with npm ci.');+ }+ }+}++function readProjectRequirements(projectRoot) {+ requireValue(typeof projectRoot === 'string' && projectRoot.length > 0, 'A project root is required.');+ const config = readJson(path.join(projectRoot, 'app.json'), 'app.json');+ const metadata = config.expo?.extra?.powerappsNative;+ requireValue(object(metadata)+ && metadata.schemaVersion === 1 && positiveInteger(metadata.templateVersion)+ && keys(metadata.nativeRuntimeVersions, ['android', 'ios'])+ && Object.values(metadata.nativeRuntimeVersions).every(positiveInteger), 'Missing or invalid protected app.json expo.extra.powerappsNative metadata. Use a verified template; do not invent or rewrite runtime versions.');+ return {+ schemaVersion: metadata.schemaVersion,+ templateVersion: metadata.templateVersion,+ nativeRuntimeVersions: { ...metadata.nativeRuntimeVersions },+ };+}++function readProject(projectRoot, platformContext) {+ const metadata = readProjectRequirements(projectRoot);+ const pkg = readJson(path.join(projectRoot, 'package.json'), 'package.json');+ const declarations = dependencySections(pkg);+ const lock = readJson(path.join(projectRoot, 'package-lock.json'), 'package-lock.json');+ requireValue([2, 3].includes(lock.lockfileVersion) && object(lock.packages) && object(lock.packages['']), 'A complete npm package-lock.json v2 or v3 is required to verify this runtime.');+ const lockDeclarations = dependencySections(lock.packages['']);+ for (const section of SECTIONS) {+ const declared = declarations[section] || {};+ const locked = lockDeclarations[section] || {};+ requireValue(Object.keys(declared).length === Object.keys(locked).length+ && Object.entries(declared).every(([name, version]) => locked[name] === version), 'package.json declarations do not match the app lock. Restore the approved lock and install with npm ci.');+ }+ const installed = inspectInstalledPackages(projectRoot, lock);+ for (const [installPath, entry] of Object.entries(lock.packages)) {+ if (installPath === '') continue;+ requireValue(safeInstallPath(installPath) && object(entry) && !entry.link && exactVersion(entry.version), 'Invalid or linked app lock package inventory.');+ const actual = installed.get(installPath);+ requireValue(!actual || actual.version === entry.version, 'An installed dependency version differs from the app lock. Restore the reviewed installation with npm ci.');+ }+ for (const installPath of installed.keys()) {+ requireValue(Object.hasOwn(lock.packages, installPath), 'An installed dependency is absent from the app lock. Restore the reviewed installation with npm ci.');+ }+ validateDependencyReachability(lock, installed, platformContext);+ return { metadata, declarations, lock, installed };+}++function validateProjectAgainstRelease(project, release) {+ const { declarations, installed, lock } = project;+ const managed = new Set();+ for (const section of SECTIONS) {+ for (const [name, spec] of Object.entries(release.managedDependencies[section] || {})) {+ requireValue(declarations[section]?.[name] === spec, `Managed dependency ${name} does not match the reviewed release declaration. Restore the release dependency set.`);+ requireValue(SECTIONS.every((other) => other === section || !Object.hasOwn(declarations[other] || {}, name)), 'A managed dependency is shadowed in another dependency section.');+ managed.add(name);+ }+ }+ for (const dependencies of Object.values(declarations)) {+ for (const name of Object.keys(dependencies)) {+ requireValue(managed.has(name) || !(isRuntimePackage(name) || installed.get(`node_modules/${name}`)?.native), `Native/runtime dependency ${name} is not managed by this app's verified release.`);+ }+ }+ for (const [installPath, version] of Object.entries(release.nativePackages)) {+ requireValue(installed.get(installPath)?.version === version && lock.packages[installPath]?.version === version, 'Installed native inventory does not match the reviewed release, including nested package versions. Restore the release lock and installation.');+ }+ for (const [installPath, actual] of installed) {+ requireValue(!actual.native || release.nativePackages[installPath] === actual.version, 'Unreviewed native package detected in the installed dependency tree. Select a verified runtime that includes it; JavaScript approval cannot add native code.');+ }+}++function reviewedProjectCatalog(catalog) {+ validateCatalog(catalog);+ requireValue(catalog.releases.length > 0, 'No verified mobile releases are configured. A maintainer must review public template, host, Android/iOS player and base evidence before this workflow can proceed.');+ return catalog;+}++function matchingProjectRequirements(metadata, catalog) {+ const candidates = catalog.releases.filter((release) => release.templateVersion === metadata.templateVersion+ && ['android', 'ios'].every((platform) => release.nativeRuntimeVersions[platform] === metadata.nativeRuntimeVersions[platform]));+ requireValue(candidates.length > 0, 'Protected app metadata does not match a verified release. Do not substitute the newest template or invent runtime metadata.');+ return candidates;+}++function selectProjectRelease(projectRoot, catalog) {+ if (catalog === undefined) return require('./mobile-published-packages').readSourceRequirements(projectRoot);+ reviewedProjectCatalog(catalog);+ // Read-only update planning must survive host/dependency drift. This identifies+ // the source template's requirements, not an admitted installation or deployment.+ let candidates = matchingProjectRequirements(readProjectRequirements(projectRoot), catalog);+ if (candidates.length > 1) {+ // Host-only releases can share protected runtime counters. Use only the+ // installed host identity to break that tie; declarations or npm latest must+ // not choose a source record, and this still does not admit the installation.+ for (const relativePath of ['node_modules', 'node_modules/@microsoft', `node_modules/${HOST}`]) {+ const directory = path.join(projectRoot, relativePath);+ requireValue(fs.existsSync(directory), 'Protected app requirements match multiple reviewed releases and the installed host is unavailable. Restore a reviewed host installation before update planning.');+ requireValue(!fs.lstatSync(directory).isSymbolicLink(), 'Linked host installations cannot disambiguate reviewed project requirements.');+ }+ const host = readJson(path.join(projectRoot, 'node_modules', HOST, 'package.json'), 'installed host package manifest');+ requireValue(host.name === HOST && exactVersion(host.version), 'Installed host identity or version is invalid; it cannot disambiguate reviewed project requirements.');+ candidates = candidates.filter((release) => release.nativePackages[`node_modules/${HOST}`] === host.version);+ }+ requireValue(candidates.length === 1, 'Protected app requirements match multiple reviewed releases and the installed host does not identify a unique source record. A maintainer must disambiguate the policy before update planning.');+ return candidates[0];+}++function resolveProjectRelease(projectRoot, catalog, platformContext = readPlatformContext(), options) {+ return resolveProjectReleaseWithInventory(projectRoot, catalog, platformContext, options).release;+}++function resolveProjectReleaseWithInventory(projectRoot, catalog, platformContext = readPlatformContext(), options) {+ if (catalog !== undefined) reviewedProjectCatalog(catalog);+ requireValue(keys(platformContext, ['os', 'cpu', 'libc']) && typeof platformContext.os === 'string'+ && /^[a-z0-9_-]+$/.test(platformContext.os) && typeof platformContext.cpu === 'string'+ && /^[a-z0-9_-]+$/.test(platformContext.cpu) && [null, 'glibc', 'musl'].includes(platformContext.libc),+ 'A valid installation platform context is required.');+ const project = readProject(projectRoot, platformContext);+ if (catalog === undefined) {+ const release = require('./mobile-published-packages').projectContract(projectRoot, project, options);+ validateRelease(release);+ validateProjectAgainstRelease(project, release);+ return { release, installed: project.installed };+ }+ const candidates = matchingProjectRequirements(project.metadata, catalog);+ const matches = [];+ let mismatch;+ for (const release of candidates) {+ try {+ validateProjectAgainstRelease(project, release);+ matches.push(release);+ } catch (error) {+ if (error.code !== 'MOBILE_RELEASE_BLOCKED') throw error;+ mismatch = error;+ }+ }+ if (matches.length === 0) throw mismatch;+ requireValue(matches.length === 1, 'The project matches multiple reviewed releases. A maintainer must disambiguate the release policy.');+ return { release: matches[0], installed: project.installed };+}++function summarizeRelease(release) {+ if (release?.validationScope === 'requirements-only') return { ...release };+ validateRelease(release);+ // Only reviewed policy metadata: canonical package-relative inventory and+ // safe declarations are useful to planners. Never include project config,+ // absolute filesystem paths, or app lockfile resolution URLs.+ return {+ id: release.id,+ template: { ...release.template },+ templateVersion: release.templateVersion,+ nativeRuntimeVersions: { ...release.nativeRuntimeVersions },+ hostVersion: release.nativePackages[`node_modules/${HOST}`],+ managedDependencies: Object.fromEntries(Object.entries(release.managedDependencies)+ .map(([section, dependencies]) => [section, { ...dependencies }])),+ nativePackages: { ...release.nativePackages },+ platforms: Object.fromEntries(['android', 'ios'].map((platform) => [platform, {+ fingerprint: release.platforms[platform].fingerprint,+ ...(release.source !== 'npm' ? {+ base: { ...release.platforms[platform].base },+ player: { ...release.platforms[platform].player },+ } : {}),+ }])),+ ...(release.source === 'npm'+ ? { source: 'npm', host: { ...release.host }, binaryAvailability: 'not-checked' }+ : { evidence: [...release.evidence] }),+ };+}++module.exports = {+ selectRelease, resolveProjectRelease, resolveProjectReleaseWithInventory, validateRelease, summarizeRelease,+ readProjectRequirements, selectProjectRelease,+ // Shared by the backwards-compatible write validator; not a release bypass.+ dependencySections, inspectInstalledPackages, isRuntimePackage, resolveInstalledDependency, readPlatformContext, npmAliasTarget,+ readProject, validateProjectAgainstRelease, exactVersion, declarationSpec, validHostIntegrity,+};diff --git a/plugins/mobile-apps/scripts/lib/npm-context.js b/plugins/mobile-apps/scripts/lib/npm-context.jsnew file mode 100644index 000000000..84c3eafe0--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/npm-context.js@@ -0,0 +1,57 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { runCliSync } = require('./process-runner');++/** Keep project npm settings local to the isolated installation, never the scaffold. */+function withNpmContext(sourceRoot, installRoot, operation) {+ const cwd = fs.realpathSync.native(sourceRoot);+ let prefix;+ try {+ const options = { cwd, encoding: 'utf8', timeout: 30000, maxBuffer: 1024 * 1024 };+ prefix = runCliSync('npm', ['prefix', '--silent'], options).trim();+ if (!path.isAbsolute(prefix)) {+ throw new Error('Invalid npm configuration context');+ }+ } catch {+ const error = new Error('Cannot preserve the caller npm configuration. Check the local npm installation and configuration; no isolated install was started.');+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+ }+ const env = { ...process.env };+ const settings = {+ prefix: path.resolve(installRoot),+ global: 'false',+ workspaces: 'false',+ };+ for (const [key, value] of Object.entries(settings)) {+ for (const name of Object.keys(env)) {+ if (name.toLowerCase() === `npm_config_${key}`) delete env[name];+ }+ env[`npm_config_${key}`] = value;+ }+ const source = path.join(prefix, '.npmrc');+ const destination = path.join(installRoot, '.npmrc');+ let created = false;+ try {+ if (fs.existsSync(source)) {+ const content = fs.readFileSync(source);+ if (fs.existsSync(destination)) {+ const stat = fs.lstatSync(destination);+ if (!stat.isFile() || stat.isSymbolicLink() || !content.equals(fs.readFileSync(destination))) {+ throw new Error('The isolated npm configuration differs from the original context; review the snapshot before installing.');+ }+ } else {+ fs.writeFileSync(destination, content, { flag: 'wx', mode: 0o600 });+ created = true;+ }+ }+ // npm's prefix isolates package writes; the original cwd preserves relative TLS/auth paths.+ return operation(env, cwd);+ } finally {+ if (created) fs.unlinkSync(destination);+ }+}++module.exports = { withNpmContext };diff --git a/plugins/mobile-apps/scripts/mobile-template-lifecycle.js b/plugins/mobile-apps/scripts/mobile-template-lifecycle.jsnew file mode 100644index 000000000..7b7861ede--- /dev/null+++ b/plugins/mobile-apps/scripts/mobile-template-lifecycle.js@@ -0,0 +1,384 @@+#!/usr/bin/env node+'use strict';++const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { createHash } = require('node:crypto');+const { isDeepStrictEqual } = require('node:util');+const { runCliSync, CliLaunchError } = require('./lib/process-runner');+const { withNpmContext } = require('./lib/npm-context');+const { planPublishedUpdate, readSourceRequirements } = require('./lib/mobile-published-packages');+const {+ selectRelease,+ summarizeRelease,+ dependencySections,+ inspectInstalledPackages,+ isRuntimePackage,+} = require('./lib/mobile-release');++const HOST = '@microsoft/power-apps-native-host';+const TEMPLATE = '@microsoft/power-apps-native-template';++function readJson(file) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch {+ throw new Error(`Cannot read valid ${path.basename(file)}; restore it before continuing`);+ }+}++function assertEmptyDestination(destination) {+ const stat = fs.lstatSync(destination, { throwIfNoEntry: false });+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink() || fs.readdirSync(destination).length)) {+ throw new Error('Creation requires a new or empty real directory; existing apps are never overwritten');+ }+}++function run(command, args, cwd, { env = process.env, failureMessage } = {}) {+ const isNpm = command === 'npm';+ const configuredTimeoutMs = Number.parseInt(process.env.MOBILE_TEMPLATE_NPM_TIMEOUT_MS ?? '', 10);+ const timeoutMs = Number.isFinite(configuredTimeoutMs) && configuredTimeoutMs > 0+ ? configuredTimeoutMs+ : 10 * 60 * 1000;+ try {+ return runCliSync(command, args, {+ cwd,+ encoding: 'utf8',+ timeout: timeoutMs,+ maxBuffer: 4 * 1024 * 1024,+ env: { ...env, npm_config_ignore_scripts: 'true' },+ });+ } catch (error) {+ if (!(error instanceof CliLaunchError) && !(Number.isInteger(error.status) && error.status > 0)) throw error;+ throw new Error(failureMessage || `${isNpm ? 'Template package installation' : 'Template CLI'} failed; check registry access, slow network conditions, package support locally, or increase MOBILE_TEMPLATE_NPM_TIMEOUT_MS if the command is timing out (raw output withheld)`);+ }+}++function assertTemplateManifest(manifest, release) {+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)+ || manifest.schemaVersion !== 1+ || manifest.templatePackage?.name !== TEMPLATE+ || manifest.templatePackage?.version !== release.template.version+ || manifest.templateVersion !== release.templateVersion+ || ['android', 'ios'].some((platform) => (+ manifest.nativeRuntimeVersions?.[platform] !== release.nativeRuntimeVersions[platform]+ ))) {+ throw new Error('Packaged template manifest does not match the reviewed release');+ }+}++function assertSelfContainedTemplate(installed, lock, packageRoot) {+ if (['dependencies', 'optionalDependencies', 'peerDependencies'].some(section => (+ Object.keys(installed[section] || {}).length > 0+ )) || installed.bundleDependencies === true || installed.bundledDependencies === true+ || installed.bundleDependencies?.length || installed.bundledDependencies?.length+ || Object.keys(lock.packages || {}).some(name => name && name !== `node_modules/${TEMPLATE}`)+ || fs.existsSync(path.join(packageRoot, 'node_modules'))) {+ throw new Error('Template creation requires a self-contained CLI with no acquired or bundled dependencies.');+ }+ const modules = path.dirname(path.dirname(packageRoot));+ if (fs.readdirSync(modules).some(name => !['.bin', '.package-lock.json', '@microsoft'].includes(name))+ || fs.readdirSync(path.join(modules, '@microsoft')).some(name => name !== 'power-apps-native-template')) {+ throw new Error('The template tooling installation contains unexpected packages; no creation CLI was executed.');+ }+}++function inspectDestination(destination) {+ const target = path.resolve(destination);+ assertEmptyDestination(target);+ let parent = path.dirname(target);+ while (!fs.lstatSync(parent, { throwIfNoEntry: false })) parent = path.dirname(parent);+ if (!fs.statSync(parent).isDirectory()) throw new Error('Creation requires an existing directory ancestor.');+ const canonicalParent = fs.realpathSync.native(parent);+ const resolved = path.resolve(canonicalParent, path.relative(parent, target));+ assertEmptyDestination(resolved);+ return { parent: canonicalParent, destination: resolved, exists: fs.existsSync(resolved) };+}++function acquireTemplate(destination, releaseId, options = {}) {+ const release = options.catalog ? selectRelease(releaseId, options.catalog)+ : require('./lib/mobile-published-packages').selectTemplateContract(releaseId, options);+ const target = path.resolve(destination);+ assertEmptyDestination(target);+ const execute = options.run || run;+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-template-package-'));+ fs.chmodSync(staging, 0o700);+ try {+ fs.writeFileSync(path.join(staging, 'package.json'), '{"name":"template-acquisition","private":true}\n');+ withNpmContext(options.cwd || process.cwd(), staging, (env, cwd) => execute('npm', [+ 'install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact',+ `${TEMPLATE}@${release.template.version}`, '--prefix', staging,+ ], cwd, { env }));+ const packageRoot = path.join(staging, 'node_modules', TEMPLATE);+ if (!fs.lstatSync(packageRoot).isDirectory() || fs.lstatSync(packageRoot).isSymbolicLink()) {+ throw new Error('Template must be an installed registry package, not a symbolic link');+ }+ const installed = readJson(path.join(packageRoot, 'package.json'));+ const lock = readJson(path.join(staging, 'package-lock.json'));+ const locked = lock.packages?.[`node_modules/${TEMPLATE}`];+ if (installed.name !== TEMPLATE || installed.version !== release.template.version+ || locked?.version !== release.template.version || locked?.integrity !== release.template.integrity) {+ throw new Error('Installed template version/integrity does not match the reviewed release');+ }+ assertSelfContainedTemplate(installed, lock, packageRoot);+ const bin = installed.bin?.['create-power-app-native'];+ if (typeof bin !== 'string' || path.isAbsolute(bin) || bin.split(/[\\/]/).includes('..')) {+ throw new Error('Template package does not expose the supported creation CLI');+ }+ const executable = path.join(packageRoot, bin);+ const relative = path.relative(fs.realpathSync(packageRoot), fs.realpathSync(executable));+ if (relative.startsWith('..') || path.isAbsolute(relative) || !fs.lstatSync(executable).isFile()) {+ throw new Error('Template CLI must be a regular file inside its package');+ }+ let manifest;+ try {+ manifest = JSON.parse(execute(process.execPath, [executable, '--manifest'], staging));+ } catch {+ throw new Error('Template CLI inspection failed or returned an unsupported manifest');+ }+ assertTemplateManifest(manifest, release);+ assertEmptyDestination(target);+ execute(process.execPath, [executable, target], staging);+ const created = readJson(path.join(target, 'app.json')).expo?.extra?.powerappsNative;+ assertTemplateManifest({ ...created, templatePackage: manifest.templatePackage }, release);+ return { release: summarizeRelease(release), installedDependencies: false };+ } finally {+ // This is only the unique temporary package install, never the customer's target.+ fs.rmSync(staging, { recursive: true, force: true });+ }+}++function acquireHost(destination, version, options = {}) {+ const target = path.resolve(destination);+ assertEmptyDestination(target);+ const published = require('./lib/mobile-published-packages');+ const source = published.createSource(options);+ const contract = published.selectPublishedContract(version, {+ ...options, readPackage: source.read, versions: source.versions,+ });+ const profile = source.read(HOST, version).profile;+ const execute = options.run || run;+ assertEmptyDestination(target);+ fs.mkdirSync(target, { recursive: true });+ withNpmContext(options.cwd || process.cwd(), target, (env, cwd) => {+ fs.writeFileSync(path.join(target, 'package.json'), `${JSON.stringify({+ name: 'mobile-upgrade-tooling', private: true,+ ...contract.managedDependencies,+ dependencies: { ...contract.managedDependencies.dependencies, [HOST]: version },+ ...(profile.managedOverrides ? { overrides: profile.managedOverrides } : {}),+ }, null, 2)}\n`, { flag: 'wx' });+ return execute('npm', [+ 'install', '--ignore-scripts', '--strict-peer-deps', '--no-legacy-peer-deps', '--no-force', '--no-audit', '--no-fund',+ '--prefix', target,+ ], cwd, { env });+ });+ const hostRoot = path.join(target, 'node_modules', HOST);+ const installed = readJson(path.join(hostRoot, 'package.json'));+ const locked = readJson(path.join(target, 'package-lock.json')).packages?.[`node_modules/${HOST}`];+ if (installed.name !== HOST || installed.version !== version || locked?.version !== version+ || locked.integrity !== contract.host.integrity || locked.link+ || !fs.lstatSync(hostRoot).isDirectory() || fs.lstatSync(hostRoot).isSymbolicLink()) {+ throw new Error('The tooling installation does not match the selected published host integrity');+ }+ const executable = installed.bin?.['upgrade-template'];+ if (typeof executable !== 'string' || path.isAbsolute(executable) || executable.split(/[\\/]/).includes('..')) {+ throw new Error('The published host does not expose a contained upgrade-template CLI');+ }+ const relative = path.relative(fs.realpathSync(hostRoot), fs.realpathSync(path.join(hostRoot, executable)));+ if (relative.startsWith('..') || path.isAbsolute(relative) || !fs.lstatSync(path.join(hostRoot, executable)).isFile()) {+ throw new Error('The upgrade CLI must be a regular file inside the published host package');+ }+ return {+ target: summarizeRelease(contract), installedDependencies: true, lifecycleScriptsExecuted: false,+ upgradeCli: `node_modules/${HOST}/${executable.replaceAll('\\', '/')}`,+ };+}++function restorePreviewDependencies(projectRoot, previewRoot, options = {}) {+ const source = fs.realpathSync.native(path.resolve(projectRoot));+ const preview = fs.realpathSync.native(path.resolve(previewRoot));+ const related = (parent, child) => {+ const relative = path.relative(parent, child);+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));+ };+ if (related(source, preview) || related(preview, source)) {+ throw new Error('Source and preview must be separate, non-nested directories; source dependencies cannot be restored during preview.');+ }+ const modules = path.join(preview, 'node_modules');+ if (fs.lstatSync(modules, { throwIfNoEntry: false })?.isSymbolicLink()) {+ throw new Error('Preview node_modules must not be a symbolic link.');+ }+ const snapshots = new Map();+ for (const name of ['package.json', 'package-lock.json', 'app.json', '.npmrc']) {+ const sourcePath = path.join(source, name);+ const previewPath = path.join(preview, name);+ if (name === '.npmrc' && !fs.existsSync(sourcePath) && !fs.existsSync(previewPath)) continue;+ for (const file of [sourcePath, previewPath]) {+ if (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()) {+ throw new Error('Source and preview inputs must be regular files.');+ }+ }+ const original = fs.readFileSync(sourcePath);+ if (!original.equals(fs.readFileSync(previewPath))) {+ throw new Error(`Preview ${name} differs from the source; create and review a fresh snapshot.`);+ }+ snapshots.set(name, original);+ }+ const manifest = readJson(path.join(source, 'package.json'));+ const lock = readJson(path.join(source, 'package-lock.json'));+ if (manifest.workspaces || fs.existsSync(path.join(source, 'npm-shrinkwrap.json'))+ || (manifest.packageManager && !manifest.packageManager.startsWith('npm@'))+ || ![2, 3].includes(lock.lockfileVersion) || !lock.packages?.['']) {+ throw new Error('Preview dependency restore requires a standalone npm package-lock project.');+ }+ const execute = options.run || run;+ try {+ withNpmContext(source, preview, (env, cwd) => execute('npm', [+ 'ci', '--ignore-scripts', '--no-legacy-peer-deps', '--no-force', '--no-audit', '--no-fund',+ '--prefix', preview,+ ], cwd, { env }));+ } finally {+ for (const [name, content] of snapshots) {+ if (!content.equals(fs.readFileSync(path.join(source, name)))+ || !content.equals(fs.readFileSync(path.join(preview, name)))) {+ throw new Error(`Preview dependency restore changed ${name}; preserve the snapshot and investigate before continuing.`);+ }+ }+ }+ return { previewRoot: preview, installedDependencies: true, sourceModified: false, lifecycleScriptsExecuted: false };+}++function checkSdk(projectRoot, options = {}) {+ const root = fs.realpathSync.native(path.resolve(projectRoot));+ const expoRoot = fs.realpathSync.native(path.join(root, 'node_modules/expo'));+ const expo = readJson(path.join(expoRoot, 'package.json'));+ const bin = typeof expo.bin === 'string' ? expo.bin : expo.bin?.expo;+ if (expo.name !== 'expo' || typeof bin !== 'string' || !bin || path.isAbsolute(bin)) {+ throw new Error('SDK validation requires the project\'s installed Expo CLI; automatic acquisition is not allowed.');+ }+ const cli = fs.realpathSync.native(path.resolve(expoRoot, bin));+ const relative = path.relative(expoRoot, cli);+ if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)+ || !fs.statSync(cli).isFile()) {+ throw new Error('The installed Expo CLI must be contained in its package.');+ }+ const output = (options.run || run)(process.execPath, [cli, 'install', '--check'], root, {+ env: { ...process.env, EXPO_OFFLINE: '1' },+ failureMessage: 'Installed Expo SDK validation failed. Preserve the release pins and investigate the local compatibility mismatch; do not install newer online recommendations (raw output withheld).',+ });+ return { projectRoot: root, expoVersion: expo.version, versionSource: 'installed-expo', output: output.trim() };+}++function snapshotNativeDependencies(projectRoot) {+ const root = fs.realpathSync.native(path.resolve(projectRoot));+ const requirements = readSourceRequirements(root);+ const installed = inspectInstalledPackages(root);+ const declarations = dependencySections(readJson(path.join(root, 'package.json')));+ const nativeDeclarations = {};+ for (const [section, dependencies] of Object.entries(declarations)) {+ nativeDeclarations[section] = Object.fromEntries(Object.entries(dependencies).filter(([name]) => {+ const actual = installed.get(`node_modules/${name}`);+ if (isRuntimePackage(name) && !actual) {+ throw new Error('Restore the missing native/runtime dependency before preparing a JavaScript-only update.');+ }+ return isRuntimePackage(name) || actual?.native;+ }));+ if (!Object.keys(nativeDeclarations[section]).length) delete nativeDeclarations[section];+ }+ return {+ schemaVersion: 1,+ projectRoot: root,+ requirements,+ nativeDeclarations,+ nativePackages: Object.fromEntries([...installed].filter(([, item]) => item.native)+ .map(([installPath, item]) => [installPath, {+ name: item.canonicalName,+ version: item.version,+ manifestSha256: createHash('sha256').update(JSON.stringify(item.pkg)).digest('hex'),+ }])),+ };+}++function checkNativeDependencies(projectRoot, baselinePath) {+ if (!fs.lstatSync(baselinePath).isFile() || fs.lstatSync(baselinePath).isSymbolicLink()) {+ throw new Error('The JavaScript update baseline must be a regular snapshot file.');+ }+ const baseline = readJson(baselinePath);+ const current = snapshotNativeDependencies(projectRoot);+ if (baseline?.schemaVersion !== 1 || baseline.projectRoot !== current.projectRoot) {+ throw new Error('The native dependency snapshot is invalid or belongs to another app.');+ }+ if (!isDeepStrictEqual(baseline, current)) {+ throw new Error('JavaScript-only update changed native/runtime dependencies or app requirements. Restore the package snapshot and its installation before continuing.');+ }+ return { nativeDependenciesUnchanged: true };+}++function main(argv) {+ const [action, ...args] = argv;+ const values = {};+ const allowed = action === 'check-sdk' ? ['--project-root']+ : ['snapshot-native', 'check-native'].includes(action) ? ['--project-root', '--baseline']+ : action === 'restore-preview' ? ['--project-root', '--preview-root']+ : action === 'destination' ? ['--destination'] : action === 'acquire'+ ? ['--destination', '--release', '--host-version', '--template-version']+ : ['--project-root', '--release', '--host-version'];+ if (!['acquire', 'plan', 'destination', 'restore-preview', 'check-sdk', 'snapshot-native', 'check-native'].includes(action)) throw new Error('Use acquire, plan, destination, restore-preview, check-sdk, snapshot-native or check-native with explicit arguments; the published host CLI owns migration writes');+ for (let index = 0; index < args.length; index += 2) {+ const key = args[index];+ if (!allowed.includes(key) || values[key] !== undefined || !args[index + 1]+ || args[index + 1].startsWith('--')) throw new Error('Unknown, duplicate, or missing lifecycle argument');+ values[key] = args[index + 1];+ }+ if (action === 'snapshot-native' || action === 'check-native') {+ if (!values['--project-root'] || !values['--baseline']) {+ throw new Error('Required: --project-root and --baseline for the JavaScript-only update snapshot.');+ }+ if (action === 'check-native') return checkNativeDependencies(values['--project-root'], values['--baseline']);+ const snapshot = snapshotNativeDependencies(values['--project-root']);+ const baseline = path.resolve(values['--baseline']);+ const relative = path.relative(snapshot.projectRoot, fs.realpathSync.native(path.dirname(baseline)));+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {+ throw new Error('Save the native dependency snapshot inside this app recovery directory.');+ }+ fs.writeFileSync(baseline, `${JSON.stringify(snapshot, null, 2)}\n`, { flag: 'wx', mode: 0o600 });+ return { snapshotCreated: true };+ }+ if (action === 'check-sdk') {+ if (!values['--project-root']) throw new Error('Required: --project-root for installed SDK validation.');+ return checkSdk(values['--project-root']);+ }+ if (action === 'restore-preview') {+ if (!values['--project-root'] || !values['--preview-root']) {+ throw new Error('Required: --project-root and --preview-root for an approved isolated snapshot.');+ }+ return restorePreviewDependencies(values['--project-root'], values['--preview-root']);+ }+ if (action === 'destination') {+ if (!values['--destination']) throw new Error('Required: --destination for read-only creation inspection');+ return inspectDestination(values['--destination']);+ }+ if (!values[allowed[0]] || ['--release', '--host-version', '--template-version']+ .filter((key) => values[key]).length !== 1) {+ throw new Error(`Required: ${allowed[0]} and one exact host/template version`);+ }+ if (action === 'plan') return planPublishedUpdate(path.resolve(values['--project-root']), values['--host-version'] || values['--release']);+ return values['--host-version']+ ? acquireHost(values['--destination'], values['--host-version'])+ : acquireTemplate(values['--destination'], values['--template-version'] || values['--release']);+}++if (require.main === module) {+ try {+ process.stdout.write(`${JSON.stringify(main(process.argv.slice(2)), null, 2)}\n`);+ } catch (error) {+ process.stderr.write(`BLOCKED: ${error.message}\n`);+ process.exitCode = 2;+ }+}++module.exports = {+ acquireTemplate, acquireHost, assertEmptyDestination, assertTemplateManifest, checkSdk,+ snapshotNativeDependencies, checkNativeDependencies, inspectDestination, main, restorePreviewDependencies,+};diff --git a/plugins/mobile-apps/scripts/prepare-mobile-template.js b/plugins/mobile-apps/scripts/prepare-mobile-template.jsindex f2439dd63..64edbe906 100644--- a/plugins/mobile-apps/scripts/prepare-mobile-template.js+++ b/plugins/mobile-apps/scripts/prepare-mobile-template.js@@ -4,9 +4,11 @@const fs = require('fs');const path = require('path');+const { readProjectRequirements } = require('./lib/mobile-release');const REQUIRED_FILES = ['package.json',+ 'app.json','app.config.js','auth.config.json','tamagui.config.ts',@@ -99,6 +101,7 @@ function assertFreshTemplate(projectRoot) {}verifyHostTsconfig(projectRoot);+ readProjectRequirements(projectRoot);}function updateIdentity(projectRoot, displayName, slug) {@@ -127,7 +130,13 @@ function removeEmptyPowerConfig(projectRoot) {if (!fs.existsSync(powerConfigPath)) return false;const powerConfig = readJson(powerConfigPath);- if (typeof powerConfig.environmentId === 'string' && powerConfig.environmentId.trim()) {+ const emptyPlaceholderKeys = new Set([+ 'environmentId', 'appId', 'appDisplayName', 'databaseReferences', 'connectionReferences',+ ]);+ const isEmptyValue = (value) => value === '' || value === null+ || (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0);+ if (!powerConfig || Array.isArray(powerConfig) || typeof powerConfig !== 'object'+ || Object.entries(powerConfig).some(([key, value]) => !emptyPlaceholderKeys.has(key) || !isEmptyValue(value))) {return false;}diff --git a/plugins/mobile-apps/scripts/resolve-mobile-release.js b/plugins/mobile-apps/scripts/resolve-mobile-release.jsnew file mode 100644index 000000000..73d2185a5--- /dev/null+++ b/plugins/mobile-apps/scripts/resolve-mobile-release.js@@ -0,0 +1,104 @@+#!/usr/bin/env node+'use strict';++function fail(message) {+ const error = new Error(message);+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+}++function main(argv) {+ const {+ selectRelease, resolveProjectRelease, selectProjectRelease, summarizeRelease,+ } = require('./lib/mobile-release');+ const values = {};+ const flags = new Set(['--project-root', '--release', '--host-version', '--template-version', '--default', '--platform', '--base-version', '--base-fingerprint', '--base-runtime-version', '--requirements-only']);+ for (let index = 0; index < argv.length; index += 1) {+ const flag = argv[index];+ if (!flags.has(flag) || Object.hasOwn(values, flag)) fail('Unknown or duplicate release resolver argument.');+ if (flag === '--default' || flag === '--requirements-only') {+ values[flag] = true;+ } else {+ const value = argv[++index];+ if (!value || value.startsWith('--')) fail('A release resolver argument is missing its value.');+ values[flag] = value;+ }+ }+ if ([values['--release'], values['--host-version'], values['--default']].filter(Boolean).length > 1) {+ fail('Choose one host version selection, not multiple selectors.');+ }+ if (values['--template-version'] && (values['--release'] || values['--host-version'] || values['--default'])) {+ fail('Select the host or the template package, not both.');+ }+ if (!values['--project-root'] && !values['--release'] && !values['--host-version'] && !values['--template-version'] && !values['--default']) {+ fail('Use --project-root DIR, --host-version VERSION, --template-version VERSION, or --default.');+ }+ if (values['--platform'] && !['android', 'ios'].includes(values['--platform'])) fail('Deployment platform must be android or ios.');+ if ((values['--base-version'] || values['--base-fingerprint'] || values['--base-runtime-version']) && !values['--platform']) {+ fail('Checking a deployment base requires --platform android or ios.');+ }+ if (values['--platform'] && (!values['--base-version'] || !values['--base-fingerprint'])) {+ fail('Deployment checks require both --base-version and --base-fingerprint from the actual selected platform base. Version alone does not verify native compatibility.');+ }+ if (values['--platform'] && !values['--project-root']) {+ fail('Deployment-base validation requires --project-root to verify the app metadata, lock and installed native dependencies.');+ }+ if (values['--requirements-only']) {+ if (!values['--project-root']) fail('Read-only --requirements-only planning requires --project-root DIR.');+ if (['--release', '--host-version', '--template-version', '--default', '--platform', '--base-version', '--base-fingerprint', '--base-runtime-version'].some((flag) => values[flag])) {+ fail('Requirements-only planning cannot assert a selected release or check deployment targets. Use strict project resolution for admission and deployment.');+ }+ }++ let selected = null;+ const context = values['--project-root'] ? { cwd: values['--project-root'] } : {};+ if (values['--template-version']) {+ selected = require('./lib/mobile-published-packages').selectTemplateContract(values['--template-version'], context);+ } else if (values['--release'] || values['--host-version'] || values['--default']) {+ const version = values['--host-version'] || values['--release']+ || require('./lib/mobile-published-packages').createSource(context).defaultVersion();+ selected = selectRelease(version, undefined, context);+ }+ let current = null;+ if (values['--project-root']) {+ current = values['--requirements-only']+ ? selectProjectRelease(values['--project-root'])+ : resolveProjectRelease(values['--project-root'], undefined, undefined, {+ templateVersion: values['--template-version'],+ });+ }+ if (selected && current && selected.id !== current.id) fail('The project does not match the exact selected verified release.');+ const release = current || selected;+ if (values['--base-version'] && release.source !== 'npm'+ && release.platforms[values['--platform']].base.version !== values['--base-version']) {+ fail('The deployment base does not match the selected platform in the verified release.');+ }+ if (values['--base-fingerprint'] && release.platforms[values['--platform']].fingerprint !== values['--base-fingerprint']) {+ fail('The deployment base fingerprint does not match the selected platform in the verified release. Do not deploy with an unverified native base.');+ }+ const summary = summarizeRelease(release);+ if (values['--platform'] && release.source === 'npm') {+ const runtime = values['--base-runtime-version'];+ if (!/^[1-9]\d*$/.test(runtime || '') || !Number.isSafeInteger(Number(runtime))+ || Number(runtime) !== release.nativeRuntimeVersions[values['--platform']]) {+ fail('Published package admission also requires the actual selected base runtime version; it must match the host contract.');+ }+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,127}$/.test(values['--base-version'])) fail('Invalid selected base version.');+ summary.deploymentBase = {+ platform: values['--platform'], version: values['--base-version'],+ nativeRuntimeVersion: Number(runtime), fingerprint: values['--base-fingerprint'],+ };+ summary.validationScope = 'app-and-base-native-contract; regional availability must be verified by Wrap';+ }+ if (values['--requirements-only']) summary.validationScope = 'requirements-only';+ process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);+}++try {+ main(process.argv.slice(2));+} catch (error) {+ const message = error.code === 'MOBILE_RELEASE_BLOCKED'+ ? error.message : 'Unable to verify published package compatibility. Check registry access and the project installation.';+ process.stderr.write(`BLOCKED: ${message}\n`);+ process.exitCode = 2;+}diff --git a/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.jsindex 787b8dfd6..72b786da3 100644--- a/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js+++ b/plugins/mobile-apps/scripts/tests/app-working-directory-contract.test.js@@ -109,14 +109,32 @@ function fixture(t) {fs.mkdirSync(installed, { recursive: true });fs.writeFileSync(path.join(installed, 'package.json'), JSON.stringify({ version: '0.2.9' }));}+ // Root-binding tests do not query npm. The actual package-source/inventory+ // behavior is tested separately; this probe checks argv, cwd and refusal.+ fs.writeFileSync(path.join(directory, 'fixture-release-resolver.cjs'), `+ const fs = require('node:fs');+ const path = require('node:path');+ const root = process.argv[process.argv.indexOf('--project-root') + 1];+ if (!root || fs.realpathSync.native(root) !== fs.realpathSync.native(process.cwd())) {+ console.error('BLOCKED: package contract inspected the wrong app root');+ process.exit(1);+ }+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));+ if (!Object.keys(pkg.dependencies || {}).length) {+ console.error('MISSING: installed package contract');+ process.exit(1);+ }+ `);return { directory, owner, caller };}function run(block, owner, caller) {const command = block+ .replaceAll('"${PLUGIN_ROOT}/scripts/resolve-mobile-release.js"', '"$FIXTURE_RELEASE_RESOLVER"').replaceAll('<working_dir>', shellLiteralContents(owner)).replaceAll('<approved-artifact-keys-json>', '["scanner"]')- .replaceAll('<expo-module-name>', 'expo-secure-store');+ .replaceAll('<expo-module-name>', 'expo-secure-store')+ .replaceAll('<resolved-package-name>', 'expo-secure-store');// Use the current Node executable; mutation tests supply local CLI probes.const result = spawnSync(bash, ['-s'], {input: `node() { "$REAL_NODE" "$@"; }\nPA="npx --no-install pa"\nPA_KIND=pa\n${command}`,@@ -125,6 +143,7 @@ function run(block, owner, caller) {...process.env,REAL_NODE: process.execPath.replaceAll('\\', '/'),PLUGIN_ROOT: pluginRoot.replaceAll('\\', '/'),+ FIXTURE_RELEASE_RESOLVER: path.join(path.dirname(caller), 'fixture-release-resolver.cjs').replaceAll('\\', '/'),POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',},encoding: 'utf8',@@ -739,7 +758,8 @@ for (const file of files) {test(`${name} executes project and package gates against the owner, not the launch directory`, (t) => {const { owner, caller } = fixture(t);const projectGate = blocks[0];- const packageGate = blocks.find((block) => block.includes("require('./package.json')"));+ const packageGate = blocks.find((block) => block.includes("require('./package.json')"))+ || blocks.find((block) => block.includes('scripts/resolve-mobile-release.js'));assert.ok(packageGate);for (const gate of new Set([projectGate, packageGate])) {const result = run(gate, owner, caller);diff --git a/plugins/mobile-apps/scripts/tests/helpers/mobile-release-fixture.js b/plugins/mobile-apps/scripts/tests/helpers/mobile-release-fixture.jsnew file mode 100644index 000000000..5f8e6d42e--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/helpers/mobile-release-fixture.js@@ -0,0 +1,184 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');+const { randomUUID } = require('node:crypto');+const { spawnSync } = require('node:child_process');++const PLUGIN_ROOT = path.resolve(__dirname, '../../..');+const HOST = '@microsoft/power-apps-native-host';++// Synthetic injected contracts only; they never populate a shipped catalogue+// or assert publication, compatibility, or real-device verification.+function fixtureRelease(number = 1) {+ const version = `${number}.0.0`;+ const dependencies = { [HOST]: `^${version}`, expo: version, 'react-native': version, react: version, 'expo-haptics': version };+ const target = (platform) => ({+ fingerprint: `fixture-${platform}-${number}`,+ base: { version: `fixture-base-${number}`, evidence: `https://example.com/fixture/${number}/${platform}/base` },+ player: { version: `fixture-player-${number}`, evidence: `https://example.com/fixture/${number}/${platform}/player` },+ });+ return {+ id: `fixture-release-${number}`,+ template: {+ package: '@microsoft/power-apps-native-template',+ version,+ integrity: `sha512-${Buffer.alloc(64, number).toString('base64')}`,+ },+ templateVersion: number,+ nativeRuntimeVersions: { android: number, ios: number },+ managedDependencies: { dependencies },+ nativePackages: Object.fromEntries(Object.keys(dependencies).map((name) => [`node_modules/${name}`, version])),+ platforms: { android: target('android'), ios: target('ios') },+ evidence: [`https://example.com/fixture/${number}/publication`, `https://example.com/fixture/${number}/device-validation`],+ };+}++function makeRelease(overrides = {}) {+ function merge(target, source) {+ for (const [key, value] of Object.entries(source)) {+ if (value && typeof value === 'object' && !Array.isArray(value)+ && target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {+ merge(target[key], value);+ } else {+ target[key] = structuredClone(value);+ }+ }+ return target;+ }+ return merge(fixtureRelease(), overrides);+}++function writeJson(filePath, value) {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);+}++function readJson(filePath) {+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));+}++function modifyJson(filePath, change) {+ const value = readJson(filePath);+ change(value);+ writeJson(filePath, value);+}++function installPackage(projectRoot, installPath, version, properties = {}) {+ const name = installPath.split('/node_modules/').pop().replace(/^node_modules\//, '');+ writeJson(path.join(projectRoot, installPath, 'package.json'), { name, version, ...properties });+}++function addDependency(projectRoot, name, version, { section = 'dependencies', properties = {}, installPath = `node_modules/${name}` } = {}) {+ if (section) modifyJson(path.join(projectRoot, 'package.json'), (pkg) => {+ pkg[section] ||= {};+ pkg[section][name] = version;+ });+ modifyJson(path.join(projectRoot, 'package-lock.json'), (lock) => {+ if (section) {+ lock.packages[''][section] ||= {};+ lock.packages[''][section][name] = version;+ }+ lock.packages[installPath] = { version };+ });+ installPackage(projectRoot, installPath, version, properties);+}++function writeProject(projectRoot, release) {+ writeJson(path.join(projectRoot, 'app.json'), {+ expo: { extra: {+ powerappsNative: { schemaVersion: 1, templateVersion: release.templateVersion, nativeRuntimeVersions: release.nativeRuntimeVersions },+ appInsightsConfig: { connectionString: 'fixture-secret-do-not-echo' },+ } },+ });+ const manifest = { name: 'fixture-mobile-app', version: '1.0.0', ...release.managedDependencies };+ writeJson(path.join(projectRoot, 'package.json'), manifest);+ const packages = { '': manifest };+ for (const [installPath, version] of Object.entries(release.nativePackages)) {+ packages[installPath] = { version };+ installPackage(projectRoot, installPath, version);+ }+ for (const section of Object.values(release.managedDependencies)) {+ for (const [name, spec] of Object.entries(section)) {+ const installPath = `node_modules/${name}`;+ if (packages[installPath]) continue;+ const version = /^\d+\.\d+\.\d+$/.test(spec) ? spec : '1.0.0';+ packages[installPath] = { version };+ installPackage(projectRoot, installPath, version);+ }+ }+ writeJson(path.join(projectRoot, 'package-lock.json'), { name: manifest.name, lockfileVersion: 3, packages });+ return projectRoot;+}++function createFixture(t, { release = fixtureRelease(), catalog = { schemaVersion: 1, defaultRelease: release.id, releases: [release] } } = {}) {+ const directory = path.resolve(__dirname, '..', `.release-fixture-${randomUUID()}`);+ const pluginRoot = path.join(directory, 'plugin');+ const projectRoot = path.join(directory, 'project');+ fs.mkdirSync(projectRoot, { recursive: true });+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ for (const file of [+ 'scripts/lib/mobile-release.js', 'scripts/resolve-mobile-release.js',+ 'scripts/vendor/semver.cjs',+ 'scripts/validate-mobile-files.js', 'scripts/lib/mobile-validator-manifest.js',+ 'hooks/validate-package-deps.js', 'hooks/validate-write-safety.js', 'hooks/validate-protected-paths.js',+ ]) {+ const target = path.join(pluginRoot, file);+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.copyFileSync(path.join(PLUGIN_ROOT, file), target);+ }+ writeJson(path.join(pluginRoot, 'shared/fixture-contracts.json'), catalog);+ // Isolate the old inventory/CLI tests from npm. Package-source tests exercise+ // the real registry/archive reader separately; no runtime override is added.+ fs.writeFileSync(path.join(pluginRoot, 'scripts/lib/mobile-published-packages.js'), `+ 'use strict';+ const fs = require('node:fs');+ const path = require('node:path');+ const contracts = () => JSON.parse(fs.readFileSync(path.join(__dirname, '../../shared/fixture-contracts.json'), 'utf8'));+ const release = () => require('./mobile-release');+ module.exports = {+ createSource: () => ({ defaultVersion: () => contracts().defaultRelease }),+ selectPublishedContract: id => release().selectRelease(id, contracts()),+ selectTemplateContract: id => release().selectRelease(id, contracts()),+ readSourceRequirements: root => ({+ ...release().summarizeRelease(release().selectProjectRelease(root, contracts())),+ validationScope: 'requirements-only',+ }),+ projectContract: root => release().resolveProjectRelease(root, contracts()),+ };+ `);+ writeProject(projectRoot, release);+ return { directory, pluginRoot, projectRoot, release, catalog };+}++function runCli(fixture, args) {+ return spawnSync(process.execPath, [path.join(fixture.pluginRoot, 'scripts/resolve-mobile-release.js'), ...args], {+ cwd: fixture.projectRoot, encoding: 'utf8',+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ });+}++function runValidator(fixture, { approved = [], explicit = true, tool = 'Write', input = {} } = {}) {+ const filePath = path.join(fixture.projectRoot, 'package.json');+ return spawnSync(process.execPath, [path.join(fixture.pluginRoot, 'hooks/validate-package-deps.js')], {+ cwd: fixture.projectRoot, encoding: 'utf8',+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ input: JSON.stringify({+ tool_name: tool,+ tool_input: {+ file_path: filePath,+ ...(explicit ? { validation_mode: 'explicit-mobile-workflow' } : {}),+ approved_js_dependencies: approved.map((entry) => {+ const separator = entry.lastIndexOf('@');+ return { name: entry.slice(0, separator), version: entry.slice(separator + 1) };+ }),+ ...input,+ },+ }),+ });+}++module.exports = {+ HOST, PLUGIN_ROOT, fixtureRelease, makeRelease, writeProject, createFixture, writeJson, readJson, modifyJson,+ installPackage, addDependency, runCli, runValidator,+};diff --git a/plugins/mobile-apps/scripts/tests/mobile-package-artifacts.test.js b/plugins/mobile-apps/scripts/tests/mobile-package-artifacts.test.jsnew file mode 100644index 000000000..7de771d98--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-package-artifacts.test.js@@ -0,0 +1,245 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { createHash } = require('node:crypto');+const { spawnSync } = require('node:child_process');+const test = require('node:test');+const { unpack, readOfflineContract, verifyInstalledOfflineSdk } = require('../lib/mobile-package-artifacts');+const { createSource } = require('../lib/mobile-published-packages');++const HOST = '@microsoft/power-apps-native-host';+const OFFLINE = '@microsoft/power-apps-native-offline';+const ENTRY = `node_modules/${OFFLINE}`;+const hash = bytes => createHash('sha256').update(bytes).digest('hex');++function directory(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-package-artifact-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return root;+}++test('archive inspection rejects links, duplicate names and traversal before extraction', t => {+ const root = directory(t);+ const archive = path.join(root, 'source.tgz');+ fs.writeFileSync(archive, 'verified test archive');+ for (const [names, types, valid] of [+ ['package/\npackage/package.json', 'drwx package/\n-rw package/package.json', true],+ ['package/../escape', '-rw package/../escape', false],+ ['package/file\npackage/file', '-rw package/file\n-rw package/file', false],+ ['package/link', 'lrwx package/link -> /outside', false],+ ['package/drive:C', '-rw package/drive:C', false],+ ]) {+ let extracted = false;+ const execute = () => unpack(archive, root, (_command, args, cwd) => {+ assert.equal(cwd, root);+ assert.deepEqual(fs.readFileSync(path.join(root, 'artifact.tgz')), fs.readFileSync(archive));+ if (args[0] === '-tzf') return names;+ if (args[0] === '-tvzf') return types;+ extracted = true;+ return '';+ });+ if (valid) assert.equal(execute(), path.join(root, 'package'));+ else assert.throws(execute, /unsafe archive paths/);+ assert.equal(extracted, valid);+ assert.equal(fs.existsSync(path.join(root, 'artifact.tgz')), false);+ assert.equal(fs.readFileSync(archive, 'utf8'), 'verified test archive');+ }+ assert.throws(() => unpack(archive, root, () => { throw new Error('tar failed'); }), /tar failed/);+ assert.equal(fs.existsSync(path.join(root, 'artifact.tgz')), false);+});++function offlineFixture(t) {+ const root = directory(t);+ const sdk = path.join(root, ENTRY);+ const profile = {+ expoSdk: 57, runtimeFamily: 'expo57-rn86-hermes-newarch', offlineContractVersion: 1,+ managedDependencies: { [OFFLINE]: '0.2.0', 'react-native': '0.86.3' },+ };+ const host = { version: '1.0.0', peerDependencies: { [OFFLINE]: '0.2.0' } };+ const pkg = { name: OFFLINE, version: '0.2.0', peerDependencies: { [HOST]: '^1.0.0', 'react-native': '0.86.3' } };+ const artifact = 'android/runtime.aar';+ const contract = {+ schemaVersion: 2, complete: true, sourceDirty: false, packageVersion: '0.2.0',+ expoSdkVersion: 57, reactNativeVersion: '0.86.3',+ runtimeFamily: profile.runtimeFamily, offlineContractVersion: 1, engine: 'hermes',+ hostPeerRange: '^1.0.0', platformArchitectures: { android: ['new'], ios: ['new'] },+ artifacts: { [artifact]: hash('native fixture'), 'android/runtime.h': hash('native header fixture') },+ };+ fs.mkdirSync(path.join(sdk, 'android'), { recursive: true });+ fs.writeFileSync(path.join(sdk, artifact), 'native fixture');+ fs.writeFileSync(path.join(sdk, 'android/runtime.h'), 'native header fixture');+ const lock = { packages: { [ENTRY]: { version: '0.2.0', integrity: `sha512-${'A'.repeat(86)}==` } } };+ const reference = structuredClone(lock);+ const published = {+ publication: { package: OFFLINE, version: '0.2.0', integrity: reference.packages[ENTRY].integrity },+ pkg: structuredClone(pkg),+ contract: structuredClone(contract),+ };+ const reads = [];+ const readPackage = (name, version) => {+ reads.push({ name, version });+ assert.equal(name, OFFLINE);+ assert.equal(version, '0.2.0');+ return structuredClone(published);+ };+ return {+ root, sdk, profile, host, pkg, contract, lock, reference, published, reads, readPackage,+ verify() {+ fs.writeFileSync(path.join(sdk, 'package.json'), JSON.stringify(pkg));+ fs.writeFileSync(path.join(sdk, 'compatibility.json'), JSON.stringify(contract));+ verifyInstalledOfflineSdk(root, profile, host, lock, reference, readPackage);+ },+ };+}++test('published offline admission verifies the exact SDK, peer contract and native artifacts', t => {+ const f = offlineFixture(t);+ assert.doesNotThrow(() => f.verify());+ assert.equal(fs.readFileSync(path.join(f.sdk, 'android/runtime.aar'), 'utf8'), 'native fixture');+ assert.deepEqual(f.reads, [{ name: OFFLINE, version: '0.2.0' }]);+ assert.doesNotThrow(() => verifyInstalledOfflineSdk(f.root, {}, {}, {}, {}));+});++test('offline native admission rejects drift without rewriting profiles or SDK files', t => {+ for (const mutate of [+ f => { f.lock.packages[ENTRY].version = '0.1.32'; },+ f => { f.reference.packages[ENTRY].integrity = `sha512-${'B'.repeat(86)}==`; },+ f => { f.published.publication.integrity = `sha512-${'B'.repeat(86)}==`; },+ f => { f.published.publication.version = '0.2.1'; },+ f => { f.host.version = '0.5.1'; },+ f => { f.contract.sourceDirty = true; },+ f => { f.contract.runtimeFamily = 'different-runtime'; },+ f => { f.contract.offlineContractVersion = 2; },+ f => { f.contract.engine = 'jsc'; },+ f => { f.contract.platformArchitectures.ios = ['old']; },+ f => { f.pkg.peerDependencies[HOST] = '^2.0.0'; },+ f => { f.contract.artifacts = {}; },+ f => { f.contract.artifacts = { '../outside': hash('outside') }; },+ f => { delete f.contract.artifacts['android/runtime.h']; },+ f => { fs.unlinkSync(path.join(f.sdk, 'android/runtime.h')); },+ f => {+ fs.writeFileSync(path.join(f.sdk, 'android/runtime.aar'), 'changed native binary');+ f.contract.artifacts['android/runtime.aar'] = hash('changed native binary');+ },+ f => {+ fs.writeFileSync(path.join(f.sdk, 'android/runtime.h'), 'changed header');+ delete f.contract.artifacts['android/runtime.h'];+ },+ f => { fs.appendFileSync(path.join(f.sdk, 'android/runtime.aar'), 'changed'); },+ ]) {+ const f = offlineFixture(t);+ mutate(f);+ const before = structuredClone(f.profile);+ assert.throws(() => f.verify(), error => error.code === 'MOBILE_RELEASE_BLOCKED');+ assert.deepEqual(f.profile, before);+ }+});++test('offline admission cannot fall back to installed metadata when the verified archive is unavailable', t => {+ const f = offlineFixture(t);+ assert.doesNotThrow(() => f.verify());+ assert.throws(() => verifyInstalledOfflineSdk(f.root, f.profile, f.host, f.lock, f.reference),+ /requires an integrity-verified published SDK archive/);+ assert.throws(() => verifyInstalledOfflineSdk(f.root, f.profile, f.host, f.lock, f.reference, () => {+ throw new Error('SDK publication unavailable');+ }), /SDK publication unavailable/);+});++test('a faithfully installed published SDK still must satisfy the host peers and native runtime contract', t => {+ for (const edit of [+ f => { f.contract.runtimeFamily = 'different-family'; },+ f => { f.contract.offlineContractVersion = 2; },+ f => { f.contract.reactNativeVersion = '0.85.0'; },+ f => { f.contract.expoSdkVersion = '55'; },+ f => { f.contract.engine = 'jsc'; },+ f => { f.contract.platformArchitectures.ios = ['old']; },+ f => { f.contract.complete = false; },+ f => { f.contract.sourceDirty = true; },+ f => { f.pkg.peerDependencies[HOST] = f.contract.hostPeerRange = '^2.0.0'; },+ f => { f.pkg.peerDependencies['react-native'] = '0.85.x'; },+ f => { f.host.peerDependencies[OFFLINE] = '^0.3.0'; },+ ]) {+ const f = offlineFixture(t);+ edit(f);+ f.published.pkg = structuredClone(f.pkg);+ f.published.contract = structuredClone(f.contract);+ assert.throws(() => f.verify(), /peers and native runtime contract disagree/);+ }+});++test('SDK archive inspection checks all declared artifacts and rejects an internally inconsistent contract', t => {+ const f = offlineFixture(t);+ f.verify();+ assert.deepEqual(readOfflineContract(f.sdk), f.published.contract);+ fs.writeFileSync(path.join(f.sdk, 'android/runtime.h'), 'bad published header');+ assert.throws(() => readOfflineContract(f.sdk), /artifact hash differs/);+});++test('offline admission binds the verified registry archive to the immutable template SRI and cleans scratch', t => {+ const f = offlineFixture(t);+ f.verify();+ fs.cpSync(f.sdk, path.join(f.root, 'package'), { recursive: true });+ const archive = path.join(f.root, 'offline.tgz');+ const packed = spawnSync('tar', ['-czf', 'offline.tgz', 'package'], { cwd: f.root, encoding: 'utf8' });+ assert.equal(packed.status, 0, packed.stderr);+ const integrity = `sha512-${createHash('sha512').update(fs.readFileSync(archive)).digest('base64')}`;+ for (const lock of [f.lock, f.reference]) lock.packages[ENTRY].integrity = integrity;+ const scratch = [];+ let corrupt = false;+ let missingIntegrity = false;+ const options = {+ cwd: f.root,+ run(command, args, cwd) {+ if (command === 'npm') {+ assert.equal(cwd, f.root);+ assert.equal(args[1], `${OFFLINE}@0.2.0`);+ if (args[0] === 'view') return JSON.stringify({+ name: OFFLINE, version: '0.2.0', dist: missingIntegrity ? {} : { integrity },+ });+ assert.deepEqual(args.slice(0, 5), ['pack', `${OFFLINE}@0.2.0`, '--ignore-scripts', '--json', '--pack-destination']);+ const destination = args[5];+ scratch.push(destination);+ fs.copyFileSync(archive, path.join(destination, 'offline.tgz'));+ if (corrupt) fs.appendFileSync(path.join(destination, 'offline.tgz'), 'altered archive');+ return JSON.stringify([{ name: OFFLINE, version: '0.2.0', integrity, filename: 'offline.tgz' }]);+ }+ assert.equal(command, 'tar');+ const result = spawnSync(command, args, { cwd, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ return result.stdout;+ },+ };+ const source = createSource(options);+ const verify = reader => verifyInstalledOfflineSdk(f.root, f.profile, f.host, f.lock, f.reference, reader);+ verify(source.read);+ assert.deepEqual(source.read(OFFLINE, '0.2.0').contract.artifacts, f.contract.artifacts);+ assert.equal(scratch.length, 1, 'Reuse the verified reference within the same resolution');+ for (const lock of [f.lock, f.reference]) lock.packages[ENTRY].integrity = `sha512-${'B'.repeat(86)}==`;+ assert.throws(() => verify(source.read), /immutable template lock integrity/);+ for (const lock of [f.lock, f.reference]) lock.packages[ENTRY].integrity = integrity;+ corrupt = true;+ assert.throws(() => verify(createSource(options).read), /bytes do not match/);+ corrupt = false;+ missingIntegrity = true;+ assert.throws(() => verify(createSource(options).read), /integrity/);+ assert.ok(scratch.every(directory => !fs.existsSync(directory)));+});++test('retired artifact options cannot acquire templates or admit a project', t => {+ const root = directory(t);+ for (const args of [+ ['resolve-mobile-release.js', '--diagnostic-artifacts', 'retired.json'],+ ['mobile-template-lifecycle.js', 'acquire', '--destination', path.join(root, 'app'), '--diagnostic-artifacts', 'retired.json'],+ ['validate-mobile-files.js', '--project-root', root, '--all-source', '--diagnostic-artifacts', 'retired.json'],+ ]) {+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '..', args[0]), ...args.slice(1)], {+ encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ });+ assert.equal(result.status, 2, result.stderr);+ assert.match(result.stderr, /BLOCKED/);+ assert.equal(fs.existsSync(path.join(root, 'app')), false);+ }+});diff --git a/plugins/mobile-apps/scripts/tests/mobile-published-packages.test.js b/plugins/mobile-apps/scripts/tests/mobile-published-packages.test.jsnew file mode 100644index 000000000..fabada46f--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-published-packages.test.js@@ -0,0 +1,490 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');+const { createHash } = require('node:crypto');+const { spawnSync } = require('node:child_process');+const {+ HOST, TEMPLATE, compareVersions, createSource, selectPublishedContract, selectTemplateContract,+ readSourceRequirements, projectContract, planPublishedUpdate,+} = require('../lib/mobile-published-packages');+const { acquireHost } = require('../mobile-template-lifecycle');+const { readProject, readPlatformContext, validateProjectAgainstRelease, resolveProjectRelease } = require('../lib/mobile-release');+const { fixtureRelease, writeProject, writeJson, modifyJson, addDependency } = require('./helpers/mobile-release-fixture');++function fixture(t) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'published-mobile-test-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const projectRoot = path.join(directory, 'app');+ const release = fixtureRelease();+ release.platforms.android.fingerprint = 'a'.repeat(64);+ release.platforms.ios.fingerprint = 'b'.repeat(64);+ writeProject(projectRoot, release);+ const packages = new Map();+ const publication = (name, version) => ({+ package: name, version, integrity: `sha512-${Buffer.alloc(64, 1).toString('base64')}`,+ });+ function host(version, templateVersion = 1, nativeVersion = 1, migrations = []) {+ const profile = {+ schemaVersion: 1, targetTemplateVersion: templateVersion, expoVersion: '1.0.0',+ managedDependencies: { expo: '1.0.0', react: '1.0.0', 'react-native': '1.0.0', 'expo-haptics': '1.0.0' },+ nativeRuntime: {+ android: { version: nativeVersion, fingerprint: (nativeVersion === 1 ? 'a' : 'c').repeat(64) },+ ios: { version: nativeVersion, fingerprint: (nativeVersion === 1 ? 'b' : 'd').repeat(64) },+ },+ migrations: migrations.map((migration) => migration.id),+ };+ const record = { publication: publication(HOST, version), pkg: { name: HOST, version }, profile, migrations };+ packages.set(`${HOST}@${version}`, record);+ return record;+ }+ function template(version, hostVersion = '1.0.0') {+ const selectedHost = packages.get(`${HOST}@${hostVersion}`);+ const manifest = { name: 'fixture-app', dependencies: { ...release.managedDependencies.dependencies, [HOST]: `^${hostVersion}` } };+ const record = {+ publication: publication(TEMPLATE, version), pkg: { name: TEMPLATE, version },+ app: { expo: { extra: { powerappsNative: {+ schemaVersion: 1, templateVersion: selectedHost.profile.targetTemplateVersion,+ nativeRuntimeVersions: Object.fromEntries(['android', 'ios'].map((platform) => [platform, selectedHost.profile.nativeRuntime[platform].version])),+ } } } },+ manifest,+ lock: {+ lockfileVersion: 3,+ packages: {+ '': structuredClone(manifest),+ ...Object.fromEntries(Object.entries(release.nativePackages).map(([name, installedVersion]) => [name, {+ version: name === `node_modules/${HOST}` ? hostVersion : installedVersion,+ }])),+ },+ },+ };+ packages.set(`${TEMPLATE}@${version}`, record);+ return record;+ }+ const baseline = host('1.0.0');+ template('1.0.0');+ writeJson(path.join(projectRoot, 'node_modules', HOST, 'compatibility/current.json'), baseline.profile);+ const requests = [];+ const options = {+ versions: () => [...packages.values()].filter((record) => record.pkg.name === TEMPLATE).map((record) => record.pkg.version),+ readPackage(name, version) {+ requests.push(`${name}@${version}`);+ const record = packages.get(`${name}@${version}`);+ if (!record) {+ const error = new Error('Selected exact package is not published');+ error.code = 'MOBILE_RELEASE_BLOCKED';+ throw error;+ }+ return structuredClone(record);+ },+ };+ return { directory, projectRoot, release, packages, requests, host, template, options };+}++function migration(version = '2.0.0', from = '^1.0.0') {+ return {+ id: 'template-v2', fromTemplateVersion: 1, toTemplateVersion: 2,+ targetProfile: { hostVersion: version },+ packageTransitions: { dependencies: { [HOST]: { from, to: `^${version}` } } },+ };+}++test('published package version comparisons are numeric, inclusive and stable-only', () => {+ assert.equal(compareVersions('1.10.0', '1.9.9'), 1);+ assert.equal(compareVersions('1.0.0', '1.0.0'), 0);+ assert.equal(compareVersions('1.0.0', '2.0.0'), -1);+ assert.equal(compareVersions('1.0.0+build.1', '1.0.0+build.2'), 0);+ for (const version of ['latest', '^1.0.0', '01.0.0', '1.0.0-beta.1']) {+ assert.throws(() => compareVersions(version, '1.0.0'), /exact stable/);+ }+});++test('requirements-only inspection reads recorded state without a catalogue or registry', (t) => {+ const f = fixture(t);+ modifyJson(path.join(f.projectRoot, 'node_modules', HOST, 'package.json'), (pkg) => { pkg.version = '2.0.0'; });+ assert.deepEqual(readSourceRequirements(f.projectRoot), {+ templateVersion: 1, nativeRuntimeVersions: { android: 1, ios: 1 },+ hostVersion: '2.0.0', validationScope: 'requirements-only',+ });+ assert.deepEqual(f.requests, []);+});++test('published contract derives native pins from the template lock without inventing binary availability', (t) => {+ const f = fixture(t);+ const result = selectPublishedContract('1.0.0', f.options);+ assert.equal(result.source, 'npm');+ assert.equal(result.host.version, '1.0.0');+ assert.equal(result.template.version, '1.0.0');+ assert.deepEqual(result.platforms.android, { fingerprint: 'a'.repeat(64) });+ assert.equal(result.evidence, undefined);+ assert.equal(selectTemplateContract('1.0.0', f.options).id, result.id);+});++test('explicit template selection is retained when resolving a compatible installed project', t => {+ const f = fixture(t);+ f.template('1.0.1');+ const installed = readProject(f.projectRoot, readPlatformContext());+ const selected = projectContract(f.projectRoot, installed, { ...f.options, templateVersion: '1.0.0' });+ assert.equal(selected.template.version, '1.0.0');+ validateProjectAgainstRelease(installed, selected);+ assert.equal(projectContract(f.projectRoot, installed, f.options).template.version, '1.0.1');+ const records = path.join(f.directory, 'packages.json');+ writeJson(records, Object.fromEntries(f.packages));+ const preload = path.join(f.directory, 'published-fixture.cjs');+ fs.writeFileSync(preload, `+const records = require(${JSON.stringify(records)});+const source = require(${JSON.stringify(require.resolve('../lib/mobile-published-packages'))});+const injected = {+ readPackage(name, version) { return structuredClone(records[name + '@' + version]); },+ versions() { return Object.values(records).filter(record => record.pkg.name === ${JSON.stringify(TEMPLATE)}).map(record => record.pkg.version); },+};+for (const name of ['selectTemplateContract', 'projectContract']) {+ const original = source[name];+ source[name] = (...args) => {+ const index = name === 'projectContract' ? 2 : 1;+ args[index] = { ...injected, ...args[index] };+ return original(...args);+ };+}+`);+ const result = spawnSync(process.execPath, [+ '--require', preload, path.resolve(__dirname, '../resolve-mobile-release.js'),+ '--project-root', f.projectRoot, '--template-version', '1.0.0',+ ], { cwd: f.projectRoot, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(JSON.parse(result.stdout).template.version, '1.0.0');+});++test('same-runtime host patch uses the existing compatible template without a Player release record', (t) => {+ const f = fixture(t);+ f.host('1.0.1');+ const result = planPublishedUpdate(f.projectRoot, '1.0.1', f.options);+ assert.equal(result.kind, 'host-repair');+ assert.equal(result.migrationRequired, false);+ assert.equal(result.nativeChanged, false);+ assert.equal(result.target.hostVersion, '1.0.1');+ assert.equal(result.target.template.version, '1.0.0');+ assert.match(result.binaryAvailability, /not-checked/);+});++test('a non-native template migration advances template state without changing native runtime', (t) => {+ const f = fixture(t);+ f.host('1.1.0', 2, 1, [migration('1.1.0')]);+ f.template('1.1.0', '1.1.0');+ const result = planPublishedUpdate(f.projectRoot, '1.1.0', f.options);+ assert.equal(result.kind, 'template-upgrade');+ assert.equal(result.nativeChanged, false);+ assert.deepEqual(result.target.nativeRuntimeVersions, { android: 1, ios: 1 });+});++test('native major transition uses host migrations and reports binary availability separately', (t) => {+ const f = fixture(t);+ f.host('2.0.0', 2, 2, [migration()]);+ f.template('2.0.0', '2.0.0');+ const result = planPublishedUpdate(f.projectRoot, '2.0.0', f.options);+ assert.equal(result.kind, 'template-upgrade');+ assert.equal(result.nativeChanged, true);+ assert.equal(result.fullChainPreviewRequired, true);+ assert.equal(result.target.nativeRuntimeVersions.android, 2);+ assert.equal(result.target.platforms.android.player, undefined);+});++test('a manually updated host does not hide the older recorded template or require another host major', (t) => {+ const f = fixture(t);+ f.host('2.0.0', 2, 2, [migration()]);+ f.template('2.0.0', '2.0.0');+ modifyJson(path.join(f.projectRoot, 'node_modules', HOST, 'package.json'), (pkg) => { pkg.version = '2.0.0'; });+ const result = planPublishedUpdate(f.projectRoot, '2.0.0', f.options);+ assert.equal(result.kind, 'template-upgrade');+ assert.equal(result.hostInstallRequired, false);+ assert.equal(result.source.templateVersion, 1);+ assert.equal(result.target.templateVersion, 2);+});++test('native changes cannot be hidden in a patch or minor target', (t) => {+ const f = fixture(t);+ f.host('1.1.0', 2, 2, [migration('1.1.0')]);+ f.template('1.1.0', '1.1.0');+ assert.throws(() => planPublishedUpdate(f.projectRoot, '1.1.0', f.options), /new host major/);+});++test('unpublished or unfinalized targets fail before mutation without falling back', (t) => {+ const f = fixture(t);+ const before = fs.readFileSync(path.join(f.projectRoot, 'package.json'), 'utf8');+ assert.throws(() => planPublishedUpdate(f.projectRoot, '2.0.0', f.options), /not published/);+ assert.deepEqual(f.requests, [`${HOST}@2.0.0`]);+ f.host('2.0.0', 2, 2, [migration('__RELEASE_HOST_VERSION__')]);+ assert.throws(() => planPublishedUpdate(f.projectRoot, '2.0.0', f.options), /unfinalized/);+ f.host('2.0.0', 2, 2, [migration()]).profile.runtimePreparation = { baseCommit: 'a'.repeat(40) };+ assert.throws(() => planPublishedUpdate(f.projectRoot, '2.0.0', f.options), /diagnostic runtime preparation/);+ assert.equal(fs.readFileSync(path.join(f.projectRoot, 'package.json'), 'utf8'), before);+});++test('downgrades and missing migration edges are rejected', (t) => {+ const f = fixture(t);+ f.host('0.9.0');+ assert.throws(() => planPublishedUpdate(f.projectRoot, '0.9.0', f.options), /downgrade/);+ f.host('2.0.0', 2, 2);+ f.template('2.0.0', '2.0.0');+ assert.throws(() => planPublishedUpdate(f.projectRoot, '2.0.0', f.options), /migration chain/);+});++test('current-version upgrade planning does not read the app lock or dependency inventory', (t) => {+ const f = fixture(t);+ assert.equal(planPublishedUpdate(f.projectRoot, '1.0.0', f.options).kind, 'current');+ fs.writeFileSync(path.join(f.projectRoot, 'package-lock.json'), 'not JSON');+ fs.writeFileSync(path.join(f.projectRoot, 'node_modules/expo-haptics/package.json'), 'not JSON');+ assert.equal(planPublishedUpdate(f.projectRoot, '1.0.0', f.options).kind, 'current');+ fs.unlinkSync(path.join(f.projectRoot, 'package-lock.json'));+ assert.equal(planPublishedUpdate(f.projectRoot, '1.0.0', f.options).kind, 'current');+});++test('native inventory comes from the published lock, never from the customer lock', (t) => {+ const f = fixture(t);+ const project = () => readProject(f.projectRoot, readPlatformContext());+ validateProjectAgainstRelease(project(), projectContract(f.projectRoot, project(), f.options));+ modifyJson(path.join(f.projectRoot, 'node_modules/expo-haptics/package.json'), (pkg) => { pkg.version = '1.0.1'; });+ modifyJson(path.join(f.projectRoot, 'package-lock.json'), (lock) => { lock.packages['node_modules/expo-haptics'].version = '1.0.1'; });+ const changed = project();+ assert.throws(() => validateProjectAgainstRelease(changed, projectContract(f.projectRoot, changed, f.options)), /native inventory/);+});++test('custom native code cannot extend the fixed runtime', (t) => {+ const f = fixture(t);+ addDependency(f.projectRoot, 'ordinary-wrapper', '1.0.0');+ fs.mkdirSync(path.join(f.projectRoot, 'node_modules/ordinary-wrapper/android'));+ const project = readProject(f.projectRoot, readPlatformContext());+ assert.throws(() => validateProjectAgainstRelease(project, projectContract(f.projectRoot, project, f.options)), /not managed|Unreviewed native/);+});++test('runtime labels cannot excuse mismatching published fingerprints', (t) => {+ const f = fixture(t);+ f.host('1.0.1').profile.nativeRuntime.android.fingerprint = 'f'.repeat(64);+ assert.throws(() => selectPublishedContract('1.0.1', f.options), /fingerprint/);+});++test('upgrade fingerprint differences are warnings rather than blockers', (t) => {+ const f = fixture(t);+ f.host('1.1.0', 2, 1, [migration('1.1.0')]).profile.nativeRuntime.android.fingerprint = 'f'.repeat(64);+ f.template('1.1.0', '1.1.0');+ const result = planPublishedUpdate(f.projectRoot, '1.1.0', f.options);+ assert.equal(result.kind, 'template-upgrade');+ assert.deepEqual(result.warnings, ['android native fingerprints differ; verify Dev Player/Wrap compatibility separately.']);+});++test('current-state admission rejects a locally altered host profile', (t) => {+ const f = fixture(t);+ modifyJson(path.join(f.projectRoot, 'node_modules', HOST, 'compatibility/current.json'), (profile) => {+ profile.managedDependencies['expo-haptics'] = '2.0.0';+ });+ assert.equal(planPublishedUpdate(f.projectRoot, '1.0.0', f.options).kind, 'current');+ assert.throws(() => resolveProjectRelease(f.projectRoot, undefined, undefined, f.options), /metadata differs/);+});++test('strict admission verifies offline artifacts while upgrade planning leaves installation checks to the host', t => {+ const offline = '@microsoft/power-apps-native-offline';+ const entry = `node_modules/${offline}`;+ for (const mode of ['admit', 'current']) {+ const f = fixture(t);+ const host = f.packages.get(`${HOST}@1.0.0`);+ const template = f.packages.get(`${TEMPLATE}@1.0.0`);+ Object.assign(host.profile, { expoSdk: 1, runtimeFamily: 'fixture-native-family', offlineContractVersion: 1 });+ host.profile.managedDependencies[offline] = '0.2.0';+ host.pkg.peerDependencies = { [offline]: '^0.2.0' };+ writeJson(path.join(f.projectRoot, 'node_modules', HOST, 'compatibility/current.json'), host.profile);+ const pkg = {+ name: offline, version: '0.2.0', peerDependencies: { [HOST]: '^1.0.0', 'react-native': '1.0.0' },+ };+ const contract = {+ schemaVersion: 2, complete: true, sourceDirty: false, packageVersion: pkg.version,+ reactNativeVersion: '1.0.0', expoSdkVersion: '1', runtimeFamily: host.profile.runtimeFamily,+ offlineContractVersion: 1, engine: 'hermes', hostPeerRange: pkg.peerDependencies[HOST],+ platformArchitectures: { android: ['new'], ios: ['new'] },+ artifacts: { 'android/runtime.aar': createHash('sha256').update('native fixture').digest('hex') },+ };+ const publication = {+ package: offline, version: pkg.version, integrity: `sha512-${Buffer.alloc(64, 2).toString('base64')}`,+ };+ f.packages.set(`${offline}@0.2.0`, { publication, pkg, contract });+ addDependency(f.projectRoot, offline, pkg.version);+ const sdk = path.join(f.projectRoot, entry);+ writeJson(path.join(sdk, 'package.json'), pkg);+ writeJson(path.join(sdk, 'compatibility.json'), contract);+ fs.mkdirSync(path.join(sdk, 'android'));+ fs.writeFileSync(path.join(sdk, 'android/runtime.aar'), 'native fixture');+ modifyJson(path.join(f.projectRoot, 'package-lock.json'), lock => {+ lock.packages[entry].integrity = publication.integrity;+ });+ template.manifest.dependencies[offline] = pkg.version;+ template.lock.packages[''].dependencies[offline] = pkg.version;+ template.lock.packages[entry] = { version: pkg.version, integrity: publication.integrity };+ const verify = () => mode === 'admit'+ ? resolveProjectRelease(f.projectRoot, undefined, undefined, f.options)+ : planPublishedUpdate(f.projectRoot, '1.0.0', f.options);+ assert.doesNotThrow(verify);+ assert.equal(f.requests.filter(request => request === `${offline}@0.2.0`).length, mode === 'admit' ? 1 : 0);+ fs.writeFileSync(path.join(sdk, 'android/runtime.aar'), 'altered native fixture');+ modifyJson(path.join(sdk, 'compatibility.json'), metadata => {+ metadata.artifacts['android/runtime.aar'] = createHash('sha256').update('altered native fixture').digest('hex');+ });+ if (mode === 'admit') assert.throws(verify, /metadata differs from its integrity-verified published archive/);+ else assert.equal(verify().kind, 'current');+ }+});++test('metadata cannot substitute the wrong template lock or core runtime', (t) => {+ const f = fixture(t);+ const template = f.packages.get(`${TEMPLATE}@1.0.0`);+ template.lock.packages['node_modules/expo'].version = '2.0.0';+ assert.throws(() => selectPublishedContract('1.0.0', f.options), /Expo\/React/);+ template.lock.packages['node_modules/expo'].version = '1.0.0';+ template.manifest.dependencies.react = '2.0.0';+ assert.throws(() => selectPublishedContract('1.0.0', f.options), /declarations differ/);+});++test('native metadata mutation is rejected without a template edge', (t) => {+ const f = fixture(t);+ f.host('2.0.0', 1, 2);+ f.template('2.0.0', '2.0.0');+ assert.throws(() => planPublishedUpdate(f.projectRoot, '2.0.0', f.options), /host-owned template migration/);+});++test('archive inspection checks real bytes, skips lifecycle scripts, and cleans scratch', (t) => {+ const f = fixture(t);+ const packageRoot = path.join(f.directory, 'package');+ const host = f.packages.get(`${HOST}@1.0.0`);+ writeJson(path.join(packageRoot, 'package.json'), { ...host.pkg, scripts: { postinstall: 'never-run-this' } });+ writeJson(path.join(packageRoot, 'compatibility/current.json'), host.profile);+ const archive = path.join(f.directory, 'host.tgz');+ const packed = spawnSync('tar', ['-czf', 'host.tgz', 'package'], { cwd: f.directory, encoding: 'utf8' });+ assert.equal(packed.status, 0, packed.stderr);+ const integrity = `sha512-${createHash('sha512').update(fs.readFileSync(archive)).digest('base64')}`;+ const workspaces = [];+ let corrupt = false;+ let legacy = false;+ const options = {+ cwd: f.projectRoot,+ run(command, args, cwd) {+ if (command === 'npm') {+ assert.equal(cwd, f.projectRoot, 'npm must retain the calling project registry configuration');+ if (args[0] === 'view') return JSON.stringify({+ name: HOST, version: '1.0.0',+ dist: legacy ? { shasum: createHash('sha1').update(fs.readFileSync(archive)).digest('hex') } : { integrity },+ });+ assert.deepEqual(args.slice(0, 5), ['pack', `${HOST}@1.0.0`, '--ignore-scripts', '--json', '--pack-destination']);+ const destination = args[5];+ workspaces.push(destination);+ fs.copyFileSync(archive, path.join(destination, 'host.tgz'));+ if (corrupt) fs.appendFileSync(path.join(destination, 'host.tgz'), 'corrupt');+ return JSON.stringify([{ name: HOST, version: '1.0.0', integrity, filename: 'host.tgz' }]);+ }+ assert.equal(command, 'tar');+ const result = spawnSync(command, args, { cwd, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ return result.stdout;+ },+ };+ assert.equal(createSource(options).read(HOST, '1.0.0').profile.targetTemplateVersion, 1);+ assert.ok(workspaces.every((directory) => !fs.existsSync(directory)));+ legacy = true;+ assert.match(createSource(options).read(HOST, '1.0.0').publication.integrity, /^sha1-/);+ corrupt = true;+ assert.throws(() => createSource(options).read(HOST, '1.0.0'), /bytes do not match/);+ assert.ok(workspaces.every((directory) => !fs.existsSync(directory)));+});++test('selectors reject tags, prereleases, URLs and shell syntax before npm runs', () => {+ const source = createSource({ run() { assert.fail('npm must not run for invalid selectors'); } });+ for (const version of ['latest', '^1.0.0', '1.0.0-preview.1', 'https://example.com/package.tgz', '1.0.0;echo secret']) {+ assert.throws(() => source.read(HOST, version), /exact stable/);+ }+});++test('host acquisition is isolated, script-disabled, integrity-bound and cannot overwrite an app', (t) => {+ const f = fixture(t);+ f.packages.get(`${HOST}@1.0.0`).profile.managedOverrides = { 'fixture-peer': '1.0.0' };+ const before = fs.readFileSync(path.join(f.projectRoot, 'package.json'), 'utf8');+ const destination = path.join(f.directory, 'tooling');+ const options = {+ ...f.options,+ cwd: f.projectRoot,+ run(command, args, cwd, invocation) {+ assert.equal(command, 'npm');+ assert.equal(cwd, fs.realpathSync.native(f.projectRoot));+ assert.equal(invocation.env.npm_config_prefix, destination);+ const tooling = JSON.parse(fs.readFileSync(path.join(destination, 'package.json'), 'utf8'));+ assert.deepEqual(tooling.dependencies, {+ ...f.packages.get(`${HOST}@1.0.0`).profile.managedDependencies, [HOST]: '1.0.0',+ });+ assert.deepEqual(tooling.overrides, { 'fixture-peer': '1.0.0' });+ assert.deepEqual(args, ['install', '--ignore-scripts', '--strict-peer-deps', '--no-legacy-peer-deps', '--no-force', '--no-audit', '--no-fund', '--prefix', destination]);+ const hostRoot = path.join(destination, 'node_modules', HOST);+ writeJson(path.join(hostRoot, 'package.json'), { name: HOST, version: '1.0.0', bin: { 'upgrade-template': 'scripts/upgrade.js' } });+ fs.mkdirSync(path.join(hostRoot, 'scripts'));+ fs.writeFileSync(path.join(hostRoot, 'scripts/upgrade.js'), '// fixture; never executed\n');+ writeJson(path.join(destination, 'package-lock.json'), { packages: {+ [`node_modules/${HOST}`]: { version: '1.0.0', integrity: f.packages.get(`${HOST}@1.0.0`).publication.integrity },+ } });+ return '';+ },+ };+ const result = acquireHost(destination, '1.0.0', options);+ assert.equal(result.lifecycleScriptsExecuted, false);+ assert.equal(result.upgradeCli, `node_modules/${HOST}/scripts/upgrade.js`);+ assert.equal(fs.readFileSync(path.join(f.projectRoot, 'package.json'), 'utf8'), before);+ assert.equal(f.requests.filter(request => request === `${HOST}@1.0.0`).length, 1,+ 'Reuse the verified publication rather than fetching a second profile for tooling');+ assert.throws(() => acquireHost(f.projectRoot, '1.0.0', options), /existing apps are never overwritten/);+ assert.throws(() => acquireHost(destination, '1.0.0', options), /existing apps are never overwritten/);+});++test('host acquisition from an empty child cwd captures the parent npm context before creating a manifest', t => {+ const f = fixture(t);+ const context = '@microsoft:registry=https://packages.example.invalid/\n'+ + '//packages.example.invalid/:_authToken=synthetic-parent-token\n';+ fs.writeFileSync(path.join(f.projectRoot, '.npmrc'), context);+ const parentManifest = fs.readFileSync(path.join(f.projectRoot, 'package.json'));+ const parentLock = fs.readFileSync(path.join(f.projectRoot, 'package-lock.json'));+ for (const fail of [false, true]) {+ const destination = path.join(f.projectRoot, fail ? 'failed-tooling' : 'tooling');+ fs.mkdirSync(destination);+ const action = () => acquireHost(destination, '1.0.0', {+ ...f.options,+ cwd: destination,+ run(command, args, cwd, invocation) {+ assert.equal(command, 'npm');+ assert.equal(cwd, fs.realpathSync.native(destination));+ assert.equal(invocation.env.npm_config_prefix, destination);+ assert.equal(args[args.indexOf('--prefix') + 1], destination);+ assert.equal(fs.readFileSync(path.join(destination, '.npmrc'), 'utf8'), context,+ 'Use the same parent registry/auth context as package inspection');+ assert.equal(JSON.parse(fs.readFileSync(path.join(destination, 'package.json'), 'utf8')).name, 'mobile-upgrade-tooling');+ if (fail) throw new Error('Synthetic isolated install failure');+ const hostRoot = path.join(destination, 'node_modules', HOST);+ writeJson(path.join(hostRoot, 'package.json'), { name: HOST, version: '1.0.0', bin: { 'upgrade-template': 'scripts/upgrade.js' } });+ fs.mkdirSync(path.join(hostRoot, 'scripts'));+ fs.writeFileSync(path.join(hostRoot, 'scripts/upgrade.js'), '// fixture; never executed\n');+ writeJson(path.join(destination, 'package-lock.json'), { packages: {+ [`node_modules/${HOST}`]: { version: '1.0.0', integrity: f.packages.get(`${HOST}@1.0.0`).publication.integrity },+ } });+ return '';+ },+ });+ if (fail) assert.throws(action, /Synthetic isolated install failure/);+ else assert.equal(action().installedDependencies, true);+ assert.equal(fs.existsSync(path.join(destination, '.npmrc')), false);+ assert.equal(fs.readFileSync(path.join(f.projectRoot, '.npmrc'), 'utf8'), context);+ assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'package.json')), parentManifest);+ assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'package-lock.json')), parentLock);+ }+});++test('older hosts do not accidentally select a newer template baseline', (t) => {+ const f = fixture(t);+ f.host('1.0.1');+ f.template('1.0.1', '1.0.1');+ assert.equal(selectPublishedContract('1.0.0', f.options).template.version, '1.0.0');+});diff --git a/plugins/mobile-apps/scripts/tests/mobile-release-surfaces.test.js b/plugins/mobile-apps/scripts/tests/mobile-release-surfaces.test.jsnew file mode 100644index 000000000..af7168ce9--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-release-surfaces.test.js@@ -0,0 +1,380 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const test = require('node:test');+const { spawnSync } = require('node:child_process');+const { shellBlocks } = require('./helpers/markdown-shell-blocks');++const pluginRoot = path.resolve(__dirname, '../..');+const read = (file) => fs.readFileSync(path.join(pluginRoot, file), 'utf8');+const entrySkills = ['add-native', 'deploy', 'edit-app', 'debug-app', 'report-issue'];+const nativeHelpers = ['add-camera', 'add-geolocation', 'add-pdf-report', 'add-pdf-viewer', 'add-pen-input'];+const agents = ['native-app-planner', 'screen-planner', 'screen-builder', 'data-model-architect', 'offline-profile-architect'];+const resolver = 'node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root \'<working_dir>\'';++function codeBlock(source, marker) {+ const blocks = [...source.matchAll(/```(?:ts|typescript|tsx)\r?\n([\s\S]*?)```/g)];+ const block = blocks.find((match) => match[1].includes(marker));+ assert.ok(block, `Missing example: ${marker}`);+ return block[1];+}++test('native example extraction supports LF and CRLF Markdown fences', () => {+ for (const newline of ['\n', '\r\n']) {+ for (const language of ['ts', 'typescript', 'tsx']) {+ const marker = 'export async function nativeExample() {}';+ const source = ['```js', 'unrelated();', '```', `\`\`\`${language}`, marker, '```'].join(newline);+ assert.equal(codeBlock(source, marker), `${marker}${newline}`);+ assert.throws(() => codeBlock(source, 'missingExample'), /Missing example/);+ }+ }+});++test('entry skills and native helpers resolve the existing app and share lifecycle policy', () => {+ const files = [+ ...entrySkills.map((skill) => `skills/${skill}/SKILL.md`),+ ...nativeHelpers.map((skill) => `skills/add-native/${skill}/SKILL.md`),+ ];+ for (const file of files) {+ const source = read(file);+ assert.ok(source.includes(resolver), `${file}: missing app-matched resolver`);+ assert.match(source, /mobile-release-lifecycle\.md/, file);+ assert.doesNotMatch(source, /\$\{PLUGIN_ROOT\}\/template\/package\.json/, file);+ assert.doesNotMatch(source, /Re-scaffold via \/create-mobile-app|adopt the current template's Metro config/, file);+ }+});++test('all planning and building agents receive the same release context, not plugin-native pins', () => {+ for (const agent of agents) {+ const source = read(`agents/${agent}.md`);+ assert.match(source, /mobile-release-lifecycle\.md/, agent);+ assert.match(source, /sanitized[\s\S]{0,100}resolved (?:release )?context/i, agent);+ assert.doesNotMatch(source, /\$\{PLUGIN_ROOT\}\/template\/package\.json/, agent);+ }+ const builder = read('agents/screen-builder.md');+ assert.match(builder, /missing wrapper is `BLOCKED`/);+ assert.doesNotMatch(builder, /TODO\(native-not-yet-added\)/);+ assert.match(builder, /source\/UI work may[\s\S]{0,120}unverified/);+ const planner = read('agents/native-app-planner.md');+ assert.match(planner, /`nativePackages`/);+ assert.match(planner, /`managedDependencies`/);+ assert.match(planner, /Do not collapse distinct nested package versions/);+ assert.match(planner, /requirements-only[\s\S]{0,90}cannot authorize native mutation/);+});++test('creation handoffs retain published npm acquisition and separate installation approval', () => {+ const planner = read('agents/native-app-planner.md');+ const start = planner.indexOf('Next steps for the orchestrator:');+ assert.ok(start >= 0);+ const handoff = planner.slice(start, planner.indexOf('\n```', start));+ assert.match(handoff, /orchestrator-approved/);+ assert.match(handoff, /exact stable published npm template/);+ assert.match(handoff, /verified package creation CLI/);+ assert.match(handoff, /separately approved shipped-lock `npm ci`/);+ assert.doesNotMatch(planner, /\bdegit\b|power-platform-skills\/plugins\/mobile-apps\/template#main/);+});++test('screen planning follows the foreground npm scaffold owner instead of a retired clone pipeline', () => {+ const planner = read('agents/screen-planner.md');+ const start = planner.indexOf('**The scaffolded project');+ assert.ok(start >= 0);+ const scaffold = planner.slice(start, planner.indexOf('## Workflow', start));+ assert.match(scaffold, /reviewed published npm template/);+ assert.match(scaffold, /separately approved shipped-lock `npm ci`/);+ assert.match(scaffold, /foreground-only/);+ assert.match(scaffold, /DEFERRED_CONCERNS\[\]/);+ assert.doesNotMatch(scaffold, /Step 2d background pipeline|clone\s*\u2192|cp -R|after JOIN/);++ const creation = read('skills/create-mobile-app/SKILL.md');+ const mode = creation.slice(creation.indexOf('### Step 2d'), creation.indexOf('### Step 3'));+ assert.match(mode, /fresh-template gate/);+ assert.match(mode, /separately approved shipped-lock `npm ci`/);+ assert.doesNotMatch(mode, /`npm install`/);+});++test('README keeps the bundled directory as a fixture rather than a new-app template source', () => {+ const entry = read('README.md').split(/\r?\n/).find(line => line.startsWith('- [`plugins/mobile-apps/template`]'));+ assert.ok(entry, 'Keep the fixture navigation link with its actual scope');+ assert.match(entry, /legacy preparation\/test fixture/);+ assert.match(entry, /missing-guidance defaults/);+ assert.match(entry, /not an app-template acquisition source/);+ assert.doesNotMatch(entry, /fresh-template working directory source/);+});++test('release links are valid local references from every owned surface', () => {+ const files = [+ ...entrySkills.map((skill) => `skills/${skill}/SKILL.md`),+ ...nativeHelpers.map((skill) => `skills/add-native/${skill}/SKILL.md`),+ ...agents.map((agent) => `agents/${agent}.md`),+ 'skills/add-native/references/native-controls.md',+ 'shared/version-check.md',+ 'shared/references/javascript-dependency-planning.md',+ ];+ for (const file of files) {+ const source = read(file);+ for (const [, target] of source.matchAll(/\]\(([^)\s]*(?:mobile-release-lifecycle|native-controls)\.md)\)/g)) {+ assert.ok(fs.existsSync(path.resolve(pluginRoot, path.dirname(file), target)), `${file}: ${target}`);+ }+ }+});++test('deploy checks both actual intended base versions and fingerprints before build and every push', () => {+ const source = read('skills/deploy/SKILL.md');+ for (const platform of ['android', 'ios']) {+ assert.ok(source.includes(`${resolver} --platform ${platform} --base-version "<actual-intended-${platform}-base-version>" --base-fingerprint "<actual-intended-${platform}-base-fingerprint>"`));+ }+ assert.ok(source.indexOf('### Step 1.2') < source.indexOf('### Step 1.5'));+ assert.match(source, /Missing selection is a blocker/);+ assert.match(source, /version label alone does not[\s\S]{0,60}prove matching native runtime content/);+ assert.match(source, /missing or mismatched fingerprint blocks/);+ assert.match(source, /requirements-only[\s\S]{0,70}cannot authorize deployment/);+ assert.match(source, /Unknown\/missing package contracts or base metadata[\s\S]{0,120}STOP/);+ assert.match(source, /--base-runtime-version/);+ assert.match(source, /no `deploy without compatibility` override/);+ assert.match(source, /Re-run Step 1\.2[\s\S]{0,160}fingerprints before this push/);+ assert.match(source, /Hermes magic bytes[\s\S]{0,180}compatibility/);+ assert.match(source, /not.*newest bundled template|never use the newest bundled template/);+});++test('multi-command native admission blocks propagate the first resolver failure', t => {+ const root = fs.mkdtempSync(path.join(require('node:os').tmpdir(), 'mobile-admission-gate-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const candidates = process.platform === 'win32'+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)+ : [];+ const bash = candidates.find(file => /[\\/]Git[\\/]/i.test(file)) || 'bash';+ for (const [file, marker] of [+ ['skills/add-native/add-pdf-report/SKILL.md', "const required='expo-print'"],+ ['skills/deploy/SKILL.md', '--platform android'],+ ]) {+ const block = shellBlocks(read(file)).find(value => value.includes(marker));+ assert.ok(block, file);+ const command = block.replaceAll('<working_dir>', root.replaceAll('\\', '/').replaceAll("'", "'\\''"));+ const probe = 'count=0\nnode() { count=$((count + 1)); if [ \"$count\" -eq 1 ]; then return 23; fi; printf \"unexpected-followup\"; }\n';+ const result = spawnSync(bash, ['-s'], {+ input: probe + command, encoding: 'utf8', timeout: 10000,+ });+ assert.equal(result.status, 23, file);+ assert.equal(result.stdout, '', 'No later successful command may hide native admission failure');+ }+});+test('deployment retains app-ID two-pass packaging, offline reconciliation, and user confirmation', () => {+ const source = read('skills/deploy/SKILL.md');+ assert.match(source, /two full build\+push cycles are required/);+ assert.match(source, /In cycle 2, `npm run build` \*and\* the Step 2\.4 native packaging commands must all re-run/);+ assert.match(source, /npm run bundle:android/);+ assert.match(source, /npm run bundle:ios/);+ assert.match(source, /c61fbc03/);+ assert.match(source, /powerapps-customer-assets-android\/manifest\.json/);+ assert.match(source, /powerapps-customer-assets-ios\/manifest\.json/);+ assert.match(source, /offline-profile-delta\.js/);+ assert.match(source, /exact phrase `deploy without offline`/);+ assert.match(source, /exact phrase `yes deploy to <env-name>`/);+ assert.match(source, /explicitly type `override`/);+ assert.match(source, /Do not proceed on a bare `y`/);+});++test('controls adoption is conditional and documents the public aggregate contract', () => {+ const source = read('skills/add-native/references/native-controls.md');+ assert.match(source, /root is metadata, not a runtime[\s\S]{0,20}barrel/);+ assert.match(source, /power-apps-native-controls\/pdf` \| `NativePdfViewer`/);+ assert.match(source, /power-apps-native-controls\/pen` \| `PenInputNative`, `PenInputStatus`, `PenInputErrorCode`/);+ assert.match(source, /power-apps-native-controls\/geolocation` \| `BgLocationClient`, `geoService`, `AuthMethod`, `ConnectionType`/);+ assert.match(source, /no barcode subpath/);+ for (const version of ['0.2.0', '0.2.9', '0.1.9', '0.2.3', '0.4.2', '0.83.6']) {+ assert.ok(source.includes(version), `Missing published controls fact: ${version}`);+ }+ assert.match(source, /Expo 55/);+ assert.match(source, /not evidence of Expo 57 compatibility/);+ assert.match(source, /Do not install the aggregate to[\s\S]{0,20}fix older binaries/);+ assert.match(source, /Legacy leaf imports are allowed only when the resolved release actually includes[\s\S]{0,50}matching leaf and version/);+ assert.match(source, /installed public README, exports, and types/);+});++test('control wrapper examples guard platforms before lazy literal subpath imports', () => {+ for (const [helper, marker, subpath] of [+ ['add-pdf-viewer', 'export async function openHttpsPdf', 'pdf'],+ ['add-pen-input', 'export async function captureSignature', 'pen'],+ ['add-geolocation', 'export async function getCurrentLocation', 'geolocation'],+ ]) {+ const source = read(`skills/add-native/${helper}/SKILL.md`);+ const example = codeBlock(source, marker);+ const guard = example.indexOf("Platform.OS !== 'ios' && Platform.OS !== 'android'");+ const lazyImport = example.indexOf(`await import('@microsoft/power-apps-native-controls/${subpath}')`);+ assert.ok(guard >= 0 && lazyImport > guard, `${helper}: native guard must precede import`);+ assert.ok(example.lastIndexOf('try {', lazyImport) > guard, `${helper}: import must be caught`);+ assert.doesNotMatch(example, /from ['"]@microsoft\/power-apps-native-/);+ assert.doesNotMatch(example, /import\(['"]@microsoft\/power-apps-native-controls['"]\)/);+ assert.match(source, /legacy/i);+ assert.match(source, /verified release|resolved release/);+ }+});++test('PDF and pen wrappers preserve useful failure and artifact boundaries', () => {+ const pdf = read('skills/add-native/add-pdf-viewer/SKILL.md');+ const pen = read('skills/add-native/add-pen-input/SKILL.md');+ const native = read('skills/add-native/SKILL.md');+ assert.match(pdf, /content:\/\/.*blob:.*http:\/\//);+ assert.match(pdf, /response\.error === 'NATIVE_MODULE_MISSING'/);+ assert.match(pen, /result\.error === PenInputErrorCode\.NativeModuleMissing/);+ assert.match(pen, /result\.error === PenInputErrorCode\.UserCancelled/);+ assert.match(pen, /PNG data URI/);+ assert.match(native, /Dataverse File\/Image columns use host controls/);+ assert.match(native, /Never put File column bytes in the create\/update JSON body/);+ assert.match(native, /Service\.upload|generated `upload\(\.\.\.\)`/);+});++test('one-shot location does not inherit tracking setup and shared tracking is explicit', () => {+ const source = read('skills/add-native/add-geolocation/SKILL.md');+ const oneShot = codeBlock(source, 'export async function getCurrentLocation');+ assert.match(oneShot, /new BgLocationClient\(\)\.getCurrentLocation\(\)/);+ assert.doesNotMatch(oneShot, /app_id|geoService|dataSource|startTracking|msdyn_locationrecords/);+ assert.match(source, /no `app_id`, data source, target table, or `startTracking`/);+ assert.match(source, /0\.2\.3[\s\S]{0,120}background permissions[\s\S]{0,70}trackInBackground: false/);+ assert.match(source, /Tracking is shared/);+ assert.match(source, /`stopTracking\(\)` and `isTracking\(\)` have no `app_id`/);+ assert.match(source, /unrelated screen's unmount/);+ assert.match(source, /tracking-only/);+ assert.match(source, /BLOCKED \(target table missing\)/);+ assert.match(source, /configureSync.*HttpSyncContract/);+ assert.match(source, /Do not replace native behavior[\s\S]{0,60}JS timers, upload loops/);+});++test('native registration and permission wrapping cannot become customer-side workarounds', () => {+ const source = read('skills/add-native/references/native-controls.md');+ assert.match(source, /enableNativeControls[\s\S]{0,200}verified host release/);+ assert.match(source, /0\.4\.0 lacks it/);+ assert.match(source, /Package inclusion/);+ assert.match(source, /OS declarations/);+ assert.match(source, /Runtime permission grants/);+ assert.match(source, /actually invokes a capability/);+ assert.match(source, /does[\s\S]{0,20}\*\*not\*\* remove unused default Android permissions/);+ assert.match(source, /Different declarations need another verified base/);+ assert.match(source, /permission wrapping is deferred/);+});++test('source-only editing and JS planning stay available without a native compatibility claim', () => {+ const edit = read('skills/edit-app/SKILL.md');+ const js = read('shared/references/javascript-dependency-planning.md');+ const version = read('shared/version-check.md');+ assert.match(edit, /block native mutations, not[\s\S]{0,60}pure source\/UI planning and editing/);+ assert.match(edit, /exact verified release/);+ assert.match(edit, /Release context: <sanitized resolved tuple/);+ assert.match(edit, /Approve and apply/);+ assert.match(edit, /--plan-only/);+ assert.match(js, /block native mutations, not pure source\/UI/);+ assert.match(js, /npm install --save-exact <package>@<exact-version>/);+ assert.doesNotMatch(js, /known-good version for the current template baseline/);+ assert.match(version, /immutable, prebuilt native runtime/);+ assert.match(version, /does not prebuild or compile new native code/);+ assert.match(version, /--base-fingerprint <fingerprint>/);+ assert.match(version, /Missing or[\s\S]{0,30}mismatched fingerprint blocks deployment/);+ assert.doesNotMatch(version, /Adding a native capability =|Pinned version|JSON\.stringify\(require\('\.\/app\.json'\)/);+});++test('debug and report surfaces preserve package ownership and sanitized evidence', () => {+ const debug = read('skills/debug-app/SKILL.md');+ const report = read('skills/report-issue/SKILL.md');+ assert.match(debug, /route verified-release migrations to `\/check-updates`/);+ assert.match(debug, /Never patch or fork first-party native packages/);+ assert.match(debug, /User consent to a dependency install does not waive this gate/);+ assert.match(report, /Reporting must still work|reporting must still work/);+ assert.match(report, /sanitized tuple/);+ assert.match(report, /--base-fingerprint <actual-intended-fingerprint>/);+ assert.match(report, /No raw app\/auth config/);+ assert.doesNotMatch(report, /console\.log\(JSON\.stringify\(\{env:|paste that output into the issue|include the full Metro\/Gradle\/Xcode log/);+ assert.match(report, /microsoft\/power-platform-skills\/issues\/new/);+});++test('all existing workflow telemetry checkpoint IDs remain unchanged', () => {+ const expected = {+ 'add-native': ['resolve_native_capability', 'dispatch_native_capability', 'generate_native_wrapper', 'validate_native_wrapper'],+ deploy: ['build_power_apps_bundle', 'validate_offline_profile_coverage', 'push_app_to_power_platform'],+ 'edit-app': ['assess_app_health_and_drift', 'analyze_edit_impact', 'revise_affected_app_plan', 'approve_app_mutation_plan', 'apply_app_mutations', 'rebuild_affected_screens', 'validate_edited_app', 'refresh_app_preview_and_history'],+ 'debug-app': ['validate_metro_session', 'capture_runtime_baseline', 'collect_runtime_logs', 'classify_runtime_failures', 'confirm_runtime_health', 'repair_and_verify_runtime_issue'],+ 'report-issue': ['capture_issue_description', 'collect_issue_diagnostics', 'render_issue_report', 'generate_issue_submission_url'],+ };+ for (const [skill, checkpoints] of Object.entries(expected)) {+ const source = read(`skills/${skill}/SKILL.md`);+ const actual = [...source.matchAll(/\*\*Telemetry checkpoint: `([^`]+)`\*\*/g)].map((match) => match[1]);+ assert.deepEqual(actual, checkpoints, skill);+ assert.match(source, /scripts\/check-version\.js/, `${skill}: startup notification`);+ }+});++test('production workflows use published packages without advertising retired diagnostic acquisition', () => {+ for (const skill of ['create-mobile-app', 'check-updates', 'edit-app', 'add-native', 'debug-app', 'report-issue']) {+ assert.doesNotMatch(read(`skills/${skill}/SKILL.md`), /--diagnostic-artifacts/, skill);+ }+ for (const helper of nativeHelpers) {+ assert.doesNotMatch(read(`skills/add-native/${helper}/SKILL.md`), /--diagnostic-artifacts/, helper);+ }+ for (const file of [+ 'AGENTS.md', 'README.md', 'shared/shared-instructions.md', 'shared/version-check.md',+ ...['create-mobile-app', 'check-updates', 'edit-app', 'add-native'].map(skill => `skills/${skill}/SKILL.md`),+ ...nativeHelpers.map(helper => `skills/add-native/${helper}/SKILL.md`),+ ]) {+ assert.doesNotMatch(read(file), /online-only Android|online-only test inventory/, file);+ }+ assert.equal(fs.existsSync(path.join(pluginRoot, 'shared/mobile-releases.json')), false);+ const lifecycle = read('shared/references/mobile-release-lifecycle.md');+ assert.match(lifecycle, /source manifest[\s\S]{0,120}not evidence of a[\s\S]{0,10}matching binary/);+ assert.match(lifecycle, /`--no-install` separately/);+ assert.doesNotMatch(lifecycle, /stage-diagnostic/);+ assert.match(lifecycle, /diagnostic artifact mode is retired/);+ assert.doesNotMatch(lifecycle, /--diagnostic-artifacts|diagnostic-57-v1/);+ const workflow = fs.readFileSync(path.resolve(pluginRoot, '../../.github/workflows/mobile-apps-script-tests.yml'), 'utf8');+ assert.match(workflow, /node --check plugins\/mobile-apps\/scripts\/lib\/mobile-package-artifacts\.js/);+ assert.doesNotMatch(workflow, /mobile-diagnostic-artifacts/);+ assert.match(lifecycle, /Do not delete profiles,/);+ assert.match(lifecycle, /native artifact hashes/);+ assert.match(lifecycle, /database upgrades[\s\S]{0,10}need separate device tests/);+ assert.match(read('skills/deploy/SKILL.md'), /Reject any `--diagnostic-artifacts`[\s\S]{0,100}before building or pushing/);+ assert.match(read('skills/debug-app/SKILL.md'), /actual[\s\S]{0,10}supported counters/);+});++test('upgrade rehearsals preserve source config context and require reviewed override resolutions', () => {+ const skill = read('skills/check-updates/SKILL.md');+ const lifecycle = read('shared/references/mobile-release-lifecycle.md');+ assert.match(skill, /restore-preview --project-root '<working_dir>' --preview-root '<preview_dir>'/);+ assert.match(skill, /Never run bare `npm ci`/);+ assert.match(skill, /check-sdk --project-root '<preview_dir>'/);+ assert.match(skill, /check-sdk --project-root '<working_dir>'/);+ assert.match(skill, /Expo compatibility, Expo Doctor, TypeScript and platform bundles are mandatory/);+ assert.match(skill, /any failure blocks application/);+ assert.match(skill, /Do not run strict app admission/);+ assert.doesNotMatch(skill, /resolve-mobile-release\.js[^\n]*--upgrade-only/);+ assert.doesNotMatch(skill, /`npx --no-install expo install --check`/);+ for (const source of [skill, lifecycle]) {+ assert.match(source, /restore-preview/);+ assert.match(source, /EXPO_OFFLINE=1/);+ assert.match(source, /installed SDK|frozen\s+SDK/);+ assert.match(source, /source dependencies from its\s+unchanged (?:source )?lock/);+ assert.match(source, /target-reference `NODE_PATH`/);+ assert.match(source, /source dependency context/);+ assert.match(source, /(?:Package override conflicts are blocking|override is a blocking preview)/);+ assert.match(source, /approve?[\s\S]{0,45}(?:exact resolution|exact override resolution)|approval for the[\s\S]{0,30}exact resolution/);+ assert.match(source, /EOVERRIDE/);+ assert.match(source, /[Tt]est-fixture-only/);+ }+});++test('upgrade skills reuse the verified external host CLI rather than duplicating installation', () => {+ const skill = read('skills/check-updates/SKILL.md');+ const lifecycle = read('shared/references/mobile-release-lifecycle.md');+ for (const source of [skill, lifecycle]) {+ assert.match(source, /mobile-template-lifecycle\.js acquire/);+ assert.match(source, /bin\["upgrade-template"\]/);+ assert.match(source, /guarded lock regeneration/);+ assert.match(source, /producer fix/);+ assert.match(source, /Player.build scripts|Player-build scripts/);+ }+ assert.match(skill, /separate private tooling installation/);+ assert.match(skill, /not by installing it into the old app's dependency graph/);+ assert.match(skill, /same verified reference host CLI/);+ assert.match(skill, /never[\s\S]{0,90}delete the app's lock or `node_modules`/);+ assert.doesNotMatch(skill, /Install the \*\*exact reviewed target host\*\* only in the disposable copy/);+ assert.match(lifecycle, /Published migrations use the host-owned strict npm installer/);+});diff --git a/plugins/mobile-apps/scripts/tests/mobile-release.test.js b/plugins/mobile-apps/scripts/tests/mobile-release.test.jsnew file mode 100644index 000000000..81a46f9d5--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-release.test.js@@ -0,0 +1,874 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const {+ selectRelease, resolveProjectRelease, validateRelease, summarizeRelease,+ readProjectRequirements, selectProjectRelease, readPlatformContext,+} = require('../lib/mobile-release');+const {+ HOST, fixtureRelease, makeRelease, writeProject, createFixture, writeJson, modifyJson, installPackage, addDependency, runCli, runValidator,+} = require('./helpers/mobile-release-fixture');++function blocked(result, message) {+ assert.equal(result.status, 2, result.stderr);+ assert.equal(result.stdout, '');+ assert.match(result.stderr, /^BLOCKED:/);+ if (message) assert.match(result.stderr, message);+ assert.doesNotMatch(result.stderr, /fixture-secret-do-not-echo/);+}++test('production resolution has no bundled catalogue or speculative package selection', () => {+ assert.equal(fs.existsSync(path.resolve(__dirname, '../../shared/mobile-releases.json')), false);+ assert.throws(() => selectRelease(), /exact stable host or template package version/);+});++test('reusable fixtures deep-merge overrides and write a strictly resolvable synthetic project', (t) => {+ const fixture = createFixture(t);+ const overrides = {+ id: 'fixture-reusable-project',+ templateVersion: 4,+ nativeRuntimeVersions: { android: 4 },+ managedDependencies: { devDependencies: { typescript: '5.0.0' } },+ nativePackages: { 'node_modules/expo/node_modules/ordinary-bridge': '1.0.0' },+ };+ const originalOverrides = structuredClone(overrides);+ const release = makeRelease(overrides);+ assert.equal(release.nativeRuntimeVersions.ios, 1);+ assert.equal(release.nativePackages[`node_modules/${HOST}`], '1.0.0');+ assert.deepEqual(overrides, originalOverrides);+ assert.equal(validateRelease(release), release);+ const root = path.join(fixture.directory, 'standalone-project');+ assert.equal(writeProject(root, release), root);+ const catalog = { schemaVersion: 1, defaultRelease: release.id, releases: [release] };+ assert.equal(resolveProjectRelease(root, catalog), release);+ release.managedDependencies.devDependencies.typescript = '6.0.0';+ assert.equal(overrides.managedDependencies.devDependencies.typescript, '5.0.0');+ assert.equal(makeRelease().id, 'fixture-release-1');+});++test('selection returns the exact reviewed record, explicitly or through its default', () => {+ const release = fixtureRelease();+ const catalog = { schemaVersion: 1, defaultRelease: release.id, releases: [release] };+ assert.equal(validateRelease(release), release);+ assert.equal(selectRelease(release.id, catalog), release);+ assert.equal(selectRelease(undefined, catalog), release);+ assert.throws(() => selectRelease('unreviewed', catalog), /No verified mobile release/);+ assert.throws(() => selectRelease('fixture-secret-do-not-echo/invalid', catalog), /valid reviewed release id/);+ assert.throws(() => selectRelease(undefined, { ...catalog, defaultRelease: null }), /No verified mobile release/);+});++test('reviewed native declarations must accept the pinned npm version with standard SemVer ranges', () => {+ const release = fixtureRelease();+ release.nativePackages['node_modules/expo'] = '57.0.25';+ for (const spec of ['^57.0.0', '~57.0.20', '>=57.0.21 <58', '57.x', '55 || 57', '57.0.0 - 57.0.30']) {+ release.managedDependencies.dependencies.expo = spec;+ assert.equal(validateRelease(release), release, spec);+ }+ for (const spec of ['^55.0.0', '~57.1.0', '<57.0.25']) {+ release.managedDependencies.dependencies.expo = spec;+ assert.throws(() => validateRelease(release), /does not accept its reviewed exact version/, spec);+ }+ release.managedDependencies.dependencies.expo = 'file:./vendor/expo.tgz';+ assert.equal(validateRelease(release), release, 'Reviewed archive declarations are not registry ranges');+});++test('catalog schema, defaults and duplicate identities are strict', () => {+ const release = fixtureRelease();+ for (const catalog of [+ { schemaVersion: 2, defaultRelease: release.id, releases: [release] },+ { schemaVersion: 1, defaultRelease: 'unreviewed', releases: [release] },+ { schemaVersion: 1, defaultRelease: release.id, releases: [release, release] },+ { schemaVersion: 1, defaultRelease: release.id, releases: [release], latest: release.id },+ ]) assert.throws(() => selectRelease(undefined, catalog));+});++for (const [label, mutate] of [+ ['unknown record field', (r) => { r.verified = true; }],+ ['unsafe id', (r) => { r.id = '../release'; }],+ ['wrong template package', (r) => { r.template.package = 'unreviewed-template'; }],+ ['template prerelease', (r) => { r.template.version = '1.0.0-preview.1'; }],+ ['template range', (r) => { r.template.version = '^1.0.0'; }],+ ['leading-zero semver', (r) => { r.template.version = '01.0.0'; }],+ ['missing integrity', (r) => { delete r.template.integrity; }],+ ['invalid integrity', (r) => { r.template.integrity = 'sha512-short'; }],+ ['invalid templateVersion', (r) => { r.templateVersion = 0; }],+ ['missing platform runtime', (r) => { delete r.nativeRuntimeVersions.ios; }],+ ['string platform runtime', (r) => { r.nativeRuntimeVersions.android = '1'; }],+ ['missing host declaration', (r) => { delete r.managedDependencies.dependencies[HOST]; }],+ ['missing react declaration', (r) => { delete r.managedDependencies.dependencies.react; }],+ ['duplicate managed name', (r) => { r.managedDependencies.devDependencies = { react: '1.0.0' }; }],+ ['unknown managed section', (r) => { r.managedDependencies.other = {}; }],+ ['managed URL dependency', (r) => { r.managedDependencies.dependencies[HOST] = 'https://example.com/archive.tgz'; }],+ ['malformed managed range', (r) => { r.managedDependencies.dependencies[HOST] = '^1.0.0-...'; }],+ ['vendor traversal', (r) => { r.managedDependencies.dependencies[HOST] = 'file:./vendor/../host.tgz'; }],+ ['missing host inventory', (r) => { delete r.nativePackages[`node_modules/${HOST}`]; }],+ ['published host prerelease', (r) => { r.nativePackages[`node_modules/${HOST}`] = '1.0.0-preview.1'; }],+ ['missing expo inventory', (r) => { delete r.nativePackages['node_modules/expo']; }],+ ['native version range', (r) => { r.nativePackages['node_modules/react'] = '^1.0.0'; }],+ ['native prerelease leading zero', (r) => { r.nativePackages['node_modules/react'] = '1.0.0-01'; }],+ ['path traversal', (r) => { r.nativePackages['node_modules/../outside'] = '1.0.0'; }],+ ['absolute package path', (r) => { r.nativePackages['/node_modules/outside'] = '1.0.0'; }],+ ['backslash path', (r) => { r.nativePackages['node_modules\\outside'] = '1.0.0'; }],+ ['invalid node_modules name', (r) => { r.nativePackages['node_modules/node_modules'] = '1.0.0'; }],+ ['missing iOS evidence', (r) => { delete r.platforms.ios; }],+ ['empty fingerprint', (r) => { r.platforms.android.fingerprint = ''; }],+ ['empty player version', (r) => { r.platforms.ios.player.version = ''; }],+ ['no verification references', (r) => { r.evidence = []; }],+]) {+ test(`rejects ${label} in reviewed policy`, () => {+ const release = fixtureRelease();+ mutate(release);+ assert.throws(() => validateRelease(release), (error) => error.code === 'MOBILE_RELEASE_BLOCKED');+ });+}++for (const evidence of [+ 'http://example.com/release',+ 'https:example.com/release',+ 'https://user:[email protected]/release',+ 'https://example.com/release?token=fixture-secret-do-not-echo',+ 'https://example.com/release#fixture-secret-do-not-echo',+ 'https://localhost/release',+ 'https://127.0.0.1/release',+ 'https://[::1]/release',+ 'https://review.internal/release',+ 'https://example.ghe.com/release',+ 'https://example.com:8443/release',+]) {+ test('rejects non-public or credential-bearing evidence without echoing it', () => {+ const release = fixtureRelease();+ release.evidence = [evidence];+ assert.throws(() => validateRelease(release), (error) => {+ assert.doesNotMatch(error.message, /fixture-secret-do-not-echo/);+ return error.code === 'MOBILE_RELEASE_BLOCKED';+ });+ release.evidence = ['https://example.com/fixture/verification'];+ release.platforms.android.base.evidence = evidence;+ assert.throws(() => validateRelease(release));+ });+}++test('supports all managed sections and nested scoped native inventory', () => {+ const release = fixtureRelease();+ release.managedDependencies.devDependencies = { typescript: '~5.0.0' };+ release.managedDependencies.optionalDependencies = { 'optional-fixture': '>=1.0.0 <2.0.0' };+ release.managedDependencies.peerDependencies = { 'peer-fixture': '^1.0.0 || ^2.0.0' };+ release.nativePackages['node_modules/expo/node_modules/@scope/native-fixture'] = '1.0.0-preview.1';+ assert.equal(validateRelease(release), release);+});++test('summary includes reviewed capability inventory and safe specs without project config', () => {+ const release = fixtureRelease();+ release.managedDependencies.devDependencies = { typescript: '~5.0.0' };+ release.managedDependencies.optionalDependencies = { 'fixture-archive': 'file:./vendor/fixture-archive-1.0.0.tgz' };+ const summary = summarizeRelease(release);+ assert.deepEqual(Object.keys(summary), ['id', 'template', 'templateVersion', 'nativeRuntimeVersions', 'hostVersion', 'managedDependencies', 'nativePackages', 'platforms', 'evidence']);+ assert.equal(summary.hostVersion, release.nativePackages[`node_modules/${HOST}`]);+ assert.deepEqual(summary.nativePackages, release.nativePackages);+ assert.deepEqual(summary.managedDependencies, release.managedDependencies);+ assert.doesNotMatch(JSON.stringify(summary), /connectionString|appInsightsConfig|projectRoot|resolved/);+ summary.platforms.android.base.version = 'changed';+ assert.notEqual(release.platforms.android.base.version, 'changed');+ summary.nativePackages[`node_modules/${HOST}`] = '99.0.0';+ summary.managedDependencies.dependencies[HOST] = '^99.0.0';+ summary.managedDependencies.devDependencies.typescript = '99.0.0';+ assert.equal(release.nativePackages[`node_modules/${HOST}`], '1.0.0');+ assert.equal(release.managedDependencies.dependencies[HOST], '^1.0.0');+ assert.equal(release.managedDependencies.devDependencies.typescript, '~5.0.0');+});++test('summary rejects credentials and unsafe paths rather than publishing dependency specs', (t) => {+ for (const mutate of [+ (release) => { release.managedDependencies.dependencies[HOST] = 'https://user:[email protected]/archive.tgz'; },+ (release) => { release.managedDependencies.dependencies[HOST] = 'file:../fixture-secret-do-not-echo/archive.tgz'; },+ (release) => { release.nativePackages['node_modules/../fixture-secret-do-not-echo'] = '1.0.0'; },+ ]) {+ const release = fixtureRelease();+ const fixture = createFixture(t, { release });+ mutate(release);+ assert.throws(() => summarizeRelease(release), (error) => {+ assert.doesNotMatch(error.message, /fixture-secret-do-not-echo/);+ return error.code === 'MOBILE_RELEASE_BLOCKED';+ });+ writeJson(path.join(fixture.pluginRoot, 'shared/fixture-contracts.json'), {+ schemaVersion: 1, defaultRelease: release.id, releases: [release],+ });+ blocked(runCli(fixture, ['--default']));+ }+});++test('project resolution returns its exact record, including an older release than the default', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ const catalog = { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] };+ const fixture = createFixture(t, { release: old, catalog });+ assert.equal(resolveProjectRelease(fixture.projectRoot, catalog), old);+ const result = runCli(fixture, ['--project-root', fixture.projectRoot]);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(JSON.parse(result.stdout).id, old.id);+ assert.doesNotMatch(result.stdout, /fixture-secret-do-not-echo|appInsightsConfig/);+ assert.ok(!result.stdout.includes(fixture.projectRoot));+ assert.equal(JSON.parse(result.stdout).nativePackages[`node_modules/${HOST}`], old.nativePackages[`node_modules/${HOST}`]);+});++test('same runtime counters are disambiguated using managed and installed versions, not newest', (t) => {+ const old = fixtureRelease();+ const newer = fixtureRelease(2);+ newer.templateVersion = old.templateVersion;+ newer.nativeRuntimeVersions = { ...old.nativeRuntimeVersions };+ const catalog = { schemaVersion: 1, defaultRelease: newer.id, releases: [newer, old] };+ const fixture = createFixture(t, { release: old, catalog });+ assert.equal(resolveProjectRelease(fixture.projectRoot, catalog), old);+ assert.equal(selectProjectRelease(fixture.projectRoot, catalog), old);+});++test('shared protected requirements use installed host identity, not declarations or default, for planning', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ newest.templateVersion = old.templateVersion;+ newest.nativeRuntimeVersions = { ...old.nativeRuntimeVersions };+ const catalog = { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] };+ const fixture = createFixture(t, { release: old, catalog });+ for (const file of ['package.json', 'package-lock.json']) {+ fs.writeFileSync(path.join(fixture.projectRoot, file), '{"fixture-secret-do-not-echo":');+ }+ assert.equal(selectProjectRelease(fixture.projectRoot, catalog), old);+ const planning = runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']);+ assert.equal(planning.status, 0, planning.stderr);+ assert.equal(JSON.parse(planning.stdout).id, old.id);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]));+ installPackage(fixture.projectRoot, `node_modules/${HOST}`, '2.0.0');+ assert.equal(selectProjectRelease(fixture.projectRoot, catalog), newest);+});++test('ambiguous requirements block when installed host is missing, unreviewed, malformed or linked', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ newest.templateVersion = old.templateVersion;+ newest.nativeRuntimeVersions = { ...old.nativeRuntimeVersions };+ const catalog = { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] };+ for (const edit of [+ (root) => fs.rmSync(path.join(root, 'node_modules', HOST), { recursive: true }),+ (root) => installPackage(root, `node_modules/${HOST}`, '99.0.0'),+ (root) => fs.writeFileSync(path.join(root, 'node_modules', HOST, 'package.json'), '{"fixture-secret-do-not-echo":'),+ (root) => installPackage(root, `node_modules/${HOST}`, '1.0.0', { name: 'ordinary-host-impostor' }),+ (root) => {+ const original = path.join(root, 'node_modules', HOST);+ const linked = path.join(root, 'linked-fixture-host');+ fs.renameSync(original, linked);+ fs.symlinkSync(linked, original, 'dir');+ },+ ]) {+ const fixture = createFixture(t, { release: old, catalog });+ edit(fixture.projectRoot);+ assert.throws(() => selectProjectRelease(fixture.projectRoot, catalog), (error) => error.code === 'MOBILE_RELEASE_BLOCKED');+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']));+ }+});++test('requirements reads return only validated protected fields without consulting dependency files', (t) => {+ const fixture = createFixture(t);+ for (const file of ['package.json', 'package-lock.json']) {+ fs.writeFileSync(path.join(fixture.projectRoot, file), '{"fixture-secret-do-not-echo":');+ }+ fs.rmSync(path.join(fixture.projectRoot, 'node_modules'), { recursive: true });+ const requirements = readProjectRequirements(fixture.projectRoot);+ assert.deepEqual(requirements, {+ schemaVersion: 1,+ templateVersion: fixture.release.templateVersion,+ nativeRuntimeVersions: fixture.release.nativeRuntimeVersions,+ });+ assert.equal(selectProjectRelease(fixture.projectRoot, fixture.catalog), fixture.release);+ const result = runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']);+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(JSON.parse(result.stdout), {+ ...summarizeRelease(fixture.release), validationScope: 'requirements-only',+ });+ assert.doesNotMatch(result.stdout, /fixture-secret-do-not-echo|appInsightsConfig/);+ assert.ok(!result.stdout.includes(fixture.projectRoot));+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]));+});++test('requirements planning preserves tenant configuration and returns only protected version fields', (t) => {+ const fixture = createFixture(t);+ const file = path.join(fixture.projectRoot, 'app.json');+ modifyJson(file, config => Object.assign(config.expo.extra.powerappsNative, {+ tenantMode: 'multi',+ appDisplayName: 'Customer-specific label',+ appName: 'customer_app',+ tenantPolicy: { allowedTenantIds: ['11111111-1111-4111-8111-111111111111'] },+ }));+ const before = fs.readFileSync(file, 'utf8');+ assert.deepEqual(readProjectRequirements(fixture.projectRoot), {+ schemaVersion: 1,+ templateVersion: fixture.release.templateVersion,+ nativeRuntimeVersions: fixture.release.nativeRuntimeVersions,+ });+ assert.equal(selectProjectRelease(fixture.projectRoot, fixture.catalog), fixture.release);+ const result = runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stdout, /tenantMode|tenantPolicy|Customer-specific|customer_app|11111111/);+ assert.equal(fs.readFileSync(file, 'utf8'), before);+});++test('requirements-only selection preserves the source record despite manual host drift', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ const catalog = { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] };+ for (const source of [old, newest]) {+ const fixture = createFixture(t, { release: source, catalog });+ const driftedHost = source === old ? '2.0.0' : '1.0.0';+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (data) => {+ (data.packages?.[''] || data).dependencies[HOST] = `^${driftedHost}`;+ });+ installPackage(fixture.projectRoot, `node_modules/${HOST}`, driftedHost);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages[`node_modules/${HOST}`].version = driftedHost;+ });+ assert.equal(selectProjectRelease(fixture.projectRoot, catalog), source);+ const planning = runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']);+ assert.equal(planning.status, 0, planning.stderr);+ assert.equal(JSON.parse(planning.stdout).id, source.id);+ assert.equal(JSON.parse(planning.stdout).hostVersion, source.nativePackages[`node_modules/${HOST}`]);+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, catalog), /Managed dependency/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Managed dependency/);+ blocked(runValidator(fixture), /Managed dependency/);+ }+});++test('equal host versions do not promote stale template requirements to the default release', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ old.managedDependencies.dependencies[HOST] = newest.managedDependencies.dependencies[HOST];+ old.nativePackages[`node_modules/${HOST}`] = newest.nativePackages[`node_modules/${HOST}`];+ const catalog = { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] };+ const fixture = createFixture(t, { release: old, catalog });+ assert.equal(selectProjectRelease(fixture.projectRoot, catalog), old);+ const result = runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(JSON.parse(result.stdout).templateVersion, old.templateVersion);+});++test('requirements planning never infers missing, invalid or unreviewed protected metadata', (t) => {+ for (const edit of [+ (config) => { delete config.expo.extra.powerappsNative; },+ (config) => { delete config.expo.extra.powerappsNative.schemaVersion; },+ (config) => { delete config.expo.extra.powerappsNative.templateVersion; },+ (config) => { delete config.expo.extra.powerappsNative.nativeRuntimeVersions; },+ (config) => { delete config.expo.extra.powerappsNative.nativeRuntimeVersions.ios; },+ (config) => { config.expo.extra.powerappsNative.schemaVersion = 2; },+ (config) => { config.expo.extra.powerappsNative.templateVersion = '1'; },+ (config) => { config.expo.extra.powerappsNative.nativeRuntimeVersions.android = 0; },+ ]) {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'app.json'), edit);+ assert.throws(() => readProjectRequirements(fixture.projectRoot), /Missing or invalid protected/);+ assert.throws(() => selectProjectRelease(fixture.projectRoot, fixture.catalog), /Missing or invalid protected/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']), /Missing or invalid protected/);+ }+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'app.json'), (config) => { config.expo.extra.powerappsNative.templateVersion = 99; });+ assert.throws(() => selectProjectRelease(fixture.projectRoot, fixture.catalog), /does not match a verified release/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']), /does not match a verified release/);+});++test('requirements-only CLI is explicitly planning, not release assertion or deployment admission', (t) => {+ const fixture = createFixture(t);+ for (const args of [+ ['--requirements-only'],+ ['--release', fixture.release.id, '--requirements-only'],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--requirements-only'],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--default'],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--release', fixture.release.id],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--platform', 'ios'],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--platform', 'android', '--base-version', fixture.release.platforms.android.base.version],+ ['--project-root', fixture.projectRoot, '--requirements-only', '--platform', 'android',+ '--base-version', fixture.release.platforms.android.base.version, '--base-fingerprint', fixture.release.platforms.android.fingerprint],+ ]) blocked(runCli(fixture, args));+ const strict = runCli(fixture, ['--project-root', fixture.projectRoot]);+ assert.equal(strict.status, 0, strict.stderr);+ assert.equal(JSON.parse(strict.stdout).validationScope, undefined);+});++test('requirements planning still requires a reviewed plugin policy and unambiguous source metadata', (t) => {+ const release = fixtureRelease();+ const duplicate = structuredClone(release);+ duplicate.id = 'fixture-same-requirements';+ for (const catalog of [+ { schemaVersion: 1, defaultRelease: null, releases: [] },+ { schemaVersion: 1, defaultRelease: release.id, releases: [release, duplicate] },+ ]) {+ const fixture = createFixture(t, { release, catalog });+ assert.throws(() => selectProjectRelease(fixture.projectRoot, catalog), /No verified mobile releases|multiple reviewed releases/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--requirements-only']));+ }+});++test('duplicate compatible records fail closed rather than guessing', (t) => {+ const release = fixtureRelease();+ const duplicate = structuredClone(release);+ duplicate.id = 'fixture-duplicate';+ const catalog = { schemaVersion: 1, defaultRelease: release.id, releases: [release, duplicate] };+ const fixture = createFixture(t, { release, catalog });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /multiple reviewed releases/);+});++test('CLI supports explicit/default selection and exact project-release assertions', (t) => {+ const old = fixtureRelease();+ const newer = fixtureRelease(2);+ const fixture = createFixture(t, { release: old, catalog: { schemaVersion: 1, defaultRelease: newer.id, releases: [old, newer] } });+ for (const [args, id] of [+ [['--release', old.id], old.id],+ [['--default'], newer.id],+ [['--project-root', fixture.projectRoot, '--release', old.id], old.id],+ ]) {+ const result = runCli(fixture, args);+ assert.equal(result.status, 0, result.stderr);+ assert.equal(JSON.parse(result.stdout).id, id);+ }+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--release', newer.id]), /exact selected/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--default']), /exact selected/);+});++test('deployment checks require a platform, exact base version and actual base fingerprint', (t) => {+ const release = fixtureRelease();+ release.platforms.ios.base.version = 'fixture-ios-base';+ const fixture = createFixture(t, { release });+ const args = ['--project-root', fixture.projectRoot, '--platform', 'ios', '--base-version', 'fixture-ios-base',+ '--base-fingerprint', release.platforms.ios.fingerprint];+ assert.equal(runCli(fixture, args).status, 0);+ blocked(runCli(fixture, ['--default', '--base-version', 'fixture-ios-base']), /requires --platform/);+ blocked(runCli(fixture, ['--default', '--base-fingerprint', release.platforms.ios.fingerprint]), /requires --platform/);+ for (const args of [+ ['--default', '--platform', 'ios'],+ ['--default', '--platform', 'ios', '--base-version', 'fixture-ios-base'],+ ['--default', '--platform', 'ios', '--base-fingerprint', release.platforms.ios.fingerprint],+ ]) blocked(runCli(fixture, args), /both --base-version and --base-fingerprint/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--platform', 'android', '--base-version', 'fixture-ios-base',+ '--base-fingerprint', release.platforms.android.fingerprint]), /deployment base/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--platform', 'ios', '--base-version', release.platforms.ios.player.version,+ '--base-fingerprint', release.platforms.ios.fingerprint]), /deployment base/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--platform', 'ios', '--base-version', 'fixture-ios-base',+ '--base-fingerprint', release.platforms.android.fingerprint]), /deployment base fingerprint/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--platform', 'ios', '--base-version', 'fixture-ios-base',+ '--base-fingerprint', 'fixture-secret-do-not-echo']), /deployment base fingerprint/);+});++test('deployment checks cannot substitute catalogue selection for an installed project', (t) => {+ const fixture = createFixture(t);+ for (const selection of [['--default'], ['--release', fixture.release.id]]) {+ for (const platform of ['android', 'ios']) {+ const target = fixture.release.platforms[platform];+ blocked(runCli(fixture, [...selection, '--platform', platform,+ '--base-version', target.base.version, '--base-fingerprint', target.fingerprint]), /requires --project-root/);+ assert.equal(runCli(fixture, ['--project-root', fixture.projectRoot, ...selection, '--platform', platform,+ '--base-version', target.base.version, '--base-fingerprint', target.fingerprint]).status, 0);+ }+ }+});++test('matching deployment evidence cannot bypass strict project native inventory validation', (t) => {+ const fixture = createFixture(t);+ const platform = fixture.release.platforms.android;+ addDependency(fixture.projectRoot, '@microsoft/power-apps-native-controls', '1.0.0');+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot, '--platform', 'android',+ '--base-version', platform.base.version, '--base-fingerprint', platform.fingerprint]), /Native\/runtime dependency/);+});++test('CLI rejects unknown, duplicate, conflicting and incomplete arguments without echoing values', (t) => {+ const fixture = createFixture(t);+ for (const args of [+ [], ['--unknown', 'fixture-secret-do-not-echo'], ['--default', '--default'],+ ['--release', fixture.release.id, '--release', fixture.release.id],+ ['--project-root', fixture.projectRoot, '--project-root', fixture.projectRoot],+ ['--default', '--platform', 'ios', '--platform', 'android'],+ ['--default', '--platform', 'ios', '--base-version', 'one', '--base-version', 'two'],+ ['--default', '--platform', 'ios', '--base-fingerprint', 'one', '--base-fingerprint', 'two'],+ ['--release', fixture.release.id, '--default'], ['--release'],+ ['--project-root', '--default'], ['--default', '--platform', 'web'],+ ['--default', '--base-version', ''], ['--default', '--platform'],+ ['--default', '--base-fingerprint'],+ ['--default', 'fixture-secret-do-not-echo'],+ ]) blocked(runCli(fixture, args));+});++test('CLI blocks the intentionally empty policy with actionable publication guidance', (t) => {+ const fixture = createFixture(t, { catalog: { schemaVersion: 1, defaultRelease: null, releases: [] } });+ blocked(runCli(fixture, ['--default']), /maintainer.*publish.*review/);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /No verified mobile releases/);+});++test('does not evaluate app.config.js or leak app config on malformed JSON', (t) => {+ const fixture = createFixture(t);+ fs.writeFileSync(path.join(fixture.projectRoot, 'app.config.js'), 'throw new Error("fixture-secret-do-not-echo");');+ assert.equal(runCli(fixture, ['--project-root', fixture.projectRoot]).status, 0);+ fs.writeFileSync(path.join(fixture.projectRoot, 'app.json'), '{"fixture-secret-do-not-echo":');+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Cannot read valid app.json/);+});++test('missing locks, old locks, root declaration drift and invalid dependency sections fail closed', (t) => {+ for (const edit of [+ (root) => fs.rmSync(path.join(root, 'package-lock.json')),+ (root) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.lockfileVersion = 1; }),+ (root) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.packages[''].dependencies.expo = '9.0.0'; }),+ (root) => modifyJson(path.join(root, 'package.json'), (pkg) => { pkg.dependencies = []; }),+ (root) => modifyJson(path.join(root, 'package.json'), (pkg) => { pkg.devDependencies = { react: '1.0.0' }; }),+ ]) {+ const fixture = createFixture(t);+ edit(fixture.projectRoot);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]));+ }+});++test('npm v2 app locks are supported', (t) => {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.lockfileVersion = 2; });+ assert.equal(runCli(fixture, ['--project-root', fixture.projectRoot]).status, 0);+});++test('declared managed dependencies cannot be moved to another section', (t) => {+ const fixture = createFixture(t);+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (data) => {+ const root = data.packages?.[''] || data;+ root.devDependencies = { [HOST]: root.dependencies[HOST] };+ delete root.dependencies[HOST];+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Managed dependency/);+});++test('uninstalled, untracked and lock-mismatched native dependencies cannot pass', (t) => {+ for (const edit of [+ (root) => fs.rmSync(path.join(root, 'node_modules/expo'), { recursive: true }),+ (root) => installPackage(root, 'node_modules/ordinary-native', '1.0.0', { codegenConfig: {} }),+ (root) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.packages['node_modules/expo'].version = '2.0.0'; }),+ ]) {+ const fixture = createFixture(t);+ edit(fixture.projectRoot);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]));+ }+});++test('an uninstalled ordinary-name direct dependency is not presumed JS-only', (t) => {+ const fixture = createFixture(t);+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (data) => {+ (data.packages?.[''] || data).dependencies['ordinary-uninstalled'] = '1.0.0';+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /declared dependency is not installed/);+});++test('an ordinary-name wrapper cannot conceal an uninstalled transitive module', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-wrapper', '1.0.0', {+ properties: { dependencies: { 'ordinary-uninstalled': '1.0.0' } },+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /incomplete transitive dependency tree/);+});++test('transitive dependency resolution supports hoisting and nested scoped packages', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, '@scope/wrapper', '1.0.0', {+ properties: { dependencies: { 'ordinary-tool': '1.0.0' } },+ });+ addDependency(fixture.projectRoot, 'ordinary-tool', '1.0.0', {+ section: null, properties: { dependencies: { '@scope/nested': '1.0.0' } },+ });+ addDependency(fixture.projectRoot, '@scope/nested', '1.0.0', {+ section: null, installPath: 'node_modules/ordinary-tool/node_modules/@scope/nested',+ properties: { peerDependencies: { react: '1.0.0' } },+ });+ assert.equal(runCli(fixture, ['--project-root', fixture.projectRoot]).status, 0);+});++test('missing CLI implementation files still produce sanitized BLOCKED errors', (t) => {+ const fixture = createFixture(t);+ fs.rmSync(path.join(fixture.pluginRoot, 'scripts/lib/mobile-release.js'));+ blocked(runCli(fixture, ['--default']), /Unable to verify/);+});++test('a nested second native instance cannot borrow approval from a root instance', (t) => {+ const release = fixtureRelease();+ release.nativePackages['node_modules/ordinary-bridge'] = '1.0.0';+ const fixture = createFixture(t, { release });+ addDependency(fixture.projectRoot, 'ordinary-bridge', '2.0.0', {+ section: null, installPath: 'node_modules/expo/node_modules/ordinary-bridge', properties: { codegenConfig: {} },+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Unreviewed native/);+});++test('unsafe lock paths and symlinked installations fail closed', (t) => {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages['node_modules/../outside'] = { version: '1.0.0' }; });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Invalid or linked app lock/);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { delete lock.packages['node_modules/../outside']; });+ const external = path.join(fixture.directory, 'linked-package');+ writeJson(path.join(external, 'package.json'), { name: 'ordinary-link', version: '1.0.0' });+ fs.symlinkSync(external, path.join(fixture.projectRoot, 'node_modules/ordinary-link'), 'dir');+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Linked packages/);+});++test('missing optional packages for another installation platform do not hide reviewed native packages', (t) => {+ const fixture = createFixture(t);+ const otherPlatform = process.platform === 'win32' ? 'linux' : 'win32';+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/optional-fixture'] = { version: '1.0.0', optional: true, os: [otherPlatform] };+ });+ assert.equal(runCli(fixture, ['--project-root', fixture.projectRoot]).status, 0);+ fs.rmSync(path.join(fixture.projectRoot, 'node_modules/expo'), { recursive: true });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/expo'].optional = true;+ lock.packages['node_modules/expo'].os = [otherPlatform];+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /native inventory|declared dependency is not installed/);+});++// Minimal npm-generated alias layout: CLIUI resolves both the ESM canonical+// package and an older CJS alias. The payloads and release policy remain synthetic.+function addCliuiAlias(fixture, { alias = 'string-width-cjs', canonical = 'string-width', properties = {} } = {}) {+ const cliui = '@isaacs/cliui';+ const dependencies = { [alias]: `npm:${canonical}@^4.2.0` };+ addDependency(fixture.projectRoot, cliui, '8.0.2', { properties: { dependencies } });+ const installPath = `node_modules/${alias}`;+ addDependency(fixture.projectRoot, alias, '4.2.3', { section: null, properties: { name: canonical, ...properties } });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages[`node_modules/${cliui}`].dependencies = dependencies;+ lock.packages[installPath].name = canonical;+ });+ return installPath;+}++test('ordinary npm JS aliases retain canonical identity and exact lock versions', (t) => {+ const fixture = createFixture(t);+ const aliasPath = addCliuiAlias(fixture);+ addDependency(fixture.projectRoot, 'string-width', '5.1.2', { section: null });+ for (const file of [`node_modules/@isaacs/cliui/package.json`, 'package-lock.json']) {+ modifyJson(path.join(fixture.projectRoot, file), (value) => {+ const entry = value.packages ? value.packages['node_modules/@isaacs/cliui'] : value;+ entry.dependencies['string-width'] = '^5.1.2';+ });+ }+ assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog), fixture.release);+ assert.equal(runValidator(fixture).status, 0);+ assert.equal(runValidator(fixture, { explicit: false }).status, 0);+ assert.equal(JSON.parse(fs.readFileSync(path.join(fixture.projectRoot, aliasPath, 'package.json'))).name, 'string-width');+});++test('direct npm JS aliases can be verified without promoting them into the native policy', (t) => {+ const fixture = createFixture(t);+ const aliasPath = addCliuiAlias(fixture);+ for (const file of ['package.json', 'package-lock.json']) {+ modifyJson(path.join(fixture.projectRoot, file), (value) => {+ (value.packages?.[''] || value).dependencies['string-width-cjs'] = 'npm:string-width@^4.2.0';+ });+ }+ assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog), fixture.release);+ assert.equal(fixture.release.nativePackages[aliasPath], undefined);+});++test('aliases fail closed on missing canonical lock identity or installed/lock identity and version drift', (t) => {+ for (const edit of [+ (root, entry) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { delete lock.packages[entry].name; }),+ (root, entry) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.packages[entry].name = 'other-package'; }),+ (root, entry) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.packages[entry].version = '4.2.4'; }),+ (root, entry) => modifyJson(path.join(root, 'package-lock.json'), (lock) => { lock.packages[entry].link = true; }),+ (root, entry) => modifyJson(path.join(root, entry, 'package.json'), (pkg) => { pkg.version = '4.2.2'; }),+ (root, entry) => modifyJson(path.join(root, entry, 'package.json'), (pkg) => { pkg.name = 'other-package'; }),+ ]) {+ const fixture = createFixture(t);+ const alias = addCliuiAlias(fixture);+ edit(fixture.projectRoot, alias);+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /alias|canonical identity/);+ blocked(runValidator(fixture, { explicit: false }), /alias|canonical identity/);+ }+});++test('native aliases are rejected using alias names, canonical names and detected native code', (t) => {+ for (const aliasOptions of [+ { alias: 'expo-notifications', canonical: 'string-width' },+ { alias: 'string-width-cjs', canonical: '@microsoft/power-apps-native-controls' },+ { alias: 'string-width-cjs', canonical: 'ordinary-bridge', properties: { codegenConfig: {} } },+ { alias: 'string-width-cjs', canonical: 'ordinary-bridge', source: true },+ ]) {+ const release = fixtureRelease();+ const aliasPath = `node_modules/${aliasOptions.alias}`;+ release.nativePackages[aliasPath] = '4.2.3';+ const fixture = createFixture(t, { release });+ addCliuiAlias(fixture, aliasOptions);+ if (aliasOptions.source) fs.writeFileSync(path.join(fixture.projectRoot, aliasPath, 'Bridge.swift'), '');+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /Native\/runtime npm aliases/);+ blocked(runValidator(fixture, { explicit: false }), /Native\/runtime npm aliases/);+ }+});++test('ordinary non-aliased packages also reject contradictory canonical lock identities', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'date-fns', '4.1.0');+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/date-fns'].name = 'different-package';+ });+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /canonical identity/);+});++test('an alias canonical identity must also agree with its requesting package declaration', (t) => {+ for (const spec of ['npm:other-package@^4.2.0', '^4.2.0']) {+ const fixture = createFixture(t);+ addCliuiAlias(fixture);+ for (const file of ['node_modules/@isaacs/cliui/package.json', 'package-lock.json']) {+ modifyJson(path.join(fixture.projectRoot, file), (value) => {+ (value.packages?.['node_modules/@isaacs/cliui'] || value).dependencies['string-width-cjs'] = spec;+ });+ }+ blocked(runCli(fixture, ['--project-root', fixture.projectRoot]), /canonical identity.*dependency declaration/);+ }+});++const LINUX_GLIBC = { os: 'linux', cpu: 'x64', libc: 'glibc' };++function addLightningCssPlatforms(fixture, installedLibc = 'glibc') {+ const version = '1.29.2';+ const variants = { glibc: 'lightningcss-linux-x64-gnu', musl: 'lightningcss-linux-x64-musl' };+ const optionalDependencies = Object.fromEntries(Object.values(variants).map((name) => [name, version]));+ addDependency(fixture.projectRoot, 'lightningcss', version, { properties: { optionalDependencies } });+ installPackage(fixture.projectRoot, `node_modules/${variants[installedLibc]}`, version);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/lightningcss'].optionalDependencies = optionalDependencies;+ for (const [libc, name] of Object.entries(variants)) {+ lock.packages[`node_modules/${name}`] = { version, optional: true, os: ['linux'], cpu: ['x64'], libc: [libc] };+ }+ });+}++test('Linux/glibc accepts omitted optional musl LightningCSS without skipping the active GNU package', (t) => {+ const fixture = createFixture(t);+ addLightningCssPlatforms(fixture);+ const context = readPlatformContext({+ os: 'linux', cpu: 'x64',+ getReport: () => ({ header: { glibcVersionRuntime: '2.39' }, environmentVariables: { credential: 'fixture-secret-do-not-echo' } }),+ });+ assert.deepEqual(context, LINUX_GLIBC);+ assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog, context), fixture.release);+ fs.rmSync(path.join(fixture.projectRoot, 'node_modules/lightningcss-linux-x64-gnu'), { recursive: true });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, context), /incomplete transitive dependency tree/);+});++test('Linux/musl accepts omitted optional glibc binaries using in-memory report detection', (t) => {+ const fixture = createFixture(t);+ addLightningCssPlatforms(fixture, 'musl');+ const context = readPlatformContext({+ os: 'linux', cpu: 'x64', getReport: () => ({ header: {}, sharedObjects: ['/lib/ld-musl-x86_64.so.1'] }),+ });+ assert.deepEqual(context, { os: 'linux', cpu: 'x64', libc: 'musl' });+ assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog, context), fixture.release);+});++test('unavailable libc evidence fails closed without leaking diagnostic reports or raw errors', (t) => {+ const fixture = createFixture(t);+ addLightningCssPlatforms(fixture);+ for (const getReport of [+ () => ({}),+ () => { throw new Error('fixture-secret-do-not-echo'); },+ ]) {+ const context = readPlatformContext({ os: 'linux', cpu: 'x64', getReport });+ assert.equal(context.libc, null);+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, context),+ (error) => error.code === 'MOBILE_RELEASE_BLOCKED' && !error.message.includes('fixture-secret-do-not-echo'));+ }+ assert.deepEqual(readPlatformContext({ os: 'darwin', cpu: 'arm64', getReport: () => assert.fail('must not read reports on other platforms') }),+ { os: 'darwin', cpu: 'arm64', libc: null });+});++test('npm platform constraints support string/array forms and negation, but not a blanket optional skip', (t) => {+ for (const [constraints, omitted] of [+ [{ os: 'win32' }, true],+ [{ os: ['!linux'] }, true],+ [{ cpu: 'arm64' }, true],+ [{ cpu: ['!x64'] }, true],+ [{ libc: 'musl' }, true],+ [{ libc: ['!glibc'] }, true],+ [{ os: ['any'] }, false],+ [{ os: ['!win32'] }, false],+ [{ cpu: ['x64'] }, false],+ [{ libc: ['glibc'] }, false],+ [{}, false],+ ]) {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/fixture-platform-addon'] = { version: '1.0.0', optional: true, ...constraints };+ });+ if (omitted) assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), fixture.release);+ else assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /locked dependency is not installed/);+ }+});++function addOmittedWindowsSubtree(fixture, { nested = false, childName = 'fixture-optional-js-child' } = {}) {+ const parentName = 'fixture-windows-parent';+ const parentPath = `node_modules/${parentName}`;+ const childPath = nested ? `${parentPath}/node_modules/${childName}` : `node_modules/${childName}`;+ const optionalDependencies = { [parentName]: '1.0.0' };+ addDependency(fixture.projectRoot, 'fixture-platform-loader', '1.0.0', { properties: { optionalDependencies } });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages['node_modules/fixture-platform-loader'].optionalDependencies = optionalDependencies;+ lock.packages[parentPath] = { version: '1.0.0', optional: true, os: ['win32'], dependencies: { [childName]: '^1.0.0' } };+ lock.packages[childPath] = { version: '1.0.0', optional: true };+ });+ return { parentPath, childPath, childName };+}++test('omitted Windows optional parents permit exclusively omitted JS children without their own os constraint', (t) => {+ for (const nested of [false, true]) {+ const fixture = createFixture(t);+ const { childPath } = addOmittedWindowsSubtree(fixture, { nested });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages[childPath].dependencies = { 'fixture-optional-grandchild': '1.0.0' };+ lock.packages['node_modules/fixture-optional-grandchild'] = { version: '1.0.0', optional: true };+ });+ assert.equal(resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), fixture.release);+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, { os: 'win32', cpu: 'x64', libc: null }),+ /incomplete transitive dependency tree/);+ }+});++test('a child shared with an active dependency cannot borrow an omitted optional parent exemption', (t) => {+ for (const section of ['dependencies', 'optionalDependencies', 'peerDependencies']) {+ const fixture = createFixture(t);+ const { childName } = addOmittedWindowsSubtree(fixture);+ addDependency(fixture.projectRoot, 'fixture-active-consumer', '1.0.0', { properties: { [section]: { [childName]: '1.0.0' } } });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /incomplete transitive dependency tree/);+ }+});++test('required root dependencies cannot be excused by inherited optional flags or platform incompatibility', (t) => {+ const fixture = createFixture(t);+ const { childName, childPath } = addOmittedWindowsSubtree(fixture);+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (value) => {+ (value.packages?.[''] || value).dependencies[childName] = '1.0.0';+ });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages[childPath].os = ['win32']; });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /declared dependency is not installed/);+});++test('missing required lock entries are not optional merely because a skipped parent references them', (t) => {+ const fixture = createFixture(t);+ const { childPath } = addOmittedWindowsSubtree(fixture);+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { delete lock.packages[childPath].optional; });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /locked dependency is not installed/);+});++test('all reviewed native entries remain mandatory even inside an exclusively omitted optional subtree', (t) => {+ const release = fixtureRelease();+ const nativePath = 'node_modules/fixture-required-native';+ release.nativePackages[nativePath] = '1.0.0';+ const fixture = createFixture(t, { release });+ addOmittedWindowsSubtree(fixture, { childName: 'fixture-required-native' });+ fs.rmSync(path.join(fixture.projectRoot, nativePath), { recursive: true });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /native inventory/);+});++test('an installed native leftover is inspected even when its optional parent is omitted', (t) => {+ const fixture = createFixture(t);+ const { childPath } = addOmittedWindowsSubtree(fixture);+ installPackage(fixture.projectRoot, childPath, '1.0.0', { codegenConfig: {} });+ assert.throws(() => resolveProjectRelease(fixture.projectRoot, fixture.catalog, LINUX_GLIBC), /Unreviewed native package/);+});diff --git a/plugins/mobile-apps/scripts/tests/mobile-template-lifecycle.test.js b/plugins/mobile-apps/scripts/tests/mobile-template-lifecycle.test.jsnew file mode 100644index 000000000..34b3fe789--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-template-lifecycle.test.js@@ -0,0 +1,425 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const { randomUUID } = require('node:crypto');+const { spawnSync } = require('node:child_process');+const path = require('node:path');+const test = require('node:test');+const {+ acquireTemplate, assertEmptyDestination, assertTemplateManifest, checkSdk, inspectDestination, main,+ restorePreviewDependencies,+} = require('../mobile-template-lifecycle');+const { fixtureRelease, writeJson, writeProject, modifyJson, installPackage, addDependency } = require('./helpers/mobile-release-fixture');++const HOST = '@microsoft/power-apps-native-host';+const TEMPLATE = '@microsoft/power-apps-native-template';++function release(id = 'fixture-v1', templateVersion = 1, host = '1.0.0') {+ const entry = fixtureRelease(templateVersion);+ entry.id = id;+ entry.managedDependencies.dependencies[HOST] = host;+ entry.nativePackages[`node_modules/${HOST}`] = host;+ return entry;+}++function catalog(...releases) {+ return { schemaVersion: 1, defaultRelease: releases[0]?.id || null, releases };+}++function directory(t) {+ const root = path.join(__dirname, `.template-lifecycle-test-${randomUUID()}`);+ fs.mkdirSync(root);+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return root;+}++function manifest(entry) {+ return {+ schemaVersion: 1, templateVersion: entry.templateVersion,+ nativeRuntimeVersions: entry.nativeRuntimeVersions,+ templatePackage: { name: TEMPLATE, version: entry.template.version },+ };+}++function packageRunner(entry, overrides = {}) {+ const calls = [];+ const execute = (command, args, cwd, options) => {+ const installRoot = options?.env?.npm_config_prefix;+ calls.push({ command, args, cwd, installRoot });+ if (command === 'npm') {+ if (overrides.installError) throw new Error('Registry unavailable');+ assert.ok(installRoot, 'npm install must have an explicit isolated prefix');+ const packageRoot = path.join(installRoot, 'node_modules', TEMPLATE);+ writeJson(path.join(packageRoot, 'package.json'), {+ name: TEMPLATE, version: entry.template.version,+ bin: { 'create-power-app-native': overrides.bin || 'bin/create.js' },+ ...overrides.packageMetadata,+ });+ fs.mkdirSync(path.join(packageRoot, 'bin'));+ fs.writeFileSync(path.join(packageRoot, 'bin/create.js'), '// synthetic fixture CLI\n');+ writeJson(path.join(installRoot, 'package-lock.json'), { packages: {+ [`node_modules/${TEMPLATE}`]: {+ version: entry.template.version, integrity: overrides.integrity || entry.template.integrity,+ },+ } });+ if (overrides.extraPackage) {+ writeJson(path.join(installRoot, 'node_modules/unreviewed/package.json'), { name: 'unreviewed', version: '1.0.0' });+ }+ return '';+ }+ if (args[1] === '--manifest') {+ return overrides.manifestOutput ?? JSON.stringify(manifest(entry));+ }+ writeJson(path.join(args[1], 'app.json'), { expo: { extra: {+ powerappsNative: overrides.createdMetadata || {+ schemaVersion: 1, templateVersion: entry.templateVersion, nativeRuntimeVersions: entry.nativeRuntimeVersions,+ },+ } } });+ return 'Created synthetic fixture';+ };+ return { calls, run: execute };+}++function nativeSnapshotFixture(t) {+ const root = directory(t);+ writeProject(root, fixtureRelease());+ addDependency(root, 'ordinary-ui', '1.0.0', { properties: { peerDependencies: { react: '*' } } });+ const baseline = path.join(root, '.tmp/native-before.json');+ fs.mkdirSync(path.dirname(baseline));+ main(['snapshot-native', '--project-root', root, '--baseline', baseline]);+ const check = () => spawnSync(process.execPath, [+ path.join(__dirname, '../mobile-template-lifecycle.js'), 'check-native',+ '--project-root', root, '--baseline', baseline,+ ], { encoding: 'utf8' });+ return { root, baseline, check };+}++test('JS-only native comparison permits pure-JS updates and existing peers without matching a template lock', t => {+ const fixture = nativeSnapshotFixture(t);+ addDependency(fixture.root, 'ordinary-ui', '2.0.0', { properties: { peerDependencies: { react: '*' } } });+ assert.equal(fixture.check().status, 0);+ fs.unlinkSync(path.join(fixture.root, 'package-lock.json'));+ assert.equal(fixture.check().status, 0, 'A lockless JS workflow keeps the same installed native baseline');+ const snapshot = JSON.parse(fs.readFileSync(fixture.baseline, 'utf8'));+ assert.doesNotMatch(JSON.stringify(snapshot), /fixture-secret-do-not-echo/);+});++test('JS-only comparison rejects new native code in updated packages and their installed transitive closure', t => {+ for (const mode of ['direct-codegen', 'nested-bridge', 'nested-peer']) {+ const { root, check } = nativeSnapshotFixture(t);+ if (mode === 'direct-codegen') {+ addDependency(root, 'ordinary-ui', '2.0.0', { properties: { codegenConfig: {} } });+ } else {+ addDependency(root, 'ordinary-ui', '2.0.0', { properties: {+ [mode === 'nested-peer' ? 'peerDependencies' : 'dependencies']: { 'ordinary-bridge': '1.0.0' },+ } });+ addDependency(root, 'ordinary-bridge', '1.0.0', {+ section: null, installPath: 'node_modules/ordinary-ui/node_modules/ordinary-bridge',+ });+ fs.writeFileSync(path.join(root, 'node_modules/ordinary-ui/node_modules/ordinary-bridge/Bridge.swift'), 'import Foundation\n');+ }+ const result = check();+ assert.equal(result.status, 2, mode);+ assert.match(result.stderr, /BLOCKED: JavaScript-only update changed native\/runtime.*Restore the package snapshot/);+ }+});++test('JS-only comparison rejects changed native identity, placement, declarations and recorded requirements', t => {+ for (const change of [+ root => installPackage(root, 'node_modules/expo-haptics', '1.0.1'),+ root => modifyJson(path.join(root, 'node_modules/expo-haptics/package.json'), pkg => { pkg.codegenConfig = {}; }),+ root => {+ fs.mkdirSync(path.join(root, 'node_modules/ordinary-ui/node_modules'));+ fs.renameSync(path.join(root, 'node_modules/expo-haptics'), path.join(root, 'node_modules/ordinary-ui/node_modules/expo-haptics'));+ },+ root => modifyJson(path.join(root, 'package.json'), pkg => { pkg.dependencies['expo-haptics'] = '^1.0.0'; }),+ root => modifyJson(path.join(root, 'app.json'), app => { app.expo.extra.powerappsNative.nativeRuntimeVersions.ios = 2; }),+ root => fs.rmSync(path.join(root, 'node_modules/expo-haptics'), { recursive: true }),+ ]) {+ const { root, check } = nativeSnapshotFixture(t);+ change(root);+ const result = check();+ assert.equal(result.status, 2);+ assert.match(result.stderr, /BLOCKED:/);+ assert.doesNotMatch(result.stderr, /fixture-secret-do-not-echo/);+ }+});++test('native comparison fails closed on missing, malformed or wrong-app snapshots without rewriting them', t => {+ const fixture = nativeSnapshotFixture(t);+ const other = nativeSnapshotFixture(t);+ for (const data of ['not JSON', '{}', fs.readFileSync(other.baseline, 'utf8')]) {+ fs.writeFileSync(fixture.baseline, data);+ assert.equal(fixture.check().status, 2);+ assert.equal(fs.readFileSync(fixture.baseline, 'utf8'), data);+ }+ fs.unlinkSync(fixture.baseline);+ assert.equal(fixture.check().status, 2);+ assert.throws(() => main(['snapshot-native']), /Required/);+ assert.throws(() => main(['check-native', '--project-root', fixture.root]), /--baseline/);+});++test('native snapshots cannot be replaced after an update and accept only restored native state', t => {+ const { root, baseline, check } = nativeSnapshotFixture(t);+ const before = fs.readFileSync(baseline);+ installPackage(root, 'node_modules/expo-haptics', '1.0.1');+ assert.throws(() => main(['snapshot-native', '--project-root', root, '--baseline', baseline]), { code: 'EEXIST' });+ assert.deepEqual(fs.readFileSync(baseline), before);+ assert.equal(check().status, 2);+ installPackage(root, 'node_modules/expo-haptics', '1.0.0');+ assert.equal(check().status, 0);+ assert.deepEqual(fs.readFileSync(baseline), before);+ const outside = path.join(directory(t), 'native-before.json');+ assert.throws(() => main(['snapshot-native', '--project-root', root, '--baseline', outside]), /inside this app/);+ assert.equal(fs.existsSync(outside), false);+});++test('SDK validation binds the installed Expo CLI and cwd without changing the parent environment', t => {+ const root = directory(t);+ const expo = path.join(root, 'node_modules/expo');+ writeJson(path.join(expo, 'package.json'), { name: 'expo', version: '57.0.25', bin: { expo: 'bin/cli' } });+ fs.mkdirSync(path.join(expo, 'bin'));+ fs.writeFileSync(path.join(expo, 'bin/cli'), '// synthetic fixture CLI\n');+ const before = { ...process.env };+ const result = checkSdk(root, { run(command, args, cwd, invocation) {+ assert.equal(command, process.execPath);+ assert.deepEqual(args, [path.join(expo, 'bin/cli'), 'install', '--check']);+ assert.equal(cwd, fs.realpathSync.native(root));+ assert.deepEqual(invocation.env, { ...before, EXPO_OFFLINE: '1' });+ return 'Dependencies are up to date\n';+ } });+ assert.equal(result.expoVersion, '57.0.25');+ assert.equal(result.versionSource, 'installed-expo');+ assert.deepEqual({ ...process.env }, before);+ assert.throws(() => checkSdk(root, { run() { throw new Error('SDK mismatch'); } }), /SDK mismatch/);+ assert.deepEqual({ ...process.env }, before);+ assert.throws(() => main(['check-sdk']), /--project-root/);+});++test('SDK validation cannot download Expo or execute a CLI outside the installed package', t => {+ const root = directory(t);+ const options = { run() { assert.fail('Invalid installed SDK must fail before execution'); } };+ assert.throws(() => checkSdk(root, options), /ENOENT/);+ const expo = path.join(root, 'node_modules/expo');+ writeJson(path.join(expo, 'package.json'), { name: 'expo', bin: { expo: '../../outside.js' } });+ fs.writeFileSync(path.join(root, 'outside.js'), '// outside package\n');+ assert.throws(() => checkSdk(root, options), /contained in its package/);+});++test('preview dependency restore always targets the preview prefix, even when npm runs from the source context', t => {+ const root = directory(t);+ const source = path.join(root, 'source');+ const preview = path.join(root, 'preview');+ const files = {+ 'package.json': { name: 'source-fixture', private: true, dependencies: {},+ scripts: { postinstall: 'node -e "process.exit(41)"' } },+ 'package-lock.json': { lockfileVersion: 3, packages: { '': { dependencies: {} } } },+ 'app.json': { expo: { extra: { powerappsNative: { templateVersion: 1 } } } },+ };+ for (const [file, value] of Object.entries(files)) {+ writeJson(path.join(source, file), value);+ writeJson(path.join(preview, file), value);+ }+ const config = '@microsoft:registry=https://packages.example.invalid/\n';+ fs.writeFileSync(path.join(source, '.npmrc'), config);+ fs.writeFileSync(path.join(preview, '.npmrc'), config);+ writeJson(path.join(source, 'node_modules/source-marker.json'), { preserve: true });+ let calls = 0;+ const result = restorePreviewDependencies(source, preview, {+ run(command, args, cwd, invocation) {+ calls++;+ assert.equal(command, 'npm');+ assert.equal(cwd, fs.realpathSync.native(source));+ assert.deepEqual(args, ['ci', '--ignore-scripts', '--no-legacy-peer-deps', '--no-force',+ '--no-audit', '--no-fund', '--prefix', fs.realpathSync.native(preview)]);+ assert.equal(invocation.env.npm_config_prefix, fs.realpathSync.native(preview));+ assert.equal(invocation.env.npm_config_global, 'false');+ assert.equal(invocation.env.npm_config_workspaces, 'false');+ assert.equal(fs.readFileSync(path.join(preview, '.npmrc'), 'utf8'), config);+ writeJson(path.join(preview, 'node_modules/restored.json'), { restored: true });+ return '';+ },+ });+ assert.equal(calls, 1);+ assert.equal(result.sourceModified, false);+ assert.equal(fs.existsSync(path.join(source, 'node_modules/restored.json')), false);+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(source, 'node_modules/source-marker.json'))), { preserve: true });+ assert.equal(fs.readFileSync(path.join(preview, '.npmrc'), 'utf8'), config);+ for (const [file, value] of Object.entries(files)) {+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(source, file))), value);+ }+ assert.equal(restorePreviewDependencies(source, preview).installedDependencies, true);+ assert.equal(fs.existsSync(path.join(preview, 'node_modules/restored.json')), false,+ 'Real npm ci must clean the disposable preview dependency tree');+ assert.equal(fs.existsSync(path.join(source, 'node_modules/source-marker.json')), true,+ 'Real npm ci must leave the source dependency tree untouched');+ assert.throws(() => restorePreviewDependencies(source, source), /separate, non-nested/);+ assert.throws(() => restorePreviewDependencies(root, preview), /separate, non-nested/);+ writeJson(path.join(preview, 'app.json'), { changed: true });+ assert.throws(() => restorePreviewDependencies(source, preview, {+ run() { assert.fail('Changed previews must fail before npm'); },+ }), /differs from the source/);+});++test('preview restoration rejects source aliases and linked dependency directories before npm runs', t => {+ const root = directory(t);+ const source = path.join(root, 'source');+ const preview = path.join(root, 'preview');+ const alias = path.join(root, 'source-alias');+ fs.mkdirSync(source);+ fs.mkdirSync(preview);+ fs.symlinkSync(source, alias, 'junction');+ const options = { run() { assert.fail('Unsafe preview paths must fail before npm'); } };+ assert.throws(() => restorePreviewDependencies(source, alias, options), /separate, non-nested/);+ assert.throws(() => restorePreviewDependencies(preview, root, options), /separate, non-nested/);+ fs.symlinkSync(source, path.join(preview, 'node_modules'), 'junction');+ assert.throws(() => restorePreviewDependencies(source, preview, options), /must not be a symbolic link/);+});++test('preview dependency failures leave source files and dependency tree untouched', t => {+ const root = directory(t);+ const source = path.join(root, 'source');+ const preview = path.join(root, 'preview');+ for (const [file, value] of Object.entries({+ 'package.json': { name: 'source-fixture', private: true },+ 'package-lock.json': { lockfileVersion: 3, packages: { '': {} } },+ 'app.json': { expo: {} },+ })) {+ writeJson(path.join(source, file), value);+ writeJson(path.join(preview, file), value);+ }+ writeJson(path.join(source, 'node_modules/source-marker.json'), { preserve: true });+ assert.throws(() => restorePreviewDependencies(source, preview, {+ run() { throw new Error('Synthetic preview registry failure'); },+ }), /Synthetic preview registry failure/);+ assert.equal(fs.existsSync(path.join(source, 'node_modules/source-marker.json')), true);+ assert.equal(fs.existsSync(path.join(source, '.npmrc')), false);+ assert.throws(() => main(['restore-preview', '--project-root', source]), /--preview-root/);+});++test('unknown release blocks acquisition before downloads or target writes', (t) => {+ const target = path.join(directory(t), 'app');+ let ran = false;+ assert.throws(() => acquireTemplate(target, 'unverified', {+ catalog: catalog(), run: () => { ran = true; },+ }), /release/i);+ assert.equal(ran, false);+ assert.equal(fs.existsSync(target), false);+});++test('creation rejects existing customer files without invoking npm', (t) => {+ const target = directory(t);+ fs.writeFileSync(path.join(target, 'customer.txt'), 'keep');+ assert.throws(() => assertEmptyDestination(target), /empty real directory/);+ const entry = release();+ const runner = packageRunner(entry);+ assert.throws(() => acquireTemplate(target, entry.id, { catalog: catalog(entry), ...runner }), /empty real directory/);+ assert.equal(runner.calls.length, 0);+ assert.equal(fs.readFileSync(path.join(target, 'customer.txt'), 'utf8'), 'keep');+});++test('creation-only destination inspection binds the existing parent without creating a new folder', t => {+ const root = directory(t);+ const target = path.join(root, 'new-parent', 'new app');+ const inspected = inspectDestination(target);+ assert.equal(inspected.parent, fs.realpathSync.native(root));+ assert.equal(inspected.destination, path.join(fs.realpathSync.native(root), 'new-parent', 'new app'));+ assert.equal(inspected.exists, false);+ assert.equal(fs.existsSync(path.join(root, 'new-parent')), false);+ assert.deepEqual(main(['destination', '--destination', target]), inspected);+ fs.mkdirSync(target, { recursive: true });+ fs.writeFileSync(path.join(target, 'customer.txt'), 'preserve');+ assert.throws(() => inspectDestination(target), /empty real directory/);+ assert.equal(fs.readFileSync(path.join(target, 'customer.txt'), 'utf8'), 'preserve');+});++test('template acquisition rejects unexpected dependencies before any creation CLI execution', t => {+ const root = directory(t);+ const entry = release();+ for (const [index, overrides] of [+ { packageMetadata: { dependencies: { unreviewed: '1.0.0' } } },+ { packageMetadata: { optionalDependencies: { unreviewed: '1.0.0' } } },+ { packageMetadata: { peerDependencies: { unreviewed: '*' } } },+ { packageMetadata: { bundledDependencies: ['unreviewed'] } },+ { extraPackage: true },+ ].entries()) {+ const target = path.join(root, `case-${index}`);+ const runner = packageRunner(entry, overrides);+ assert.throws(() => acquireTemplate(target, entry.id, { catalog: catalog(entry), ...runner }),+ /self-contained|unexpected packages/);+ assert.equal(runner.calls.length, 1, 'No --manifest or scaffold command may execute');+ assert.equal(fs.existsSync(target), false);+ assert.equal(fs.existsSync(runner.calls[0].installRoot), false);+ }+});++test('acquisition validates integrity before CLI execution and cleans its temporary install', (t) => {+ const target = path.join(directory(t), 'new app with spaces');+ const entry = release();+ const runner = packageRunner(entry);+ const result = acquireTemplate(target, entry.id, { catalog: catalog(entry), ...runner });+ assert.equal(result.installedDependencies, false);+ assert.equal(runner.calls.length, 3);+ assert.deepEqual(runner.calls[0].args, [+ 'install', '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact', `${TEMPLATE}@1.0.0`,+ '--prefix', runner.calls[0].installRoot,+ ]);+ assert.equal(runner.calls[1].args[1], '--manifest');+ assert.equal(runner.calls[2].args[1], target);+ assert.equal(fs.existsSync(runner.calls[0].installRoot), false);+ assert.equal(fs.existsSync(path.join(target, 'node_modules')), false);+});++test('published acquisition can target an empty current directory without staging inside it', (t) => {+ const target = path.join(directory(t), 'current-directory');+ fs.mkdirSync(target);+ const previous = process.cwd();+ const entry = release();+ const runner = packageRunner(entry);+ try {+ process.chdir(target);+ const result = acquireTemplate('.', entry.id, { catalog: catalog(entry), ...runner });+ assert.equal(result.installedDependencies, false);+ assert.equal(fs.existsSync(path.join(target, 'app.json')), true);+ const relative = path.relative(target, runner.calls[0].installRoot);+ assert.ok(relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative));+ assert.equal(fs.existsSync(runner.calls[0].installRoot), false);+ } finally {+ process.chdir(previous);+ }+});++test('integrity, manifest, executable and registry failures never fall back to another template', (t) => {+ const root = directory(t);+ const entry = release();+ for (const [index, overrides] of [+ { integrity: 'sha512-wrong' }, { manifestOutput: '{}' }, { manifestOutput: 'not-json' },+ { bin: '../outside.js' }, { installError: true },+ ].entries()) {+ const target = path.join(root, `case-${index}`);+ const runner = packageRunner(entry, overrides);+ assert.throws(() => acquireTemplate(target, entry.id, { catalog: catalog(entry), ...runner }));+ assert.equal(fs.existsSync(target), false);+ assert.equal(fs.existsSync(runner.calls[0].installRoot), false);+ assert.ok(runner.calls.length <= 2);+ }+ assert.throws(() => assertTemplateManifest({+ ...manifest(entry), nativeRuntimeVersions: { android: 99, ios: 1 },+ }, entry), /manifest does not match/);+});++test('post-copy mismatch is reported and partial target is preserved for review', (t) => {+ const target = path.join(directory(t), 'partial');+ const entry = release();+ const runner = packageRunner(entry, { createdMetadata: {} });+ assert.throws(() => acquireTemplate(target, entry.id, { catalog: catalog(entry), ...runner }), /manifest/);+ assert.equal(fs.existsSync(path.join(target, 'app.json')), true);+});++test('lifecycle CLI rejects unknown, duplicate and missing arguments', () => {+ for (const args of [+ [], ['apply'], ['acquire', '--release'], ['plan', '--project-root', '.', '--project-root', '.'],+ ['acquire', '--destination', '.', '--release', 'test', '--force', 'true'],+ ]) assert.throws(() => main(args), /Use acquire|argument|Required/);+});diff --git a/plugins/mobile-apps/scripts/tests/mobile-template-workflow.test.js b/plugins/mobile-apps/scripts/tests/mobile-template-workflow.test.jsnew file mode 100644index 000000000..eb3fdc7a9--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-template-workflow.test.js@@ -0,0 +1,183 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');+const { spawnSync } = require('node:child_process');+const { shellBlocks } = require('./helpers/markdown-shell-blocks');++const root = path.resolve(__dirname, '../..');+const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');+const updates = read('skills/check-updates/SKILL.md');+const create = read('skills/create-mobile-app/SKILL.md');+const lifecycle = read('shared/references/mobile-release-lifecycle.md');++test('native updates are evaluated independently of outdated-host discovery', () => {+ assert.match(updates, /even when the host is absent from `outdated\.json`/);+ assert.match(updates, /The plan below reads the recorded source state and installed host identity/);+ assert.match(updates, /Equal supported targets are valid/);+ assert.match(updates, /Do not require or fabricate template advancement/);+ assert.match(updates, /even if `hostInstallRequired` is false/);+ assert.doesNotMatch(updates, /Do not run `upgrade-template`/);+});++test('rehearsal, full-chain approval, drift checks and recovery are separate gates', () => {+ const rehearsal = updates.indexOf('Prepare isolated preview');+ const perEdge = updates.indexOf('repeat dry-run and apply');+ const approval = updates.indexOf('Apply reviewed release');+ const apply = updates.indexOf('### Apply only the approved plan');+ assert.ok(rehearsal < perEdge && perEdge < approval && approval < apply);+ assert.match(updates, /nonzero preview is never automatically a clean plan/);+ assert.match(updates, /`--no-install` to simulate state advancement/);+ assert.match(updates, /under `<working_dir>`/);+ assert.match(updates, /Changed inputs invalidate approval/);+ assert.match(updates, /restore only touched files/);+ assert.match(updates, /rollback or journal recovery cannot complete safely/);+ assert.match(updates, /Never report `DONE` for a partial migration/);+ assert.match(updates, /Skipping excludes all coupled packages/);+});++test('JavaScript updates retain approval and audit safeguards without native bumps', () => {+ assert.match(updates, /Skip package.*recommended default/);+ assert.match(updates, /validate-mobile-files\.js --upgrade-only/);+ assert.equal((updates.match(/npm outdated --json --depth=0/g) || []).length, 1);+ assert.doesNotMatch(updates, /Run `npm install --ignore-scripts`/);+ assert.match(updates, /installed transitive closure adds native code/);+ assert.match(updates, /isDirect: true/);+ assert.match(updates, /Ignore string-only `via` rollups/);+ assert.match(updates, /Never run `npx expo install --fix`/);+ for (const checkpoint of [+ 'check_mobile_app_plugin_version', 'update_native_host_dependency',+ 'update_microsoft_dependencies', 'update_remaining_npm_dependencies',+ ]) assert.ok(updates.includes(`\`${checkpoint}\``), checkpoint);+});++test('JavaScript package updates check installed native drift before accepting changes and roll back failures', () => {+ const javascript = updates.slice(updates.indexOf('## Step 3:'));+ const snapshot = javascript.indexOf('snapshot-native');+ const install = javascript.indexOf('Install with `--ignore-scripts`');+ const check = javascript.indexOf(' check-native ');+ assert.ok(snapshot >= 0 && snapshot < install && install < check);+ const commands = shellBlocks(javascript);+ assert.equal(commands.length, 2);+ assert.match(commands[0], /snapshot-native[\s\S]*--project-root '<working_dir>'/);+ assert.match(commands[1], /check-native[\s\S]*--baseline '<working_dir>\/\.tmp\/dependency-maintenance\/native-before\.json'/);+ assert.match(javascript, /A failed snapshot blocks installation/);+ assert.match(javascript, /Do not recapture the\s+baseline after installation/);+ assert.match(javascript, /including `check-native`, restore that package's snapshot/);+ assert.match(javascript, /does\s+not replace `check-native`/);+ assert.doesNotMatch(updates.slice(0, updates.indexOf('## Step 3:')), /snapshot-native|check-native/);+ assert.match(lifecycle, /Host-owned native migration\/repair/);+});++test('registry authentication recovery preserves the reviewed feed and interrupted-install boundary', () => {+ assert.match(updates, /For `E401`, pause mutations/);+ assert.match(updates, /user-approved credential-provider command against its `\.npmrc`/);+ assert.match(updates, /do not replace the project `\.npmrc`/);+ assert.match(updates, /retry the same reviewed publication/);+ assert.match(updates, /project-scoped journal and recovery instructions before resuming/);+});++test('requested Metro smoke tests distinguish bundle compilation from runtime behavior', () => {+ assert.match(updates, /a responding `\/status` endpoint alone does not verify bundling/);+ assert.match(updates, /load the intended route and exercise the customer\s+workflow/);+ assert.match(updates, /Report bundle and runtime results separately/);+ assert.match(updates, /do not fabricate\s+environment\/auth configuration/);+});++test('creation resolves immutable published package metadata before planning or data mutations', () => {+ assert.match(create, /Missing or incompatible published package metadata means `BLOCKED` before scaffolding or data-platform mutations/);+ assert.match(create, /mobile-template-lifecycle\.js acquire/);+ assert.match(create, /Separately approve dependency installation/);+ assert.match(create, /Never run acquisition over a non-empty directory/);+ assert.match(create, /Pass its sanitized compatibility context to every planner\/builder/);+ assert.match(create, /`app\.json` byte-for-byte/);+ assert.match(create, /project-rooted aliases/);+ assert.doesNotMatch(create, /npx degit|template#main/);+ assert.match(lifecycle, /no plugin-owned release catalogue/);+ assert.match(lifecycle, /host's `compatibility\/current\.json` owns/);+ assert.match(updates, /npm outdated --json --depth=0/);+ assert.match(updates, /--host-version "<exact-host-version>"/);+ assert.doesNotMatch(updates, /--release "<release-id>"|empty production catalogue/);+ assert.match(lifecycle, /Per-customer optional-permission selection during wrapping\s+is not part/);+ assert.match(create, /mobile-template-lifecycle\.js destination --destination/);+ assert.match(create, /does\s+not apply to an existing app or a creation continuation/);+ assert.match(create, /missing root remains `BLOCKED`/);+ assert.match(create, /Only after acquisition\s+approval may the package CLI create the destination/);+ const readme = read('README.md');+ assert.ok(readme.indexOf('copilot plugin install') < readme.indexOf('resolve-mobile-release.js'));+ assert.ok(readme.indexOf('export PLUGIN_ROOT=') < readme.indexOf('resolve-mobile-release.js'));+});++test('release workflow command extraction accepts LF and Windows CRLF checkouts', () => {+ for (const [file, language] of [['README.md', 'sh'], ['shared/references/mobile-release-lifecycle.md', 'bash']]) {+ const normalized = read(file).replace(/\r\n/g, '\n');+ const commands = shellBlocks(normalized, language);+ assert.ok(commands.length > 0);+ assert.deepEqual(shellBlocks(normalized.replace(/\n/g, '\r\n'), language), commands);+ }+});++test('README creation never installs after failed resolution, acquisition or directory entry', t => {+ const commands = shellBlocks(read('README.md'), 'sh').find(block => block.includes('--destination ./my-mobile-app'));+ assert.ok(commands);+ const bashPaths = process.platform === 'win32'+ ? (spawnSync('where.exe', ['bash'], { encoding: 'utf8' }).stdout || '').split(/\r?\n/)+ : [];+ const bash = bashPaths.find(entry => /[\\/]Git[\\/]/i.test(entry)) || 'bash';+ const stubs = `+node() {+ case "$1" in+ */resolve-mobile-release.js) [ "$FAILURE_STAGE" != resolution ] ;;+ */mobile-template-lifecycle.js)+ [ "$FAILURE_STAGE" != acquisition ] || return 1+ [ "$FAILURE_STAGE" != directory ] || return 0+ "$REAL_NODE" -e 'require("node:fs").mkdirSync("my-mobile-app")'+ ;;+ *) return 99 ;;+ esac+}+npm() {+ [ "$1" = ci ] || return 98+ "$REAL_NODE" -e 'const fs=require("node:fs"); fs.writeFileSync("install-ran.txt", fs.realpathSync.native(process.cwd()))'+}+`;+ for (const failure of ['resolution', 'acquisition', 'directory', 'none']) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "mobile creation owner's "));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const destination = path.join(directory, 'my-mobile-app');+ if (failure === 'acquisition') {+ fs.mkdirSync(destination);+ fs.writeFileSync(path.join(destination, 'customer.txt'), 'preserve customer content');+ }+ const result = spawnSync(bash, ['-s'], {+ cwd: directory, input: `${stubs}\n${commands}`, encoding: 'utf8', timeout: 10000,+ env: {+ ...process.env, FAILURE_STAGE: failure, PLUGIN_ROOT: '/fixture plugin',+ REAL_NODE: process.execPath.replaceAll('\\', '/'),+ },+ });+ assert.equal(result.error, undefined);+ assert.equal(result.status === 0, failure === 'none', result.stderr);+ assert.equal(fs.existsSync(path.join(directory, 'install-ran.txt')), false);+ assert.equal(fs.existsSync(path.join(destination, 'install-ran.txt')), failure === 'none');+ if (failure === 'none') {+ assert.equal(fs.readFileSync(path.join(destination, 'install-ran.txt'), 'utf8'), fs.realpathSync.native(destination));+ }+ if (failure === 'acquisition') {+ assert.equal(fs.readFileSync(path.join(destination, 'customer.txt'), 'utf8'), 'preserve customer content');+ }+ }+});++test('deployment instructions require all three actual selected-base values', () => {+ const commands = shellBlocks(lifecycle).find(block => block.includes('--base-version'));+ assert.ok(commands);+ for (const option of ['version', 'fingerprint', 'runtime-version']) {+ assert.ok(commands.includes(`--base-${option} "<actual-base-${option}>"`));+ }+ assert.match(lifecycle, /Obtain all three values[\s\S]*from the selected deployment target/);+ assert.match(lifecycle, /not by copying expected policy values just to pass/);+});diff --git a/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js b/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.jsindex f72b6d04d..f3292f052 100644--- a/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js+++ b/plugins/mobile-apps/scripts/tests/native-helper-reuse-contract.test.js@@ -39,9 +39,9 @@ const helpers = [})),{name: 'add-geolocation',- reconcile: '## 2a. Reconcile requested artifacts',- writes: ['## 3. Write `src/native/geolocation.ts`'],- verify: '## 5. Type-check and summary',+ reconcile: '## 4a. Reconcile requested tracking artifacts',+ writes: ['## 5. Write the tracking wrapper from installed docs/types'],+ verify: '## 6. Validate and summarize',files: ['geolocation.ts'],},];@@ -78,7 +78,7 @@ function assertHelperContract(raw, helper) {for (const heading of helper.writes) {assert.ok(text.indexOf(helper.reconcile) < text.indexOf(heading), 'Reconcile before each write');const write = prose(section(text, heading));- assert.match(write, /Apply Step 2a's (?:independent )?decision/);+ assert.match(write, /Apply Step (?:2a|4a)'s (?:independent )?decision/);assert.match(write, /reuse unchanged only if compatible/);assert.match(write, /approved scoped\s+update/);}@@ -279,7 +279,7 @@ test('PDF generation does not mistake generate-only output or package presence f}assert.match(pdf, /Package presence alone does not authorize adding sharing/);const report = skill('add-pdf-report');- assert.match(section(report, '### 2. Verify packages are already present'),+ assert.match(section(report, "### 2. Verify the app's release and packages"),/requirement specifically includes sharing, STOP/);assert.match(section(report, helpers[1].reconcile), /Generate-only\s+compatibility does not satisfy a share\/upload request/);assert.match(section(report, helpers[1].writes[0]), /Do not\s+remove compatible existing share exports/);@@ -294,10 +294,11 @@ test('PDF viewer compares URI behavior and installed version, not just an exportassert.ok(viewer.includes(input), input);}assert.match(viewer, /HTTPS-only old wrapper is incompatible with a local PDF request/);- const versionGate = section(skill('add-pdf-viewer'), '### 2. Verify package is already present');- assert.match(versionGate, /node_modules/);- assert.match(versionGate, /UNSUPPORTED_VERSION/);- assert.match(versionGate, /If the check fails, STOP/);+ const versionGate = section(skill('add-pdf-viewer'), '### 2. Verify the app-matched release and import path');+ assert.match(versionGate, /resolve-mobile-release\.js/);+ assert.match(versionGate, /file URI support requires the PDF 0\.2\.9\+ contract/);+ assert.match(versionGate, /If resolution fails,\s+STOP/);+ assert.match(versionGate, /exact leaf\/version is included/);});test('pen capture-only reuse cannot conceal required Image/File normalization', () => {@@ -321,11 +322,12 @@ test('geolocation rejects one-shot or unverified storage substitutes', () => {assert.match(geo, /MSAL-only/);assert.match(geo, /one-shot `expo-location` wrapper is not equivalent/);assert.match(geo, /msdyn_locationrecords.*every default `msdyn_\*` mapped column/);- const verification = section(skill('add-geolocation'), '## 2. Verify the Dataverse target table first');- assert.match(verification, /Empty `value: \[\]`: stop.*BLOCKED/);- assert.match(verification, /Auth\/environment error: stop.*UNVERIFIED/);- assert.match(verification, /If any active `fieldMap` column is missing, stop/);- assert.match(verification, /Do not create the table, do not route to `\/add-dataverse`/);+ const verification = section(skill('add-geolocation'), '## 4. Verify the tracking Dataverse target');+ assert.match(verification, /Empty `value: \[\]`: `BLOCKED/);+ assert.match(verification, /Auth\/environment failure: `UNVERIFIED.*Stop/);+ assert.match(verification, /Missing active columns block tracking/);+ assert.match(verification, /Do not invent a custom table, create the table, or route missing-table\s+provisioning through `\/add-dataverse`/);+ assert.match(verification, /tracking-only.*never a prerequisite for a one-shot read/);});test('storage comparison protects generated outputs and does not implement owner-side screens', () => {diff --git a/plugins/mobile-apps/scripts/tests/npm-context.test.js b/plugins/mobile-apps/scripts/tests/npm-context.test.jsnew file mode 100644index 000000000..30265e512--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/npm-context.test.js@@ -0,0 +1,153 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const test = require('node:test');+const { fork } = require('node:child_process');+const { runCliSync } = require('../lib/process-runner');+const { withNpmContext } = require('../lib/npm-context');++function fixture(t) {+ const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-npm-context-')));+ const source = path.join(root, 'source app');+ const target = path.join(root, 'tooling');+ for (const dir of [source, target]) {+ fs.mkdirSync(dir);+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"context-fixture","private":true}');+ }+ const previous = { ...process.env };+ for (const key of Object.keys(process.env)) {+ if (/^npm_config_/i.test(key)) delete process.env[key];+ }+ process.env.npm_config_userconfig = path.join(root, 'user.npmrc');+ process.env.npm_config_globalconfig = path.join(root, 'global.npmrc');+ process.env.npm_config_cache = path.join(root, 'cache');+ fs.writeFileSync(process.env.npm_config_globalconfig, 'registry=https://global.example.invalid/\n');+ fs.writeFileSync(process.env.npm_config_userconfig, 'registry=https://user.example.invalid/\nfetch-retries=4\n');+ t.after(() => {+ for (const key of Object.keys(process.env)) if (!(key in previous)) delete process.env[key];+ Object.assign(process.env, previous);+ fs.rmSync(root, { recursive: true, force: true });+ });+ const get = (cwd, env, key) => runCliSync('npm', ['config', 'get', key], {+ cwd, env, encoding: 'utf8', timeout: 15000,+ }).trim();+ return { root, source, target, get };+}++test('isolated npm retains project, user and environment precedence and removes temporary credentials', t => {+ const { root, source, target, get } = fixture(t);+ const config = [+ 'registry=https://project.example.invalid/',+ '@fixture:registry=https://scoped.example.invalid/',+ '//scoped.example.invalid/:_authToken=synthetic-test-token',+ 'fetch-retries=2',+ 'cafile=./certificate.pem',+ '',+ ].join('\n');+ fs.writeFileSync(path.join(source, '.npmrc'), config);+ fs.writeFileSync(path.join(source, 'certificate.pem'), 'fixture-only certificate');+ process.env.npm_config_fetch_retries = '1';+ for (const fail of [false, true]) {+ const operation = () => withNpmContext(source, target, (env, cwd) => {+ assert.equal(cwd, fs.realpathSync.native(source));+ assert.equal(get(cwd, env, 'registry'), get(source, process.env, 'registry'));+ assert.equal(get(cwd, env, '@fixture:registry'), 'https://scoped.example.invalid/');+ assert.equal(get(cwd, env, 'fetch-retries'), '1');+ assert.equal(get(cwd, env, 'cafile'), path.join(source, 'certificate.pem'));+ assert.equal(env.npm_config_userconfig, path.join(root, 'user.npmrc'));+ assert.equal(env.npm_config_global, 'false');+ assert.equal(env.npm_config_prefix, target);+ assert.match(fs.readFileSync(path.join(target, '.npmrc'), 'utf8'), /synthetic-test-token/);+ if (process.platform !== 'win32') assert.equal(fs.statSync(path.join(target, '.npmrc')).mode & 0o777, 0o600);+ if (fail) throw new Error('Synthetic failed installation');+ return 'installed';+ });+ if (fail) assert.throws(operation, /Synthetic failed installation/);+ else assert.equal(operation(), 'installed');+ assert.equal(fs.existsSync(path.join(target, '.npmrc')), false);+ assert.equal(fs.readFileSync(path.join(source, '.npmrc'), 'utf8'), config);+ }+});++test('npm context never overwrites a pre-existing tooling config', t => {+ const { source, target } = fixture(t);+ fs.writeFileSync(path.join(source, '.npmrc'), 'registry=https://project.example.invalid/\n');+ fs.writeFileSync(path.join(target, '.npmrc'), 'keep');+ assert.throws(() => withNpmContext(source, target, () => assert.fail('Do not install')), /configuration differs/);+ assert.equal(fs.readFileSync(path.join(target, '.npmrc'), 'utf8'), 'keep');+});++test('npm context preserves an identical preview config on success and failure', t => {+ const { source, target } = fixture(t);+ const config = 'registry=https://project.example.invalid/\n';+ fs.writeFileSync(path.join(source, '.npmrc'), config);+ fs.writeFileSync(path.join(target, '.npmrc'), config);+ for (const fail of [false, true]) {+ const operation = () => withNpmContext(source, target, () => {+ if (fail) throw new Error('Synthetic preview failure');+ return 'installed';+ });+ if (fail) assert.throws(operation, /Synthetic preview failure/);+ else assert.equal(operation(), 'installed');+ assert.equal(fs.readFileSync(path.join(source, '.npmrc'), 'utf8'), config);+ assert.equal(fs.readFileSync(path.join(target, '.npmrc'), 'utf8'), config);+ }+});++test('real npm acquisition writes only its isolated prefix and never executes package lifecycle scripts', t => {+ const { root, source, target } = fixture(t);+ const original = '{"name":"source-app","private":true,"dependencies":{"unavailable-source-package":"99.0.0"}}';+ fs.writeFileSync(path.join(source, 'package.json'), original);+ fs.mkdirSync(path.join(root, 'package'));+ fs.writeFileSync(path.join(root, 'package/package.json'), JSON.stringify({+ name: 'context-probe', version: '1.0.0',+ scripts: { install: 'node -e "throw new Error(\'Lifecycle must not execute\')"' },+ }));+ runCliSync('tar', ['-czf', 'probe.tgz', 'package'], { cwd: root, encoding: 'utf8', timeout: 10000 });+ withNpmContext(source, target, (env, cwd) => runCliSync('npm', [+ 'install', path.join(root, 'probe.tgz'), '--ignore-scripts', '--no-audit', '--no-fund',+ '--prefix', target,+ ], { cwd, env, encoding: 'utf8', timeout: 30000 }));+ const installed = JSON.parse(fs.readFileSync(path.join(target, 'node_modules/context-probe/package.json'), 'utf8'));+ assert.equal(installed.version, '1.0.0');+ assert.equal(fs.readFileSync(path.join(source, 'package.json'), 'utf8'), original);+ assert.equal(fs.existsSync(path.join(source, 'node_modules')), false);+ assert.equal(fs.existsSync(path.join(source, 'package-lock.json')), false);+ assert.equal(fs.existsSync(path.join(target, '.npmrc')), false);+});++test('real isolated npm requests carry only the synthetic project-scoped registry credential', async t => {+ const { root, source, target } = fixture(t);+ const serverFile = path.join(root, 'registry.cjs');+ const requestFile = path.join(root, 'request.json');+ fs.writeFileSync(serverFile, `+const http = require('node:http');+const fs = require('node:fs');+const server = http.createServer((request, response) => {+ fs.writeFileSync(${JSON.stringify(requestFile)}, JSON.stringify({ url: request.url, authorization: request.headers.authorization }));+ response.setHeader('content-type', 'application/json');+ response.end(JSON.stringify({ name: 'context-fixture', 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': { name: 'context-fixture', version: '1.0.0' } } }));+});+server.listen(0, '127.0.0.1', () => process.send({ port: server.address().port }));+`);+ const server = fork(serverFile, [], { stdio: ['ignore', 'ignore', 'pipe', 'ipc'] });+ t.after(() => { if (server.exitCode === null && server.signalCode === null) server.kill(); });+ const port = await new Promise((resolve, reject) => {+ server.once('message', message => resolve(message.port));+ server.once('error', reject);+ server.once('exit', code => reject(new Error(`Fixture registry exited: ${code}`)));+ });+ fs.writeFileSync(path.join(source, '.npmrc'),+ `registry=http://127.0.0.1:${port}/\n//127.0.0.1:${port}/:_authToken=synthetic-registry-token\n`);+ const result = withNpmContext(source, target, (env, cwd) => runCliSync('npm', [+ 'view', 'context-fixture', 'version', '--json', '--fetch-timeout=5000', '--fetch-retries=0',+ ], { cwd, env, encoding: 'utf8', timeout: 10000 }));+ assert.equal(JSON.parse(result), '1.0.0');+ assert.deepEqual(JSON.parse(fs.readFileSync(requestFile, 'utf8')), {+ url: '/context-fixture', authorization: 'Bearer synthetic-registry-token',+ });+ assert.equal(fs.existsSync(path.join(target, '.npmrc')), false);+});diff --git a/plugins/mobile-apps/scripts/tests/npx-no-install-contract.test.js b/plugins/mobile-apps/scripts/tests/npx-no-install-contract.test.jsindex 3b30f2f42..cadfb92f0 100644--- a/plugins/mobile-apps/scripts/tests/npx-no-install-contract.test.js+++ b/plugins/mobile-apps/scripts/tests/npx-no-install-contract.test.js@@ -18,11 +18,9 @@ const test = require('node:test');const pluginRoot = path.resolve(__dirname, '..', '..');const testsDir = path.join(pluginRoot, 'scripts', 'tests');-// Commands the developer types by hand; no skill runs them. The degit scaffold creates the project-// before it has any dependencies, and the native-host upgrade deliberately runs the newest-// `upgrade-template` (`/check-updates` says "Do not run `upgrade-template`").+// Developer-run examples retained in the legacy template documentation; no+// operational skill executes these acquisition or floating-upgrade commands.const USER_RUN = [- ['README.md', 'npx degit microsoft/power-platform-skills/plugins/mobile-apps/template#main'],['template/README.md', 'npx degit microsoft/power-platform-skills/plugins/mobile-apps/template#main'],['template/README.md', 'npx --package @microsoft/power-apps-native-host@latest'],['template/CUSTOMIZATION.md', 'npx --package @microsoft/power-apps-native-host@latest'],diff --git a/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.jsindex 3f8783e66..b51348691 100644--- a/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js+++ b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js@@ -450,7 +450,12 @@ test('scaffold validation uses preparation writes, not later generator output',});}- const manualFiles = [...prepared.writtenFiles, 'memory-bank.md'];+ // The bundled fixture is not a verified runtime release. Source preparation+ // can still be tested, but its package write must not bypass native admission.+ const packageValidation = validate(['package.json']);+ assert.strictEqual(packageValidation.status, 2, packageValidation.stderr);+ assert.match(packageValidation.stderr, /package-lock\.json/i);+ const manualFiles = [...prepared.writtenFiles.filter((file) => file !== 'package.json'), 'memory-bank.md'];const valid = validate(manualFiles);assert.strictEqual(valid.status, 0, valid.stderr);for (const file of ['power.config.json', path.relative(projectRoot, generatedPath)]) {@@ -723,3 +728,55 @@ test('failed full preparation restores every mutated file', () => {assertSnapshotsEqual(before, fileSnapshot(projectRoot));});++test('preparation preserves compatibility, customer extras, instructions and explicit aliases', (t) => {+ const projectRoot = copyTemplate();+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ const appConfig = JSON.parse(fs.readFileSync(path.join(projectRoot, 'app.json'), 'utf8'));+ appConfig.expo.extra.powerappsNative = {+ schemaVersion: 1, templateVersion: 7, nativeRuntimeVersions: { android: 4, ios: 6 },+ };+ appConfig.expo.extra.customerSetting = { enabled: true, nested: ['keep'] };+ const preservedFiles = {+ 'app.json': JSON.stringify(appConfig),+ 'AGENTS.md': '# Customer rules\nDo not replace this file.\n',+ 'CLAUDE.md': '@AGENTS.md\n# Custom extension\n',+ '.github/copilot-instructions.md': 'Follow the customer rules.\n',+ 'tsconfig.json': JSON.stringify({+ extends: HOST_TSCONFIG,+ compilerOptions: {+ baseUrl: '.',+ paths: { '@/*': ['./src/*'], '@/native/*': ['./src/native/*'] },+ },+ }),+ 'power.config.json': '{"environmentId":"","connectionReferences":{"customer":{"keep":true}}}',+ };+ for (const [file, content] of Object.entries(preservedFiles)) {+ fs.mkdirSync(path.dirname(path.join(projectRoot, file)), { recursive: true });+ fs.writeFileSync(path.join(projectRoot, file), content);+ }+ const result = prepareMobileTemplate({+ workingDir: projectRoot, displayName: 'Preservation probe', slug: 'preservation-probe',+ });+ assert.equal(result.removedPowerConfig, false);+ for (const [file, content] of Object.entries(preservedFiles)) {+ assert.equal(fs.readFileSync(path.join(projectRoot, file), 'utf8'), content, file);+ }+});++test('missing or malformed compatibility metadata blocks before any preparation edits', (t) => {+ const projectRoot = copyTemplate();+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+ for (const powerappsNative of [+ undefined,+ { schemaVersion: 1, templateVersion: 1, nativeRuntimeVersions: { android: 1 } },+ { schemaVersion: 1, templateVersion: '1.0.0', nativeRuntimeVersions: { android: 1, ios: 1 } },+ ]) {+ fs.writeFileSync(path.join(projectRoot, 'app.json'), JSON.stringify({ expo: { extra: { powerappsNative } } }));+ const before = fileSnapshot(projectRoot);+ assert.throws(() => prepareMobileTemplate({+ workingDir: projectRoot, displayName: 'Do not write', slug: 'do-not-write',+ }), /powerappsNative|metadata|runtime|templateVersion/i);+ assertSnapshotsEqual(before, fileSnapshot(projectRoot));+ }+});diff --git a/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js b/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.jsindex 5b59b7227..d581dd780 100644--- a/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js+++ b/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js@@ -30,6 +30,11 @@ test('protected paths remain blocked with POSIX and Windows path separators', ()});assert.strictEqual(result.status, 2, `${filePath}: ${result.stderr}`);assert.match(result.stderr, /BLOCKED: protected path/);+ if (filePath.endsWith('.tgz')) {+ assert.match(result.stderr, /reviewed published npm template\/dependency set/);+ assert.match(result.stderr, /\/check-updates/);+ assert.doesNotMatch(result.stderr, /github\.com\/microsoft\/power-platform-skills|sourced from plugins\/mobile-apps\/template/);+ }}for (const filePath of ['/project/src/items.ts', 'C:\\project\\src\\items.ts']) {const result = spawnSync(process.execPath, [@@ -48,6 +53,39 @@ test('all-source flag is explicit and does not require individual files', () =>assert.deepStrictEqual(parsed.targets, []);});+test('retired diagnostic manifest paths fail before filesystem or package validation', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-diagnostic-path-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const project = path.join(root, 'project');+ fs.mkdirSync(project);+ const manifest = path.join(root, 'diagnostic-artifacts.json');+ fs.writeFileSync(manifest, '{}');+ for (const selected of [path.join(root, 'missing.json'), root, manifest]) {+ const result = spawnSync(process.execPath, [+ path.resolve(__dirname, '../validate-mobile-files.js'), '--project-root', project,+ '--all-source', '--diagnostic-artifacts', selected,+ ], { cwd: project, encoding: 'utf8' });+ assert.strictEqual(result.status, 2, result.stderr);+ assert.match(result.stderr, /diagnostic-artifacts.*retired/);+ assert.doesNotMatch(result.stdout, /Mobile validation passed/);+ }+});++test('retired diagnostic manifests do not become an implicit published selection', (t) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-external-diagnostic-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const project = path.join(root, 'project');+ fs.mkdirSync(project);+ const manifest = path.join(root, 'diagnostic-artifacts.json');+ fs.writeFileSync(manifest, '{}');+ const result = spawnSync(process.execPath, [+ path.resolve(__dirname, '../validate-mobile-files.js'), '--project-root', project,+ '--all-source', '--diagnostic-artifacts', manifest,+ ], { cwd: project, encoding: 'utf8' });+ assert.strictEqual(result.status, 2, result.stderr);+ assert.match(result.stderr, /retired/);+});+test('all-source rejects explicit validation targets', () => {let stderr = '';const originalWrite = process.stderr.write;diff --git a/plugins/mobile-apps/scripts/tests/validate-package-deps.test.js b/plugins/mobile-apps/scripts/tests/validate-package-deps.test.jsindex 061400bf6..748bc5d97 100644--- a/plugins/mobile-apps/scripts/tests/validate-package-deps.test.js+++ b/plugins/mobile-apps/scripts/tests/validate-package-deps.test.js@@ -1,145 +1,511 @@'use strict';const test = require('node:test');-const assert = require('node:assert');+const assert = require('node:assert/strict');const fs = require('node:fs');-const os = require('node:os');const path = require('node:path');const { spawnSync } = require('node:child_process');--const DISPATCHER = path.resolve(__dirname, '..', 'validate-mobile-files.js');-const VALIDATOR = path.resolve(__dirname, '..', '..', 'hooks', 'validate-package-deps.js');-const TEMPLATE_PACKAGE = path.resolve(__dirname, '..', '..', 'template', 'package.json');--function makeProject(packageName, version = '1.0.0') {- const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-package-deps-'));- fs.writeFileSync(- path.join(projectRoot, 'package.json'),- JSON.stringify({ name: 'fixture', dependencies: { [packageName]: version } }),- );- return projectRoot;+const {+ HOST, fixtureRelease, createFixture, writeJson, modifyJson, installPackage,+ addDependency, runValidator,+} = require('./helpers/mobile-release-fixture');++function blocked(result, expression = /BLOCKED:/) {+ assert.equal(result.status, 2, result.stderr);+ assert.match(result.stderr, /^BLOCKED:/);+ assert.match(result.stderr, expression);+ assert.doesNotMatch(result.stderr, /fixture-secret-do-not-echo/);}-function validate(projectRoot, approvedDependencies = []) {- const args = [- DISPATCHER,- '--project-root',- projectRoot,- '--file',- 'package.json',- ];- for (const approvedDependency of approvedDependencies) {- args.push('--approved-js-dependency', approvedDependency);+test('empty or invalid validator stdin is a non-blocking no-op', (t) => {+ const fixture = createFixture(t);+ const hook = path.join(fixture.pluginRoot, 'hooks/validate-package-deps.js');+ for (const input of ['', '{', '[]']) {+ const result = spawnSync(process.execPath, [hook], {+ cwd: fixture.projectRoot, encoding: 'utf8', input,+ });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.stderr, '');}- return spawnSync(process.execPath, args, {- cwd: projectRoot,- encoding: 'utf8',+});++test('allows the version-matched release and its shipped haptics, not a snapshot name allowlist', (t) => {+ const fixture = createFixture(t);+ const result = runValidator(fixture);+ assert.equal(result.status, 0, result.stderr);+});++test('explicit validation reuses one installed inventory per invocation without missing new native code', t => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-wrapper', '1.0.0');+ const plugin = path.resolve(__dirname, '../..');+ const instrumented = `+ const fs = require('node:fs');+ const path = require('node:path');+ const root = process.argv[1];+ const plugin = process.argv[2];+ const release = JSON.parse(fs.readFileSync(process.argv[3], 'utf8')).releases[0];+ require(path.join(plugin, 'scripts/lib/mobile-published-packages.js')).projectContract = () => release;+ const original = fs.readdirSync;+ let scans = 0;+ fs.readdirSync = function (directory, ...args) {+ if (path.resolve(directory) === path.join(root, 'node_modules')) scans++;+ return original.call(this, directory, ...args);+ };+ process.on('exit', () => fs.writeSync(1, String(scans)));+ require(path.join(plugin, 'hooks/validate-package-deps.js'));+ `;+ const invoke = () => spawnSync(process.execPath, [+ '-e', instrumented, fixture.projectRoot, plugin, path.join(fixture.pluginRoot, 'shared/fixture-contracts.json'),+ ], {+ cwd: fixture.projectRoot, encoding: 'utf8',+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },+ input: JSON.stringify({ tool_name: 'Write', tool_input: {+ file_path: path.join(fixture.projectRoot, 'package.json'),+ validation_mode: 'explicit-mobile-workflow',+ } }),});-}+ const initial = invoke();+ assert.equal(initial.status, 0, initial.stderr);+ assert.equal(initial.stdout, '1');+ fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/ordinary-wrapper/Bridge.swift'), 'import Foundation\n');+ const changed = invoke();+ blocked(changed, /Native\/runtime dependency|Unreviewed native/);+ assert.equal(changed.stdout, '1', 'Fresh validation must rescan once rather than retain stale package evidence');+});++test('blocks a new ambiguous dependency without exact plan approval', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');+ blocked(runValidator(fixture), /user-approved JavaScript Dependencies plan/);+});++test('allows the exact installed JS-only dependency approved in the plan', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');+ const result = runValidator(fixture, { approved: ['[email protected]'] });+ assert.equal(result.status, 0, result.stderr);+});++test('blocks mismatched or non-exact JS approval', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');+ for (const approved of ['[email protected]', 'react-native-calendars@^1.1314.0']) {+ blocked(runValidator(fixture, { approved: [approved] }), /user-approved JavaScript Dependencies plan/);+ }+});++test('does not let plan approval bypass known native or Microsoft native-family packages', (t) => {+ for (const name of ['expo-notifications', '@microsoft/power-apps-native-controls']) {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, name, '1.0.0');+ blocked(runValidator(fixture, { approved: [`${name}@1.0.0`] }), /Native\/runtime dependency/);+ }+});++test('allows ordinary JS packages, including scoped dependencies', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'date-fns', '4.1.0');+ addDependency(fixture.projectRoot, '@scope/calendar-tools', '2.3.4');+ const result = runValidator(fixture);+ assert.equal(result.status, 0, result.stderr);+});++test('explicit admission inspects ordinary-name packages that depend on the existing native runtime', (t) => {+ for (const section of ['dependencies', 'optionalDependencies']) {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-runtime-wrapper', '1.0.0', {+ properties: { [section]: { expo: '1.0.0' } },+ });+ blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency/);+ }+});++test('the dispatcher uses the isolated policy and preserves exact JS-approval parsing', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0');+ const invoke = (approval) => spawnSync(process.execPath, [+ path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),+ '--project-root', fixture.projectRoot, '--file', 'package.json',+ '--approved-js-dependency', approval,+ ], { cwd: fixture.projectRoot, encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' } });+ const approved = invoke('[email protected]');+ assert.equal(approved.status, 0, approved.stderr);+ const invalid = invoke('react-native-calendars@^1.1314.0');+ assert.equal(invalid.status, 1);+ assert.match(invalid.stderr, /Invalid --approved-js-dependency/);+});++test('upgrade file validation skips lock and installed-inventory admission but retains package policy', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'expo-custom-module', '1.0.0');+ const invoke = (upgrade) => spawnSync(process.execPath, [+ path.join(fixture.pluginRoot, 'scripts/validate-mobile-files.js'),+ '--project-root', fixture.projectRoot, '--file', 'package.json',+ ...(upgrade ? ['--upgrade-only'] : []),+ ], { cwd: fixture.projectRoot, encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' } });+ const result = invoke(true);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /WARNING:.*does not verify Dev Player\/Wrap compatibility/);+ blocked(invoke(false), /Native\/runtime dependency/);+ fs.writeFileSync(path.join(fixture.projectRoot, 'package-lock.json'), 'not JSON');+ fs.writeFileSync(path.join(fixture.projectRoot, 'node_modules/expo-custom-module/package.json'), 'not JSON');+ assert.equal(invoke(true).status, 0);+ fs.unlinkSync(path.join(fixture.projectRoot, 'package-lock.json'));+ assert.equal(invoke(true).status, 0);+ writeJson(path.join(fixture.projectRoot, 'package-lock.json'), { lockfileVersion: 3, packages: { '': {} } });+ addDependency(fixture.projectRoot, 'axios', '1.0.0');+ blocked(invoke(true), /Forbidden dependency/);+});++test('old apps are admitted by their release, not by a newer default release', (t) => {+ const old = fixtureRelease();+ const newest = fixtureRelease(2);+ newest.managedDependencies.dependencies['expo-notifications'] = '2.0.0';+ newest.nativePackages['node_modules/expo-notifications'] = '2.0.0';+ const fixture = createFixture(t, {+ release: old,+ catalog: { schemaVersion: 1, defaultRelease: newest.id, releases: [old, newest] },+ });+ assert.equal(runValidator(fixture).status, 0);+ addDependency(fixture.projectRoot, 'expo-notifications', '2.0.0');+ blocked(runValidator(fixture), /Native\/runtime dependency/);+});++test('unknown, missing or malformed policy fails closed without reading template dependencies', (t) => {+ for (const mode of ['empty', 'missing', 'malformed']) {+ const fixture = createFixture(t);+ const policy = path.join(fixture.pluginRoot, 'shared/fixture-contracts.json');+ if (mode === 'empty') writeJson(policy, { schemaVersion: 1, defaultRelease: null, releases: [] });+ if (mode === 'missing') fs.rmSync(policy);+ if (mode === 'malformed') fs.writeFileSync(policy, '{"fixture-secret-do-not-echo":');+ blocked(runValidator(fixture), /verified mobile|mobile release policy|Unable to verify package dependencies/);+ }+});-test('blocks a new react-native-prefixed package without plan approval', (t) => {- const projectRoot = makeProject('react-native-calendars', '1.1314.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('does not exempt the bundled template path from release admission', (t) => {+ const fixture = createFixture(t);+ const template = path.join(fixture.pluginRoot, 'template');+ fs.cpSync(fixture.projectRoot, template, { recursive: true });+ fixture.projectRoot = template;+ addDependency(template, '@microsoft/power-apps-native-controls', '1.0.0');+ blocked(runValidator(fixture), /Native\/runtime dependency/);+});++test('rejects absent protected metadata and runtime versions changed to unknown values', (t) => {+ for (const edit of [+ (config) => { delete config.expo.extra.powerappsNative; },+ (config) => { config.expo.extra.powerappsNative.nativeRuntimeVersions.ios = 99; },+ ]) {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'app.json'), edit);+ blocked(runValidator(fixture), /metadata|runtime/);+ }+});- const result = validate(projectRoot);+test('managed declarations must match the selected release even when the app lock was updated', (t) => {+ const fixture = createFixture(t);+ for (const file of ['package.json', 'package-lock.json']) {+ modifyJson(path.join(fixture.projectRoot, file), (data) => {+ const root = data.packages ? data.packages[''] : data;+ root.dependencies[HOST] = '^1.1.0';+ });+ }+ blocked(runValidator(fixture), /Managed dependency/);+});- assert.strictEqual(result.status, 2);- assert.match(result.stderr, /user-approved JavaScript Dependencies plan/);+test('a JS-only host remains runtime-sensitive and its installed version cannot drift', (t) => {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'node_modules', HOST, 'package.json'), (pkg) => { pkg.version = '1.0.1'; });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => {+ lock.packages[`node_modules/${HOST}`].version = '1.0.1';+ });+ blocked(runValidator(fixture), /native inventory/);});-test('allows the exact react-native-prefixed package version approved in the plan', (t) => {- const projectRoot = makeProject('react-native-calendars', '1.1314.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('nested native instances must match their exact reviewed path and version', (t) => {+ const release = fixtureRelease();+ const nested = 'node_modules/expo/node_modules/ordinary-bridge';+ release.nativePackages[nested] = '1.0.0';+ const fixture = createFixture(t, { release });+ assert.equal(runValidator(fixture).status, 0);+ installPackage(fixture.projectRoot, nested, '1.0.1', { codegenConfig: {} });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages[nested].version = '1.0.1'; });+ blocked(runValidator(fixture), /nested package versions/);+});- const result = validate(projectRoot, ['[email protected]']);+for (const [label, relativeFile, properties] of [+ ['native source', 'source/bridge/Bridge.swift', {}],+ ['podspec', 'ordinary-widget.podspec', {}],+ ['codegen', null, { codegenConfig: {} }],+ ['Expo module', 'expo-module.config.json', {}],+ ['Expo config plugin', 'app.plugin.js', {}],+ ['platform project', 'android/build.gradle', {}],+]) {+ test(`detects an ordinary-name dependency through ${label}`, (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-widget', '1.0.0', { properties });+ if (relativeFile) {+ const target = path.join(fixture.projectRoot, 'node_modules/ordinary-widget', relativeFile);+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, '');+ }+ blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency|Unreviewed native/);+ });+}- assert.strictEqual(result.status, 0, result.stderr);+test('JS approval cannot hide native code in an ambiguous react-native package', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0', { properties: { codegenConfig: {} } });+ blocked(runValidator(fixture, { approved: ['[email protected]'] }), /Native\/runtime dependency/);});-test('blocks an approved package when package.json has a different version', (t) => {- const projectRoot = makeProject('react-native-calendars', '1.1314.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('detects ordinary-name native modules in a JS dependency transitive closure', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-ui', '1.0.0', { properties: { dependencies: { 'ordinary-bridge': '1.0.0' } } });+ addDependency(fixture.projectRoot, 'ordinary-bridge', '1.0.0', {+ section: null, installPath: 'node_modules/ordinary-ui/node_modules/ordinary-bridge', properties: { codegenConfig: {} },+ });+ blocked(runValidator(fixture), /Unreviewed native package/);+});- const result = validate(projectRoot, ['[email protected]']);+test('rejects malformed package, app, lock and installed JSON without leaking content', (t) => {+ for (const file of ['package.json', 'app.json', 'package-lock.json', `node_modules/${HOST}/package.json`]) {+ const fixture = createFixture(t);+ fs.writeFileSync(path.join(fixture.projectRoot, file), '{"fixture-secret-do-not-echo":');+ blocked(runValidator(fixture), /JSON|json|manifest/);+ }+});- assert.strictEqual(result.status, 2);- assert.match(result.stderr, /react-native-calendars@1\.1314\.0/);+test('preserves forbidden dependencies in every declaration section', (t) => {+ for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'axios', '1.0.0', { section });+ blocked(runValidator(fixture), /Forbidden dependency `axios`/);+ }});-test('does not let plan approval bypass a known native package block', (t) => {- const projectRoot = makeProject('expo-notifications', '1.0.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('preserves vendor-only archive requirements without echoing registry credentials', (t) => {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => {+ pkg.dependencies['expo-msal-intune'] = 'https://user:[email protected]/archive.tgz';+ });+ blocked(runValidator(fixture), /Vendor-only dependency/);+});- const result = validate(projectRoot, ['[email protected]']);+test('allows a reviewed vendor archive declaration, never an arbitrary file path', (t) => {+ const release = fixtureRelease();+ release.managedDependencies.dependencies['expo-msal-intune'] = 'file:./vendor/fixture-auth-1.0.0.tgz';+ release.nativePackages['node_modules/expo-msal-intune'] = '1.0.0';+ const fixture = createFixture(t, { release });+ assert.equal(runValidator(fixture).status, 0);+ modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => {+ pkg.dependencies['expo-msal-intune'] = 'file:../outside.tgz';+ });+ blocked(runValidator(fixture), /Vendor-only dependency/);+});- assert.strictEqual(result.status, 2);- assert.match(result.stderr, /Native\/runtime dependency `expo-notifications`/);+test('legacy edits preserve their reconstructed baseline without requiring release metadata', (t) => {+ const fixture = createFixture(t);+ fs.rmSync(path.join(fixture.projectRoot, 'app.json'));+ addDependency(fixture.projectRoot, 'date-fns', '4.1.0');+ const result = runValidator(fixture, { explicit: false, tool: 'Edit', input: { old_string: '"fixture-before"', new_string: '"fixture-mobile-app"' } });+ assert.equal(result.status, 0, result.stderr);});-test('allows the template-shipped expo-haptics version', (t) => {- const templatePackage = JSON.parse(fs.readFileSync(TEMPLATE_PACKAGE, 'utf8'));- const hapticsVersion = templatePackage.dependencies?.['expo-haptics'];- assert.strictEqual(hapticsVersion, '55.0.16');+test('legacy edits block known native declaration drift even after npm rewrites the lock', (t) => {+ const fixture = createFixture(t);+ const result = runValidator(fixture, {+ explicit: false, tool: 'Edit', input: { old_string: `"${HOST}": "^0.9.0"`, new_string: `"${HOST}": "^1.0.0"` },+ });+ blocked(result, /Native\/runtime dependency/);+});- const projectRoot = makeProject('expo-haptics', hapticsVersion);- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('legacy edits block installed native drift against the lock', (t) => {+ const fixture = createFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'node_modules/expo/package.json'), (pkg) => { pkg.version = '1.0.1'; });+ blocked(runValidator(fixture, { explicit: false }), /native dependency drift/);+});- const result = validate(projectRoot);+test('legacy validation rejects deletion of known or detected native baseline dependencies', (t) => {+ for (const tool of ['Write', 'Edit', 'MultiEdit']) {+ for (const name of ['expo', HOST, 'ordinary-native']) {+ const fixture = createFixture(t);+ if (name === 'ordinary-native') {+ addDependency(fixture.projectRoot, name, '1.0.0', { properties: { codegenConfig: {} } });+ }+ const file = path.join(fixture.projectRoot, 'package.json');+ const before = fs.readFileSync(file, 'utf8');+ modifyJson(file, (pkg) => { delete pkg.dependencies[name]; });+ const after = fs.readFileSync(file, 'utf8');+ const edit = { old_string: before, new_string: after };+ blocked(runValidator(fixture, {+ explicit: false, tool,+ input: tool === 'Write' ? {} : tool === 'MultiEdit' ? { edits: [edit] } : edit,+ }), /Native\/runtime dependency/);+ }+ }+});- assert.strictEqual(result.status, 0, result.stderr);+test('legacy validation still allows deleting an ordinary JavaScript dependency', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'date-fns', '4.1.0');+ modifyJson(path.join(fixture.projectRoot, 'package.json'), (pkg) => { delete pkg.dependencies['date-fns']; });+ const result = runValidator(fixture, { explicit: false });+ assert.equal(result.status, 0, result.stderr);});-test('continues to allow ordinary JavaScript packages without an exception', (t) => {- const projectRoot = makeProject('date-fns', '4.1.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('legacy edits detect transitive native additions with an ordinary root package name', (t) => {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'ordinary-ui', '1.0.0', { properties: { dependencies: { 'ordinary-bridge': '1.0.0' } } });+ addDependency(fixture.projectRoot, 'ordinary-bridge', '1.0.0', {+ section: null, installPath: 'node_modules/ordinary-ui/node_modules/ordinary-bridge', properties: { codegenConfig: {} },+ });+ const result = runValidator(fixture, {+ explicit: false, tool: 'Edit', input: { old_string: '', new_string: ',\n "ordinary-ui": "1.0.0"' },+ });+ blocked(result, /Native\/runtime dependency/);+});- const result = validate(projectRoot);+test('legacy fresh JS-only writes remain allowed without metadata or an installation', (t) => {+ const fixture = createFixture(t);+ fs.rmSync(path.join(fixture.projectRoot, 'node_modules'), { recursive: true });+ fs.rmSync(path.join(fixture.projectRoot, 'package-lock.json'));+ writeJson(path.join(fixture.projectRoot, 'package.json'), { dependencies: { 'date-fns': '4.1.0' } });+ assert.equal(runValidator(fixture, { explicit: false }).status, 0);+ writeJson(path.join(fixture.projectRoot, 'package.json'), { dependencies: { '@microsoft/power-apps-native-controls': '1.0.0' } });+ blocked(runValidator(fixture, { explicit: false }), /Native\/runtime dependency/);+});- assert.strictEqual(result.status, 0, result.stderr);+test('legacy malformed package JSON also fails closed', (t) => {+ const fixture = createFixture(t);+ fs.writeFileSync(path.join(fixture.projectRoot, 'package.json'), '{');+ blocked(runValidator(fixture, { explicit: false }), /malformed package.json/);});-test('rejects non-exact approved dependency versions', (t) => {- const projectRoot = makeProject('react-native-calendars', '1.1314.0');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+function calendarFixture(t) {+ const release = fixtureRelease();+ for (const [name, version] of Object.entries({ react: '19.2.0', 'react-native': '0.83.6' })) {+ release.managedDependencies.dependencies[name] = version;+ release.nativePackages[`node_modules/${name}`] = version;+ }+ const fixture = createFixture(t, { release });+ const before = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');+ addDependency(fixture.projectRoot, 'react-native-calendars', '1.1314.0', {+ properties: { peerDependencies: { react: '>=16.3.0', 'react-native': '>=0.60.0' } },+ });+ return { fixture, before };+}++function validateCalendarEdit(fixture, before, tool = 'Edit') {+ const after = fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8');+ const edit = { old_string: before, new_string: after };+ return runValidator(fixture, {+ explicit: false, tool, approved: ['[email protected]'],+ input: tool === 'MultiEdit' ? { edits: [edit] } : edit,+ });+}- const result = validate(projectRoot, ['react-native-calendars@^1.1314.0']);+test('legacy Edit and MultiEdit admit approved JS UI libraries using existing unchanged React/RN peers', (t) => {+ for (const tool of ['Edit', 'MultiEdit']) {+ const { fixture, before } = calendarFixture(t);+ const result = validateCalendarEdit(fixture, before, tool);+ assert.equal(result.status, 0, result.stderr);+ const unapproved = runValidator(fixture, {+ explicit: false, tool: 'Edit',+ input: { old_string: before, new_string: fs.readFileSync(path.join(fixture.projectRoot, 'package.json'), 'utf8') },+ });+ blocked(unapproved, /user-approved JavaScript Dependencies plan/);+ }+});++test('explicit admission preserves approved JavaScript UI reuse of unchanged React/RN peers', (t) => {+ const { fixture } = calendarFixture(t);+ const result = runValidator(fixture, { approved: ['[email protected]'] });+ assert.equal(result.status, 0, result.stderr);+});- assert.strictEqual(result.status, 1);- assert.match(result.stderr, /Invalid --approved-js-dependency value/);+test('legacy JS peer reuse does not excuse changed root runtime declarations or installed native versions', (t) => {+ for (const updateLock of [false, true]) {+ const { fixture, before } = calendarFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native/package.json'), (pkg) => { pkg.version = '0.83.7'; });+ if (updateLock) {+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (value) => {+ (value.packages?.[''] || value).dependencies['react-native'] = '0.83.7';+ if (value.packages) value.packages['node_modules/react-native'].version = '0.83.7';+ });+ }+ blocked(validateCalendarEdit(fixture, before, 'MultiEdit'), /native dependency drift|Native\/runtime dependency/);+ }});-test('parses scoped exact-version approvals', (t) => {- const projectRoot = makeProject('@scope/calendar-tools', '2.3.4');- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));+test('updating the app lock cannot hide installed runtime drift against an unchanged exact before-pin', (t) => {+ const { fixture, before } = calendarFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native/package.json'), (pkg) => { pkg.version = '0.83.7'; });+ modifyJson(path.join(fixture.projectRoot, 'package-lock.json'), (lock) => { lock.packages['node_modules/react-native'].version = '0.83.7'; });+ blocked(validateCalendarEdit(fixture, before), /native dependency drift/);+});- const result = validate(projectRoot, ['@scope/[email protected]']);+test('approved JS UI may consume a JS transitive helper that reuses unchanged React/RN peers', (t) => {+ const { fixture, before } = calendarFixture(t);+ addDependency(fixture.projectRoot, 'react-native-swipe-gestures', '1.0.5', {+ section: null, properties: { peerDependencies: { react: '*', 'react-native': '*' } },+ });+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {+ pkg.dependencies = { 'react-native-swipe-gestures': '^1.0.5' };+ });+ const result = validateCalendarEdit(fixture, before, 'MultiEdit');+ assert.equal(result.status, 0, result.stderr);+});- assert.strictEqual(result.status, 0, result.stderr);+test('legacy JS peer reuse never admits native source, new native children or nested runtime peers', (t) => {+ for (const mutate of [+ (fixture) => modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => { pkg.codegenConfig = {}; }),+ (fixture) => {+ addDependency(fixture.projectRoot, 'react-native', '0.82.0', {+ section: null, installPath: 'node_modules/react-native-calendars/node_modules/react-native',+ });+ },+ (fixture) => {+ const dependencies = { 'ordinary-native-child': '1.0.0' };+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => { pkg.dependencies = dependencies; });+ addDependency(fixture.projectRoot, 'ordinary-native-child', '1.0.0', {+ section: null, properties: { codegenConfig: {} },+ });+ },+ ]) {+ const { fixture, before } = calendarFixture(t);+ mutate(fixture);+ blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);+ }});-test('blocks explicit validation when the template allowlist cannot be loaded', (t) => {- const projectRoot = makeProject('date-fns', '4.1.0');- const isolatedPluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-validator-plugin-'));- const isolatedValidator = path.join(isolatedPluginRoot, 'hooks', 'validate-package-deps.js');- fs.mkdirSync(path.dirname(isolatedValidator), { recursive: true });- fs.copyFileSync(VALIDATOR, isolatedValidator);- t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));- t.after(() => fs.rmSync(isolatedPluginRoot, { recursive: true, force: true }));+test('a newly introduced root native peer cannot be treated as an existing runtime', (t) => {+ const { fixture, before } = calendarFixture(t);+ addDependency(fixture.projectRoot, 'react-native-screens', '4.23.0');+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {+ pkg.peerDependencies['react-native-screens'] = '>=4.0.0';+ });+ blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);+});- const packageJsonPath = path.join(projectRoot, 'package.json');- const result = spawnSync(process.execPath, [isolatedValidator], {- cwd: projectRoot,- encoding: 'utf8',- input: JSON.stringify({- tool_name: 'Write',- tool_input: {- content: fs.readFileSync(packageJsonPath, 'utf8'),- file_path: packageJsonPath,- validation_mode: 'explicit-mobile-workflow',- },- }),+test('React as a hard native/runtime dependency does not borrow the unchanged-peer exception', (t) => {+ const { fixture, before } = calendarFixture(t);+ modifyJson(path.join(fixture.projectRoot, 'node_modules/react-native-calendars/package.json'), (pkg) => {+ pkg.dependencies = { react: '19.2.0' };});+ blocked(validateCalendarEdit(fixture, before), /Native\/runtime dependency/);+});- assert.strictEqual(result.status, 2);- assert.match(result.stderr, /unable to load native dependency allowlist/);+test('JS alias support does not bypass forbidden-library and vendor-only rules', (t) => {+ for (const canonical of ['axios', 'lucide-react', 'expo-msal-intune']) {+ const fixture = createFixture(t);+ addDependency(fixture.projectRoot, 'friendly-alias', '1.0.0', { properties: { name: canonical } });+ for (const file of ['package.json', 'package-lock.json']) modifyJson(path.join(fixture.projectRoot, file), (value) => {+ (value.packages?.[''] || value).dependencies['friendly-alias'] = `npm:${canonical}@1.0.0`;+ if (value.packages) value.packages['node_modules/friendly-alias'].name = canonical;+ });+ blocked(runValidator(fixture), /Forbidden dependency|Vendor-only dependency/);+ blocked(runValidator(fixture, { explicit: false }), /Forbidden dependency|Vendor-only dependency/);+ }});diff --git a/plugins/mobile-apps/scripts/validate-mobile-files.js b/plugins/mobile-apps/scripts/validate-mobile-files.jsindex 145081b61..fde9e331e 100644--- a/plugins/mobile-apps/scripts/validate-mobile-files.js+++ b/plugins/mobile-apps/scripts/validate-mobile-files.js@@ -15,11 +15,12 @@ const PLUGIN_ROOT = path.resolve(__dirname, '..');function usage() {return [- 'Usage: node validate-mobile-files.js --project-root <path> (--all-source | --file <path> [--file <path> ...]) [--approved-js-dependency <name>@<exact-version> ...]',+ 'Usage: node validate-mobile-files.js --project-root <path> (--all-source | --file <path> [--file <path> ...]) [--approved-js-dependency <name>@<exact-version> ...] [--upgrade-only]','','Paths must be regular files. Relative paths resolve from --project-root.','--all-source validates every .ts/.tsx file under app/ and src/, plus root .ts/.tsx files.','Approved JavaScript dependencies must use exact semver versions from the reviewed app plan.',+ '--upgrade-only skips app-lock/native-inventory admission; the upgrade must pass Expo, Expo Doctor and TypeScript checks.',].join('\n');}@@ -41,6 +42,7 @@ function parseArgs(argv) {errors: [],projectRoot: null,targets: [],+ upgradeOnly: false,};for (let index = 0; index < argv.length; index += 1) {@@ -53,6 +55,12 @@ function parseArgs(argv) {index += 1;} else if (arg === '--all-source') {parsed.allSource = true;+ } else if (arg === '--upgrade-only') {+ parsed.upgradeOnly = true;+ } else if (arg === '--diagnostic-artifacts') {+ parsed.errors.push('BLOCKED: --diagnostic-artifacts is retired. Use published host/template packages.');+ parsed.blocked = true;+ if (argv[index + 1] && !argv[index + 1].startsWith('--')) index++;} else if (arg === '--approved-js-dependency') {const approvedDependency = parseApprovedJsDependency(argv[index + 1]);if (approvedDependency) {@@ -104,7 +112,7 @@ function collectSourceTargets(projectRoot) {return targets.sort();}-function runValidator(validatorName, filePath, content, projectRoot, approvedJsDependencies) {+function runValidator(validatorName, filePath, content, projectRoot, approvedJsDependencies, upgradeOnly) {const validatorPath = path.join(PLUGIN_ROOT, 'hooks', validatorName);const payload = JSON.stringify({cwd: projectRoot,@@ -115,6 +123,7 @@ function runValidator(validatorName, filePath, content, projectRoot, approvedJsDfilePath,validation_mode: 'explicit-mobile-workflow',approved_js_dependencies: approvedJsDependencies,+ ...(upgradeOnly ? { validation_scope: 'upgrade-only' } : {}),},});@@ -134,10 +143,12 @@ function main(argv) {const {allSource,approvedJsDependencies,+ blocked: invalidSelection,errors,help,projectRoot: projectRootArg,targets,+ upgradeOnly,} = parseArgs(argv);if (help) {process.stdout.write(`${usage()}\n`);@@ -145,7 +156,7 @@ function main(argv) {}if (errors.length > 0) {process.stderr.write(`${errors.join('\n')}\n\n${usage()}\n`);- return 1;+ return invalidSelection ? 2 : 1;}if (!projectRootArg@@ -213,6 +224,7 @@ function main(argv) {content,projectRoot,approvedJsDependencies,+ upgradeOnly,);if (result.stdout) process.stdout.write(result.stdout);if (result.stderr) process.stderr.write(result.stderr);diff --git a/plugins/mobile-apps/scripts/vendor/semver.LICENSE b/plugins/mobile-apps/scripts/vendor/semver.LICENSEnew file mode 100644index 000000000..19129e315--- /dev/null+++ b/plugins/mobile-apps/scripts/vendor/semver.LICENSE@@ -0,0 +1,15 @@+The ISC License++Copyright (c) Isaac Z. Schlueter and Contributors++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.diff --git a/plugins/mobile-apps/scripts/vendor/semver.cjs b/plugins/mobile-apps/scripts/vendor/semver.cjsnew file mode 100644index 000000000..90e83bcbe--- /dev/null+++ b/plugins/mobile-apps/scripts/vendor/semver.cjs@@ -0,0 +1,1935 @@+// Generated from npm semver 7.7.4; ISC license in semver.LICENSE. See semver.json for provenance.+"use strict";+var __getOwnPropNames = Object.getOwnPropertyNames;+var __commonJS = (cb, mod) => function __require() {+ try {+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;+ } catch (e) {+ throw mod = 0, e;+ }+};++// internal/constants.js+var require_constants = __commonJS({+ "internal/constants.js"(exports2, module2) {+ "use strict";+ var SEMVER_SPEC_VERSION = "2.0.0";+ var MAX_LENGTH = 256;+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */+ 9007199254740991;+ var MAX_SAFE_COMPONENT_LENGTH = 16;+ var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;+ var RELEASE_TYPES = [+ "major",+ "premajor",+ "minor",+ "preminor",+ "patch",+ "prepatch",+ "prerelease"+ ];+ module2.exports = {+ MAX_LENGTH,+ MAX_SAFE_COMPONENT_LENGTH,+ MAX_SAFE_BUILD_LENGTH,+ MAX_SAFE_INTEGER,+ RELEASE_TYPES,+ SEMVER_SPEC_VERSION,+ FLAG_INCLUDE_PRERELEASE: 1,+ FLAG_LOOSE: 2+ };+ }+});++// internal/debug.js+var require_debug = __commonJS({+ "internal/debug.js"(exports2, module2) {+ "use strict";+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {+ };+ module2.exports = debug;+ }+});++// internal/re.js+var require_re = __commonJS({+ "internal/re.js"(exports2, module2) {+ "use strict";+ var {+ MAX_SAFE_COMPONENT_LENGTH,+ MAX_SAFE_BUILD_LENGTH,+ MAX_LENGTH+ } = require_constants();+ var debug = require_debug();+ exports2 = module2.exports = {};+ var re = exports2.re = [];+ var safeRe = exports2.safeRe = [];+ var src = exports2.src = [];+ var safeSrc = exports2.safeSrc = [];+ var t = exports2.t = {};+ var R = 0;+ var LETTERDASHNUMBER = "[a-zA-Z0-9-]";+ var safeRegexReplacements = [+ ["\\s", 1],+ ["\\d", MAX_LENGTH],+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]+ ];+ var makeSafeRegex = (value) => {+ for (const [token, max] of safeRegexReplacements) {+ value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);+ }+ return value;+ };+ var createToken = (name, value, isGlobal) => {+ const safe = makeSafeRegex(value);+ const index = R++;+ debug(name, index, value);+ t[name] = index;+ src[index] = value;+ safeSrc[index] = safe;+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);+ safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);+ };+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");+ createToken("NUMERICIDENTIFIERLOOSE", "\\d+");+ createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);+ createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);+ createToken("GTLT", "((?:<|>)?=?)");+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);+ createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);+ createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);+ createToken("COERCERTL", src[t.COERCE], true);+ createToken("COERCERTLFULL", src[t.COERCEFULL], true);+ createToken("LONETILDE", "(?:~>?)");+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);+ exports2.tildeTrimReplace = "$1~";+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("LONECARET", "(?:\\^)");+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);+ exports2.caretTrimReplace = "$1^";+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);+ exports2.comparatorTrimReplace = "$1$2$3";+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);+ createToken("STAR", "(<|>)?=?\\s*\\*");+ createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");+ createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");+ }+});++// internal/parse-options.js+var require_parse_options = __commonJS({+ "internal/parse-options.js"(exports2, module2) {+ "use strict";+ var looseOption = Object.freeze({ loose: true });+ var emptyOpts = Object.freeze({});+ var parseOptions = (options) => {+ if (!options) {+ return emptyOpts;+ }+ if (typeof options !== "object") {+ return looseOption;+ }+ return options;+ };+ module2.exports = parseOptions;+ }+});++// internal/identifiers.js+var require_identifiers = __commonJS({+ "internal/identifiers.js"(exports2, module2) {+ "use strict";+ var numeric = /^[0-9]+$/;+ var compareIdentifiers = (a, b) => {+ if (typeof a === "number" && typeof b === "number") {+ return a === b ? 0 : a < b ? -1 : 1;+ }+ const anum = numeric.test(a);+ const bnum = numeric.test(b);+ if (anum && bnum) {+ a = +a;+ b = +b;+ }+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;+ };+ var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);+ module2.exports = {+ compareIdentifiers,+ rcompareIdentifiers+ };+ }+});++// classes/semver.js+var require_semver = __commonJS({+ "classes/semver.js"(exports2, module2) {+ "use strict";+ var debug = require_debug();+ var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();+ var { safeRe: re, t } = require_re();+ var parseOptions = require_parse_options();+ var { compareIdentifiers } = require_identifiers();+ var SemVer2 = class _SemVer {+ constructor(version, options) {+ options = parseOptions(options);+ if (version instanceof _SemVer) {+ if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {+ return version;+ } else {+ version = version.version;+ }+ } else if (typeof version !== "string") {+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);+ }+ if (version.length > MAX_LENGTH) {+ throw new TypeError(+ `version is longer than ${MAX_LENGTH} characters`+ );+ }+ debug("SemVer", version, options);+ this.options = options;+ this.loose = !!options.loose;+ this.includePrerelease = !!options.includePrerelease;+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);+ if (!m) {+ throw new TypeError(`Invalid Version: ${version}`);+ }+ this.raw = version;+ this.major = +m[1];+ this.minor = +m[2];+ this.patch = +m[3];+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {+ throw new TypeError("Invalid major version");+ }+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {+ throw new TypeError("Invalid minor version");+ }+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {+ throw new TypeError("Invalid patch version");+ }+ if (!m[4]) {+ this.prerelease = [];+ } else {+ this.prerelease = m[4].split(".").map((id) => {+ if (/^[0-9]+$/.test(id)) {+ const num = +id;+ if (num >= 0 && num < MAX_SAFE_INTEGER) {+ return num;+ }+ }+ return id;+ });+ }+ this.build = m[5] ? m[5].split(".") : [];+ this.format();+ }+ format() {+ this.version = `${this.major}.${this.minor}.${this.patch}`;+ if (this.prerelease.length) {+ this.version += `-${this.prerelease.join(".")}`;+ }+ return this.version;+ }+ toString() {+ return this.version;+ }+ compare(other) {+ debug("SemVer.compare", this.version, this.options, other);+ if (!(other instanceof _SemVer)) {+ if (typeof other === "string" && other === this.version) {+ return 0;+ }+ other = new _SemVer(other, this.options);+ }+ if (other.version === this.version) {+ return 0;+ }+ return this.compareMain(other) || this.comparePre(other);+ }+ compareMain(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ if (this.major < other.major) {+ return -1;+ }+ if (this.major > other.major) {+ return 1;+ }+ if (this.minor < other.minor) {+ return -1;+ }+ if (this.minor > other.minor) {+ return 1;+ }+ if (this.patch < other.patch) {+ return -1;+ }+ if (this.patch > other.patch) {+ return 1;+ }+ return 0;+ }+ comparePre(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ if (this.prerelease.length && !other.prerelease.length) {+ return -1;+ } else if (!this.prerelease.length && other.prerelease.length) {+ return 1;+ } else if (!this.prerelease.length && !other.prerelease.length) {+ return 0;+ }+ let i = 0;+ do {+ const a = this.prerelease[i];+ const b = other.prerelease[i];+ debug("prerelease compare", i, a, b);+ if (a === void 0 && b === void 0) {+ return 0;+ } else if (b === void 0) {+ return 1;+ } else if (a === void 0) {+ return -1;+ } else if (a === b) {+ continue;+ } else {+ return compareIdentifiers(a, b);+ }+ } while (++i);+ }+ compareBuild(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ let i = 0;+ do {+ const a = this.build[i];+ const b = other.build[i];+ debug("build compare", i, a, b);+ if (a === void 0 && b === void 0) {+ return 0;+ } else if (b === void 0) {+ return 1;+ } else if (a === void 0) {+ return -1;+ } else if (a === b) {+ continue;+ } else {+ return compareIdentifiers(a, b);+ }+ } while (++i);+ }+ // preminor will bump the version up to the next minor release, and immediately+ // down to pre-release. premajor and prepatch work the same way.+ inc(release, identifier, identifierBase) {+ if (release.startsWith("pre")) {+ if (!identifier && identifierBase === false) {+ throw new Error("invalid increment argument: identifier is empty");+ }+ if (identifier) {+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);+ if (!match || match[1] !== identifier) {+ throw new Error(`invalid identifier: ${identifier}`);+ }+ }+ }+ switch (release) {+ case "premajor":+ this.prerelease.length = 0;+ this.patch = 0;+ this.minor = 0;+ this.major++;+ this.inc("pre", identifier, identifierBase);+ break;+ case "preminor":+ this.prerelease.length = 0;+ this.patch = 0;+ this.minor++;+ this.inc("pre", identifier, identifierBase);+ break;+ case "prepatch":+ this.prerelease.length = 0;+ this.inc("patch", identifier, identifierBase);+ this.inc("pre", identifier, identifierBase);+ break;+ // If the input is a non-prerelease version, this acts the same as+ // prepatch.+ case "prerelease":+ if (this.prerelease.length === 0) {+ this.inc("patch", identifier, identifierBase);+ }+ this.inc("pre", identifier, identifierBase);+ break;+ case "release":+ if (this.prerelease.length === 0) {+ throw new Error(`version ${this.raw} is not a prerelease`);+ }+ this.prerelease.length = 0;+ break;+ case "major":+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {+ this.major++;+ }+ this.minor = 0;+ this.patch = 0;+ this.prerelease = [];+ break;+ case "minor":+ if (this.patch !== 0 || this.prerelease.length === 0) {+ this.minor++;+ }+ this.patch = 0;+ this.prerelease = [];+ break;+ case "patch":+ if (this.prerelease.length === 0) {+ this.patch++;+ }+ this.prerelease = [];+ break;+ // This probably shouldn't be used publicly.+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.+ case "pre": {+ const base = Number(identifierBase) ? 1 : 0;+ if (this.prerelease.length === 0) {+ this.prerelease = [base];+ } else {+ let i = this.prerelease.length;+ while (--i >= 0) {+ if (typeof this.prerelease[i] === "number") {+ this.prerelease[i]++;+ i = -2;+ }+ }+ if (i === -1) {+ if (identifier === this.prerelease.join(".") && identifierBase === false) {+ throw new Error("invalid increment argument: identifier already exists");+ }+ this.prerelease.push(base);+ }+ }+ if (identifier) {+ let prerelease2 = [identifier, base];+ if (identifierBase === false) {+ prerelease2 = [identifier];+ }+ if (compareIdentifiers(this.prerelease[0], identifier) === 0) {+ if (isNaN(this.prerelease[1])) {+ this.prerelease = prerelease2;+ }+ } else {+ this.prerelease = prerelease2;+ }+ }+ break;+ }+ default:+ throw new Error(`invalid increment argument: ${release}`);+ }+ this.raw = this.format();+ if (this.build.length) {+ this.raw += `+${this.build.join(".")}`;+ }+ return this;+ }+ };+ module2.exports = SemVer2;+ }+});++// functions/parse.js+var require_parse = __commonJS({+ "functions/parse.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var parse2 = (version, options, throwErrors = false) => {+ if (version instanceof SemVer2) {+ return version;+ }+ try {+ return new SemVer2(version, options);+ } catch (er) {+ if (!throwErrors) {+ return null;+ }+ throw er;+ }+ };+ module2.exports = parse2;+ }+});++// functions/valid.js+var require_valid = __commonJS({+ "functions/valid.js"(exports2, module2) {+ "use strict";+ var parse2 = require_parse();+ var valid2 = (version, options) => {+ const v = parse2(version, options);+ return v ? v.version : null;+ };+ module2.exports = valid2;+ }+});++// functions/clean.js+var require_clean = __commonJS({+ "functions/clean.js"(exports2, module2) {+ "use strict";+ var parse2 = require_parse();+ var clean2 = (version, options) => {+ const s = parse2(version.trim().replace(/^[=v]+/, ""), options);+ return s ? s.version : null;+ };+ module2.exports = clean2;+ }+});++// functions/inc.js+var require_inc = __commonJS({+ "functions/inc.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var inc2 = (version, release, options, identifier, identifierBase) => {+ if (typeof options === "string") {+ identifierBase = identifier;+ identifier = options;+ options = void 0;+ }+ try {+ return new SemVer2(+ version instanceof SemVer2 ? version.version : version,+ options+ ).inc(release, identifier, identifierBase).version;+ } catch (er) {+ return null;+ }+ };+ module2.exports = inc2;+ }+});++// functions/diff.js+var require_diff = __commonJS({+ "functions/diff.js"(exports2, module2) {+ "use strict";+ var parse2 = require_parse();+ var diff2 = (version1, version2) => {+ const v1 = parse2(version1, null, true);+ const v2 = parse2(version2, null, true);+ const comparison = v1.compare(v2);+ if (comparison === 0) {+ return null;+ }+ const v1Higher = comparison > 0;+ const highVersion = v1Higher ? v1 : v2;+ const lowVersion = v1Higher ? v2 : v1;+ const highHasPre = !!highVersion.prerelease.length;+ const lowHasPre = !!lowVersion.prerelease.length;+ if (lowHasPre && !highHasPre) {+ if (!lowVersion.patch && !lowVersion.minor) {+ return "major";+ }+ if (lowVersion.compareMain(highVersion) === 0) {+ if (lowVersion.minor && !lowVersion.patch) {+ return "minor";+ }+ return "patch";+ }+ }+ const prefix = highHasPre ? "pre" : "";+ if (v1.major !== v2.major) {+ return prefix + "major";+ }+ if (v1.minor !== v2.minor) {+ return prefix + "minor";+ }+ if (v1.patch !== v2.patch) {+ return prefix + "patch";+ }+ return "prerelease";+ };+ module2.exports = diff2;+ }+});++// functions/major.js+var require_major = __commonJS({+ "functions/major.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var major2 = (a, loose) => new SemVer2(a, loose).major;+ module2.exports = major2;+ }+});++// functions/minor.js+var require_minor = __commonJS({+ "functions/minor.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var minor2 = (a, loose) => new SemVer2(a, loose).minor;+ module2.exports = minor2;+ }+});++// functions/patch.js+var require_patch = __commonJS({+ "functions/patch.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var patch2 = (a, loose) => new SemVer2(a, loose).patch;+ module2.exports = patch2;+ }+});++// functions/prerelease.js+var require_prerelease = __commonJS({+ "functions/prerelease.js"(exports2, module2) {+ "use strict";+ var parse2 = require_parse();+ var prerelease2 = (version, options) => {+ const parsed = parse2(version, options);+ return parsed && parsed.prerelease.length ? parsed.prerelease : null;+ };+ module2.exports = prerelease2;+ }+});++// functions/compare.js+var require_compare = __commonJS({+ "functions/compare.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var compare2 = (a, b, loose) => new SemVer2(a, loose).compare(new SemVer2(b, loose));+ module2.exports = compare2;+ }+});++// functions/rcompare.js+var require_rcompare = __commonJS({+ "functions/rcompare.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var rcompare2 = (a, b, loose) => compare2(b, a, loose);+ module2.exports = rcompare2;+ }+});++// functions/compare-loose.js+var require_compare_loose = __commonJS({+ "functions/compare-loose.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var compareLoose2 = (a, b) => compare2(a, b, true);+ module2.exports = compareLoose2;+ }+});++// functions/compare-build.js+var require_compare_build = __commonJS({+ "functions/compare-build.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var compareBuild2 = (a, b, loose) => {+ const versionA = new SemVer2(a, loose);+ const versionB = new SemVer2(b, loose);+ return versionA.compare(versionB) || versionA.compareBuild(versionB);+ };+ module2.exports = compareBuild2;+ }+});++// functions/sort.js+var require_sort = __commonJS({+ "functions/sort.js"(exports2, module2) {+ "use strict";+ var compareBuild2 = require_compare_build();+ var sort2 = (list, loose) => list.sort((a, b) => compareBuild2(a, b, loose));+ module2.exports = sort2;+ }+});++// functions/rsort.js+var require_rsort = __commonJS({+ "functions/rsort.js"(exports2, module2) {+ "use strict";+ var compareBuild2 = require_compare_build();+ var rsort2 = (list, loose) => list.sort((a, b) => compareBuild2(b, a, loose));+ module2.exports = rsort2;+ }+});++// functions/gt.js+var require_gt = __commonJS({+ "functions/gt.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var gt2 = (a, b, loose) => compare2(a, b, loose) > 0;+ module2.exports = gt2;+ }+});++// functions/lt.js+var require_lt = __commonJS({+ "functions/lt.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var lt2 = (a, b, loose) => compare2(a, b, loose) < 0;+ module2.exports = lt2;+ }+});++// functions/eq.js+var require_eq = __commonJS({+ "functions/eq.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var eq2 = (a, b, loose) => compare2(a, b, loose) === 0;+ module2.exports = eq2;+ }+});++// functions/neq.js+var require_neq = __commonJS({+ "functions/neq.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var neq2 = (a, b, loose) => compare2(a, b, loose) !== 0;+ module2.exports = neq2;+ }+});++// functions/gte.js+var require_gte = __commonJS({+ "functions/gte.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var gte2 = (a, b, loose) => compare2(a, b, loose) >= 0;+ module2.exports = gte2;+ }+});++// functions/lte.js+var require_lte = __commonJS({+ "functions/lte.js"(exports2, module2) {+ "use strict";+ var compare2 = require_compare();+ var lte2 = (a, b, loose) => compare2(a, b, loose) <= 0;+ module2.exports = lte2;+ }+});++// functions/cmp.js+var require_cmp = __commonJS({+ "functions/cmp.js"(exports2, module2) {+ "use strict";+ var eq2 = require_eq();+ var neq2 = require_neq();+ var gt2 = require_gt();+ var gte2 = require_gte();+ var lt2 = require_lt();+ var lte2 = require_lte();+ var cmp2 = (a, op, b, loose) => {+ switch (op) {+ case "===":+ if (typeof a === "object") {+ a = a.version;+ }+ if (typeof b === "object") {+ b = b.version;+ }+ return a === b;+ case "!==":+ if (typeof a === "object") {+ a = a.version;+ }+ if (typeof b === "object") {+ b = b.version;+ }+ return a !== b;+ case "":+ case "=":+ case "==":+ return eq2(a, b, loose);+ case "!=":+ return neq2(a, b, loose);+ case ">":+ return gt2(a, b, loose);+ case ">=":+ return gte2(a, b, loose);+ case "<":+ return lt2(a, b, loose);+ case "<=":+ return lte2(a, b, loose);+ default:+ throw new TypeError(`Invalid operator: ${op}`);+ }+ };+ module2.exports = cmp2;+ }+});++// functions/coerce.js+var require_coerce = __commonJS({+ "functions/coerce.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var parse2 = require_parse();+ var { safeRe: re, t } = require_re();+ var coerce2 = (version, options) => {+ if (version instanceof SemVer2) {+ return version;+ }+ if (typeof version === "number") {+ version = String(version);+ }+ if (typeof version !== "string") {+ return null;+ }+ options = options || {};+ let match = null;+ if (!options.rtl) {+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);+ } else {+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];+ let next;+ while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) {+ if (!match || next.index + next[0].length !== match.index + match[0].length) {+ match = next;+ }+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;+ }+ coerceRtlRegex.lastIndex = -1;+ }+ if (match === null) {+ return null;+ }+ const major2 = match[2];+ const minor2 = match[3] || "0";+ const patch2 = match[4] || "0";+ const prerelease2 = options.includePrerelease && match[5] ? `-${match[5]}` : "";+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";+ return parse2(`${major2}.${minor2}.${patch2}${prerelease2}${build}`, options);+ };+ module2.exports = coerce2;+ }+});++// internal/lrucache.js+var require_lrucache = __commonJS({+ "internal/lrucache.js"(exports2, module2) {+ "use strict";+ var LRUCache = class {+ constructor() {+ this.max = 1e3;+ this.map = /* @__PURE__ */ new Map();+ }+ get(key) {+ const value = this.map.get(key);+ if (value === void 0) {+ return void 0;+ } else {+ this.map.delete(key);+ this.map.set(key, value);+ return value;+ }+ }+ delete(key) {+ return this.map.delete(key);+ }+ set(key, value) {+ const deleted = this.delete(key);+ if (!deleted && value !== void 0) {+ if (this.map.size >= this.max) {+ const firstKey = this.map.keys().next().value;+ this.delete(firstKey);+ }+ this.map.set(key, value);+ }+ return this;+ }+ };+ module2.exports = LRUCache;+ }+});++// classes/range.js+var require_range = __commonJS({+ "classes/range.js"(exports2, module2) {+ "use strict";+ var SPACE_CHARACTERS = /\s+/g;+ var Range2 = class _Range {+ constructor(range, options) {+ options = parseOptions(options);+ if (range instanceof _Range) {+ if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {+ return range;+ } else {+ return new _Range(range.raw, options);+ }+ }+ if (range instanceof Comparator2) {+ this.raw = range.value;+ this.set = [[range]];+ this.formatted = void 0;+ return this;+ }+ this.options = options;+ this.loose = !!options.loose;+ this.includePrerelease = !!options.includePrerelease;+ this.raw = range.trim().replace(SPACE_CHARACTERS, " ");+ this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);+ if (!this.set.length) {+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`);+ }+ if (this.set.length > 1) {+ const first = this.set[0];+ this.set = this.set.filter((c) => !isNullSet(c[0]));+ if (this.set.length === 0) {+ this.set = [first];+ } else if (this.set.length > 1) {+ for (const c of this.set) {+ if (c.length === 1 && isAny(c[0])) {+ this.set = [c];+ break;+ }+ }+ }+ }+ this.formatted = void 0;+ }+ get range() {+ if (this.formatted === void 0) {+ this.formatted = "";+ for (let i = 0; i < this.set.length; i++) {+ if (i > 0) {+ this.formatted += "||";+ }+ const comps = this.set[i];+ for (let k = 0; k < comps.length; k++) {+ if (k > 0) {+ this.formatted += " ";+ }+ this.formatted += comps[k].toString().trim();+ }+ }+ }+ return this.formatted;+ }+ format() {+ return this.range;+ }+ toString() {+ return this.range;+ }+ parseRange(range) {+ const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);+ const memoKey = memoOpts + ":" + range;+ const cached = cache.get(memoKey);+ if (cached) {+ return cached;+ }+ const loose = this.options.loose;+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));+ debug("hyphen replace", range);+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);+ debug("comparator trim", range);+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);+ debug("tilde trim", range);+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);+ debug("caret trim", range);+ let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));+ if (loose) {+ rangeList = rangeList.filter((comp) => {+ debug("loose invalid filter", comp, this.options);+ return !!comp.match(re[t.COMPARATORLOOSE]);+ });+ }+ debug("range list", rangeList);+ const rangeMap = /* @__PURE__ */ new Map();+ const comparators = rangeList.map((comp) => new Comparator2(comp, this.options));+ for (const comp of comparators) {+ if (isNullSet(comp)) {+ return [comp];+ }+ rangeMap.set(comp.value, comp);+ }+ if (rangeMap.size > 1 && rangeMap.has("")) {+ rangeMap.delete("");+ }+ const result = [...rangeMap.values()];+ cache.set(memoKey, result);+ return result;+ }+ intersects(range, options) {+ if (!(range instanceof _Range)) {+ throw new TypeError("a Range is required");+ }+ return this.set.some((thisComparators) => {+ return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {+ return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {+ return rangeComparators.every((rangeComparator) => {+ return thisComparator.intersects(rangeComparator, options);+ });+ });+ });+ });+ }+ // if ANY of the sets match ALL of its comparators, then pass+ test(version) {+ if (!version) {+ return false;+ }+ if (typeof version === "string") {+ try {+ version = new SemVer2(version, this.options);+ } catch (er) {+ return false;+ }+ }+ for (let i = 0; i < this.set.length; i++) {+ if (testSet(this.set[i], version, this.options)) {+ return true;+ }+ }+ return false;+ }+ };+ module2.exports = Range2;+ var LRU = require_lrucache();+ var cache = new LRU();+ var parseOptions = require_parse_options();+ var Comparator2 = require_comparator();+ var debug = require_debug();+ var SemVer2 = require_semver();+ var {+ safeRe: re,+ t,+ comparatorTrimReplace,+ tildeTrimReplace,+ caretTrimReplace+ } = require_re();+ var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();+ var isNullSet = (c) => c.value === "<0.0.0-0";+ var isAny = (c) => c.value === "";+ var isSatisfiable = (comparators, options) => {+ let result = true;+ const remainingComparators = comparators.slice();+ let testComparator = remainingComparators.pop();+ while (result && remainingComparators.length) {+ result = remainingComparators.every((otherComparator) => {+ return testComparator.intersects(otherComparator, options);+ });+ testComparator = remainingComparators.pop();+ }+ return result;+ };+ var parseComparator = (comp, options) => {+ comp = comp.replace(re[t.BUILD], "");+ debug("comp", comp, options);+ comp = replaceCarets(comp, options);+ debug("caret", comp);+ comp = replaceTildes(comp, options);+ debug("tildes", comp);+ comp = replaceXRanges(comp, options);+ debug("xrange", comp);+ comp = replaceStars(comp, options);+ debug("stars", comp);+ return comp;+ };+ var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";+ var replaceTildes = (comp, options) => {+ return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");+ };+ var replaceTilde = (comp, options) => {+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];+ return comp.replace(r, (_, M, m, p, pr) => {+ debug("tilde", comp, _, M, m, p, pr);+ let ret;+ if (isX(M)) {+ ret = "";+ } else if (isX(m)) {+ ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;+ } else if (isX(p)) {+ ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;+ } else if (pr) {+ debug("replaceTilde pr", pr);+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;+ } else {+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;+ }+ debug("tilde return", ret);+ return ret;+ });+ };+ var replaceCarets = (comp, options) => {+ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");+ };+ var replaceCaret = (comp, options) => {+ debug("caret", comp, options);+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];+ const z = options.includePrerelease ? "-0" : "";+ return comp.replace(r, (_, M, m, p, pr) => {+ debug("caret", comp, _, M, m, p, pr);+ let ret;+ if (isX(M)) {+ ret = "";+ } else if (isX(m)) {+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;+ } else if (isX(p)) {+ if (M === "0") {+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;+ } else {+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;+ }+ } else if (pr) {+ debug("replaceCaret pr", pr);+ if (M === "0") {+ if (m === "0") {+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;+ } else {+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;+ }+ } else {+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;+ }+ } else {+ debug("no pr");+ if (M === "0") {+ if (m === "0") {+ ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;+ } else {+ ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;+ }+ } else {+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;+ }+ }+ debug("caret return", ret);+ return ret;+ });+ };+ var replaceXRanges = (comp, options) => {+ debug("replaceXRanges", comp, options);+ return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");+ };+ var replaceXRange = (comp, options) => {+ comp = comp.trim();+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {+ debug("xRange", comp, ret, gtlt, M, m, p, pr);+ const xM = isX(M);+ const xm = xM || isX(m);+ const xp = xm || isX(p);+ const anyX = xp;+ if (gtlt === "=" && anyX) {+ gtlt = "";+ }+ pr = options.includePrerelease ? "-0" : "";+ if (xM) {+ if (gtlt === ">" || gtlt === "<") {+ ret = "<0.0.0-0";+ } else {+ ret = "*";+ }+ } else if (gtlt && anyX) {+ if (xm) {+ m = 0;+ }+ p = 0;+ if (gtlt === ">") {+ gtlt = ">=";+ if (xm) {+ M = +M + 1;+ m = 0;+ p = 0;+ } else {+ m = +m + 1;+ p = 0;+ }+ } else if (gtlt === "<=") {+ gtlt = "<";+ if (xm) {+ M = +M + 1;+ } else {+ m = +m + 1;+ }+ }+ if (gtlt === "<") {+ pr = "-0";+ }+ ret = `${gtlt + M}.${m}.${p}${pr}`;+ } else if (xm) {+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;+ } else if (xp) {+ ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;+ }+ debug("xRange return", ret);+ return ret;+ });+ };+ var replaceStars = (comp, options) => {+ debug("replaceStars", comp, options);+ return comp.trim().replace(re[t.STAR], "");+ };+ var replaceGTE0 = (comp, options) => {+ debug("replaceGTE0", comp, options);+ return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");+ };+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {+ if (isX(fM)) {+ from = "";+ } else if (isX(fm)) {+ from = `>=${fM}.0.0${incPr ? "-0" : ""}`;+ } else if (isX(fp)) {+ from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;+ } else if (fpr) {+ from = `>=${from}`;+ } else {+ from = `>=${from}${incPr ? "-0" : ""}`;+ }+ if (isX(tM)) {+ to = "";+ } else if (isX(tm)) {+ to = `<${+tM + 1}.0.0-0`;+ } else if (isX(tp)) {+ to = `<${tM}.${+tm + 1}.0-0`;+ } else if (tpr) {+ to = `<=${tM}.${tm}.${tp}-${tpr}`;+ } else if (incPr) {+ to = `<${tM}.${tm}.${+tp + 1}-0`;+ } else {+ to = `<=${to}`;+ }+ return `${from} ${to}`.trim();+ };+ var testSet = (set, version, options) => {+ for (let i = 0; i < set.length; i++) {+ if (!set[i].test(version)) {+ return false;+ }+ }+ if (version.prerelease.length && !options.includePrerelease) {+ for (let i = 0; i < set.length; i++) {+ debug(set[i].semver);+ if (set[i].semver === Comparator2.ANY) {+ continue;+ }+ if (set[i].semver.prerelease.length > 0) {+ const allowed = set[i].semver;+ if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {+ return true;+ }+ }+ }+ return false;+ }+ return true;+ };+ }+});++// classes/comparator.js+var require_comparator = __commonJS({+ "classes/comparator.js"(exports2, module2) {+ "use strict";+ var ANY = /* @__PURE__ */ Symbol("SemVer ANY");+ var Comparator2 = class _Comparator {+ static get ANY() {+ return ANY;+ }+ constructor(comp, options) {+ options = parseOptions(options);+ if (comp instanceof _Comparator) {+ if (comp.loose === !!options.loose) {+ return comp;+ } else {+ comp = comp.value;+ }+ }+ comp = comp.trim().split(/\s+/).join(" ");+ debug("comparator", comp, options);+ this.options = options;+ this.loose = !!options.loose;+ this.parse(comp);+ if (this.semver === ANY) {+ this.value = "";+ } else {+ this.value = this.operator + this.semver.version;+ }+ debug("comp", this);+ }+ parse(comp) {+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];+ const m = comp.match(r);+ if (!m) {+ throw new TypeError(`Invalid comparator: ${comp}`);+ }+ this.operator = m[1] !== void 0 ? m[1] : "";+ if (this.operator === "=") {+ this.operator = "";+ }+ if (!m[2]) {+ this.semver = ANY;+ } else {+ this.semver = new SemVer2(m[2], this.options.loose);+ }+ }+ toString() {+ return this.value;+ }+ test(version) {+ debug("Comparator.test", version, this.options.loose);+ if (this.semver === ANY || version === ANY) {+ return true;+ }+ if (typeof version === "string") {+ try {+ version = new SemVer2(version, this.options);+ } catch (er) {+ return false;+ }+ }+ return cmp2(version, this.operator, this.semver, this.options);+ }+ intersects(comp, options) {+ if (!(comp instanceof _Comparator)) {+ throw new TypeError("a Comparator is required");+ }+ if (this.operator === "") {+ if (this.value === "") {+ return true;+ }+ return new Range2(comp.value, options).test(this.value);+ } else if (comp.operator === "") {+ if (comp.value === "") {+ return true;+ }+ return new Range2(this.value, options).test(comp.semver);+ }+ options = parseOptions(options);+ if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {+ return false;+ }+ if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {+ return false;+ }+ if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {+ return true;+ }+ if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {+ return true;+ }+ if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {+ return true;+ }+ if (cmp2(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {+ return true;+ }+ if (cmp2(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {+ return true;+ }+ return false;+ }+ };+ module2.exports = Comparator2;+ var parseOptions = require_parse_options();+ var { safeRe: re, t } = require_re();+ var cmp2 = require_cmp();+ var debug = require_debug();+ var SemVer2 = require_semver();+ var Range2 = require_range();+ }+});++// functions/satisfies.js+var require_satisfies = __commonJS({+ "functions/satisfies.js"(exports2, module2) {+ "use strict";+ var Range2 = require_range();+ var satisfies2 = (version, range, options) => {+ try {+ range = new Range2(range, options);+ } catch (er) {+ return false;+ }+ return range.test(version);+ };+ module2.exports = satisfies2;+ }+});++// ranges/to-comparators.js+var require_to_comparators = __commonJS({+ "ranges/to-comparators.js"(exports2, module2) {+ "use strict";+ var Range2 = require_range();+ var toComparators2 = (range, options) => new Range2(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));+ module2.exports = toComparators2;+ }+});++// ranges/max-satisfying.js+var require_max_satisfying = __commonJS({+ "ranges/max-satisfying.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var Range2 = require_range();+ var maxSatisfying2 = (versions, range, options) => {+ let max = null;+ let maxSV = null;+ let rangeObj = null;+ try {+ rangeObj = new Range2(range, options);+ } catch (er) {+ return null;+ }+ versions.forEach((v) => {+ if (rangeObj.test(v)) {+ if (!max || maxSV.compare(v) === -1) {+ max = v;+ maxSV = new SemVer2(max, options);+ }+ }+ });+ return max;+ };+ module2.exports = maxSatisfying2;+ }+});++// ranges/min-satisfying.js+var require_min_satisfying = __commonJS({+ "ranges/min-satisfying.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var Range2 = require_range();+ var minSatisfying2 = (versions, range, options) => {+ let min = null;+ let minSV = null;+ let rangeObj = null;+ try {+ rangeObj = new Range2(range, options);+ } catch (er) {+ return null;+ }+ versions.forEach((v) => {+ if (rangeObj.test(v)) {+ if (!min || minSV.compare(v) === 1) {+ min = v;+ minSV = new SemVer2(min, options);+ }+ }+ });+ return min;+ };+ module2.exports = minSatisfying2;+ }+});++// ranges/min-version.js+var require_min_version = __commonJS({+ "ranges/min-version.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var Range2 = require_range();+ var gt2 = require_gt();+ var minVersion2 = (range, loose) => {+ range = new Range2(range, loose);+ let minver = new SemVer2("0.0.0");+ if (range.test(minver)) {+ return minver;+ }+ minver = new SemVer2("0.0.0-0");+ if (range.test(minver)) {+ return minver;+ }+ minver = null;+ for (let i = 0; i < range.set.length; ++i) {+ const comparators = range.set[i];+ let setMin = null;+ comparators.forEach((comparator) => {+ const compver = new SemVer2(comparator.semver.version);+ switch (comparator.operator) {+ case ">":+ if (compver.prerelease.length === 0) {+ compver.patch++;+ } else {+ compver.prerelease.push(0);+ }+ compver.raw = compver.format();+ /* fallthrough */+ case "":+ case ">=":+ if (!setMin || gt2(compver, setMin)) {+ setMin = compver;+ }+ break;+ case "<":+ case "<=":+ break;+ /* istanbul ignore next */+ default:+ throw new Error(`Unexpected operation: ${comparator.operator}`);+ }+ });+ if (setMin && (!minver || gt2(minver, setMin))) {+ minver = setMin;+ }+ }+ if (minver && range.test(minver)) {+ return minver;+ }+ return null;+ };+ module2.exports = minVersion2;+ }+});++// ranges/valid.js+var require_valid2 = __commonJS({+ "ranges/valid.js"(exports2, module2) {+ "use strict";+ var Range2 = require_range();+ var validRange2 = (range, options) => {+ try {+ return new Range2(range, options).range || "*";+ } catch (er) {+ return null;+ }+ };+ module2.exports = validRange2;+ }+});++// ranges/outside.js+var require_outside = __commonJS({+ "ranges/outside.js"(exports2, module2) {+ "use strict";+ var SemVer2 = require_semver();+ var Comparator2 = require_comparator();+ var { ANY } = Comparator2;+ var Range2 = require_range();+ var satisfies2 = require_satisfies();+ var gt2 = require_gt();+ var lt2 = require_lt();+ var lte2 = require_lte();+ var gte2 = require_gte();+ var outside2 = (version, range, hilo, options) => {+ version = new SemVer2(version, options);+ range = new Range2(range, options);+ let gtfn, ltefn, ltfn, comp, ecomp;+ switch (hilo) {+ case ">":+ gtfn = gt2;+ ltefn = lte2;+ ltfn = lt2;+ comp = ">";+ ecomp = ">=";+ break;+ case "<":+ gtfn = lt2;+ ltefn = gte2;+ ltfn = gt2;+ comp = "<";+ ecomp = "<=";+ break;+ default:+ throw new TypeError('Must provide a hilo val of "<" or ">"');+ }+ if (satisfies2(version, range, options)) {+ return false;+ }+ for (let i = 0; i < range.set.length; ++i) {+ const comparators = range.set[i];+ let high = null;+ let low = null;+ comparators.forEach((comparator) => {+ if (comparator.semver === ANY) {+ comparator = new Comparator2(">=0.0.0");+ }+ high = high || comparator;+ low = low || comparator;+ if (gtfn(comparator.semver, high.semver, options)) {+ high = comparator;+ } else if (ltfn(comparator.semver, low.semver, options)) {+ low = comparator;+ }+ });+ if (high.operator === comp || high.operator === ecomp) {+ return false;+ }+ if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {+ return false;+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {+ return false;+ }+ }+ return true;+ };+ module2.exports = outside2;+ }+});++// ranges/gtr.js+var require_gtr = __commonJS({+ "ranges/gtr.js"(exports2, module2) {+ "use strict";+ var outside2 = require_outside();+ var gtr2 = (version, range, options) => outside2(version, range, ">", options);+ module2.exports = gtr2;+ }+});++// ranges/ltr.js+var require_ltr = __commonJS({+ "ranges/ltr.js"(exports2, module2) {+ "use strict";+ var outside2 = require_outside();+ var ltr2 = (version, range, options) => outside2(version, range, "<", options);+ module2.exports = ltr2;+ }+});++// ranges/intersects.js+var require_intersects = __commonJS({+ "ranges/intersects.js"(exports2, module2) {+ "use strict";+ var Range2 = require_range();+ var intersects2 = (r1, r2, options) => {+ r1 = new Range2(r1, options);+ r2 = new Range2(r2, options);+ return r1.intersects(r2, options);+ };+ module2.exports = intersects2;+ }+});++// ranges/simplify.js+var require_simplify = __commonJS({+ "ranges/simplify.js"(exports2, module2) {+ "use strict";+ var satisfies2 = require_satisfies();+ var compare2 = require_compare();+ module2.exports = (versions, range, options) => {+ const set = [];+ let first = null;+ let prev = null;+ const v = versions.sort((a, b) => compare2(a, b, options));+ for (const version of v) {+ const included = satisfies2(version, range, options);+ if (included) {+ prev = version;+ if (!first) {+ first = version;+ }+ } else {+ if (prev) {+ set.push([first, prev]);+ }+ prev = null;+ first = null;+ }+ }+ if (first) {+ set.push([first, null]);+ }+ const ranges = [];+ for (const [min, max] of set) {+ if (min === max) {+ ranges.push(min);+ } else if (!max && min === v[0]) {+ ranges.push("*");+ } else if (!max) {+ ranges.push(`>=${min}`);+ } else if (min === v[0]) {+ ranges.push(`<=${max}`);+ } else {+ ranges.push(`${min} - ${max}`);+ }+ }+ const simplified = ranges.join(" || ");+ const original = typeof range.raw === "string" ? range.raw : String(range);+ return simplified.length < original.length ? simplified : range;+ };+ }+});++// ranges/subset.js+var require_subset = __commonJS({+ "ranges/subset.js"(exports2, module2) {+ "use strict";+ var Range2 = require_range();+ var Comparator2 = require_comparator();+ var { ANY } = Comparator2;+ var satisfies2 = require_satisfies();+ var compare2 = require_compare();+ var subset2 = (sub, dom, options = {}) => {+ if (sub === dom) {+ return true;+ }+ sub = new Range2(sub, options);+ dom = new Range2(dom, options);+ let sawNonNull = false;+ OUTER: for (const simpleSub of sub.set) {+ for (const simpleDom of dom.set) {+ const isSub = simpleSubset(simpleSub, simpleDom, options);+ sawNonNull = sawNonNull || isSub !== null;+ if (isSub) {+ continue OUTER;+ }+ }+ if (sawNonNull) {+ return false;+ }+ }+ return true;+ };+ var minimumVersionWithPreRelease = [new Comparator2(">=0.0.0-0")];+ var minimumVersion = [new Comparator2(">=0.0.0")];+ var simpleSubset = (sub, dom, options) => {+ if (sub === dom) {+ return true;+ }+ if (sub.length === 1 && sub[0].semver === ANY) {+ if (dom.length === 1 && dom[0].semver === ANY) {+ return true;+ } else if (options.includePrerelease) {+ sub = minimumVersionWithPreRelease;+ } else {+ sub = minimumVersion;+ }+ }+ if (dom.length === 1 && dom[0].semver === ANY) {+ if (options.includePrerelease) {+ return true;+ } else {+ dom = minimumVersion;+ }+ }+ const eqSet = /* @__PURE__ */ new Set();+ let gt2, lt2;+ for (const c of sub) {+ if (c.operator === ">" || c.operator === ">=") {+ gt2 = higherGT(gt2, c, options);+ } else if (c.operator === "<" || c.operator === "<=") {+ lt2 = lowerLT(lt2, c, options);+ } else {+ eqSet.add(c.semver);+ }+ }+ if (eqSet.size > 1) {+ return null;+ }+ let gtltComp;+ if (gt2 && lt2) {+ gtltComp = compare2(gt2.semver, lt2.semver, options);+ if (gtltComp > 0) {+ return null;+ } else if (gtltComp === 0 && (gt2.operator !== ">=" || lt2.operator !== "<=")) {+ return null;+ }+ }+ for (const eq2 of eqSet) {+ if (gt2 && !satisfies2(eq2, String(gt2), options)) {+ return null;+ }+ if (lt2 && !satisfies2(eq2, String(lt2), options)) {+ return null;+ }+ for (const c of dom) {+ if (!satisfies2(eq2, String(c), options)) {+ return false;+ }+ }+ return true;+ }+ let higher, lower;+ let hasDomLT, hasDomGT;+ let needDomLTPre = lt2 && !options.includePrerelease && lt2.semver.prerelease.length ? lt2.semver : false;+ let needDomGTPre = gt2 && !options.includePrerelease && gt2.semver.prerelease.length ? gt2.semver : false;+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt2.operator === "<" && needDomLTPre.prerelease[0] === 0) {+ needDomLTPre = false;+ }+ for (const c of dom) {+ hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";+ hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";+ if (gt2) {+ if (needDomGTPre) {+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {+ needDomGTPre = false;+ }+ }+ if (c.operator === ">" || c.operator === ">=") {+ higher = higherGT(gt2, c, options);+ if (higher === c && higher !== gt2) {+ return false;+ }+ } else if (gt2.operator === ">=" && !satisfies2(gt2.semver, String(c), options)) {+ return false;+ }+ }+ if (lt2) {+ if (needDomLTPre) {+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {+ needDomLTPre = false;+ }+ }+ if (c.operator === "<" || c.operator === "<=") {+ lower = lowerLT(lt2, c, options);+ if (lower === c && lower !== lt2) {+ return false;+ }+ } else if (lt2.operator === "<=" && !satisfies2(lt2.semver, String(c), options)) {+ return false;+ }+ }+ if (!c.operator && (lt2 || gt2) && gtltComp !== 0) {+ return false;+ }+ }+ if (gt2 && hasDomLT && !lt2 && gtltComp !== 0) {+ return false;+ }+ if (lt2 && hasDomGT && !gt2 && gtltComp !== 0) {+ return false;+ }+ if (needDomGTPre || needDomLTPre) {+ return false;+ }+ return true;+ };+ var higherGT = (a, b, options) => {+ if (!a) {+ return b;+ }+ const comp = compare2(a.semver, b.semver, options);+ return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;+ };+ var lowerLT = (a, b, options) => {+ if (!a) {+ return b;+ }+ const comp = compare2(a.semver, b.semver, options);+ return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;+ };+ module2.exports = subset2;+ }+});++// index.js+var internalRe = require_re();+var constants = require_constants();+var SemVer = require_semver();+var identifiers = require_identifiers();+var parse = require_parse();+var valid = require_valid();+var clean = require_clean();+var inc = require_inc();+var diff = require_diff();+var major = require_major();+var minor = require_minor();+var patch = require_patch();+var prerelease = require_prerelease();+var compare = require_compare();+var rcompare = require_rcompare();+var compareLoose = require_compare_loose();+var compareBuild = require_compare_build();+var sort = require_sort();+var rsort = require_rsort();+var gt = require_gt();+var lt = require_lt();+var eq = require_eq();+var neq = require_neq();+var gte = require_gte();+var lte = require_lte();+var cmp = require_cmp();+var coerce = require_coerce();+var Comparator = require_comparator();+var Range = require_range();+var satisfies = require_satisfies();+var toComparators = require_to_comparators();+var maxSatisfying = require_max_satisfying();+var minSatisfying = require_min_satisfying();+var minVersion = require_min_version();+var validRange = require_valid2();+var outside = require_outside();+var gtr = require_gtr();+var ltr = require_ltr();+var intersects = require_intersects();+var simplifyRange = require_simplify();+var subset = require_subset();+module.exports = {+ parse,+ valid,+ clean,+ inc,+ diff,+ major,+ minor,+ patch,+ prerelease,+ compare,+ rcompare,+ compareLoose,+ compareBuild,+ sort,+ rsort,+ gt,+ lt,+ eq,+ neq,+ gte,+ lte,+ cmp,+ coerce,+ Comparator,+ Range,+ satisfies,+ toComparators,+ maxSatisfying,+ minSatisfying,+ minVersion,+ validRange,+ outside,+ gtr,+ ltr,+ intersects,+ simplifyRange,+ subset,+ SemVer,+ re: internalRe.re,+ src: internalRe.src,+ tokens: internalRe.t,+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,+ RELEASE_TYPES: constants.RELEASE_TYPES,+ compareIdentifiers: identifiers.compareIdentifiers,+ rcompareIdentifiers: identifiers.rcompareIdentifiers+};diff --git a/plugins/mobile-apps/scripts/vendor/semver.json b/plugins/mobile-apps/scripts/vendor/semver.jsonnew file mode 100644index 000000000..70c10cb7f--- /dev/null+++ b/plugins/mobile-apps/scripts/vendor/semver.json@@ -0,0 +1,16 @@+{+ "name": "semver",+ "version": "7.7.4",+ "license": "ISC",+ "source": "https://github.com/npm/node-semver",+ "packageIntegrity": "sha1-KEZONgYOmR+noR0CedLT87V6foo=",+ "bundle": {+ "tool": "esbuild",+ "version": "0.28.2",+ "entry": "index.js",+ "platform": "node",+ "format": "cjs",+ "target": "node20",+ "minify": false+ }+}diff --git a/plugins/mobile-apps/shared/references/app-working-directory.md b/plugins/mobile-apps/shared/references/app-working-directory.mdindex 9d1c9b0a6..1e45c60de 100644--- a/plugins/mobile-apps/shared/references/app-working-directory.md+++ b/plugins/mobile-apps/shared/references/app-working-directory.md@@ -3,6 +3,11 @@Before any project read, package gate, or command, resolve one absolute`working_dir` for this invocation:+- **New creation only:** before an app directory exists, the creation owner's+ `mobile-template-lifecycle.js destination` check binds an existing canonical+ parent and proposed child read-only. It does not authorize creation or app+ operations. After approved acquisition creates the child, use the normal+ app-root rules below. Never apply this exception to edits or continuation.- **Child invocation:** require the owner's absolute `working_dir`, including`--working-dir` when supplied. Never fall back to the process cwd. Missing orrelative owner context returns `NEEDS_CONTEXT` before project access.diff --git a/plugins/mobile-apps/shared/references/javascript-dependency-planning.md b/plugins/mobile-apps/shared/references/javascript-dependency-planning.mdindex 046c1c34e..a36539636 100644--- a/plugins/mobile-apps/shared/references/javascript-dependency-planning.md+++ b/plugins/mobile-apps/shared/references/javascript-dependency-planning.md@@ -15,7 +15,23 @@ A package is native-bound when it or a runtime dependency ships any of these:- `app.plugin.js`, `app.plugin.ts`, or equivalent Expo config plugin- `react-native.config.js`-Those packages must already be supported by the template/runtime. A package name is not evidence: a `react-native-*` package may still be pure JavaScript.+Those packages must already be included at matching versions in the app's+[verified release context](mobile-release-lifecycle.md). The newest bundled+template is not the runtime allowlist for an older app. A package name is not+evidence: a `react-native-*` package may still be pure JavaScript.++Use the orchestrator's sanitized resolved context, or resolve it read-only:++```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Unknown/missing release records block native mutations, not pure source/UI+planning and editing. For pure-JavaScript work, inspect the existing project's+installed versions and contracts; record native compatibility as unverified,+and do not claim that a successful type-check validates a player or base.+Never install the controls aggregate, a native leaf, or a newer host to repair+an older binary; those changes belong to an approved verified-release migration.## When To Select A Library@@ -59,7 +75,7 @@ The exact version and rationale are part of the screen-plan approval. Approval a### Calendar example-A full month/week/agenda scheduling surface triggers candidate selection. Evaluate `react-native-calendars` first because it supplies established calendar and agenda primitives and is pure JavaScript; `1.1314.0` is the known-good version for the current template baseline. Confirm current metadata and compatibility before writing the row. A lightweight horizontal date strip plus `FlatList` does not require a new package.+A full month/week/agenda scheduling surface triggers candidate selection. Evaluate `react-native-calendars` first because it supplies established calendar and agenda primitives and is pure JavaScript. Select an exact version compatible with the existing app's React/React Native/Expo and Node versions, not a version assumed from the newest template. Confirm current metadata and compatibility before writing the row. A lightweight horizontal date strip plus `FlatList` does not require a new package.## Installation Contract@@ -92,3 +108,7 @@ If installed contents reveal native code/config or an incompatible runtime depen## Builder ContractBuilders may directly import only packages listed in the approved table and present at the exact version in `package.json`. Builders never select packages, edit manifests, or run installs. A missing approved package is an orchestrator block; an unplanned package is a planning-context error.++Forward the same resolved release context (or explicit unresolved/source-only+status) to planners and builders. Approval of a JS-only dependency is not+approval to alter native inventory, OS declarations, or the selected base.diff --git a/plugins/mobile-apps/shared/references/mobile-release-lifecycle.md b/plugins/mobile-apps/shared/references/mobile-release-lifecycle.mdnew file mode 100644index 000000000..c1fd8669b--- /dev/null+++ b/plugins/mobile-apps/shared/references/mobile-release-lifecycle.md@@ -0,0 +1,334 @@+# Mobile release compatibility++Use package-owned compatibility for creation, native changes, upgrades, previews,+and deployment. npm identifies published versions; the selected host supplies its+template/native requirements and migrations. The matching immutable template+supplies dependency declarations and locked native versions. A newer npm package,+matching Hermes header, or successful TypeScript build does not prove that a+player or wrapped binary contains the same native runtime.++## Resolve before native work++```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Only exit 0 authorizes using the returned release as a native dependency+baseline. Pass the sanitized result to planners/builders, not a copy of+`app.json`, auth settings, or connection strings. Never substitute the plugin's+bundled `template/package.json`. An old app does not gain capabilities when its+plugin is updated.++The protected source is `app.json` → `expo.extra.powerappsNative`:+`schemaVersion`, `templateVersion`, and per-platform `nativeRuntimeVersions`.+These are not npm versions. Preserve them during preparation and ordinary app+edits. Only a successful host migration may advance them. Missing, malformed,+or unknown state blocks native work; do not backfill it from installed packages.+App-owned extras, telemetry preferences, branding, navigation, authentication,+offline settings, and custom instruction files remain customer-owned.+Tenant settings such as `tenantMode`, `appDisplayName`, `appName` and+`tenantPolicy` may share the `powerappsNative` object. Read only the three+protected compatibility fields for release selection, and preserve the+remaining app-owned configuration. Tenant configuration is not native release+evidence and must not be included in sanitized release/telemetry summaries.++`--requirements-only` reads the recorded source and installed host identity for+**upgrade planning**, even when installed dependencies have drifted. It does not+query npm or require a historical release record. It is not a native admission or+deployment check. Source/UI-only work can continue without claiming native+compatibility; adding or updating dependencies still needs explicit validation.++## Published package selection++There is no plugin-owned release catalogue to populate or republish. Keep+`npm outdated --json --depth=0` for update discovery and select an exact stable+host version from the supported npm channel. The resolver uses npm's configured+registry/authentication without reading or printing credentials. It downloads+archives with scripts disabled into temporary private storage, checks published+integrity and contained archive paths, reads package metadata without executing+package code, and removes its scratch files.+Template archives require sha512 integrity. Historical host packages that only+publish npm's SHA-1 shasum retain verification against that exact registry digest;+the helper never treats a missing hash as success.++The published host's `compatibility/current.json` owns target template/runtime+requirements, managed dependencies and migration references. A matching published+template's protected metadata and packaged lock provide the immutable native+inventory, including nested packages. The app's own lock is checked against that+reference; it is not allowed to declare new native packages compatible with a+fixed binary. Missing or malformed metadata, fingerprint disagreement, an+unpublished/unfinalized target, and dependency drift remain blockers.++Inspect a target without changing the app:++```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --host-version "<exact-host-version>"+```++For creation, inspect `--template-version "<exact-template-version>"` and acquire+that immutable package only after approval. For an upgrade, use+`mobile-template-lifecycle.js plan --project-root '<working_dir>' --host-version+"<exact-host-version>"`, then acquire the approved host into a separate empty+tooling directory. The host CLI, not the skill, owns migration writes and install+validation. Never independently upgrade every native dependency to npm `latest`.++Isolated acquisition retains the caller's effective project npm settings and+the original user/global configuration precedence. A project `.npmrc`, including+scoped registry authentication, exists only in the private installation directory+during npm execution and is removed on success or failure before invoking a+creation CLI. npm runs from the original context with an explicit isolated+prefix, global mode off and workspaces off, so relative TLS/auth file paths keep+their meaning without installing into the old app's dependency graph.+Credentials are never emitted in results or copied into the created app.+Template creation CLIs must be self-contained: dependency declarations,+bundled dependencies or unexpected acquired packages block execution even when+the template's own archive integrity matches.++For a proposed new app directory, the creation owner first runs+`mobile-template-lifecycle.js destination --destination '<proposed_working_dir>'`+from an existing parent. This only binds a canonical destination; acquisition+still needs approval. Existing-app and continuation flows cannot use this+creation-only exception to bypass missing-root checks.++Managed native registry ranges are checked against their exact inventory+versions with the bundled npm SemVer implementation. Reviewed vendor archives+retain their separate archive validation. Explicit template selections remain+attached to subsequent project resolution rather than silently choosing a+different, newer template with the same runtime.++Package compatibility and binary availability are separate. A same-runtime+patch/minor host update needs no new Player/base record. Native changes need a+host major, a template migration and matching native binaries before those+features can run. Compare actual Player metadata when available; do not invent+store availability or a future release date. Wrap must supply and verify its+selected base's version, native runtime and fingerprint before deployment.+The resolver reports binary availability as **not checked**, not success.++Do not invent missing package metadata or CLI flags. The template CLI's+`--manifest` reports package identity and template/runtime requirements, not+store readiness. Package inspection uses npm and `tar`; native build tools are+not prerequisites.++## Published package verification and rehearsal++The former local diagnostic artifact mode is retired. Missing or unfinalized+publications block native adoption; do not substitute local archives, a mutable+Git checkout or the plugin's bundled template. Package archive inspection keeps+the archive and extraction in one private scratch directory for Windows drive+safety, rejects links and unsafe paths, and removes scratch on success or failure.++For hosts advertising a versioned offline contract, the installed SDK's exact+version and integrity must match the selected published template lock. Its host+and React Native peers, runtime family, offline-contract version, Hermes/New+Architecture declarations and native artifact hashes must agree with the+published host. Read the expected SDK contract and complete declared native+artifact inventory from its integrity-verified registry archive, bound to the+immutable template lock's SHA-512 integrity. Compare the installed metadata and+every declared artifact against that reference; editing a local manifest or+removing one of its entries cannot authorize changed native files. Archive+inspection never installs packages or runs their lifecycle scripts. Missing or+unverifiable publication evidence blocks admission rather than trusting local+hashes. Historical hosts without that contract retain their existing+native admission rules; do not invent new metadata for them.+Do not delete profiles, disable offline or remove SDK imports to make validation+pass. Preserve app-owned source, settings, overrides, database contents and pending+writes. Offline synchronization, disconnected cold launch and database upgrades+need separate device tests. A source manifest or profile is not evidence of a+matching binary.++Use the **verified reference installation's target host CLI** for rehearsal, not+an older app's host or an invented target. Resolve its real `package.json`+`bin["upgrade-template"]` path. Restore the preview's source dependencies from its+unchanged source lock before reading inherited TypeScript configurations.+For a standalone npm app, use `mobile-template-lifecycle.js restore-preview+--project-root '<working_dir>' --preview-root '<preview_dir>'` with a snapshot+outside the source app. It verifies disjoint canonical paths and unchanged inputs,+preserves npm configuration, and binds `npm ci` to the preview's explicit prefix.+Never rely on a previous shell's `cd` or run bare installs during preview setup.+Unsupported workspace/package-manager layouts require review, not a fallback install.+The isolated target tooling acquisition uses the verified release's managed pins+and overrides so optional peers cannot float to an unreviewed newer SDK.+Run the independent Expo check with `mobile-template-lifecycle.js check-sdk+--project-root '<app_dir>'`, in both rehearsal and approved application. It runs+the app's installed CLI in that app's directory with `EXPO_OFFLINE=1` scoped only+to the explicit SDK version check. This still rejects incompatible dependencies+against the installed SDK's bundled versions; it does not skip validation or+adopt newer online recommendations. Keep npm installation, Expo Doctor,+configuration, TypeScript and bundle checks in their normal environment.+Do not use target-reference `NODE_PATH` instead of the source dependency context.+Preview one edge with `--project '<preview_dir>' --dry-run`, then apply only an+approved clean edge with the same CLI and its normal validated installation.+An intermediate write-only operation must use `--no-install` separately; it+does not advance state and is not completed migration.++An incompatible retained direct-dependency override is a blocking preview, not+permission to delete a customer pin or bypass npm `EOVERRIDE`. Review and approve+the exact override resolution, then rerun the preview. Keep test-fixture-only+pins distinguishable from genuine customer customizations.+Published migrations use the host-owned strict npm installer and guarded lock+regeneration. A broken published CLI requires a producer fix; do not locally+rewrite first-party packages or use Player-build scripts to repair an app.+After every edge, recheck the target requirements and run changed-file validation before+advancing through the reviewed migration chain.++During the Host-owned native migration/repair in `/check-updates` Step 2, do not+run strict app-lock or installed-package/native inventory admission. The host+CLI owns installation; re-run its published plan+and require `current` to confirm the target host/template/runtime requirements.+Pass `--upgrade-only` to changed-file validation to retain file/package policies+without duplicating npm's dependency checks. Expo compatibility, Expo Doctor,+TypeScript and platform bundles are mandatory, blocking checks. Fingerprint+differences are warnings only; Player/Wrap compatibility remains unverified.+Strict creation, native feature and deployment admission are unchanged.++Ordinary JavaScript-only updates in Steps 3 and 4 have a separate boundary:+run `mobile-template-lifecycle.js snapshot-native --project-root '<working_dir>' --baseline '<saved-native-before.json>'`+before the approved installation, then `check-native --project-root '<working_dir>' --baseline '<saved-native-before.json>'`+afterward. The comparison uses the app's own installed native package paths,+identities, versions and manifest digests, native declarations and protected+requirements. It does not compare the app to a reference template lock or claim+Player compatibility. Any drift, unreadable baseline or failed check requires+the package-scoped rollback. Store the snapshot in the app's recovery directory;+creation refuses an existing file or a directory resolving outside the app.+Never use `--upgrade-only` or `--requirements-only`+alone as proof that a JavaScript update did not introduce native dependencies.++Compare app requirements with the actual supported counters of a selected Player+when available. A mismatch requires a matching binary or an approved migration,+never rewriting compatibility labels. Package publication does not establish+store availability or device qualification.++## Immutable creation++After the user approves acquisition and installation, use:++```bash+node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" acquire \+ --template-version "<exact-template-version>" --destination '<new-empty-directory>'+```++The helper installs the exact template package in a private temporary directory+with install scripts disabled, checks its lockfile integrity before executing+its CLI, compares `--manifest`, and scaffolds only a new/empty destination. It+does not install app dependencies. Use the shipped lockfile with `npm ci` after+approval, then resolve the resulting app release before preparation. If package+publication, authentication, CLI support, manifest, or integrity checks fail,+stop; never fall back to `degit`, a mutable branch, or copying a bundled template.+Failed creation may leave a partial target: report it and preserve it for review,+do not overwrite it on retry.++Keep scaffolded `AGENTS.md`, `CLAUDE.md`, and `.github/copilot-instructions.md`.+Existing apps opt into instruction changes through a separate reviewed merge;+upgrades never silently replace or delete them.++## Coordinated upgrade or repair++Use `/check-updates` for the full approval/rollback workflow. Its read-only+decision helper runs even if `npm outdated` reports no host update:++```bash+node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" plan \+ --project-root '<working_dir>' --host-version "<exact-host-version>"+```++An equal supported target is valid. A stale template still needs migrations+when the host is already at target; a host-only repair does not require template+advancement. Reject lower target host versions or recorded template/native+versions; never infer an old template package version from a runtime counter.+Runtime counter or fingerprint changes require a published template migration.+No independent host, Expo, React Native, controls, or other native package bumps+are permitted.++At published planning, a native transition must target a **new host major** and+a host-owned template migration, not only new runtime counters. Producers own+the coordinated host/template release-version rules.+Published host and template identities require exact stable versions; prerelease+hosts are restricted to the diagnostic contract. Scaffoldable local diagnostics and controlled private prerelease targets require+a new host and template package major for a native transition.+Previously verified `0.x` source-version `upgrade-inspection-only` artifacts+instead report the required production major and cannot claim to satisfy that+production release requirement.++The currently supported `upgrade-template` CLI previews **one edge** per call+with `--dry-run`. It has no promised JSON/multi-edge planning API or+`--from-version` flag. `--no-install` does not advance template state. A nonzero+dry-run can mean conflicts, not just a broken command. Diagnose its sanitized+output; never treat every failure as a clean preview or apply it to the real app.++Keep the target CLI outside the source dependency graph. For a published+release, reuse `mobile-template-lifecycle.js acquire` with a new private+tooling directory and `--host-version "<exact-host-version>"`. The helper installs+that exact host with scripts disabled, verifies its registry/lock integrity,+and resolves its installed host's actual `bin["upgrade-template"]` path.+Review any required lifecycle scripts before separately approving them.+The tooling directory is not a scaffold and its lock never replaces the app lock.+Use that same verified CLI with `--project` for both the disposable rehearsal+and the separately approved real application. Diagnostic mode already supplies+its immutable reference. Neither path preinstalls an incompatible target host+into the old app, chooses `latest`, or re-scaffolds over customer files.++The host owns dependency edits, guarded lock regeneration and validation.+For changed standalone npm inputs it resolves in isolation, checks retained+direct dependency versions, then installs with strict `npm ci`. It never copies+the reference/template lock over the customer's lock; phase rollback retains+the original. Workspace and shrinkwrap upgrades keep their package-manager+boundary and strict in-place resolution, with conflicts requiring review.+Do not duplicate this installer in a skill or invoke migration-authoring,+runtime-preparation, release-tagging or Player-build scripts on a customer app.+An older published host without a safe install path requires a producer fix,+not a force/legacy-peer bypass or a skill-authored repair.++To approve a whole chain, first rehearse it in a user-approved private disposable+copy of the app, with the exact target host, normal validated installs, and a+separate preview and diff for **every edge**. Record source/target state and+customer conflicts throughout. Stop on conflicts, no progress, skipped edges,+overshoot, unsupported CLI behavior, or an interrupted journal. Never guess+later operations from the first preview. If a complete safe rehearsal cannot+be produced, block the real upgrade and report the missing contract.++Review the aggregate diff, installs, runtime/base/player change, and recovery+plan with the user before touching the real app. Approval of the rehearsal is+not approval of application. Preserve local uncommitted changes with a bounded+file snapshot; never use a Git reset. Recheck source bytes and dependency state+after approval. Any changed input or newly discovered operation invalidates+approval. Apply only the reviewed sequence and validate after each edge.++## Controls and binary boundaries++Use controls only when the resolved inventory includes them. Existing aggregate+controls are `@microsoft/power-apps-native-controls/pdf`, `/pen`, and+`/geolocation`; the root exports metadata, not these native functions.+An older binary cannot acquire those native modules through an npm install.++Dependency inclusion, signed OS declarations, runtime permission grants, and+actually using a control are different. The existing aggregate retains its+Android library declarations even when a control is unused. A fixed-capability+base may contain unused compiled code. Different declarations require another+verified base build. Per-customer optional-permission selection during wrapping+is not part of this workflow.++## Deployment and diagnostics++For each target platform, verify the **actual intended base** before packaging,+again before push if anything changed:++```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" \+ --project-root '<working_dir>' --platform android \+ --base-version "<actual-base-version>" --base-fingerprint "<actual-base-fingerprint>" \+ --base-runtime-version "<actual-base-runtime-version>"+```++Use `ios` independently for iOS. Obtain all three values (base version, native+fingerprint and native runtime counter) from the selected deployment target,+not by copying expected policy values just to pass. If the target cannot expose+a verifiable version, fingerprint and runtime counter, block native deployment rather+than infer it from Hermes bytecode or the npm host. Preserve deployment approval,+first-app-ID regeneration, and offline reconciliation gates.+`--platform` always requires `--project-root`: inspecting a catalogue default+or named release alone is not deployment admission.++When debugging or reporting, include only the helper's sanitized tuple and+whether resolution succeeded. Do not attach full manifests, auth/config files,+logs, reject files, dependency snapshots, or tenant identifiers. A compatibility+failure is not permission to patch first-party packages or suppress diagnostics.diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.mdindex 5eb82d6de..5117f744c 100644--- a/plugins/mobile-apps/shared/shared-instructions.md+++ b/plugins/mobile-apps/shared/shared-instructions.md@@ -125,6 +125,21 @@ feature requests, first capture the lightweight entry choice below; do not runversion/auth checks before the user chooses to proceed. Notifies the user if atool version is below the supported minimum (Node 22+, npm 10+, Expo SDK 55+, etc.).+Use the selected package contract's tooling requirements rather than assuming newer Expo/React Native versions work with an older binary.++Native work also follows [mobile-release-lifecycle.md](./references/mobile-release-lifecycle.md).+Resolve the app-version-matched inventory before adding native usage or changing+dependencies, and verify the intended base before deployment. Never use the+newest bundled template as an old app's native allowlist. This is an explicit+workflow gate, not a telemetry/write hook. Source-only edits can continue when+release evidence is unavailable without claiming native validation.++Local diagnostic artifact selection is retired. Use the finalized published+host/template contract and preserve app-owned offline configuration, normal+approvals and telemetry checkpoints. Package inspection does not establish+device execution or offline-sync success. Never send local paths, raw CLI+output or package/native binaries to telemetry.+---## Workflow Checkpointsdiff --git a/plugins/mobile-apps/shared/version-check.md b/plugins/mobile-apps/shared/version-check.mdindex 2f7d41005..aebf4ae07 100644--- a/plugins/mobile-apps/shared/version-check.md+++ b/plugins/mobile-apps/shared/version-check.md@@ -1,6 +1,13 @@# Version Check — Power Apps Native Code App-Single source of truth for minimum tool versions. Every skill should reference this file from its prereqs phase rather than hard-coding versions.+Tooling prerequisites only. Runtime compatibility comes from the app-matched+[verified release context](references/mobile-release-lifecycle.md), not this+file or the newest bundled template.++Published package inspection uses npm and `tar`; it does not discover devices+or build native code. The former local diagnostic artifact mode is retired.+Keep normal tooling tiers unchanged and report binary/device availability+separately from package compatibility.## Guiding principle — **scope-aware checks, not blanket gates**@@ -12,32 +19,35 @@ This plugin uses scope-aware checks based on the mobile workflow:Result: the only required tooling is what Node/npm, the Power Apps CLI (`pa`), and the relevant helper scripts need. Xcode/JDK/Android Studio are explicitly out of scope.-This is also a standard **Expo managed workflow** project. That means:--- `ios/` and `android/` folders are **generated artifacts** — produced by `expo prebuild` from `app.json` plugins. They are **git-ignored**. Developers never hand-edit them.-- Adding a native capability = `expo install <plugin>` + add the plugin name to `app.json` plugins array. The plugin's "config plugin" patches `Info.plist` / `AndroidManifest.xml` automatically on the next prebuild (which happens transparently inside `npm run build` and native run workflows when needed).-- Tamagui, Expo Router, MSAL, secure-store, camera, etc. all ship as plugins — you `npm install` them like any other package. **No Xcode project surgery, no `build.gradle` edits.**+These apps use an **immutable, prebuilt native runtime**. `npm run build`+exports application JavaScript; it does not prebuild or compile new native code.+Adding a dependency or config plugin cannot add native support to a player/base.+Use `/add-native` only for packages and versions already verified in that app's+release. Changing native dependencies requires a maintainer-verified release+migration through `/check-updates`, not an ad hoc install or local native build.### What the user owns vs what Expo generates| Layer | Edited by user? | Source of truth ||---|---|---|| `app/`, `src/`, `assets/`, `tamagui.config.ts` | ✅ yes | application code |-| `app.json` (plugins, permissions, infoPlist, intentFilters) | ✅ yes | declarative native config |-| `package.json` (deps + Expo plugin packages) | ✅ yes | npm |-| `ios/` | ❌ never | generated by `expo prebuild` |-| `android/` | ❌ never | generated by `expo prebuild` |-| `Info.plist`, `AndroidManifest.xml` | ❌ never | generated from `app.json` |+| `app.json` app metadata / opt-in app telemetry | ✅ within the owning skill | app configuration, not native compatibility proof |+| `package.json` pure-JavaScript dependencies | ✅ with approval | exact-version JavaScript dependency plan |+| Native dependencies, plugins, permissions, Info.plist / manifest declarations | ❌ not per-customer capability edits | verified fixed-capability base |+| `ios/`, `android/`, `Info.plist`, `AndroidManifest.xml` | ❌ never in these skills | maintainer-built native release |-If `/add-native` adds `expo-camera`, the only changes that get committed are: `package.json` (dep) + `app.json` (plugin entry + iOS `NSCameraUsageDescription`).+Package inclusion, OS declarations, runtime grants, and app usage are four+separate facts. Disabling a control or omitting its JS import does not remove+default Android permissions. Different declarations require another verified+base; optional permission wrapping is deferred.## Always required (any target)| Tool | Min version | Check command | Why ||---|---|---|---|-| Node.js | `22.0.0` | `node --version` | Expo SDK 55 + React Native 0.83 require Node 22+ |+| Node.js | `22.0.0`, or higher when the resolved release requires it | `node --version` | Also honor installed package engines and verified release tooling requirements || npm | `10.0.0` | `npm --version` | Expo install / lockfile v3 |-| Expo CLI (via npx) | `0.21.0` | `npx --no-install expo --version` | SDK 55 prebuild support |+| Expo CLI (project-local via npx) | release-matched | `npx --no-install expo --version` | Export with the app's resolved Expo release; never fetch a newer CLI to repair native compatibility || TypeScript (project-local) | `5.4.0` | `npx --no-install tsc --version` | Required by generated service types || POSIX shell (Windows only) | bash 4+ / zsh 5+ | `echo $BASH_VERSION || echo $ZSH_VERSION` | Skills use `cp -R`, `rm -rf`, `mkdir -p`, `grep`, `sed`, `find`. Native PowerShell / cmd.exe lack these. Use **Git Bash** or **WSL** on Windows. See [shared-instructions.md → Shell Requirement](./shared-instructions.md#shell-requirement-windows-users). |@@ -64,18 +74,35 @@ The following are needed **only** if the user manually runs platform-specific naIf the user asks how to run on a real device or simulator: point them at the Expo docs (https://docs.expo.dev/get-started/set-up-your-environment/) and let them install whatever they need. Do not gate any plugin skill on these.-## Required SDKs (in `package.json`)+## Resolve SDK and native package versions+```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```-| Package | Pinned version | Notes |-|---|---|---|-| `expo` | `55.0.26` | SDK 55 |-| `react-native` | `0.83.6` | matched to Expo SDK 55 |-| All `expo-*` packages | `55.x.y` | router, auth-session, secure-store, dev-client, etc. — version line tied to SDK |-| `@microsoft/power-apps` | `1.2.7` | Power Apps code app SDK |-| `@microsoft/power-apps-native-host` | `^0.4.0` | native runtime host |-| `@microsoft/power-apps-native-offline` | `^0.1.3` | offline runtime package |-| `tamagui`, `@tamagui/*` | `2.4.5` | design system primitives with Config v5, all `@tamagui/*` packages tracked together |+Use only its sanitized tuple for the app's template, host, Expo, React Native,+native inventory, and package-owned runtime requirements. A package version existing+on npm is not a verified player/base release. There is no bundled release list:+unknown/missing published contracts block native mutations and deployment. Existing pure+source/UI work may continue with installed contracts and an explicit+`native compatibility unverified` limitation.++The tuple's `nativePackages` contains reviewed canonical `node_modules`-relative+package paths and exact versions; `managedDependencies` contains reviewed+registry declarations or safe `file:./vendor/*.tgz` specs. These policy values+are not absolute project paths, raw config, or lockfile download URLs. Preserve+the nested inventory when handing context to planners/builders.++`--host-version <version>` selects an exact stable published host; `--release`+is its backwards-compatible alias, not a catalogue ID. `--default` reads npm's+default host channel and then verifies that exact package contract. Deployment+must also check each actual intended base using `--platform android|ios+--base-version <version> --base-fingerprint <fingerprint>+--base-runtime-version <runtime-counter>`, together with `--project-root`.+All four base flags are required together for deployment. Obtain the values+from the selected target's verifiable metadata;+do not copy the policy's expected values to make a check pass. Missing or+mismatched fingerprint blocks deployment even when the version label matches.## Standard prereq snippet for skills@@ -92,7 +119,7 @@ node --version # expect v22+# Project-local (only if inside a project)test -f power.config.json && echo "OK: code app project"-node -e "console.log(JSON.stringify(require('./app.json').expo, null, 2))" 2>/dev/null # SDK + plugins+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'```**Do NOT call `xcodebuild`, `java -version`, or check for Android Studio in any skill.** Local native compile is the user's choice, not a plugin concern.@@ -110,6 +137,5 @@ node -e "console.log(JSON.stringify(require('./app.json').expo, null, 2))" 2>/de## When to update this file- New skill needs a tool not listed → add it here, then reference from the skill (don't hard-code in the skill).-- An SDK pin changes in [`plugins/mobile-apps/template/package.json`](https://github.com/microsoft/power-platform-skills/tree/main/plugins/mobile-apps/template/package.json) → update the SDK table here.+- A verified release changes tooling requirements → update this tooling guidance; keep runtime pins in the shared release policy, not a duplicate SDK table here.- A new Power Platform CLI feature requires a newer minimum → bump the table, surface a one-line warning in the affected skills.-diff --git a/plugins/mobile-apps/skills/add-native/SKILL.md b/plugins/mobile-apps/skills/add-native/SKILL.mdindex 701b04096..cf8f68086 100644--- a/plugins/mobile-apps/skills/add-native/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/SKILL.md@@ -20,16 +20,19 @@ every shell call and file tool, not a previous shell's cwd.**Entry routing:** use the shared [App feature entry points](../../shared/shared-instructions.md#app-feature-entry-points)preflight before the workflow below.-The leaf generates typed wrappers under `src/native/` for native capabilities that-the upstream template already ships. Screens import the wrapper instead of touching-Expo modules directly, so the discriminated-union result contract stays consistent.+Generate a typed wrapper under `src/native/` for a native capability in the app's+[verified release context](../../shared/references/mobile-release-lifecycle.md).+Screens import the wrapper instead of touching native packages directly.+Read [native controls](references/native-controls.md) for conditional aggregate+adoption, legacy imports, permission boundaries, and location ownership.## Hard rules — do NOT cross these lines-1. **Never run `npx expo install`, `npm install`, or `yarn add` for a native module.** The set of native modules in `package.json` is fixed by the upstream template. Adding a new one breaks the rewrap pipeline (the customer's binary is built from a pre-built base, not from their `package.json`).-2. **Never edit `app.config.js`** — plugins, `ios.infoPlist`, `android.permissions`, or anything else. All native config the template ships is intentional and signed off; arbitrary additions cannot be honored at rewrap time.+1. **Never run `npx expo install`, `npm install`, or `yarn add` for a native module.** Native support is fixed by the app-matched verified release and selected player/base, not the newest bundled template or the customer's manifest.+2. **Never edit `app.config.js`** — plugins, `ios.infoPlist`, `android.permissions`, or anything else. Native config belongs to the verified fixed-capability base; arbitrary additions cannot be honored at rewrap time.3. **Never edit `package.json` `dependencies` for native modules.** Native means the package ships platform source/projects, a podspec, codegen, an Expo module/config plugin, or `react-native.config.js`; a package-name prefix alone is not proof. Pure-JavaScript dependencies are out of scope for `/add-native` and are installed from an approved `JavaScript Dependencies` plan by `/create-mobile-app` or `/edit-app`.-4. **If the requested module isn't actually present in `package.json` — STOP.** That means the upstream template hasn't shipped it yet; do not work around by installing it.+4. **If release resolution fails, or package/version/native inventory disagree — STOP before native mutation.** A dependency being present is necessary, not sufficient. Do not install the controls aggregate or newer leaf to repair an older binary.+5. **Keep inclusion, declarations, grants, and usage separate.** The base owns OS declarations. Dependency/config toggles do not remove unused default Android permissions; different declarations require another verified base. Optional permission wrapping is deferred.## Routing — `/add-native` is the public entry point@@ -45,13 +48,28 @@ Current dedicated implementations:| `pdf-report`, `pdf-export`, `generate-pdf`, `print-report`, `evidence-packet` | [`add-pdf-report`](add-pdf-report/SKILL.md) internal helper | Generates app-owned local PDFs with `expo-print` and shares them only when `expo-sharing` is present || `pdf-viewer`, `native-pdf-viewer`, `pdf-control`, `open-pdf`, `@microsoft/power-apps-native-pdf-viewer` | [`add-pdf-viewer`](add-pdf-viewer/SKILL.md) internal helper | Enforces `https://` / `file://` viewer inputs and native viewer result handling || `pen-input`, `signature`, `ink`, `draw`, `@microsoft/power-apps-native-pen-input` | [`add-pen-input`](add-pen-input/SKILL.md) internal helper | Captures PNG data URI and documents Dataverse Image/File persistence |-| `geolocation`, `location-tracking`, `background-location`, `gps-tracking`, `geo-tracking`, `@microsoft/power-apps-native-bglocation` | [`add-geolocation`](add-geolocation/SKILL.md) internal helper | Native background GPS tracking with durable storage and inline Dataverse sync; distinct from one-shot `expo-location` |+| `location`, `geolocation`, `location-tracking`, `background-location`, `gps-tracking`, `geo-tracking`, `@microsoft/power-apps-native-bglocation` | [`add-geolocation`](add-geolocation/SKILL.md) internal helper | Separate one-shot coordinate reads from continuous tracking and durable Dataverse sync |For every other capability listed below, this skill writes the wrapper directly.## Native capability gate-Before adding any native control or wrapper, apply every gate: classify the intent, resolve the exact package/control from the live `package.json`, confirm it is not runtime-banned, confirm the input/output/storage constraints, then use the matching route below. If any gate fails, the native functionality is not supported for this app version — do not install packages, edit native config, or create fake wrappers.+Before adding any native control or wrapper, verify the project and run the+package-contract resolver in Step 1.++Use its sanitized tuple as the shared resolved context for helpers/planners/builders.+Unknown/missing published contracts block native mutations, not permission to+assume a runtime. No separate skills release list is required. Classify the intent, resolve+the exact package and version from this app's inventory, confirm it is not+runtime-banned, and verify input/output/storage constraints. The newest bundled+template is never a runtime allowlist. Every “present” requirement below means+present in both this release context and the installed app, with compatible+native support; manifest presence alone cannot pass the gate.++For controls, select aggregate subpaths or legacy leaves using the+[version-conditional import contract](references/native-controls.md).+`enableNativeControls` is permitted only on a verified supporting host release;+published host 0.4.0 lacks it. No root barrel or barcode subpath is available.| User intent | Add/use | Required package or control | Do not use / fallback ||---|---|---|---|@@ -61,12 +79,13 @@ Before adding any native control or wrapper, apply every gate: classify the inte| Pick/import/upload a user-selected PDF/document | `/add-native document-picker`, or host `<FilePicker>` for Dataverse File fields | `expo-document-picker` present, or host File control | Do not treat this as `pdf-report` or native PDF viewer || Generate/export/print an app-owned report PDF | `/add-native pdf-report` | `expo-print` present | If `expo-print` is absent, do not add PDF report capability || Share a generated local PDF | `pdfReport.ts` share helper | `expo-sharing` present | If `expo-sharing` is absent, do not render sharing UI |-| Open/preview an HTTPS or local file PDF | `/add-native pdf-viewer` | `@microsoft/power-apps-native-pdf-viewer` 0.2.9+ present and input is `https://` or `file://` | Do not pass `content://`, `blob:`, or `http://` URIs to the viewer |-| Capture signature, ink, drawing, or sign-off | `/add-native pen-input` | `@microsoft/power-apps-native-pen-input` present | If persisted, plan Dataverse Image/File/child Evidence target first |-| Continuous/background GPS tracking with durable Dataverse upload | `/add-native geolocation` | `@microsoft/power-apps-native-bglocation` present | Do not use one-shot `expo-location` for background tracking; do not use the `GeolocationExtension`/HostingSDK path |+| Open/preview an HTTPS or local file PDF | `/add-native pdf-viewer` | Resolved controls `/pdf` or matching legacy PDF leaf with file URI support (0.2.9+) | Do not pass `content://`, `blob:`, or `http://` URIs to the viewer |+| Capture signature, ink, drawing, or sign-off | `/add-native pen-input` | Resolved controls `/pen` or matching legacy pen leaf | If persisted, plan Dataverse Image/File/child Evidence target first |+| One-shot foreground coordinate | `/add-native location` | Resolved controls `/geolocation` or matching background-location leaf; `expo-location` only if independently verified | No `app_id`, data source, target table, or `startTracking` for `BgLocationClient.getCurrentLocation()` |+| Continuous/background GPS tracking with durable Dataverse upload | `/add-native geolocation` | Resolved controls `/geolocation` or matching legacy background-location leaf | Do not use a one-shot read for tracking; background-location 0.2.3 tracking uses background permissions even with `trackInBackground: false` || Tactile feedback for presses, selections, and operation results | `/add-native haptics` | `expo-haptics` present | Use the typed wrapper and pair every haptic with visible UI feedback || Store generated PDF/signature artifact | Generated Dataverse services after parent row exists | File/Image column or child Evidence/Attachment table exists | Never put File bytes in create/update JSON |-| Native capability not listed in this table | Resolve from `package.json`, then add an inline wrapper only when the matching package is present and not runtime-banned | Exact relevant package present in `package.json` | If no relevant package exists, or the package is runtime-banned, add a transparency note and stop |+| Native capability not listed in this table | Resolve from the app-matched native inventory, then add an inline wrapper only when installed and not runtime-banned | Exact relevant package/version in the verified release | If no relevant package exists, or the package is runtime-banned, add a transparency note and stop |Handle multi-part requests row-by-row. Example: "capture signature and attach signed report PDF" requires `pen-input`, `pdf-report`, Dataverse artifact storage, and possibly `sharing`; do not add only the native capability while leaving storage or screen states undefined. The map is not closed: for new shipped packages, resolve by capability semantics, use the directly matching package when safe, and ask once only if multiple installed packages plausibly match.@@ -135,7 +154,10 @@ Use `/add-native` wrappers only when the workflow is not a Dataverse File/Image## Supported capabilities-Apply the Native capability gate above. This table is a known capability-to-package map, not a guarantee that every listed package exists in every template version.+Apply the Native capability gate above. This is a capability map, not release+evidence. Legacy leaf names below are aliases only; use aggregate subpaths when+the resolved release includes controls, and keep a leaf import only when that+release includes the matching leaf. Read installed public docs/types first.| Capability | Module | Wrapper to generate | Notes ||---|---|---|---|@@ -143,16 +165,16 @@ Apply the Native capability gate above. This table is a known capability-to-pack| `image-picker`, `gallery`, `expo-image-picker` | `expo-image-picker` | `src/native/camera.ts` (`pickImage`) | `/add-native` routes internally to `add-camera`; preserve compatible existing re-exports || `barcode-scanner`, `qr-scanner`, `scanner`, `barcode`, `qr` | `expo-camera` | `src/native/barcodeScanner.tsx` | `/add-native` routes internally to `add-camera` || `document-picker` | `expo-document-picker` | `src/native/documentPicker.ts` | Picks/imports user-selected files (PDF, docs, etc.) from the device |-| `pdf-viewer`, `native-pdf-viewer`, `pdf-control`, `open-pdf`, `@microsoft/power-apps-native-pdf-viewer` | `@microsoft/power-apps-native-pdf-viewer` | `src/native/pdfViewer.ts` | `/add-native` routes internally to `add-pdf-viewer`; 0.2.9+ opens HTTPS URLs and file URIs |+| `pdf-viewer`, `native-pdf-viewer`, `pdf-control`, `open-pdf`, `@microsoft/power-apps-native-pdf-viewer` | Controls `/pdf` or verified legacy PDF leaf | `src/native/pdfViewer.ts` | `/add-native` routes internally to `add-pdf-viewer`; require the resolved contract's HTTPS/file URI support || `pdf-report`, `pdf-export`, `generate-pdf`, `print-report`, `evidence-packet` | `expo-print` (+ optional `expo-sharing`) | `src/native/pdfReport.ts` | `/add-native` routes internally to `add-pdf-report`; generated local files are shared only when `expo-sharing` is present, or uploaded to Dataverse |-| `pen-input`, `signature`, `ink`, `draw`, `@microsoft/power-apps-native-pen-input` | `@microsoft/power-apps-native-pen-input` | `src/native/penInput.ts` | `/add-native` routes internally to `add-pen-input`; captures PNG data URI |-| `geolocation`, `location-tracking`, `background-location`, `gps-tracking`, `geo-tracking`, `@microsoft/power-apps-native-bglocation` | `@microsoft/power-apps-native-bglocation` | `src/native/geolocation.ts` | `/add-native` routes internally to `add-geolocation`; native background tracking + durable Dataverse sync. Distinct from one-shot `location` below |+| `pen-input`, `signature`, `ink`, `draw`, `@microsoft/power-apps-native-pen-input` | Controls `/pen` or verified legacy pen leaf | `src/native/penInput.ts` | `/add-native` routes internally to `add-pen-input`; captures PNG data URI |+| `geolocation`, `location-tracking`, `background-location`, `gps-tracking`, `geo-tracking`, `@microsoft/power-apps-native-bglocation` | Controls `/geolocation` or verified background-location leaf | `src/native/geolocation.ts` | `/add-native` routes internally to `add-geolocation`; tracking + durable Dataverse sync, distinct from one-shot `location` || `secure-store` | `expo-secure-store` | `src/native/secureStore.ts` | || `file-system` | `expo-file-system` | `src/native/fileSystem.ts` | || `sharing` | `expo-sharing` | `src/native/sharing.ts` | |-| `location` | `expo-location` | `src/native/location.ts` | One-shot/foreground fix only. For continuous background tracking with Dataverse sync, use `geolocation` (`@microsoft/power-apps-native-bglocation`). Use only when the current template package contains `expo-location` |-| `biometrics`, `local-authentication` | `expo-local-authentication` | `src/native/biometrics.ts` | Use only when the current template package contains `expo-local-authentication` |-| `clipboard` | `expo-clipboard` | `src/native/clipboard.ts` | Use only when the current template package contains `expo-clipboard` |+| `location` | Resolved controls `/geolocation` or matching leaf; independently verified `expo-location` if applicable | `src/native/location.ts` | One-shot only; geolocation helper skips tracking/table setup |+| `biometrics`, `local-authentication` | `expo-local-authentication` | `src/native/biometrics.ts` | Use only when included in the app's verified release |+| `clipboard` | `expo-clipboard` | `src/native/clipboard.ts` | Use only when included in the app's verified release || `mail-composer`, `email-draft` | `expo-mail-composer` | `src/native/mailComposer.ts` | Opens native mail compose when the package is present; connectors still own server-side email sends || `audio` | `expo-audio` | `src/native/audio.ts` | Use for audio recording/playback only when package is present || `video` | `expo-video` | `src/native/video.ts` | Use for video playback only when package is present |@@ -169,9 +191,9 @@ For custom workflows outside Dataverse File/Image form fields, use the `image-pi- Do not treat every PDF request as `document-picker`.- Use `document-picker` when the user wants to pick, import, or upload a local PDF/document. This remains supported and should still be used for that use case.- Use `pdf-report` when the app generates a PDF from records, evidence, inspection data, certificates, receipts, or reports, but only if `expo-print` is present in `package.json`.-- Use `native-pdf-viewer` / `pdf-control` when the app opens/previews an HTTPS PDF URL or local `file://` URI with `@microsoft/power-apps-native-pdf-viewer` 0.2.9+. `content://`, `blob:`, and `http://` URIs are unsupported.+- Use `native-pdf-viewer` / `pdf-control` for HTTPS or local `file://` PDFs using the resolved `/pdf` or matching legacy contract (PDF 0.2.9+ file support). `content://`, `blob:`, and `http://` URIs are unsupported.- If a request says "view/open PDF" but the Power Apps viewer package is absent, fall back to `pdf-report` only when the app is generating its own report and `expo-print` is present. Do not claim generic PDF viewing support through `expo-print`; it generates local files, it does not view arbitrary PDFs.-- Use `pen-input` only for signatures, drawn approvals, ink notes, sketches, and handwritten sign-off with `@microsoft/power-apps-native-pen-input`.+- Use `pen-input` only for signatures, drawn approvals, ink notes, sketches, and handwritten sign-off through the resolved `/pen` or matching legacy contract.- For other use cases, use the relevant Expo module or other dependency already present in `package.json`; do not force the Power Apps extensions into unrelated flows.- For generated local PDFs from `expo-print`, use native PDF viewer 0.2.9+ for open/preview, `expo-sharing` for sharing, and Dataverse File storage for retention. Do not require `expo-sharing` merely to preview a local PDF.- Host `FilePicker` and `ImagePicker` are still correct for user-selected Dataverse File/Image form fields. Generated PDFs and pen captures use native wrappers first, then Dataverse persistence helpers.@@ -184,11 +206,13 @@ For custom workflows outside Dataverse File/Image form fields, use the `image-pi- Never put File column bytes in the create/update JSON body. File bytes are uploaded only after the parent row ID exists.- Screens must handle unsupported, cancelled, upload failed, and viewer failed states explicitly. Pen cancellation is a non-error result that screens can ignore.-**Missing or gated packages:** `package.json` plus the runtime gate is authoritative. If the relevant package/control is absent, stop with a transparency note.+**Missing or gated packages:** the resolved release, installed versions, and+matching native runtime are authoritative together. If any evidence is missing,+stop with a transparency note; never claim native readiness from TypeScript alone.## Workflow-1. Verify project → 2. Resolve capability → 3. Auto-route to dedicated skill if one exists → 4. Verify module is template-shipped → 5. Write wrapper → 6. Type-check → 7. Summary+1. Verify project → 2. Resolve release and capability → 3. Auto-route to dedicated skill if one exists → 4. Verify package in resolved release → 5. Write wrapper → 6. Type-check → 7. Summary---@@ -199,6 +223,13 @@ cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1;test -f app.config.js && test -f power.config.json && test -f package.json || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }```+After the project gate succeeds, resolve its native contract:++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```+### Step 2 — Resolve capability**Telemetry checkpoint: `resolve_native_capability`**@@ -207,7 +238,13 @@ If `$ARGUMENTS` includes a capability name, package name, or control name, use iNormalize the capability name to lowercase, hyphenated form (e.g., `Camera` → `camera`, `ImagePicker` → `image-picker`, `SecureStore` → `secure-store`). Also normalize aliases: `take-photo` / `photo` / `camera-control` / `expo-camera` → `camera`; `gallery` / `pick-image` / `expo-image-picker` → `image-picker`; `scanner` / `barcode` / `qr` → `barcode-scanner`; `open-pdf` / `view-pdf` / `pdf-control` / `pdf-viewer-control` / `@microsoft/power-apps-native-pdf-viewer` → `pdf-viewer`; `native-pdf-viewer` → `pdf-viewer`; `generate-pdf` / `pdf-export` → `pdf-report`; `signature` / `sign-off` / `ink` / `draw` / `pen-control` / `@microsoft/power-apps-native-pen-input` → `pen-input`; `location-tracking` / `background-location` / `gps-tracking` / `geo-tracking` / `track-location` / `power-apps-native-bglocation` / `@microsoft/power-apps-native-bglocation` → `geolocation`; `vibration` / `vibration-feedback` / `impact-feedback` / `selection-feedback` / `notification-feedback` / `expo-haptics` → `haptics`.-When the user asks for "location" or "GPS", disambiguate by intent: continuous/background tracking or durable Dataverse upload → `geolocation` (`@microsoft/power-apps-native-bglocation`); a single foreground coordinate read → `location` (`expo-location`). If the intent is unclear, ask once before routing.+When the user asks for "location" or "GPS", disambiguate by intent:+continuous/background tracking or durable Dataverse upload → `geolocation`;+a single foreground coordinate read → `location`. Both route to the geolocation+helper with the mode preserved. The one-shot path has no `app_id`, data source,+table verification, or tracking startup. If the intent is unclear, ask once.+Normalize `@microsoft/power-apps-native-controls/pdf`, `/pen`, and `/geolocation`+to their matching capability; resolve location mode separately.If the user names something not in the supported table, apply the Native capability gate: resolve the relevant package from `package.json`, continue only when present and not runtime-banned, otherwise stop with a transparency note.@@ -215,7 +252,7 @@ If the user names something not in the supported table, apply the Native capabil**Telemetry checkpoint: `dispatch_native_capability`**-For normalized `camera`, `image-picker`, `barcode-scanner`, `qr-scanner`, `pdf-report`, `pdf-viewer`, `pen-input`, or `geolocation`, do not fall through to the generic wrapper flow and do not tell the user to run another slash command. Read the nested helper and follow its steps inside this `/add-native` invocation:+For normalized `camera`, `image-picker`, `barcode-scanner`, `qr-scanner`, `pdf-report`, `pdf-viewer`, `pen-input`, `location`, or `geolocation`, do not fall through to the generic wrapper flow and do not tell the user to run another slash command. Read the nested helper and follow its steps inside this `/add-native` invocation:```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }@@ -224,7 +261,7 @@ case "<capability>" inpdf-report) test -f "${PLUGIN_ROOT}/skills/add-native/add-pdf-report/SKILL.md" && echo "INTERNAL_HELPER:add-pdf-report" ;;pdf-viewer) test -f "${PLUGIN_ROOT}/skills/add-native/add-pdf-viewer/SKILL.md" && echo "INTERNAL_HELPER:add-pdf-viewer" ;;pen-input) test -f "${PLUGIN_ROOT}/skills/add-native/add-pen-input/SKILL.md" && echo "INTERNAL_HELPER:add-pen-input" ;;- geolocation) test -f "${PLUGIN_ROOT}/skills/add-native/add-geolocation/SKILL.md" && echo "INTERNAL_HELPER:add-geolocation" ;;+ location|geolocation) test -f "${PLUGIN_ROOT}/skills/add-native/add-geolocation/SKILL.md" && echo "INTERNAL_HELPER:add-geolocation" ;;*) echo "INLINE" ;;esac```@@ -241,13 +278,15 @@ esac`/add-native` remains the only user-facing command for these controls.- **INLINE:** continue to Step 4.-### Step 4 — Verify module is template-shipped+### Step 4 — Verify module in the resolved release-Confirm the underlying native-capability package is actually present in the project's `package.json` (catches the case where the user hand-removed it or the template version is older than expected):+Require a successful release resolution before this installed-manifest check.+Confirm the exact installed version against the resolved inventory and read its+public docs/types. A matching package name alone does not prove compatibility.```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }-node -e "const p = require('./package.json'); const m = '<expo-module-name>'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template should ship it. Re-scaffold via /create-mobile-app, restore it from upstream, or wait for the template release that adds it — this skill will not install it.'); process.exit(1); }"+node -e "const p = require('./package.json'); const m = '<resolved-package-name>'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + '. Stop and reconcile the app with its verified release; do not install native packages or re-scaffold an existing app.'); process.exit(1); }"```If the check fails, STOP. Do not run `npx expo install`. Print the error verbatim.@@ -276,7 +315,7 @@ Each wrapper exports:**The contract `screen-builder` agents rely on:**- All wrappers return a discriminated-union result (`{ ok: true, ... } | { ok: false, reason, message? }`) — **never throw**- Unsupported runtime/platform states gracefully degrade or return `{ ok: false, reason: 'unsupported' }` — **never crash**-- Branch by supported native platform when a capability differs between iOS and Android+- Native controls guard the native platform before a lazy import inside `try`/`catch`; never eagerly evaluate controls in web. Expo APIs with documented web implementations retain their supported platform behavior.- Screens import these wrappers only for non-Dataverse native workflows. Dataverse File/Image fields use `@microsoft/power-apps-native-host` controls from the File/Image Picker Ownership section above.#### Haptics wrapper@@ -284,7 +323,6 @@ Each wrapper exports:For normalized capability `haptics`, generate `src/native/haptics.ts` with this contract:```ts-import * as Haptics from 'expo-haptics';import { Platform } from 'react-native';export type HapticImpactStyle = 'light' | 'medium' | 'heavy' | 'soft' | 'rigid';@@ -293,21 +331,9 @@ export type HapticResult =| { ok: true }| { ok: false; reason: 'unsupported' | 'error'; message: string };-const impactStyles: Record<HapticImpactStyle, Haptics.ImpactFeedbackStyle> = {- light: Haptics.ImpactFeedbackStyle.Light,- medium: Haptics.ImpactFeedbackStyle.Medium,- heavy: Haptics.ImpactFeedbackStyle.Heavy,- soft: Haptics.ImpactFeedbackStyle.Soft,- rigid: Haptics.ImpactFeedbackStyle.Rigid,-};--const notificationTypes: Record<HapticNotificationType, Haptics.NotificationFeedbackType> = {- success: Haptics.NotificationFeedbackType.Success,- warning: Haptics.NotificationFeedbackType.Warning,- error: Haptics.NotificationFeedbackType.Error,-};--async function runHaptic(effect: () => Promise<void>): Promise<HapticResult> {+async function runHaptic(+ effect: (haptics: typeof import('expo-haptics')) => Promise<void>,+): Promise<HapticResult> {if (Platform.OS !== 'ios' && Platform.OS !== 'android') {return {ok: false,@@ -317,7 +343,8 @@ async function runHaptic(effect: () => Promise<void>): Promise<HapticResult> {}try {- await effect();+ const Haptics = await import('expo-haptics');+ await effect(Haptics);return { ok: true };} catch (error) {return {@@ -329,17 +356,33 @@ async function runHaptic(effect: () => Promise<void>): Promise<HapticResult> {}export function triggerImpact(style: HapticImpactStyle = 'medium'): Promise<HapticResult> {- return runHaptic(() => Haptics.impactAsync(impactStyles[style]));+ return runHaptic((Haptics) => {+ const impactStyles = {+ light: Haptics.ImpactFeedbackStyle.Light,+ medium: Haptics.ImpactFeedbackStyle.Medium,+ heavy: Haptics.ImpactFeedbackStyle.Heavy,+ soft: Haptics.ImpactFeedbackStyle.Soft,+ rigid: Haptics.ImpactFeedbackStyle.Rigid,+ };+ return Haptics.impactAsync(impactStyles[style]);+ });}export function triggerNotification(type: HapticNotificationType = 'success'): Promise<HapticResult> {- return runHaptic(() => Haptics.notificationAsync(notificationTypes[type]));+ return runHaptic((Haptics) => {+ const notificationTypes = {+ success: Haptics.NotificationFeedbackType.Success,+ warning: Haptics.NotificationFeedbackType.Warning,+ error: Haptics.NotificationFeedbackType.Error,+ };+ return Haptics.notificationAsync(notificationTypes[type]);+ });}export function triggerSelection(): Promise<HapticResult> {- return runHaptic(() => Haptics.selectionAsync());+ return runHaptic((Haptics) => Haptics.selectionAsync());}```@@ -370,7 +413,6 @@ Secure-store canonical skeleton:```ts// src/native/secureStore.ts-import * as SecureStore from 'expo-secure-store';import { Platform } from 'react-native';export type SecureResult<T> =@@ -382,6 +424,7 @@ export async function getSecret(key: string): Promise<SecureResult<string>> {return { ok: false, reason: 'unsupported', message: 'SecureStore is not available on this platform.' };}try {+ const SecureStore = await import('expo-secure-store');const value = await SecureStore.getItemAsync(key);if (value === null) return { ok: false, reason: 'not-found' };return { ok: true, value };@@ -395,6 +438,7 @@ export async function setSecret(key: string, value: string): Promise<SecureResulreturn { ok: false, reason: 'unsupported', message: 'SecureStore is not available on this platform.' };}try {+ const SecureStore = await import('expo-secure-store');await SecureStore.setItemAsync(key, value);return { ok: true, value: true };} catch (e: any) {@@ -424,6 +468,8 @@ When a template/base maintainer first adds `expo-haptics` or changes its versionthat release must rebuild the Android and iOS base binaries so Expo autolinkingincludes the module.+Type-check success is not native device validation. Native package changes require a separately approved host migration and matching native binaries, not customer-side linking.+### Step 7 — SummaryReturn the shared compatibility result before the summary; use the actual@@ -432,7 +478,8 @@ created/updated/reused paths and do not claim completion for unresolved artifact```✅ Native wrapper generated: <capability>─────────────────────────────────────────────-Module (template-shipped) : <expo-module>@<version-from-package.json>+Module (release-matched) : <package>@<resolved-version>+Release context : <verified-release-id>Wrapper created : src/native/<capability>.tspackage.json : unchanged ✓app.config.js : unchanged ✓@@ -450,14 +497,16 @@ Sample usage:showToast('Camera permission required');}-⚠️ No per-app native rebuild required when using a binary produced from the current- template. The underlying native module is already linked; wrapper edits are picked- up by Metro. Template/base dependency changes require a new native base build.+⚠️ No local native build performed. Wrapper edits use the matching verified+ player/base; package changes require a verified release migration.+ Type-check alone does not prove native execution or permission grants.─────────────────────────────────────────────```## Notes- This skill never modifies `package.json`, `app.config.js`, `src/playerConfig.ts`, `src/generated/`, or any screen file.-- For capabilities not in the supported table (`expo-notifications`, Bluetooth, NFC, BLE, AR — until the template adds them), tell the user the template doesn't ship them yet — file a request at the upstream template repo. Do NOT attempt to install or configure anything yourself.+- For unlisted capabilities, resolve against the app's verified native inventory.+ Missing support requires another verified release, not a new dependency or+ configuration toggle. Do NOT install or configure native modules yourself.- Pure-JavaScript libraries are out of scope for this skill. `/create-mobile-app` or `/edit-app` selects and installs them through [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md); no native wrapper or Android/iOS rebuild is needed. The prohibition above applies only to packages with native source/config.diff --git a/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md b/plugins/mobile-apps/skills/add-native/add-camera/SKILL.mdindex 402ef6061..9f0f93179 100644--- a/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/add-camera/SKILL.md@@ -30,6 +30,8 @@ the approved artifact set below must already ship in the template/native build;if a required module is missing, STOP. Do not require unrelated capture packagesfor a scanner-only or upload-only request.+Required modules/configuration must match the app's [published compatibility context](../../../shared/references/mobile-release-lifecycle.md), not the newest plugin template. Missing contract/native support blocks only the requested native mutation.+Why: customer binaries are built from a pre-built rewrap base, not from the customer's `package.json`. Adding a native module here would compile against modules the binary doesn't actually contain, causing runtime crashes after rewrap. See [`/add-native`](../SKILL.md) for the same hard rules.Required modules depend on the approved artifact set (all must already be in@@ -51,7 +53,7 @@ capture/scanner package.## Workflow-1. Verify project → 2. Verify modules are template-shipped → 2a. Reconcile requested artifacts → 3. Apply camera decision → 3b. Apply scanner decision → 4. Confirm storage decision → 5. Apply upload decision → 6. Verify → 7. Summary+1. Verify project → 2. Verify resolved native inventory and requested modules → 2a. Reconcile requested artifacts → 3. Apply camera decision → 3b. Apply scanner decision → 4. Confirm storage decision → 5. Apply upload decision → 6. Verify → 7. Summary---@@ -64,7 +66,7 @@ test -f app.config.js && test -f power.config.json && test -f package.json || {If any file is missing, report and STOP — this skill requires an initialized Power Apps mobile app.-### Step 2 — Verify modules are template-shipped+### Step 2 — Verify resolved native inventoryResolve the approved artifact keys before this check. Missing/ambiguous intentreturns to the owner (ask standalone); do not assume all artifacts. Substitute@@ -84,6 +86,15 @@ explicitly approved custom Dataverse Image-upload helper, not automatically forcapture or scanning. The checker accepts artifact-key JSON, not raw `$ARGUMENTS`or a public capability string. Missing/ambiguous intent still returns to the owner.+Resolve the app's package contract before module checks or wrapper edits:++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Then check only the approved artifact keys:+```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }node - '<approved-artifact-keys-json>' <<'NODE'@@ -111,6 +122,8 @@ NODEIf the check fails, STOP. Print the error verbatim. Do not run `npx expo install`. Do not edit `app.config.js`. Tell the user which requested modules the template lacks; they need template support, not an app-local native-package install.+Each requested module must match the resolved native inventory and installed docs/types. Do not require unrelated capture packages for scanner-only or upload-only work. Package inclusion does not establish OS declarations or device grants. Barcode/QR uses expo-camera; there is no controls barcode subpath.+### Step 2a — Reconcile requested artifactsRead and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)@@ -583,12 +596,14 @@ unresolved, and no full-feature claim for implementation-only work.Requested native artifacts ready---Capabilities : <fulfilled requested capabilities only>-Modules (template-shipped) : <required modules for those capabilities only>+Modules (release-matched) : <required modules for those capabilities only>++Release context : <resolved published package contract>package.json : unchanged ✓app.config.js : unchanged ✓Artifacts : <one row per requested path: created / updated / reused>-Type-check : <actual result>+Type-check : <actual result; not native device validation>UI integration : <returned to owner / intentionally not performed>---```diff --git a/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md b/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.mdindex 58281a76e..dcf6d4453 100644--- a/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/add-geolocation/SKILL.md@@ -1,13 +1,13 @@---name: add-geolocation-description: Internal implementation skill invoked by /add-native for native background GPS tracking with durable storage and Dataverse sync using @microsoft/power-apps-native-bglocation.+description: Internal helper for one-shot coordinates or continuous/background GPS using release-matched geolocation controls; tracking adds durable storage and Dataverse sync.user-invocable: falsedisable-model-invocation: trueallowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestionmodel: sonnet----**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** - read first.+**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** — read first.**Working directory:** before any project read or command, execute[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).@@ -16,53 +16,116 @@ file tool to it, even when this helper starts from another directory.# Add Geolocation-Internal helper for `/add-native geolocation`, `/add-native location-tracking`, `/add-native background-location`, `/add-native gps-tracking`, and `/add-native @microsoft/power-apps-native-bglocation`.+Internal helper for `/add-native location` (one-shot), `/add-native geolocation`,+`/add-native location-tracking`, and `/add-native background-location` (tracking).+Preserve the requested mode; ask once if intent is unclear.-Use this only for continuous/background GPS tracking with native durable storage and inline Dataverse upload. For a single foreground coordinate read, use `/add-native location` (`expo-location`) instead.+Read [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)+and [native controls](../references/native-controls.md). Do not use+`GeolocationExtension`, HostingSDK, PCF, Launch URI, or Cordova bridge paths.+Do not substitute another library's `configureSync` / `HttpSyncContract` API.-Hard rules:-- Auth is MSAL-only. Do not expose OneAuth or an auth selector.-- Use `geoService(dataSource, app_id)` and `BgLocationClient`.-- Do not use `GeolocationExtension`, HostingSDK, PCF, Launch URI, or CordovaV2 bridge paths.-- Do not install packages or edit native config.-- The control is not usable until its Dataverse target table and mapped columns are verified.--## 1. Verify app and package+## 1. Verify the app and resolved release```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }-node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-bglocation'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m); process.exit(1); } console.log('OK: geolocation package present');"+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'```-If either check fails, stop. The template/app must already ship the native package.+Unknown/missing records block native mutation. Do not install packages, edit+native config, or run local native builds. Match the installed public README,+exports, and types to the resolved inventory before generating any wrapper.+Use `@microsoft/power-apps-native-controls/geolocation` only when that aggregate+is included in the verified release. Use the legacy+`@microsoft/power-apps-native-bglocation` import only when the matching leaf+is actually included. Pick one literal import at generation time, never both.-## 2. Verify the Dataverse target table first+The public runtime exports are `BgLocationClient`, `geoService`, `AuthMethod`,+and `ConnectionType`. Controls 0.2.0 uses background-location 0.2.3; do not copy+APIs from a newer leaf. Package facts are not evidence of a released player/base.-This control uses the package default Dataverse entity set:+## 2. One-shot location — no tracking setup-```text-msdyn_locationrecords+Before writing or reusing the one-shot artifact, execute the shared+native-artifact compatibility contract's Steps 1-3 for the approved request.+Inspect the actual requested location API, platform/error behavior and consumers;+reuse a compatible wrapper or make only the approved scoped change. Do not turn+an approved one-shot request into tracking, Dataverse setup or screen integration.++For a single coordinate read, write `src/native/location.ts`. This path needs+**no `app_id`, data source, target table, or `startTracking`**. Skip Steps 3–5.+Check the selected version's location permission requirements; native binary+inclusion, OS declarations, runtime grants, and use are distinct.++Conditional example for a resolved release that contains the aggregate:++```ts+import { Platform } from 'react-native';++export async function getCurrentLocation() {+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {+ return { ok: false as const, reason: 'UNSUPPORTED_PLATFORM' as const };+ }++ try {+ const { BgLocationClient } =+ await import('@microsoft/power-apps-native-controls/geolocation');+ const value = await new BgLocationClient().getCurrentLocation();+ return { ok: true as const, value };+ } catch {+ return { ok: false as const, reason: 'LOCATION_FAILED' as const };+ }+}```-Do not ask the user for a table name and do not invent a custom table. `msdyn_locationrecords` must already exist before the control can be used.+Refine permission/error results only from the installed public contract. Do not+guess fields or classify errors by matching arbitrary native error text. Screens+show an appropriate denied/unsupported/failure state without exposing raw errors.+If the resolved release instead supports `expo-location`, use its installed+one-shot contract with the same platform and result guards, not tracking setup.++## 3. Continuous tracking — permissions and ownership first++For background-location **0.2.3**, `startTracking` uses background permissions+even with `trackInBackground: false`. Do not promise foreground-only tracking+permissions. Missing OS declarations require another verified base, not a+runtime fallback or per-customer wrapping option.++Tracking is shared. `stopTracking()` and `isTracking()` have no `app_id`+parameter. Before code generation, record a single app-level tracking owner,+explicit user start/stop actions, and how other screens observe status.+Do not start duplicate sessions, reconfigure an already owned session, or stop+tracking on an unrelated screen's unmount. A JS ownership flag does not prove+ownership of a native session surviving a JS restart; reconcile native status+through the installed API before starting/stopping.++Use MSAL only; do not expose OneAuth or an auth selector. Read the installed+`geoService(dataSource, app_id)` contract, `AuthMethod.MSAL`,+`ConnectionType.Dataverse`, permissions, and persistence behavior. The tracking+target must include `connectionUrl`, `trackInBackground`, and+`persistAcrossRestarts` as required by that version. Optional interval,+distance, and notification settings must come from its types, not guesses.++## 4. Verify the tracking Dataverse target++This check is **tracking-only**, never a prerequisite for a one-shot read.+Use the package's default entity set `msdyn_locationrecords` and default field+map. Do not invent a custom table, create the table, or route missing-table+provisioning through `/add-dataverse`.```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }ENV_JSON=$(node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e "console.log(require('./power.config.json').environmentId)")")ENV_URL=$(node -e "const j=JSON.parse(process.argv[1]); process.stdout.write(j.environmentUrl || '')" "$ENV_JSON")--TABLE="msdyn_locationrecords"node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \- "EntityDefinitions?\$filter=EntitySetName eq '$TABLE'&\$select=LogicalName,EntitySetName"+ "EntityDefinitions?\$filter=EntitySetName eq 'msdyn_locationrecords'&\$select=LogicalName,EntitySetName"```-Required result:-- One row returned: capture `LogicalName` and verify columns.-- Empty `value: []`: stop. Mark `BLOCKED (target table missing)`. Do not create the table, do not route to `/add-dataverse`, and do not report the control as usable. Tell the user to run the geolocation-control table provisioning/setup mechanism, then re-run `/add-native geolocation`.-- Auth/environment error: stop. Mark `UNVERIFIED (target table not checked)`. Do not report the control as usable.--When the table exists, verify every mapped column exists:+- One row: capture its logical name and check the mapped columns below.+- Empty `value: []`: `BLOCKED (target table missing)`. Ask for the supported+ geolocation table provisioning/setup mechanism, then re-run this workflow.+- Auth/environment failure: `UNVERIFIED (target table not checked)`. Stop.```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }@@ -70,16 +133,17 @@ node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \"EntityDefinitions(LogicalName='<logicalName>')/Attributes?\$select=LogicalName,AttributeType"```-Required default `fieldMap` columns from the package README:+Confirm the installed README's default `fieldMap` columns and their types:```textmsdyn_locationrecordid, msdyn_appid, msdyn_latitude, msdyn_longitude,msdyn_altitude, msdyn_accuracy, msdyn_heading, msdyn_speed, msdyn_timestamp```-If any active `fieldMap` column is missing, stop. Mark `BLOCKED (target columns missing)` and tell the user to fix the control table through the geolocation-control table provisioning/setup mechanism.+Missing active columns block tracking. Do not report the target as ready or+silently substitute another table.-## 2a. Reconcile requested artifacts+## 4a. Reconcile requested tracking artifactsRead and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)Steps 1–3 for the geolocation row before any writes or reuse. Inherit the current@@ -87,139 +151,35 @@ approval/mode from `/add-native`; do not repeat a valid scoped approval.Inspect `src/native/geolocation.ts` for all requested tracking/status/locationexports, `GeoTrackingTarget`, MSAL-only `geoService`/`BgLocationClient`, required`connectionUrl`/`trackInBackground`/`persistAcrossRestarts`, durable storage, and-Dataverse sync. Reuse Step 2's verified `msdyn_locationrecords` columns; one-shot+Dataverse sync. Reuse Step 4's verified `msdyn_locationrecords` columns; one-shotlocation or a wrapper targeting another table is not compatible. An incompatibleartifact outside approval returns `NEEDS_CONTEXT` to the owner, or asks standalone;missing table/columns remain `BLOCKED`, never a usable-control success.-## 3. Write `src/native/geolocation.ts`+## 5. Write the tracking wrapper from installed docs/types-Apply Step 2a's decision for `src/native/geolocation.ts`: create when requested+Apply Step 4a's decision for `src/native/geolocation.ts`: create when requestedand missing, reuse unchanged only if compatible, or make only the approved scopedupdate. Preserve custom code, exports, and callers; do not overwrite from theexample. Screens import this wrapper, not the package directly.-The target config must require the README's two tracking flags:-- `trackInBackground: boolean`-- `persistAcrossRestarts: boolean`--```ts-// src/native/geolocation.ts-import {- geoService,- BgLocationClient,- AuthMethod,- ConnectionType,-} from '@microsoft/power-apps-native-bglocation';-import type {- DataverseDataSource,- LocationData,- PermissionStatus,-} from '@microsoft/power-apps-native-bglocation';--export type { LocationData, PermissionStatus } from '@microsoft/power-apps-native-bglocation';--export type GeoTrackingTarget = Omit<DataverseDataSource, 'authMethod' | 'connectionType'>;--export type GeoResult<T> =- | { ok: true; value: T }- | {- ok: false;- reason: 'NATIVE_MODULE_MISSING' | 'PERMISSION_DENIED' | 'TRACKING_FAILED';- message?: string;- };--let activeClient: BgLocationClient | null = null;--function client(): BgLocationClient {- return activeClient ?? new BgLocationClient();-}--function dataSource(target: GeoTrackingTarget): DataverseDataSource {- return {- ...target,- authMethod: AuthMethod.MSAL,- connectionType: ConnectionType.Dataverse,- };-}--function fail(error: unknown): Extract<GeoResult<never>, { ok: false }> {- const message = error instanceof Error ? error.message : String(error);- if (/native|module|not.*link|undefined is not an object|null is not an object/i.test(message)) {- return { ok: false, reason: 'NATIVE_MODULE_MISSING', message };- }- if (/permission|denied|authoriz|not granted/i.test(message)) {- return { ok: false, reason: 'PERMISSION_DENIED', message };- }- return { ok: false, reason: 'TRACKING_FAILED', message };-}--export async function startTracking(- app_id: string,- target: GeoTrackingTarget,-): Promise<GeoResult<void>> {- try {- activeClient = geoService(dataSource(target), app_id);- await activeClient.startTracking();- return { ok: true, value: undefined };- } catch (error) {- activeClient = null;- return fail(error);- }-}--export async function stopTracking(): Promise<GeoResult<void>> {- try {- await client().stopTracking();- activeClient = null;- return { ok: true, value: undefined };- } catch (error) {- return fail(error);- }-}+Only write the approved `src/native/geolocation.ts` changes after the preceding+gates pass. Screens import the wrapper, not the control. Require a native platform guard+before lazy imports inside `try`/`catch`; return discriminated results and never+throw. Preserve native capture, durable pending storage, and native upload+without depending on JavaScript being alive. Do not replace native behavior+with JS timers, upload loops, or a made-up adapter contract.-export async function isTracking(): Promise<GeoResult<boolean>> {- try {- return { ok: true, value: await client().isTracking() };- } catch (error) {- return fail(error);- }-}+Use only verified public methods from the installed version. Keep+`geoService(dataSource, app_id)` initialization and the shared tracking owner+together; do not synthesize `stopTracking(app_id)` or `isTracking(app_id)`.+Do not add data sources or tracking side effects to the one-shot wrapper.-export async function getPermissionStatus(): Promise<GeoResult<PermissionStatus>> {- try {- return { ok: true, value: await client().getPermissionStatus() };- } catch (error) {- return fail(error);- }-}+## 5a. Tracking integration guidance-export async function getCurrentLocation(): Promise<GeoResult<LocationData>> {- try {- return { ok: true, value: await client().getCurrentLocation() };- } catch (error) {- return fail(error);- }-}-```--## 4. Usage shape--Integration guidance for the owner; do not edit screens in this helper.--Screens must pass `connectionUrl`, `trackInBackground`, and `persistAcrossRestarts`. Do not pass `tableName` or `fieldMap`; the control uses the default `msdyn_locationrecords` table and default `msdyn_*` field map. `intervalMs`, `distanceFilterMeters`, and `notification` are optional.+Integration guidance for the owner; do not edit screens in this helper. Preserve the installed version's `GeoTrackingTarget` and requested tracking/status/location exports. Screens pass `connectionUrl`, `trackInBackground`, and `persistAcrossRestarts`; do not add `tableName` or `fieldMap` because this control owns its default table/mapping. Use only optional interval/distance/notification properties supported by the installed types. Do not restore an unconditional top-level native import or copy an unverified tracking implementation across package versions.-```ts-const target: GeoTrackingTarget = {- connectionUrl: 'https://org.crm.dynamics.com',- trackInBackground: true,- persistAcrossRestarts: false,-};--await startTracking('my-wrap-app', target);-```--## 5. Type-check and summary+## 6. Validate and summarize```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }@@ -233,14 +193,11 @@ files. Only after the requested artifact contract, table + columns, andTypeScript all pass, return the shared compatibility result and actualcreated/updated/reused paths before reporting:-```text-Geolocation status : READY-Package present : @microsoft/power-apps-native-bglocation-Wrapper : src/native/geolocation.ts-Required config : connectionUrl, trackInBackground, persistAcrossRestarts-Auth : MSAL only-Target table : <TABLE> verified-Native config : not changed-```+Report the mode, resolved release/package version, wrapper path, permission+requirements, ownership decision for tracking, and whether native device+validation was performed. Tracking additionally requires verified table and+columns. Type-check success alone never means native execution is validated.-If table verification failed, report `BLOCKED` or `UNVERIFIED` instead and do not update `memory-bank.md` as if the control is ready.+Update `memory-bank.md` only with completed wrapper work and explicit remaining+limitations. On any failed prerequisite, report `BLOCKED` / `UNVERIFIED`, not+`READY`; do not claim packages, players, or bases are available without evidence.diff --git a/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.mdindex df9b1d5dd..05ae327d5 100644--- a/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/add-pdf-report/SKILL.md@@ -43,15 +43,25 @@ test -f app.config.js && test -f power.config.json && test -f package.json && teIf this fails, tell the user to run `/create-mobile-app` first and STOP.-### 2. Verify packages are already present+### 2. Verify the app's release and packages-`expo-print` is required. `expo-sharing` is optional unless the plan specifically needs sharing behavior.+Read [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)+and [native controls](../references/native-controls.md). Resolve the app before+native mutations; unknown/missing records block even if a dependency is present.```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>' || exit $?node -e "const p=require('./package.json'); const deps={...p.dependencies,...p.devDependencies}; const required='expo-print'; if (!deps[required]) { console.error('MISSING: expo-print is not in package.json. The template/app must already ship it for /add-native pdf-report. This skill will not install it or edit native config. Capability not added.'); process.exit(1); } console.log('OK: expo-print package present'); console.log(deps['expo-sharing'] ? 'OK: expo-sharing package present' : 'OPTIONAL_MISSING: expo-sharing is not in package.json; generated PDFs can be created/viewed/uploaded, but sharing helpers must not be generated.');"```+`expo-print` is required. `expo-sharing` is optional unless sharing is required.+Match exact installed versions/docs/types to the resolved native inventory.+“Present” throughout this helper means verified in that app's release, not just+listed in `package.json` or available in the newest bundled template.+Native preview additionally requires a resolved PDF viewer path; generation+does not establish viewing support.+If `expo-print` is missing, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. Do not add `pdf-report` to the plan or generated wrappers for this app.If `expo-sharing` is missing:@@ -59,7 +69,7 @@ If `expo-sharing` is missing:- Continue for generate-only, native-viewer preview, or Dataverse-upload flows.- Do not import `expo-sharing`.- Do not generate `sharePdfReport(...)`.-- If the user's requirement specifically includes sharing, STOP and say sharing is not supported by this template.+- If the user's requirement specifically includes sharing, STOP and say sharing is not supported by the resolved release.### 2a. Reconcile requested artifacts@@ -94,16 +104,15 @@ Base wrapper when sharing is requested and `expo-sharing` is present:```ts// src/native/pdfReport.ts-import * as Print from 'expo-print';-import * as Sharing from 'expo-sharing';+import { Platform } from 'react-native';export type PdfReportResult =| { ok: true; uri: string; numberOfPages?: number; base64?: string }- | { ok: false; reason: 'EMPTY_HTML' | 'PRINT_FAILED'; message?: string };+ | { ok: false; reason: 'UNSUPPORTED_PLATFORM' | 'EMPTY_HTML' | 'PRINT_FAILED'; message?: string };export type PdfShareResult =| { ok: true }- | { ok: false; reason: 'INVALID_URI' | 'SHARING_UNAVAILABLE' | 'SHARE_FAILED'; message?: string };+ | { ok: false; reason: 'UNSUPPORTED_PLATFORM' | 'INVALID_URI' | 'SHARING_UNAVAILABLE' | 'SHARE_FAILED'; message?: string };export function escapePdfHtml(value: string): string {return value@@ -138,11 +147,15 @@ export async function createPdfReport(html: string,options?: { includeBase64?: boolean },): Promise<PdfReportResult> {+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {+ return { ok: false, reason: 'UNSUPPORTED_PLATFORM' };+ }if (!html.trim()) {return { ok: false, reason: 'EMPTY_HTML', message: 'PDF report HTML is empty.' };}try {+ const Print = await import('expo-print');const result = await Print.printToFileAsync({html,base64: options?.includeBase64 ?? false,@@ -160,11 +173,15 @@ export async function createPdfReport(}export async function sharePdfReport(uri: string, options?: { dialogTitle?: string }): Promise<PdfShareResult> {+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {+ return { ok: false, reason: 'UNSUPPORTED_PLATFORM' };+ }if (!uri || !uri.startsWith('file://')) {return { ok: false, reason: 'INVALID_URI', message: 'Generated PDF reports must be shared from a local file URI.' };}try {+ const Sharing = await import('expo-sharing');const available = await Sharing.isAvailableAsync();if (!available) {return { ok: false, reason: 'SHARING_UNAVAILABLE', message: 'Sharing is not available on this platform.' };@@ -276,9 +293,13 @@ Step 4. Recheck requested generation, sharing, and retention payloads, includingempty HTML, unavailable sharing, print/share failures, and absent required base64.Type-check success alone is insufficient; do not fix screen/generated files.+This does not constitute native device validation.+### 7. Native rebuild note-This skill does not install native code. If `expo-print` or `expo-sharing` was just added outside the skill, the app needs a native rebuild outside this workflow. If the packages were already in the build, Metro hot reload is enough for wrapper edits.+This skill does not install native code or run local native builds. An+out-of-band native package addition blocks compatibility. Use a separately+approved verified-release migration; Metro can update only JavaScript.### 8. Summarydiff --git a/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.mdindex f62fd90f1..c25d3af5b 100644--- a/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/add-pdf-viewer/SKILL.md@@ -1,6 +1,6 @@---name: add-pdf-viewer-description: Internal implementation skill invoked by /add-native for native PDF control workflows. Handles HTTPS and file URI PDF viewing with @microsoft/power-apps-native-pdf-viewer 0.2.9+.+description: Internal implementation skill invoked by /add-native for native PDF viewing through release-matched controls or legacy PDF leaf APIs.user-invocable: falsedisable-model-invocation: trueallowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion@@ -31,14 +31,24 @@ test -f app.config.js && test -f power.config.json && test -f package.json && teIf this fails, tell the user to run `/create-mobile-app` first and STOP.-### 2. Verify package is already present+### 2. Verify the app-matched release and import path```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }-node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pdf-viewer'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } let v; try { v=require('./node_modules/' + m + '/package.json').version; } catch { console.error('MISSING_INSTALL: cannot verify the installed ' + m + ' version. Run the project package install first.'); process.exit(1); } const [major,minor,patch]=v.split('.').map(Number); if (!(major > 0 || minor > 2 || (minor === 2 && patch >= 9))) { console.error('UNSUPPORTED_VERSION: ' + m + ' ' + v + ' does not support file:// URIs. Version 0.2.9+ is required.'); process.exit(1); } console.log('OK: native PDF viewer ' + v + ' supports https:// and file://');"+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'```-If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. Version 0.2.9+ must already be part of the app's native build.+Read [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)+and [native controls](../references/native-controls.md). If resolution fails,+STOP before writing wrappers. Do not install packages, run local native builds,+or edit native config. Check installed docs/types against the resolved native+inventory; file URI support requires the PDF 0.2.9+ contract in the binary.++The example below is conditional on a verified release containing+`@microsoft/power-apps-native-controls/pdf`. For a verified legacy release,+replace only the literal import with `@microsoft/power-apps-native-pdf-viewer`+after confirming that exact leaf/version is included. Do not import the root+aggregate or emit a runtime fallback between packages.### 2a. Reconcile requested artifacts@@ -69,16 +79,20 @@ The wrapper MUST:```ts// src/native/pdfViewer.ts-import { NativePdfViewer } from '@microsoft/power-apps-native-pdf-viewer';+import { Platform } from 'react-native';export type PdfViewerResult =| { ok: true; action?: 'shared' | 'printed' | 'dismissed' }- | { ok: false; reason: 'INVALID_URL' | 'NATIVE_MODULE_MISSING' | 'VIEWER_FAILED'; message?: string };+ | { ok: false; reason: 'UNSUPPORTED_PLATFORM' | 'INVALID_URL' | 'NATIVE_MODULE_MISSING' | 'VIEWER_FAILED'; message?: string };export async function openHttpsPdf(url: string,options?: { title?: string; maxFileSizeMb?: number; cacheEnabled?: boolean },): Promise<PdfViewerResult> {+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {+ return { ok: false, reason: 'UNSUPPORTED_PLATFORM' };+ }+let parsed: URL;try {parsed = new URL(url);@@ -92,11 +106,11 @@ export async function openHttpsPdf(return { ok: false, reason: 'INVALID_URL', message: 'Native PDF viewer supports https:// and file:// inputs only.' };}- if (!NativePdfViewer?.openPdf) {- return { ok: false, reason: 'NATIVE_MODULE_MISSING', message: 'Native PDF viewer module is not available in this build.' };- }-try {+ const { NativePdfViewer } = await import('@microsoft/power-apps-native-controls/pdf');+ if (!NativePdfViewer?.openPdf) {+ return { ok: false, reason: 'NATIVE_MODULE_MISSING' };+ }const response = await NativePdfViewer.openPdf(url, {maxFileSizeMb: 50,cacheEnabled: true,@@ -107,6 +121,9 @@ export async function openHttpsPdf(return { ok: true, action: response.result?.action };}+ if (response.error === 'NATIVE_MODULE_MISSING') {+ return { ok: false, reason: 'NATIVE_MODULE_MISSING' };+ }return { ok: false, reason: 'VIEWER_FAILED', message: response.message ?? response.error };} catch (error: any) {return { ok: false, reason: 'VIEWER_FAILED', message: error?.message ?? String(error) };@@ -146,7 +163,7 @@ if (response.ok) {Notes:- URLs must use `https://` or a non-empty `file://` URI. `content://`, `blob:`, and `http://` are not supported by this skill.-- Use `@microsoft/power-apps-native-pdf-viewer` only for this native PDF viewing use case.+- Use the selected `/pdf` or verified legacy PDF import only for native PDF viewing.- Use `expo-document-picker` for picking/importing/uploading a local PDF or document.- Use `/add-native pdf-report` for generated local PDFs. That helper requires `expo-print` and adds sharing behavior only when `expo-sharing` is already present.- Generated local PDFs from `expo-print` may be opened by native PDF viewer 0.2.9+ as `file://` URIs.@@ -165,9 +182,13 @@ Step 4. Recheck requested inputs/options/actions, invalid URI rejection, missingnative module, and viewer failures. Type-check success alone is insufficient;do not fix screen/generated files.+This does not constitute native device validation.+### 6. Native rebuild note-This skill does not install native code. If the package was just added outside the skill, the app needs a native rebuild outside this workflow. If the package was already in the build, Metro hot reload is enough for wrapper edits.+This skill does not install native code or run local native builds. An+out-of-band package addition is a compatibility block, not proof of support.+Use a separately approved verified-release migration; Metro updates only JS.### 7. Do not use HostingSDK / PCF@@ -189,7 +210,7 @@ Tell the user:```textPDF viewer added-Package present : @microsoft/power-apps-native-pdf-viewer+Release / package : <resolved release and selected package/version>Wrapper : src/native/pdfViewer.tsURL support : HTTPS and file:// (0.2.9+)Type-check : PASS@@ -201,5 +222,5 @@ HostingSDK / PCF : not usedUpdate `memory-bank.md` under `Controls`:```text-- PDF viewer added — @microsoft/power-apps-native-pdf-viewer (<ISO date>)+- PDF viewer wrapper added — <resolved release + selected import/version> (<ISO date>); native device validation: <performed / not performed>```diff --git a/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md b/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.mdindex 541ed2bf7..501e06504 100644--- a/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md+++ b/plugins/mobile-apps/skills/add-native/add-pen-input/SKILL.md@@ -1,6 +1,6 @@---name: add-pen-input-description: Internal implementation skill invoked by /add-native for pen, signature, ink, drawing, and handwriting capture workflows using @microsoft/power-apps-native-pen-input.+description: Internal implementation skill invoked by /add-native for pen, signature, ink, drawing, and handwriting capture using release-matched controls or legacy pen APIs.user-invocable: falsedisable-model-invocation: trueallowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion@@ -31,14 +31,22 @@ test -f app.config.js && test -f power.config.json && test -f package.json && teIf this fails, tell the user to run `/create-mobile-app` first and STOP.-### 2. Verify package is already present+### 2. Verify the app-matched release and import path```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }-node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-pen-input'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m + ' is not in package.json. The template/app must already ship this native extension. This skill will not install it or edit native config.'); process.exit(1); } console.log('OK: pen input package present');"+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'```-If the check fails, STOP. Do not run `npm install`, `npx expo install`, `pod install`, or edit `app.config.js`. This package contains native iOS/Android code and must already be part of the app's native build.+Read [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)+and [native controls](../references/native-controls.md). Unknown/missing release+records STOP native mutation. Match installed public docs/types and native+inventory before using the example. Do not install packages or edit native config.++The example uses `@microsoft/power-apps-native-controls/pen` only when the+verified release contains it. A verified legacy release may instead use the+literal `@microsoft/power-apps-native-pen-input` import if the matching leaf+is included. Never import both, the aggregate root, or a runtime fallback.### 2a. Reconcile requested artifacts@@ -67,26 +75,27 @@ The wrapper MUST:```ts// src/native/penInput.ts-import {- PenInputNative,- PenInputStatus,- PenInputErrorCode,-} from '@microsoft/power-apps-native-pen-input';+import { Platform } from 'react-native';export type PenInputResult =| { ok: true; dataUri: string }- | { ok: false; reason: 'USER_CANCELLED' | 'NATIVE_MODULE_MISSING' | 'CAPTURE_FAILED'; message?: string };+ | { ok: false; reason: 'UNSUPPORTED_PLATFORM' | 'USER_CANCELLED' | 'NATIVE_MODULE_MISSING' | 'CAPTURE_FAILED'; message?: string };export async function captureSignature(options?: {backgroundColor?: string;strokeColor?: string;strokeWidth?: number;}): Promise<PenInputResult> {- if (!PenInputNative?.capturePenInput) {- return { ok: false, reason: 'NATIVE_MODULE_MISSING', message: 'Pen input module is not available in this build.' };+ if (Platform.OS !== 'ios' && Platform.OS !== 'android') {+ return { ok: false, reason: 'UNSUPPORTED_PLATFORM' };}try {+ const { PenInputNative, PenInputStatus, PenInputErrorCode } =+ await import('@microsoft/power-apps-native-controls/pen');+ if (!PenInputNative?.capturePenInput) {+ return { ok: false, reason: 'NATIVE_MODULE_MISSING' };+ }const result = await PenInputNative.capturePenInput({backgroundColor: '#ffffff',strokeColor: '#0078d4',@@ -102,6 +111,9 @@ export async function captureSignature(options?: {return { ok: false, reason: 'USER_CANCELLED' };}+ if (result.error === PenInputErrorCode.NativeModuleMissing) {+ return { ok: false, reason: 'NATIVE_MODULE_MISSING' };+ }return { ok: false, reason: 'CAPTURE_FAILED', message: result.error };} catch (error: any) {return { ok: false, reason: 'CAPTURE_FAILED', message: error?.message ?? String(error) };@@ -153,7 +165,7 @@ Notes:- The result is a PNG data URI: `data:image/png;base64,...`.- Color inputs support `#RGB` and `#RRGGBB`.- Cancel is normal and returns `USER_CANCELLED`; screens should leave current state unchanged and avoid failure banners.-- Use `@microsoft/power-apps-native-pen-input` only for native freehand drawing, ink, handwriting, and signature capture. For unrelated native use cases, use the relevant Expo module or other dependency already present in `package.json`.+- Use the selected `/pen` or verified legacy pen import only for freehand drawing, ink, handwriting, and signatures. Other native use cases require their own resolved package/version and installed public contract.### 5. Optional Dataverse save@@ -195,9 +207,13 @@ Step 4. Recheck requested capture/normalization/storage behavior, including usercancellation, missing native module, capture failure, and Image versus File payloads.Type-check success alone is insufficient; do not fix screen/generated files.+This does not constitute native device validation.+### 7. Native rebuild note-This skill does not install native code. If the package was just added outside the skill, the app needs a native rebuild outside this workflow. If the package was already in the build, Metro hot reload is enough for wrapper edits.+This skill does not install native code or run local native builds. An+out-of-band package addition is a compatibility block. Use a separately approved+verified-release migration; Metro updates only JavaScript, not native modules.### 8. Do not use HostingSDK / PCF@@ -219,7 +235,7 @@ Tell the user:```textPen input added-Package present : @microsoft/power-apps-native-pen-input+Release / package : <resolved release and selected package/version>Wrapper : src/native/penInput.tsOutput : PNG data URIType-check : PASS@@ -231,5 +247,5 @@ HostingSDK / PCF : not usedUpdate `memory-bank.md` under `Controls`:```text-- Pen input added — @microsoft/power-apps-native-pen-input (<ISO date>)+- Pen input wrapper added — <resolved release + selected import/version> (<ISO date>); native device validation: <performed / not performed>```diff --git a/plugins/mobile-apps/skills/add-native/references/native-controls.md b/plugins/mobile-apps/skills/add-native/references/native-controls.mdnew file mode 100644index 000000000..385c60317--- /dev/null+++ b/plugins/mobile-apps/skills/add-native/references/native-controls.md@@ -0,0 +1,88 @@+# Native controls in a verified release++Read the [release lifecycle](../../../shared/references/mobile-release-lifecycle.md)+first. Resolve the existing app, not the newest plugin template:++```bash+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Missing/unknown release records block native mutations. A package manifest,+successful import, or successful TypeScript check does not prove that a player+or wrapped base contains matching native code. Do not install the aggregate to+fix older binaries. Upgrade only through a separately approved, exact verified+release migration.++## Public imports are release-conditional++`@microsoft/power-apps-native-controls` at the root is metadata, not a runtime+barrel. When the resolved release includes the aggregate, use these subpaths:++| Capability | Public subpath | Runtime exports |+|---|---|---|+| PDF viewer | `@microsoft/power-apps-native-controls/pdf` | `NativePdfViewer` |+| Pen/signature | `@microsoft/power-apps-native-controls/pen` | `PenInputNative`, `PenInputStatus`, `PenInputErrorCode` |+| Geolocation | `@microsoft/power-apps-native-controls/geolocation` | `BgLocationClient`, `geoService`, `AuthMethod`, `ConnectionType` |++There is no barcode subpath. Barcode/QR scanning stays with the resolved+release's `expo-camera` wrapper.++Controls **0.2.0** corresponds to PDF **0.2.9**, pen **0.1.9**, background+location **0.2.3**, and extension SDK **0.4.2**, with an **Expo 55 /+React Native 0.83.6** baseline. These are package facts, not a claim that a+verified player/base is available, and not evidence of Expo 57 compatibility.+Read the installed public README, exports, and types for the selected version;+do not infer newer method signatures or copy a different library's examples.++Legacy leaf imports are allowed only when the resolved release actually includes+the matching leaf and version:++- `@microsoft/power-apps-native-pdf-viewer`+- `@microsoft/power-apps-native-pen-input`+- `@microsoft/power-apps-native-bglocation`++Choose one literal module specifier at generation time. Do not emit a dynamic+package-name import, import both paths, or try the aggregate and fall back to a+leaf at runtime. Metro must resolve imports even when an execution branch is+not taken. Native wrappers must guard `Platform.OS` for `ios` / `android`+**before** lazy `import(...)` inside `try`/`catch`. Return explicit unsupported+or failure results; no fake native implementation.++## Native configuration is host/base owned++`enableNativeControls` is host-owned plugin registration, not a consumer+workaround. Use it only on a **verified host release** that supports it, and+only as part of that release's migration. Published host **0.4.0 lacks it**.+Never inject it into an older host or copy native config into an app.++Keep these separate:++1. Package inclusion in JS and the native binary.+2. OS declarations built into the base.+3. Runtime permission grants on the device.+4. Whether the app actually invokes a capability.++Removing controls dependencies, disabling controls, or not calling them does+**not** remove unused default Android permissions. The customer uses a fixed+capability base. Different declarations need another verified base; optional+per-customer permission wrapping is deferred. Missing declarations cannot be+repaired by a runtime permission request.++## Location modes and ownership++A one-shot read uses `new BgLocationClient().getCurrentLocation()` and requires+no `app_id`, data source, target table, or `startTracking`. It still requires a+matching native binary and the appropriate device location grant.++Continuous tracking is a separate workflow. For background-location **0.2.3**,+`startTracking` requests background permissions even with+`trackInBackground: false`; do not advertise a foreground-only permission mode.+Tracking is shared: `stopTracking()` and `isTracking()` have no `app_id`+parameter. Coordinate a single owner across screens/consumers; never stop a+session merely because an unrelated screen unmounts. Do not promise per-app+isolation.++Read that installed version's full `geoService(dataSource, app_id)` contract,+permission behavior, persistence options, and MSAL/Dataverse mapping before+implementing tracking. Do not substitute `configureSync`, `HttpSyncContract`,+or APIs from the unrelated `powerapps-geolocation-control` library.diff --git a/plugins/mobile-apps/skills/check-updates/SKILL.md b/plugins/mobile-apps/skills/check-updates/SKILL.mdindex 3a07c58e3..9e21549b1 100644--- a/plugins/mobile-apps/skills/check-updates/SKILL.md+++ b/plugins/mobile-apps/skills/check-updates/SKILL.md@@ -1,6 +1,6 @@---name: check-updates-description: Use when a Power Apps mobile project needs dependency updates or an npm audit review. Checks the mobile-app plugin first, then updates the native host, other Microsoft packages, and all remaining direct npm packages in order with validation and rollback.+description: Use when a Power Apps mobile project needs dependency updates, template migration, native-host repair, or an npm audit review. Uses published host compatibility and migration metadata before individually approved JavaScript updates, with previews, validation, and rollback.user-invocable: trueallowed-tools: Read, Write, Edit, Glob, Grep, Bash, WebFetch, AskUserQuestionmodel: opus@@ -10,7 +10,17 @@ model: opus# Check Updates (`/check-updates`)-Resolve `<working_dir>` from `--working-dir <path>` or use the current directory. Require `package.json` and `node_modules/`, then run on every invocation. If the user explicitly names one package to update, scope package discovery and mutation to that direct dependency; after Step 1, go directly to the step that owns it. Otherwise process eligible updates one package at a time in Step 2-4 order.+Resolve `<working_dir>` from `--working-dir <path>` or use the current directory. Require `package.json` and `node_modules/`, then run on every invocation. Read [mobile-release-lifecycle.md](../../shared/references/mobile-release-lifecycle.md). If the user names one package, scope discovery to it; a native/runtime package still belongs to Step 2's coupled release, not an independent bump. Explain the coupled changes and ask permission; naming a package does not approve them. Otherwise run Steps 2-4 in order.++The former local diagnostic artifact mode is retired. Never substitute local+archives or a bundled template when a finalized publication is missing.+Snapshot app-owned offline profiles, settings, source and data with the approved+preview, and verify preservation after success or rollback. Validate the selected+SDK's package-owned peer/runtime contract; never force older apps to a hardcoded+SDK version or disable offline to make validation pass. Package checks do not+certify offline synchronization, cold launch or database migration.+If the user asks only to prepare instructions/artifacts for a **later manual**+upgrade, do not invoke this workflow on their app or make a rehearsal copy.Run the steps below in order. Begin the final response with `DONE` when updates complete or are declined, or `BLOCKED` when the workflow cannot continue.@@ -38,6 +48,10 @@ Compare semantic versions. If the public version is newer, make no project changAfter the plugin is current, run this once from `<working_dir>`:+First check for an existing `.tmp/dependency-maintenance/outdated.json` or recovery+snapshot. If present, stop for review/resume rather than overwriting another+attempt. Scope all paths and commands to `<working_dir>`.+```bashmkdir -p .tmp/dependency-maintenancenpm outdated --json --depth=0 > .tmp/dependency-maintenance/outdated.json@@ -45,32 +59,161 @@ npm outdated --json --depth=0 > .tmp/dependency-maintenance/outdated.jsonUse `outdated.json` for Steps 2-4, then delete it before returning. Exit 0 or 1 is valid only when the file contains valid JSON; otherwise return `BLOCKED`. Let npm use the existing registry/auth configuration and never read or print its credentials. Only direct declarations in `dependencies`, `devDependencies`, `optionalDependencies`, and `peerDependencies` are eligible.-Before changing each package, show a one-row table with its package name, current version, declared range, and target version. Then use `AskUserQuestion` with **Update package** and **Skip package** choices; make **Skip package** the recommended default. Only an explicit **Update package** response authorizes that package's mutation. Invoking this skill or a parent skill is not approval. Validate an approved update before presenting the next package. Record skipped packages and continue in order. If the user cancels, delete `outdated.json`, stop without further package changes, and return `DONE` as the literal first line followed by `Dependency updates canceled by user.` If there are no eligible updates, continue without asking.+For `E401`, pause mutations and, with approval, run the app's existing renewal+script or the user-approved credential-provider command against its `.npmrc`.+Preserve project registry routing; do not replace the project `.npmrc` with+user-level configuration or switch feeds to bypass authentication. After renewal,+retry the same reviewed publication. If an install was interrupted, inspect its+project-scoped journal and recovery instructions before resuming.-## Step 2: Update The Native Host+Before changing each **JavaScript-only** package in Steps 3-4, show a one-row table with its package name, current version, declared range, and target version. Then use `AskUserQuestion` with **Update package** and **Skip package** choices; make **Skip package** the recommended default. Only an explicit **Update package** response authorizes that package's mutation. Step 2 instead approves the complete coupled release. Invoking this skill or a parent skill is not approval. Validate an approved update before presenting the next package. Record skipped packages and continue in order. If the user cancels, delete only this invocation's temporary discovery file, stop without further package changes, and return `DONE` as the literal first line followed by `Dependency updates canceled by user.` Do not delete recovery snapshots or interrupted journals.++## Step 2: Offer A Coordinated Native Release Or Host Repair**Telemetry checkpoint: `update_native_host_dependency`**-From the saved outdated data, offer `@microsoft/power-apps-native-host` when a newer stable version exists and it is in scope. Update only that package, preserve its dependency section and exact/`^`/`~` style, then run the validation below. Do not run `upgrade-template`.+Run this step even when the host is absent from `outdated.json`. A manual host update can leave an older template behind. The plan below reads the recorded source state and installed host identity.++Review the saved discovery's `current`, `wanted`, and `latest` host versions and the user's requested supported npm channel; do not repeat discovery or update every runtime package independently. Select one **exact stable published host version**. If the installed host is already current, still inspect that version for a pending template migration. `resolve-mobile-release.js --default` can inspect npm's default host channel, but it is not proof of Player or Wrap availability. Then run:++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" plan \+ --project-root '<working_dir>' --host-version "<exact-host-version>"+```++Planning inspects published package archives with scripts disabled. It reads the host's compatibility profile/migration graph and finds the immutable template with matching recorded requirements and native fingerprints. It does not modify the app or execute package code. There is no separate hand-maintained release array.++Missing protected metadata, unpublished packages, an unfinalized host migration, no matching published template, or an unsupported CLI means `BLOCKED` for native adoption. Do not invent versions, infer native counters from semver, independently install npm `latest`, or copy the plugin template as a fallback. Report the concrete blocker and still offer the read-only direct-advisory audit.++For a patch/minor update with unchanged native requirements, no new Player or base release record is required. A native-changing update requires the host-owned migration and a matching Player for preview. Rely on the existing Player native-version mismatch check; it directs older apps to `/check-updates`. Do not add a routine Play Store/App Store lookup or block upgrade planning on store availability. Only inspect availability when it helps explain a specific mismatch; npm publication alone does not prove availability or a release date. Wrap performs its own selected-base compatibility and availability checks before deployment.++The published planning boundary rejects native transitions without a host major+and an unambiguous template migration. Package producers own version preparation;+use actual published versions, never predicted majors or private test identities.++Interpret the decision:++| Decision | Action |+|---|---|+| `current` | Equal supported targets are valid; no install/migration is needed. Continue with individually approved JS maintenance. |+| `host-repair` | Rehearse the exact host/managed dependency repair. Do not require or fabricate template advancement. |+| `template-upgrade` | Rehearse every migration edge, even if `hostInstallRequired` is false. |+| Downgrade, unknown state, or runtime change without migration | Stop; never backfill metadata or use unsupported `--from-version`/`--json` flags. |++### Preview the entire change before approval++1. Inspect the app's installed host documentation and supported CLI. Check for an active/interrupted upgrade journal **under `<working_dir>`**, never the process's unrelated cwd. Stop for documented recovery; do not delete a journal or reset template state.+2. Show source/target template, host, Expo/RN, Android/iOS runtime requirements/fingerprints, the coupled dependency changes, and required downloads/install scripts. Report Player/base availability separately as verified or unknown; package metadata does not supply binary release evidence. Ask **Prepare isolated preview** or **Skip native release** (recommended). This only authorizes local rehearsal, not changes to the app. Skipping excludes all coupled packages from Steps 3-4.+3. Capture a private local snapshot of the current app (including dirty/untracked app-owned files, instructions, lockfiles, configuration, permissions and absent-file state). Exclude `.git`, `node_modules`, generated native build output, and logs from the rehearsal copy. Do not follow symlinks outside the project or upload the snapshot. Stop if the copy cannot preserve the app safely. No Git reset/checkout/stash.+ Restore the preview's source dependencies from its unchanged lock using the+ reviewed install policy before resolving inherited TypeScript configuration.+ For a standalone npm app, use the path-bound helper:+ `mobile-template-lifecycle.js restore-preview --project-root '<working_dir>' --preview-root '<preview_dir>'`.+ The preview must be outside the source app. Never run bare `npm ci` or+ `npm install` during preview preparation: shells do not preserve a previous+ `cd`, and doing so can replace the source app's dependencies before approval.+ The helper keeps registry/auth context but directs npm writes to the explicit+ preview prefix. Unsupported workspace/package-manager layouts block for review.+ A missing source configuration is a preparation blocker; do not substitute+ target-reference `NODE_PATH` resolution for the source dependency context.+4. Obtain the **exact reviewed target host** in a separate private tooling installation, not by installing it into the old app's dependency graph. Use `mobile-template-lifecycle.js acquire --destination '<reference_dir>' --host-version "<exact-host-version>"` with a new/empty directory. It installs the exact host with lifecycle scripts disabled, seeds the verified release's managed dependencies and overrides to avoid floating optional peers, and checks its npm lock integrity and contained upgrade CLI. Review any required lifecycle scripts separately before approving their execution. This tooling folder is not a scaffolded app; do not run app admission against it or copy its lock over the customer app. Read the installed host's actual `bin["upgrade-template"]` path and supported help; invoke that CLI with `--project '<preview_dir>' --dry-run` to preview one edge. The host owns the app's dependency edits and installation, including the section/spec recorded in the target's `managedDependencies`; an exact installed version does not authorize rewriting a reviewed range. Do not install a new host with incompatible peers into the old dependency set before previewing the coupled migration. Classify output: conflicts block application and need a reviewed resolution; other command failures block investigation. A nonzero preview is never automatically a clean plan.+ Package override conflicts are blocking even when source patches apply. Show+ the retained override and proposed direct dependency, obtain approval for the+ exact resolution, and rerun the preview. Never silently remove customer pins+ or treat npm `EOVERRIDE` as permission to force an install. Test-fixture-only+ pins must be labelled separately from genuine customer customizations.+ Reuse the host's guarded lock regeneration and strict installation; never+ delete the app's lock or `node_modules`, copy the reference lock over it, or+ implement another dependency-repair algorithm in the skill. If the selected+ published host lacks a safe validated installation path, block and request a+ producer fix. Migration authoring, release tagging, runtime preparation and+ Player build scripts are maintainer tools, not customer upgrade steps.+5. For a clean edge, apply it only to the disposable copy with `upgrade-template --project '<preview_dir>'`, including its validated install. Do not use `--no-install` to simulate state advancement. Record every changed/deleted/created file and dependency, plus the actual before/after protected metadata. Require progress without overshoot, then repeat dry-run and apply until the selected target is reached. No target migration is needed for host-only repair. Never reuse approval of one preview for unseen later edges.+6. Re-run `mobile-template-lifecycle.js plan --project-root '<preview_dir>' --host-version "<exact-host-version>"`+ and require `kind: "current"` to confirm the selected host/template/runtime+ state was reached. Do not run strict app admission or add a separate lockfile,+ installed-package or native-inventory verification gate; the host CLI owns+ dependency installation. Use `validate-mobile-files.js --project-root '<preview_dir>' --upgrade-only --file <changed-file>`+ for changed-file policies without that duplicate package admission.+ Expo compatibility, Expo Doctor, TypeScript and platform bundles are mandatory;+ any failure blocks application. Require successful Expo Doctor output from+ this host-owned installation, or run it separately through the approved tooling.+ Surface planning's fingerprint `warnings` without claiming Player/Wrap support.+ Preserve customer instructions/settings and review conflicts rather than+ replacing whole files. An incomplete rehearsal blocks real-app changes.+ Run `mobile-template-lifecycle.js check-sdk --project-root '<preview_dir>'` for+ the Expo check. It binds the actual installed Expo CLI to the explicit app+ directory and scopes `EXPO_OFFLINE=1` to that check only, validating the frozen+ SDK's bundled versions rather than newer online recommendations. Validation is+ not skipped. Do not substitute bare `expo install --check`, use `npx --prefix`+ as a working-directory change, or set offline mode globally. Use this same+ helper against the real app after approved application.+ When Metro/app-startup testing is requested, run the app's own development+ command from its explicit directory and request bundles for the target+ platforms; a responding `/status` endpoint alone does not verify bundling.+ When a client is available, load the intended route and exercise the customer+ workflow. Report bundle and runtime results separately; do not fabricate+ environment/auth configuration to manufacture a successful smoke test.+7. Present the **aggregate full-chain diff**, each edge, conflicts/resolutions, install scripts, expected binaries, and rollback scope. Ask **Apply reviewed release** or **Skip native release** (recommended). Only explicit application approval authorizes real edits.++### Apply only the approved plan++Recheck every source input against the snapshot, including lock/dependency state and the project-scoped journal. Changed inputs invalidate approval and require a new preview. Take the recovery snapshot before the first real edit, then invoke the same verified reference host CLI and migration sequence rehearsed above with the real app's `--project` path. The host performs the coordinated installation; do not separately preinstall the new host into the old app. After every edge compare operations and state with the approved preview and validate before continuing. New operations, conflicts, lack of progress, or unexpected target metadata stop the chain; do not silently extend approval.++On failure restore only touched files from this invocation's snapshot, including deleted/created paths and original modes, without disturbing pre-existing customer changes. Reconcile installed dependencies from the restored lockfile using the reviewed install policy. If rollback or journal recovery cannot complete safely, preserve the snapshot/journal, report both failures, and stop. Never report `DONE` for a partial migration.++After success re-run the metadata-only plan and the same mandatory checks as the rehearsal against `<working_dir>`, passing `--upgrade-only` to changed-file validation. Fingerprint differences remain warnings; deployment retains its separate strict admission. Only a host-validated migration may advance protected template/runtime state; never set it by hand. Update the relevant existing plan/runtime summary, not unrelated memory-bank content. Release approval is not deployment approval.## Step 3: Update Other Microsoft Packages**Telemetry checkpoint: `update_microsoft_dependencies`**-Offer each other outdated direct `@microsoft/*` package separately, preserving its dependency section and version style. Validate each approved package before offering the next one.+Offer each other outdated direct `@microsoft/*` **JavaScript-only** package separately, preserving its dependency section and version style. Exclude the release's managed packages and all native/runtime packages, including `@microsoft/power-apps-native-*`. Unknown native closure requires investigation, not a name-based JS assumption. Validate each approved package before offering the next one.+Use the per-package snapshot, native-drift check and recovery steps below for+these Microsoft JavaScript packages too.## Step 4: Update All Remaining Npm Packages**Telemetry checkpoint: `update_remaining_npm_dependencies`**-Offer each other outdated direct registry package separately, including packages bundled by the template. Preserve its dependency section and version style. Skip non-registry declarations such as file, git, workspace, URL, alias, or tag specs and record them as unmanaged. If an updated package has an exact-version row in `native-app-plan.md` under `### JavaScript Dependencies`, update that row to the same version.+Offer each remaining outdated direct **JavaScript-only** registry package separately. Exclude every managed/native/runtime dependency and any package whose installed transitive closure adds native code. Use the [JS dependency review](../../shared/references/javascript-dependency-planning.md), not the newest bundled template's package names. Skip non-registry declarations such as file, git, workspace, URL, alias, or tag specs and record them as unmanaged. If an updated package has an exact-version row in `native-app-plan.md` under `### JavaScript Dependencies`, update that row to the same version.-For each approved package update:+For each approved JavaScript-only package update in Steps 3 and 4:1. Snapshot `package.json`, existing npm lockfiles, and `native-app-plan.md` when that package will change it under `.tmp/dependency-maintenance/`.+ Before installation, capture the app's actual installed native dependencies+ and protected requirements in this package's recovery directory. The helper+ creates a new local snapshot and refuses to overwrite an existing one.++ ```bash+ node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" snapshot-native \+ --project-root '<working_dir>' \+ --baseline '<working_dir>/.tmp/dependency-maintenance/native-before.json'+ ```++ A failed snapshot blocks installation. This records the current app, not the+ reference template's lock or an approval of native compatibility.2. Install with `--ignore-scripts`; use `--package-lock=false` when the project had no npm lockfile.-3. Run `npm install --ignore-scripts`, `npx --no-install expo install --check`, the project's `type-check` script (or `npx --no-install tsc --noEmit` when TypeScript is declared), and `validate-mobile-files.js` for each changed file. Never run `npx expo install --fix`.-4. If any command fails, restore that package's snapshot, reconcile `node_modules`, return `BLOCKED` with the failed command, and do not offer later packages. Otherwise delete the snapshot and continue.+3. Before accepting the update, compare the actual installation with the saved+ baseline:++ ```bash+ node "${PLUGIN_ROOT}/scripts/mobile-template-lifecycle.js" check-native \+ --project-root '<working_dir>' \+ --baseline '<working_dir>/.tmp/dependency-maintenance/native-before.json'+ ```++ New, removed, changed or relocated native packages, including transitive+ dependencies, and changed native declarations or protected requirements+ block the JavaScript update and require rollback. Do not recapture the+ baseline after installation to make the check pass.+ Also require `mobile-template-lifecycle.js check-sdk --project-root '<working_dir>'`,+ Expo Doctor, the project's `type-check` script (or `npx --no-install tsc --noEmit`+ when TypeScript is declared), and `validate-mobile-files.js --upgrade-only`+ for each changed file (including `package.json`). That file-policy mode does+ not replace `check-native`. Never run `npx expo install --fix`.+4. If any command fails, including `check-native`, restore that package's snapshot, reconcile `node_modules`, return `BLOCKED` with the failed command, and do not offer later packages. Keep `native-before.json` until recovery is verified; otherwise delete it with the successful package snapshot and continue.Do not update transitive packages directly, add overrides, move packages between dependency sections, or use Git to roll back project files.@@ -86,4 +229,4 @@ Report a security finding only when all are true:Ignore string-only `via` rollups. When `fixAvailable` names a different package, include it only as context; never recommend a downgrade based on that graph-level fix.-Remove `outdated.json` and return `DONE` with a concise summary of changed, skipped, current, and unmanaged packages plus direct security findings. Do not include raw audit JSON or transitive package lists. If no direct advisory exists, say so.\ No newline at end of file+Remove this invocation's `outdated.json` and return `DONE` with a concise summary of changed, skipped, current, and unmanaged packages plus direct security findings. Use `BLOCKED` when release evidence, validation, migration, or recovery remains unresolved, even if the read-only audit completed. Do not include raw audit JSON, snapshots, credentials, or transitive package lists. If no direct advisory exists, say so.\ No newline at end of filediff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.mdindex 54a5c0fd4..7d743bd07 100644--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md@@ -39,7 +39,7 @@ and summary.## Fresh-template working-directory mode-This skill assumes the user already has a **fresh** `microsoft/power-platform-skills/plugins/mobile-apps/template#main` template materialized with `degit` in the target working directory and has already run `npm install` there. The skill turns that fresh template into an app; it does not clone, degit, or copy a template itself.+Only after confirming new-app intent through the state routing below, read [mobile-release-lifecycle.md](../../shared/references/mobile-release-lifecycle.md). Discover published template versions through npm, select an exact stable version, and inspect it with `resolve-mobile-release.js --template-version "<exact-template-version>"`. Missing or incompatible published package metadata means `BLOCKED` before scaffolding or data-platform mutations. The helper checks the immutable template against its published host contract; there is no plugin-owned release list. npm channel names, the plugin's bundled snapshot, and a mutable Git branch are not compatibility evidence. Report Player availability separately; if its native runtime differs, offer an explicitly selected compatible template for the new app rather than promising the latest package can run in that Player.**Fresh template required for creation.** If the working directory is not a freshtemplate, STOP creation and follow the state-specific routing below. Do not send@@ -47,6 +47,14 @@ an existing-app edit request to a new folder. Missing generated markers alone donot prove freshness: if the template is customized or its state is unclear, askbefore proceeding. Only a request for a new app requires a fresh template folder.+The former local diagnostic artifact mode is retired. Only a finalized published+template package may scaffold a new app; missing publication is a blocker, not+permission to reconstruct a template or copy a bundled snapshot.++For a new/empty target, offer **Acquire reviewed template** or **Cancel**. After explicit approval, run `mobile-template-lifecycle.js acquire --template-version "<exact-template-version>" --destination '<working_dir>'`. It verifies the immutable package and metadata before using the package's creation CLI. Separately approve dependency installation with the shipped lockfile (`npm ci`); use existing registry authentication, never print/provision credentials here. Do not fall back to `degit` or copy a bundled template on failure.++An existing **fresh installed** template may be used only after `resolve-mobile-release.js --project-root '<working_dir>' --template-version "<exact-template-version>"` succeeds. Preserve its shipped instructions and all compatibility metadata. Never run acquisition over a non-empty directory or adopt an already-created app through this gate.+Resolve the original request before classifying project state. Apply thisstate-routing table once in Step 0, in the order below; file markers aresupporting evidence, not user intent or approval.@@ -55,9 +63,10 @@ supporting evidence, not user intent or approval.|---|---|---|| Creation continuation | Explicit creation-continuation intent or a valid current create handoff for this app, not a request to edit an existing app | Use Step 0's continuation path. Require matching unfinished creation progress and confirm the next phase before continuing; missing or conflicting progress requires clarification, not fresh scaffolding. || Already-created app | Existing-app intent or confirmed app customizations/materialized state, even when generated markers are missing. `memory-bank.md`, `.datamodel-manifest.json`, and `src/generated/services/*.ts` can corroborate state, but do not select creation resume | STOP creation: never re-scaffold it. If the request changes this app, preserve the original request and execute the shared existing-app entry routing; invoke `/edit-app` only after **Full app integration**. If the user wants a separate new app, ask for a fresh template folder. |-| Fresh template | Confirmed new-app intent and a confirmed uncustomized starter; `package.json`, `app.config.js`, `auth.config.json`, and `tamagui.config.ts` exist; `node_modules/expo` exists; no materialized app bindings, `memory-bank.md`, `.datamodel-manifest.json`, or generated Dataverse services. An approved creation plan and its planning artifacts are allowed | Proceed to Step 1 only when every condition is satisfied. Missing generated markers alone do not establish freshness. |-| Template not installed | Confirmed new-app intent and a confirmed uncustomized starter with the required template files, but `node_modules/expo` is absent | STOP: ask user to run `npm install` in the template folder, then rerun. Do not provision ADO npm tokens here. |-| Not template | Confirmed new-app intent in a new/unsupported directory, after excluding existing-app work and creation continuation | STOP: ask user to materialize `microsoft/power-platform-skills/plugins/mobile-apps/template#main` into a new or empty folder with `degit` and run `npm install`; never overwrite existing work. |+| Fresh template | Confirmed new-app intent and a confirmed uncustomized starter; `package.json`, `app.config.js`, `auth.config.json`, and `tamagui.config.ts` exist; `node_modules/expo` exists; no materialized app bindings, `memory-bank.md`, `.datamodel-manifest.json`, or generated Dataverse services. An approved creation plan and its planning artifacts are allowed | Proceed to Step 1 only when every condition is satisfied and the selected published package contract resolves. Missing generated markers alone do not establish freshness. |+| Template not installed | Confirmed new-app intent and a confirmed uncustomized starter with the required template files, but `node_modules/expo` is absent | Offer the separately approved `npm ci` install from its shipped lock, then resolve the package contract. Stop for a missing/mismatched lock; do not provision registry credentials or regenerate native pins here. |+| New/empty directory | Confirmed new-app intent after excluding existing-app work and creation continuation, with no existing customer files | Offer the immutable acquisition described above, then separately approve the shipped-lock installation. |+| Not template | Confirmed new-app intent in a non-empty unsupported directory, after excluding existing-app work and creation continuation | STOP: preserve every file and select a separate empty target. Never re-scaffold existing work or copy a mutable bundled template. || Unclear state or intent | New-app versus edit intent, customization, or creation progress cannot be established | Ask before selecting a workflow. Preserve the directory, plan, and history; do not default to fresh creation or resume. |An approved `native-app-plan.md` alone is not a created-app marker. Creation@@ -223,8 +232,20 @@ itself, so it is written on every creation path after Step 0's routing decision.**Telemetry checkpoint: `validate_fresh_template`**-Before project reads or commands, bind the absolute `working_dir` through-[app-working-directory.md](../../shared/references/app-working-directory.md).+For confirmed new-app intent with a proposed new directory, first bind its+existing parent without creating the target. From the selected existing parent,+run `mobile-template-lifecycle.js destination --destination '<proposed_working_dir>'`+using the installed plugin's absolute script path. This read-only check returns+the canonical parent/destination and rejects a nonempty or invalid target.+Keep those returned paths as the scoped creation context. Only after acquisition+approval may the package CLI create the destination. Then bind the resulting+app root through+[app-working-directory.md](../../shared/references/app-working-directory.md)+before installation, preparation or app/data operations. This exception does+not apply to an existing app or a creation continuation: those must bind the+existing absolute `working_dir` through the same reference before project reads+or commands, and a missing root remains `BLOCKED`.+Apply the state-routing table above once. Classify the original request beforeconsidering a creation resume or testing freshness; do not derive the requestedoperation from the presence or absence of `memory-bank.md`.@@ -292,7 +313,9 @@ Use only a validated phase ID from the recorded creation state. Resolve the CLIbelow before entering the verified phase; do not skip unresolved approval orvalidation gates merely because an older plan exists.-**Do not silently copy a bundled template over the user's folder.** A fresh `plugins/mobile-apps/template` template may contain placeholder `power.config.json` with an empty `environmentId`; Step 5 removes that placeholder immediately before Step 6 runs `pa app init`.+Before continuing or resuming native work, resolve the app against its published host/template contract. Pass its sanitized compatibility context to every planner/builder; do not use the plugin template's current dependencies as the app's inventory.++**Do not silently copy a bundled template over the user's folder.** A fresh template may contain an empty placeholder `power.config.json`; Step 5 removes only that empty placeholder immediately before Step 6 runs `pa app init`. Preserve populated settings even when `environmentId` is empty.**Resolve the Power Apps CLI** (fresh run or resume) before any CLI command — see [cli-binary.md](${PLUGIN_ROOT}/shared/cli-binary.md). Run every command as `$PA …` (`npx --no-install pa …`), never a bare `pa`; on `power-apps`-only projects, translate per its mapping tables. If `PA_KIND=none`, STOP and ask the user to run `npm install` in the template folder. Record the result in the memory bank's `CLI Binary` row once the bank exists (Step 6.7).@@ -685,7 +708,7 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --i### Step 2d — Template-only mode-No background scaffold pipeline is used. The template is already present in `<working_dir>` and dependencies are expected to be installed before this skill starts (`npm install`). Continue directly to Step 3.+No background scaffold pipeline is used. The fresh-template gate must already have provided the reviewed published npm template at `<working_dir>` and its separately approved shipped-lock `npm ci` installation. Reuse that verified project; planning approval does not authorize another acquisition or install. Continue directly to Step 3.### Step 3 — Plan (planner agent + up to 4 applicable approval gates)@@ -1521,6 +1544,7 @@ node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' step --i```This step is template-only and foreground-only. Do not clone/copy templates, do not run background scaffold jobs, and do not use any legacy fallback path.+Acquisition and release resolution must already have passed Step 0.**Print before starting:**> "→ [Step 5/13] Preparing existing Expo standalone template in <working_dir> …"@@ -1534,13 +1558,13 @@ test -d node_modules/expo```If any required template file is missing, STOP:-> "This folder is not a fresh `expo-app-standalone` template. Materialize a fresh template with `degit` into a new folder, run `npm install`, then rerun `/create-mobile-app --working-dir <fresh-template-dir>`."+> "This folder is not a supported fresh template. Return to Step 0 to acquire a reviewed immutable release in a new empty directory."If `node_modules/expo` is missing, STOP:-> "Dependencies are not installed. Run `npm install` in the template folder, then rerun `/create-mobile-app --working-dir <fresh-template-dir>`."+> "Dependencies are not installed. Return to Step 0 for an approved lockfile installation and release validation."If already-created markers appear (`memory-bank.md`, `.datamodel-manifest.json`, or `src/generated/services/*.ts`) and Step 0 did not enter the resume path, STOP. `native-app-plan.md` is expected here because Step 3 writes the approved plan before template preparation:-> "This folder already looks like a created app. For a new app, materialize a fresh `expo-app-standalone` template with `degit` into a new folder and rerun this skill there."+> "This folder already looks like a created app. Use the approved resume path or `/edit-app`; acquire a separate empty directory for a new app."Run the deterministic preparation script once:@@ -1572,7 +1596,10 @@ only recognized legacy example hooks/query-client files, copies shared helpersonly when missing, verifies that TypeScript inherits the host configuration,and structurally verifies the root provider/theme/safe-area contract. Itpreserves custom navigation, existing helper bytes, `offlineProfile`, provider-props, and the template's `@ts-ignore` generation boundaries.+props, and the template's `@ts-ignore` generation boundaries. It must preserve+`app.json` byte-for-byte, including protected `powerappsNative` fields and+app-owned extras, plus `AGENTS.md`, `CLAUDE.md`, and `.github/copilot-instructions.md`.+Do not replace runtime IDs with installed package versions.Preparation also copies missing app-local guidance from `template/AGENTS.md`,`template/CLAUDE.md`, and `template/.github/copilot-instructions.md`. Existing@@ -1701,13 +1728,15 @@ Key points:The current template extends`@microsoft/power-apps-native-host/config/tsconfig`. That host configuration-owns the runtime package paths and the six shared-code aliases:+owns the runtime package paths. Preserve the selected template's explicit+project-rooted aliases when present (including newer templates); do not replace+its entire `compilerOptions`. Older templates inherit the six shared-code aliases:`@/components`, `@/hooks`, `@/utils`, `@/tokens`, `@/generated`, and-`@/native`. The preparation script verifies this inheritance and does not-create a second template-local alias map. Expo Metro consumes the resulting+`@/native`. The preparation script verifies inheritance without deleting+template-local aliases. Expo Metro consumes the resultingeffective TypeScript paths, so no Babel alias plug-in is required.-`<Gradient>` (used by `components/index.tsx`) requires `expo-linear-gradient`. **Assume the upstream template ships it** — do NOT edit `package.json` to add it. If `npm install` (Step 6.5) later reveals the dep is missing, STOP and ask the user to wait for the next template release; do not work around by adding the dep here (same lockdown rule as `/add-native`).+`<Gradient>` (used by `components/index.tsx`) requires `expo-linear-gradient`. Verify it in the resolved release; do NOT install a missing native module to repair an older binary. Missing support blocks this capability and requires another verified release.Do not run `npm install` inside Step 5 — in template-only mode dependencies must already be installed before the skill starts.diff --git a/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md b/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.mdindex 869740147..9f9f06d85 100644--- a/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md+++ b/plugins/mobile-apps/skills/create-mobile-app/references/requirements-discovery.md@@ -14,8 +14,8 @@ Scan the user's description and wizard answers for these signals, then confirm i| "generate PDF", "export report", "print report", "evidence packet", "certificate PDF" | PDF-report capability; retention target is resolved at the architecture gate || "view PDF", "open PDF", "preview PDF" | Native PDF viewer capability for HTTPS URLs or local `file://` URIs with viewer 0.2.9+ || "signature", "sign", "sign off", "approval", "pen", "ink", "draw" | Pen-input capability; storage target is resolved at the architecture gate |-| "track location", "background location", "GPS tracking", "follow route", "breadcrumb", "field worker location" | Geolocation capability (`@microsoft/power-apps-native-bglocation`) + Dataverse location table (default `msdyn_locationrecords`) |-| "current location", "where am I", "tag with coordinates", "one-shot location" | One-shot location capability (`expo-location`) |+| "track location", "background location", "GPS tracking", "follow route", "breadcrumb", "field worker location" | Geolocation capability from the verified release; confirm background declarations and storage at Gate 1 |+| "current location", "where am I", "tag with coordinates", "one-shot location" | One-shot location via the verified controls or Expo location API; no tracking/data-source requirement || "share", "send to", "export" | Sharing capability || "secure", "credentials", "token", "PIN" | Secure-store capability || "assign", "technician", "manager" | Multiple user types |@@ -24,7 +24,7 @@ Scan the user's description and wizard answers for these signals, then confirm i| "Teams", "chat", "message" | Teams connector || "report", "dashboard", "history", "view all" | Read/list screens |-Do not infer capabilities the template does not ship. Resolve every native signal against the live `template/package.json`; if a package is absent or runtime-banned, surface that as a transparency note instead of pretending the capability exists. Use `agents/native-app-planner.md` Step 3.0 as the canonical native allowlist.+Resolve every native signal against the app-version-matched context from `resolve-mobile-release.js`, following [mobile-release-lifecycle.md](../../../shared/references/mobile-release-lifecycle.md). Do not use the newest plugin template as an old app's inventory. If support or fixed-base declarations cannot be verified, block that capability instead of pretending it exists. Follow `agents/native-app-planner.md` Step 3.0 and `/add-native` for version-conditional controls/legacy-leaf routing.Apply the shared[`connectivity-intent-ownership.md`](${PLUGIN_ROOT}/shared/references/connectivity-intent-ownership.md)diff --git a/plugins/mobile-apps/skills/debug-app/SKILL.md b/plugins/mobile-apps/skills/debug-app/SKILL.mdindex ae7bd95a6..f8b359e80 100644--- a/plugins/mobile-apps/skills/debug-app/SKILL.md+++ b/plugins/mobile-apps/skills/debug-app/SKILL.md@@ -177,6 +177,12 @@ No unbounded redispatch: repeated setup failures consume the same attempt budget### 0.preflight Read project context+Compare the app's required native counter with the selected Player's actual+supported counters when that evidence is available. Report both on mismatch;+offer an approved `/check-updates` migration or a verified matching Player,+never a counter rewrite or first-party package patch. Package metadata alone+does not prove device execution or offline synchronization.+Follow the shared instructions before diagnosing logs:Use `workingDir` from argument parsing as `<working_dir>` throughout this workflow. It is already validated as an app root; do not derive it again from a later phase or silently switch projects.@@ -245,6 +251,11 @@ Branch as follows:| No log exists and the logging form is unavailable | This project predates project-local Metro logging or has incomplete dependencies. Enter startup diagnostics to distinguish broken install, unsupported export, and config mismatch; do not edit native/Metro config or loop on restarts. || No log exists and the current factory or legacy direct logging form resolves | If available host output contains `[powernative] Metro logging instrumentation failed`, preserve that bounded evidence. Enter startup diagnostics rather than assume a package defect or require the app to load first. |+Startup diagnosis does not authorize copying the newest template or host over+the app. Resolve native requirements against the app's package-owned contract+and route a necessary migration to `/check-updates`. Missing verified support+blocks native mutations, not read-only startup diagnosis.+The PID/port check prevents stale-log diagnosis: a log file can outlive its Metro process, so only the socket probe reveals that the log stopped belonging to the app under test. The explicit choice prevents a valid session on one port from being confused with another valid session in the same project.If no `.powernative` log exists but the host exposes a live Metro terminal, use@@ -982,6 +993,31 @@ Append to `.powernative/debug-app/fixes.md`:These recipes apply to errors classified as "Import / Bundle" in Step B. They are read from the persisted `.powernative` Metro log. Each recipe is opinionated: take the action listed if its precondition matches, otherwise fall through to the next.+**Release-aware diagnosis.** Read+[release lifecycle](../../shared/references/mobile-release-lifecycle.md) and+resolve the app read-only before attributing native import/module/ABI failures:++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Use only the sanitized tuple in diagnostic handoffs. The newest bundled+template is not this app's runtime allowlist. Unknown/missing records block+native mutations, not source-only diagnosis and fixes; mark native compatibility+unverified. User consent to a dependency install does not waive this gate.+Never install controls, a native leaf, Expo, or a newer host to fix an older+player/base; route verified-release migrations to `/check-updates`.++For controls, read [the conditional contract](../add-native/references/native-controls.md):+the root is metadata, `/pdf`, `/pen`, and `/geolocation` are public runtime+subpaths, and there is no barcode subpath. Use a leaf only when its matching+version is in the resolved release. Native wrappers guard the platform before+lazy imports. A missing native module or OS declaration is not solved by a JS+fallback, runtime grant, or `enableNativeControls` on host 0.4.0 (unsupported).+Package inclusion, declarations, grants, and use are separate; disabling+controls does not remove default Android permissions.+Before applying any recipe, run the first-party native package ownership gate when the cited source/importer or failed internal import is under `node_modules/@microsoft/power-apps-native-*`. A confirmed package-owned defect routes to `/report-issue`; never repair it with a resolver alias, copied source, patch, postinstall rewrite, or replacement dependency.| Error pattern | Precondition | Action |@@ -989,8 +1025,8 @@ Before applying any recipe, run the first-party native package ownership gate wh| `SyntaxError: <file>:<line>:<col>` in `app/`, `src/components/`, `src/hooks/`, `src/services/` | The cited line is in editable user code (NOT `src/generated/`, NOT `node_modules/`) | `Read` the file around the cited line (±10 lines), identify the syntactic issue (unclosed JSX tag, missing closing brace/paren, stray comma, missing `from` in import, unterminated string, missing semicolon between statements), apply a single minimal `Edit`. Do NOT reformat surrounding code. || `SyntaxError` in `src/generated/` | Cited file is under `src/generated/` | **Do not edit.** For `connectorSchemas.ts`, regenerate the runtime map. For services/models, resolve the existing registration and hand off to `/add-connector` or `/add-dataverse` with `--refresh --data-source-name "<registered-name>"`, the absolute app root, and approved scope for targeted CLI refresh and validation. Check the approved plan first: a removed source needs consumer cleanup through `/edit-app`, not re-registration. Missing/ambiguous registrations block refresh; do not fall back to addition. || `Unable to resolve module <name>` from `<importer>` | `<name>` starts with `.` or `..` (relative import) | `Glob` the importer's directory for files matching `<name>` with any extension (`.ts`, `.tsx`, `.js`, `.jsx`, `.json`). If found with a different extension → fix the import to drop the extension OR match the actual one. If found with a typo (Levenshtein ≤ 2) → fix the typo. If not found at all → the file genuinely doesn't exist; surface to user and ask whether to create it or remove the import. |-| `Unable to resolve module <name>` | `<name>` is a bare package AND not present in `package.json` `dependencies` / `devDependencies` | Follow [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) to classify the published package by contents, not its name. If native-bound and absent from the template, report that a template/runtime update is required. If verified pure JavaScript, ask consent for the exact version, install with `npm install --save-exact`, validate, and retry. Do NOT install without consent. |-| `Unable to resolve module <name>` | `<name>` IS in `package.json` but the bundle still fails | Run the targeted startup inspection before blaming cache: compare locked/installed versions and resolve the exact entry point. Restore only with approval when installation is broken; unsupported exports or native build mismatches need different remedies. |+| `Unable to resolve module <name>` | `<name>` is a bare package AND not present in `package.json` `dependencies` / `devDependencies` | Follow [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) to classify the published package by contents, not its name. If native-bound and absent from the app's verified runtime, report that a template/runtime update is required; unresolved classification also blocks installation. If verified pure JavaScript, ask consent for the exact version compatible with this app, install with `npm install --save-exact`, validate, and retry. Do NOT install without consent. |+| `Unable to resolve module <name>` | `<name>` IS in `package.json` but the bundle still fails | Run the targeted startup inspection before blaming cache: compare locked/installed versions, resolve the exact entry point, and check the app-matched release. Restore only with approval when installation is broken; unsupported exports, controls root/subpath mismatches or native build mismatches need different remedies. || `transform failed` referencing a babel plugin (e.g., `[BABEL] ... unknown plugin "react-native-reanimated/plugin"`) | Error references `babel.config.js` | **Hand-off.** `babel.config.js` is project config (same constraint that protects `app.config.js`). Print the cited plugin and suggested fix order (e.g., "`react-native-reanimated/plugin` MUST be the LAST plugin in `babel.config.js` `plugins` array"); skip to next issue. || `transform failed` without a babel reference | Generic transform failure (often a TS feature Metro's transformer can't handle) | Read the cited file, look for syntax that requires a specific TS lib (e.g., decorators, top-level await). If the issue is a known-bad pattern, surface and ask before fixing. Otherwise hand-off. || `predev` script failure (e.g., `npm run generate-schemas` errored before `expo start` ran) | Output shows failure before Metro started | Use startup diagnostics to identify the failed stage (installation, config, schema generation, or type-check). Do not assume a connector problem or edit `power.config.json` directly. |@@ -1105,6 +1141,13 @@ Do NOT attempt a third automated fix for the same error. Wait for user guidance.## Constraints+- **Native compatibility is fail-closed.** Resolve the existing app and use its+ installed public contracts. Do not mutate native dependencies/config or run+ local native builds, even with consent to an unrelated JS fix. No newest+ template allowlist, fabricated verified release, or runtime fallback for a+ missing native package. Optional permission wrapping remains deferred.+ Never rewrite `app.json` → `expo.extra.powerappsNative` requirements to make+ the resolver accept a mismatched installation.- **Never fix native config files** (`app.config.js`, `app.plugin.js`, `Podfile`, `build.gradle`, `gradle.properties`) — report the error to the user with the exact line and a suggested manual action.- **Startup restoration is not an upgrade.** Only the approved same-lock restoreand bounded Metro retry in the startup reference are allowed exceptions.diff --git a/plugins/mobile-apps/skills/deploy/SKILL.md b/plugins/mobile-apps/skills/deploy/SKILL.mdindex acb4b4bf7..0890b3872 100644--- a/plugins/mobile-apps/skills/deploy/SKILL.md+++ b/plugins/mobile-apps/skills/deploy/SKILL.md@@ -14,7 +14,11 @@ model: sonnetBuilds the mobile app in the current directory and pushes it to the Power Platform environment recorded in `power.config.json`.-This skill uses the standard 4-step deployment flow for this plugin: check memory bank, build, deploy, then update memory bank.+This skill checks the app-matched verified release and actual selected bases+before building and pushing. Read+[release lifecycle](../../shared/references/mobile-release-lifecycle.md).+Native compatibility is a separate gate from artifact format, environment+confirmation, offline coverage, and TypeScript.## Out of scope (deliberately)@@ -24,7 +28,7 @@ This skill uses the standard 4-step deployment flow for this plugin: check memor## Workflow-1. Check memory bank → 1.5 App ID preflight → 2. Build → 2.4 Native package → 2.5 Offline profile coverage gate → 3. Deploy → 4. Update memory bank+1. Check memory bank → 1.2 Verified release + selected bases → 1.5 App ID preflight → 2. Build → 2.4 Native package → 2.5 Offline profile coverage gate → 3. Deploy → 4. Update memory bank---@@ -38,6 +42,56 @@ Read `memory-bank.md` from the project root if present. Capture:If absent, continue — the project may have been created without the plugin. Re-derive env from `power.config.json` if needed.+### Step 1.2 — Verified release and actual intended bases++Reject any `--diagnostic-artifacts` selection or `local-diagnostic-only` context+before building or pushing. Local test archives and APK metadata never authorize+tenant/store deployment, even when their hashes and counters match. Do not+silently replace the selection with a published/default release.++Resolve the app's installed/locked template, host, Expo, React Native, and+native inventory; never use the newest bundled template as its runtime allowlist.++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Then obtain the **actual intended base version, native runtime version and fingerprint** for each target+from the selected deployment target's verifiable metadata. Do not silently+substitute the policy's expected values, assume “latest”, or claim a player/base+is available because its package exists on npm. Missing selection is a blocker.+If the target cannot expose these values, STOP; a version label alone does not+prove matching native runtime content.++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>' --platform android --base-version "<actual-intended-android-base-version>" --base-fingerprint "<actual-intended-android-base-fingerprint>" --base-runtime-version "<actual-intended-android-runtime-version>" || exit $?+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>' --platform ios --base-version "<actual-intended-ios-base-version>" --base-fingerprint "<actual-intended-ios-base-fingerprint>" --base-runtime-version "<actual-intended-ios-runtime-version>" || exit $?+```++Every resolver invocation must succeed. Unknown/missing package contracts or base metadata+STOP before build/push. npm publication does not attest regional base availability;+that selection and publication check belongs to Wrap, not a skills catalogue.+Each deployment check requires `--platform`, `--base-version`, and+`--base-fingerprint` together, plus `--base-runtime-version`. The native runtime+and fingerprint must exactly match the published host contract; a missing or mismatched fingerprint blocks.+`--requirements-only` is planning-only and cannot authorize deployment.+There is no `deploy without compatibility` override. A successful web preview,+Metro run, native import, or Hermes magic check is not evidence of native+compatibility. A newer plugin/template is not an app upgrade.++Keep only the sanitized resolved tuple and selected base versions/fingerprints in the+deployment summary; never dump raw app/auth/config files. Re-run these checks+before each push and after any manifest, lockfile, host, native inventory, or+base selection change, including the first-deploy second pass.++Package inclusion, OS declarations, runtime grants, and actual use remain+distinct. Disabling controls does not remove unused default Android permissions.+Different declarations require another verified base; optional per-customer+permission wrapping is deferred. Do not edit plugins/permissions or run a local+native build to bypass a mismatch.+### Step 1.5 — App ID preflight (first-deploy gate)Read `power.config.json` **before building anything**:@@ -83,7 +137,8 @@ If `package.json` has no `build` script, fall back to:npx --no-install expo export --platform web```-(The current template does not define a `build` script, so this fallback is the normal path for freshly scaffolded apps. Both forms produce the same `dist/` web output.)+(Use the resolved app's scripts, not assumptions about the newest template.+Both forms produce `dist/` web output, not a new native binary.)**Known issue — `expo export --platform web` never exits.** The export finishes its work (writes `dist/`, prints `Exported: dist` and the asset count) and then **hangs indefinitely**. Reproduced deterministically across separate runs; observed still alive 2h34m after completing. `dist/` is complete and correct when this happens. Suspected cause: the Metro config returned by `createPowerAppsMetroConfig` (`metro.config.js`) installs a dev-server middleware internally, which appears to hold an open handle — a web *export* should not need a dev server. Note the template itself only calls `createPowerAppsMetroConfig`; the middleware is applied inside `@microsoft/power-apps-native-host`, not in app code. **Not yet root-caused.**@@ -121,12 +176,15 @@ Verify `dist/` exists with `index.html` before continuing.**Print before starting:**> "→ Compiling the native Hermes bundle and hash-addressed asset package for iOS and Android. No JavaScript is compiled inside the wrap pipeline — it only consumes these prebuilt files. ~1–3 minutes."-**Node version gate (required).** The native export crashes on **Node < 20.19.4** — it hits `util.styleText(['yellow','inverse','bold'], …)`, which older Node rejects, failing the Metro bundle with a cryptic `ERR_INVALID_ARG_VALUE`. Check first:+**Node version gate (required).** Follow+[version-check.md](../../shared/version-check.md) and any higher engine+requirements of the resolved release. Check the common Node 22+ floor first:```bash-node -e 'const [M,m,p]=process.versions.node.split(".").map(Number); const ok = M>20 || (M===20 && (m>19 || (m===19 && p>=4))); if (!ok) { console.error(`Node ${process.versions.node} is too old; need >= 20.19.4`); process.exit(1); } console.log(`✓ Node ${process.versions.node}`);'+node -e 'const major=Number(process.versions.node.split(".")[0]); if (major < 22) { console.error("Node 22+ required; also check resolved release engines"); process.exit(1); }'```-If it exits non-zero, STOP and tell the user to switch (`nvm use 20.19.4`, or install Node ≥ 20.19.4) and rerun. Do **not** run the native packaging commands on older Node.+If this or a release-specific engine check fails, STOP and ask the user to+switch to a supported Node version. Do not fetch newer native dependencies.The web build above produces `dist/index.html` (the hosted Code App). Native **wrapped** apps additionally need a precompiled Hermes bundle **and** the customer's images/fonts as hash-addressed asset files, so the wrap pipeline never compiles or downloads JavaScript. Produce both platforms:@@ -146,6 +204,10 @@ These sit alongside `index.html` under the same container SAS, so the wrap pipel**Verify before continuing** — STOP on any failure (never push a web-only build for a native-wrapped app):+This checks packaging only. Hermes magic bytes identify the file format, not+bytecode/engine ABI, Expo/RN, native module, player, or selected-base+compatibility; Step 1.2 must also pass for both platforms.+```bash# Hermes magic bytes on both bundles (expect c61fbc03)for f in dist/index.android.bundle.hbc dist/main.jsbundle.hbc; do@@ -209,6 +271,10 @@ Do not push until the gate is resolved (reconciled to `in-sync`, or explicitly o**Telemetry checkpoint: `push_app_to_power_platform`**+Re-run Step 1.2 for the app and both actual intended base versions and+fingerprints before this push. Neither the environment override nor the+offline override can waive it.+**Resolve and confirm the target environment FIRST.** `pa app push` deploys to the environment configured in `power.config.json`. Resolve that ID to a Dataverse URL so the user catches drift before pushing.Run:@@ -258,7 +324,7 @@ If deploy fails, report the error and STOP — do not retry silently. Common fix|---|---|| `pa app push` auth error, wrong user, or multiple accounts | Follow shared-instructions command-failure handling. `az login` / `az account set` does not switch the standalone Power Apps CLI account. || Environment mismatch | Re-run `$PA app init -t MobileApp --display-name <name> --environment-id <id> --non-interactive` in a fresh/app root for the intended target|-| `$PA` is empty (`PA_KIND=none` — CLI not installed) | Ask the user to run `npm install` in the project root (the template pins `@microsoft/power-apps-cli`), then re-resolve `$PA` per [cli-binary.md](${PLUGIN_ROOT}/shared/cli-binary.md). Never fall back to a bare `npx pa` or `npx power-apps`. |+| `$PA` is empty (`PA_KIND=none` — CLI not installed) | Ask the user to restore the resolved release's existing exact locked dependencies in the project root, then re-resolve `$PA` per [cli-binary.md](${PLUGIN_ROOT}/shared/cli-binary.md). Never fall back to a bare `npx pa` or `npx power-apps`, a newer host/native package or an unrelated global CLI. |### Step 4 — Update memory bank@@ -268,6 +334,8 @@ If `memory-bank.md` exists, increment the version (`v1.0.0` → `v1.1.0`) and up- Last deployed timestamp- App URL (if captured)- Append a row to the **Build history** section: `| v1.1.0 | <timestamp> | deploy | success |`+- Record the sanitized verified release tuple and both actual selected base+ versions/fingerprints; record native device validation separately from packaging success.Print the summary card:diff --git a/plugins/mobile-apps/skills/edit-app/SKILL.md b/plugins/mobile-apps/skills/edit-app/SKILL.mdindex da997bbf0..bf31f21af 100644--- a/plugins/mobile-apps/skills/edit-app/SKILL.md+++ b/plugins/mobile-apps/skills/edit-app/SKILL.md@@ -247,7 +247,7 @@ This is a focused edit workflow, not a lighter quality bar. Reuse `/create-mobil| Navigation/routes | Navigation/layout gate, route contract check, final `tsc` || New screen | Shared scaffold gate, skeleton gate, screen-builder wave gate, style-quality sweep, route check, final `tsc` || Existing screen TSX | Screen edit gate, style-quality sweep, route check when navigation changed, final `tsc` |-| Native capability | Native allowlist gate, wrapper existence gate, final `tsc` |+| Native capability | App-matched verified release/native inventory gate, wrapper existence gate, final `tsc` (not native validation) || Pure-JavaScript dependency | Approved exact-version dependency table, package-content gate, package validation, final `tsc` || Design/component/density | Design-system gate, affected-screen style sweep, final `tsc`, preview || Application Insights configuration only | Valid `app.json`, provider `appConfig` wiring, final `tsc` only if `app/_layout.tsx` changed |@@ -275,6 +275,27 @@ Immediately run the edit documentation protocol's `temp` command and bind its re`directory`, `progress`, `progressHtml`, and `sync` paths as `<edit-temp-dir>` values before anyinferred-plan sync or progress write below.+Read [release lifecycle](../../shared/references/mobile-release-lifecycle.md).+Resolve the existing app, not the newest bundled template:++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++Keep its sanitized resolved context for every planner/builder handoff and+native helper. Unknown/missing release records block native mutations, not+existing pure source/UI planning and editing. For source-only work, inspect+installed contracts and mark native compatibility unverified. Do not claim+that preview or TypeScript validates a player/base.++Native/host/Expo upgrades are a separate approved `/check-updates` migration to+an exact verified release. Do not silently upgrade an existing app, install the+controls aggregate to fix an older binary, or copy current template config.+`--plan-only` may describe blocked native work, but does not authorize applying it.+Preserve `app.json` → `expo.extra.powerappsNative` template/runtime requirements.+Never backfill unknown state from installed packages or a plugin snapshot.+```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }test -f native-app-plan.md && echo "OK: plan found" || echo "INFO: plan will be inferred"@@ -478,7 +499,7 @@ Loophole checks before continuing:consult the `/add-datasource` routing table read-only and resolve the choicebefore approval. Execute the selected leaf only in Step 5.- If a screen requires a native wrapper, run `/add-native` before screen-builders import `src/native/*`.-- If a native capability is not shipped by the template, stop with a clear block; do not install native packages or fake support.+- If a native capability/version is absent from the app's resolved release, stop with a clear block; do not install native packages or fake support.- If a screen requires a pure-JavaScript library, add it with an exact version to `## Screens → ### JavaScript Dependencies`, include it in the mutation preview, and install it before screen builders run. Determine JS-only status from shipped contents, not from a package-name prefix.- If the request changes navigation, update route layouts and navigation contracts before spawning screen-builders.- If the request adds a new screen, generate any needed route folder, generated-service snapshot, shared code, and skeleton before building TSX.@@ -623,6 +644,7 @@ Prompt:Current section content: <verbatim>Working directory: <absolute path>Plugin root: ${PLUGIN_ROOT}+ Release context: <sanitized resolved tuple, or explicit unresolved/source-only status>Phase: planningProposal only: <true for --plan-only or a planning-phase caller>@@ -661,6 +683,26 @@ Run `progress --json-file` after writing this payload and before changing `approFor Native Capabilities (no separate agent), do it inline: read the current capability table, apply the change, regenerate the table. For PDF/pen rows, include storage/output notes in the table or immediately below it:+Read [conditional native controls](../add-native/references/native-controls.md).+Use `/pdf`, `/pen`, and `/geolocation` only when the resolved release contains+the aggregate; its root is metadata. Legacy leaves require matching resolved+inventory. There is no barcode subpath. Controls 0.2.0 uses the Expo 55 /+React Native 0.83.6 baseline, not Expo 57. Host-owned `enableNativeControls`+registration requires a verified supporting host release; published host 0.4.0+lacks it. Never change config to make an unavailable API appear supported.++Keep package inclusion, OS declarations, runtime grants, and actual use+separate. Removing controls dependencies does not remove unused default Android+permissions. Different declarations require another verified base; optional+permission wrapping is deferred.++One-shot location via `new BgLocationClient().getCurrentLocation()` needs no+`app_id`, data source, table, or `startTracking`. Background-location 0.2.3+tracking requests background permissions even with `trackInBackground: false`;+tracking is shared and `stopTracking()` / `isTracking()` have no `app_id`.+Plan a coordinated owner, not a stop-on-unmount behavior. Read installed+docs/types; do not use the unrelated `configureSync` / `HttpSyncContract` API.+- `native-pdf-viewer` 0.2.9+ opens HTTPS URLs and local `file://` URIs; it does not support `content://`, `blob:`, or `http://`.- `pdf-report` generates a local PDF only when `expo-print` is present; local output may be opened by `native-pdf-viewer` 0.2.9+, shared with `expo-sharing` when present, or uploaded to Dataverse File storage.- `pen-input` returns a PNG data URI; cancellation is a non-error state; Dataverse target must be Image, File, or child Evidence/Signature row.@@ -785,6 +827,11 @@ plan. Pass `MOBILE_APP_ORCHESTRATING=1` and the explicit implementation contextabove on each handoff, including through routers and on retries. Reuse suppliedanswers, and return to the approval gate if an unresolved choice changes scope.+Before any native wrapper/control mutation, re-resolve the release if inputs+changed and require the native inventory gate to pass. Forward the same+sanitized context to all screen-builder waves. Never replace the gate with a+package-name presence check; missing/unknown records remain a hard block.+0. **Environment drift gate for data edits** — before Dataverse, SharePoint, connector, or sample-data work, compare `memory-bank.md`, `power.config.json`, and `.resolved-environment.json`. If they disagree, show the values and ask the user which environment is intended. Do not create tables or connections until confirmed.1. **Data Model** — invoke `/add-dataverse --skip-planning` with the approveddelta and the scoped planning context below, not every row in the plan.@@ -807,7 +854,7 @@ answers, and return to the approval gate if an unresolved choice changes scope.handles empty states; never report complete seed coverage.3. **Connector/Data Source** — read and execute `/add-datasource` when ambiguous, or `/add-sharepoint` / `/add-connector` for approved connector changes. For a retained source refresh, pass skill-only `--refresh --data-source-name "<registered-name>"` with its verified identity in `approved_scope`; do not route refreshes through addition. Use the same refresh branch for service-only Dataverse repairs without schema changes. Regenerate services and record connection notes in `memory-bank.md`.4. **Pure-JavaScript Dependencies** — execute the Installation Contract in [`shared/references/javascript-dependency-planning.md`](${PLUGIN_ROOT}/shared/references/javascript-dependency-planning.md) for new or changed rows in the approved `## Screens → ### JavaScript Dependencies` table. Approval is consent for those exact packages and versions. Install and validate before screen work; if final inspection finds native code/config or incompatible runtime dependencies, remove only the newly added package and stop with the exact failed criterion.-5. **Native Capabilities** — read and execute `/add-native <capability>` for every new capability. Do not install missing native packages or fake wrappers. If a capability is unsupported by the current template, stop before rebuilding screens that import it, record the block, and tell the user what upstream template support is missing.+5. **Native Capabilities** — read and execute `/add-native <capability>` for every new capability, with the same resolved release context. Do not install missing native packages or fake wrappers. If support is absent/unverified for this app's release, stop before rebuilding consuming screens and record the missing release/native evidence.6. **Design** — read and execute the approved `/design-system` operation (refresh,reskin, theme, or rollback). Include `CODE_APPS_NATIVE_ORCHESTRATING=1` inthe child environment to suppress intermediate browser tabs, alongside thediff --git a/plugins/mobile-apps/skills/preview-screens/SKILL.md b/plugins/mobile-apps/skills/preview-screens/SKILL.mdindex c64536499..5089179db 100644--- a/plugins/mobile-apps/skills/preview-screens/SKILL.md+++ b/plugins/mobile-apps/skills/preview-screens/SKILL.md@@ -41,7 +41,7 @@ Determine the working directory:Validate the project:```text-Glob pattern="power.config.json" path="<working_dir>"+Glob pattern="power.config.json" path='<working_dir>'```If missing, check for `package.json`. If neither exists, report the error and stop.@@ -61,7 +61,7 @@ Fallback: read `name` from `package.json`.Find all TSX files under the app directory:```text-Glob pattern="app/**/*.tsx" path="<working_dir>"+Glob pattern="app/**/*.tsx" path='<working_dir>'```**Exclude** these patterns — they are not screens:@@ -119,7 +119,7 @@ Internalize:Also check if the project has custom brand tokens:```text-Glob pattern="tamagui.config.ts" path="<working_dir>"+Glob pattern="tamagui.config.ts" path='<working_dir>'```If found, read it and extract any custom color tokens (look for `tokens: { color: { ... } }`). Add them as additional CSS custom properties in the generated HTML.diff --git a/plugins/mobile-apps/skills/report-issue/SKILL.md b/plugins/mobile-apps/skills/report-issue/SKILL.mdindex 6d9daadad..121c3ebae 100644--- a/plugins/mobile-apps/skills/report-issue/SKILL.md+++ b/plugins/mobile-apps/skills/report-issue/SKILL.md@@ -50,10 +50,8 @@ Read-only checks:```bashtest -f power.config.json && echo "in_project=true" || echo "in_project=false"-pwdnode --versionnpm --version-node scripts/resolve-environment.js "$(node -e \"console.log(require('./power.config.json').environmentId)\")" 2>/dev/null || trueaz --version 2>/dev/null | head -1npx --no-install expo --version 2>/dev/nulluname -srm@@ -62,13 +60,42 @@ uname -srmIf in a project:```bash-node -e "console.log(require('./package.json').name, require('./package.json').version)" 2>/dev/null-node -e "console.log(JSON.stringify({env: require('./power.config.json').environmentId, name: require('./power.config.json').displayName}))"test -f memory-bank.md && echo "memory_bank=present"test -f native-app-plan.md && echo "plan=present"-ls src/generated/services/ 2>/dev/null | head -10+node -e "const fs=require('node:fs');const p='src/generated/services';let count=0;try{count=fs.statSync(p).isDirectory()?fs.readdirSync(p).filter(f=>f.endsWith('.ts')).length:0;}catch{}console.log('generated_service_count='+count);"```+Read [release lifecycle](../../shared/references/mobile-release-lifecycle.md).+For a mobile project, collect only the resolver's sanitized tuple:++Do not attach package archives, binaries, local paths, source profiles or private+build evidence to a public issue. Report only verified compatibility facts;+reporting still works when package or device evidence is unavailable.++```bash+cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }+node "${PLUGIN_ROOT}/scripts/resolve-mobile-release.js" --project-root '<working_dir>'+```++If the affected workflow supplied actual selected base versions and fingerprints,+check them read-only using `--platform android|ios`,+`--base-version <actual-intended-version>`, and+`--base-fingerprint <actual-intended-fingerprint>`, and+`--base-runtime-version <actual-intended-runtime-version>`. A version-only deployment+check blocks. Collect actual target metadata, never copy expected policy values.+Record unknown/missing evidence honestly; reporting must still work when the+package contract cannot be resolved. Do not infer the runtime from the newest bundled template,+claim a published package proves player/base availability, or mutate native+dependencies to make diagnostics pass.++For controls, identify the selected `/pdf`, `/pen`, or `/geolocation` contract+and matching release/leaf version using+[native controls](../add-native/references/native-controls.md). The aggregate+root is metadata, not a runtime API. Separate package inclusion, OS declarations,+runtime grants, and app usage in the reproduction. No raw app/auth config,+credentials, private repository links, package code, customer names, tenant,+environment, app, or connection IDs belong in this public issue.+If the description names a package matching `@microsoft/power-apps-native-*`, collect its declared and lockfile-resolved versions from `package.json` and `package-lock.json`. Do not read package source or metadata from `node_modules/`.```bash@@ -87,20 +114,18 @@ for (const [name, declared] of Object.entries(dependencies)) {NODE```-For native-build issues also capture:--```bash-[ "$(uname)" = "Darwin" ] && xcode-select -p-[ "$(uname)" = "Darwin" ] && pod --version 2>/dev/null-java -version 2>&1 | head -1-echo "ANDROID_HOME=$ANDROID_HOME"-```+For native runtime issues capture the platform and user-supplied player/base+version. Do not run or probe local Xcode, CocoaPods, Gradle, or JDK builds.### Step 3 — Collect diagnostics**Telemetry checkpoint: `collect_issue_diagnostics`**-Run `npx --no-install expo doctor` and capture the text output verbatim.+Run read-only project diagnostics only when available; do not auto-install or+upgrade tooling. Sanitize bounded relevant output before showing or persisting+it. A doctor/type-check pass does not validate native runtime compatibility.+Use `npx --no-install` for any available project-local diagnostic tool; report+unavailable checks without downloading a replacement or blocking issue reporting.Ask for the affected workflow's Support ID when available. Use the telemetryhelper's read-only `--report` mode from the affected project to inspect only its@@ -108,7 +133,7 @@ allowlisted timeline. Include the Support ID and relevant step/error category inthe issue body, not environment, tenant, or organization IDs. Do notupload the telemetry directory or raw timing/authentication files.-If the user pasted an error, capture verbatim. Otherwise look for recent failure signals:+If the user pasted an error, extract a sanitized minimal reproduction. Otherwise look for recent failure signals:- Last 50 lines of any Metro / Gradle / Xcode log if user mentions a build failure- `git status --short` if in a git repo (to show modified files — sanitize for secrets first)@@ -117,7 +142,8 @@ If the user pasted an error, capture verbatim. Otherwise look for recent failure**Do NOT capture:**- Contents of `src/playerConfig.ts` (contains tenantId / clientId — sensitive)- Contents of `.env` or any file matching `.env*`-- Connection IDs unless the user explicitly opted in (PII / can map to tenant)+- Connection IDs, even if a diagnostic command printed them+- Raw `app.json`, `app.config.js`, `auth.config.json`, or `power.config.json`- Anything under `node_modules/`- Package source excerpts, patched package contents, or proposed fork code- Tenant/environment/organization IDs in a public issue, even though verified@@ -153,9 +179,9 @@ Print this block — user copies into a new issue:| npm | <version> || Power Apps CLI | <version> || Expo CLI | <version> |-| Xcode | <if macOS> |-| JDK | <if android> |-| ANDROID_HOME set | <yes/no> |+| Release status | <verified release ID or unresolved category> |+| Runtime tuple | <sanitized template/host/Expo/React Native/native inventory versions> |+| Player / selected bases | <actual supplied versions and base fingerprints, or unknown> |### Project context@@ -198,7 +224,7 @@ Not run inside a mobile-app project.### Logs / errors```-<paste verbatim — sensitive values redacted>+<bounded sanitized error summary; no package source or raw configuration>```### Notes@@ -223,5 +249,7 @@ If the user wants to open it, suggest `open <url>` (macOS) / `xdg-open <url>` (L## Notes- This skill never modifies any file or invokes mutating commands. Pure diagnostic.-- For diagnosing connection-specific failures, suggest the user run `/list-connections` first and paste that output into the issue.-- For diagnosing build failures, suggest they include the full Metro/Gradle/Xcode log (not truncated).+- For connection-specific failures, use `/list-connections` locally; include only+ a sanitized category/reproduction, never raw connection output or IDs.+- For build failures, include a bounded sanitized excerpt, not full logs or+ private package source. Keep native compatibility limitations explicit.