From 85ce5b4f343f36d875de25739cc8342e2fa80437 Mon Sep 17 00:00:00 2001 From: theeket Date: Sat, 21 Nov 2026 16:40:00 +0700 Subject: [PATCH] =?UTF-8?q?feat(=F0=9F=8D=8F):=20download=20the=20Apple=20?= =?UTF-8?q?binaries=20from=20GitHub=20releases=20(CocoaPods/SPM)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/setup/action.yml | 21 +- .github/workflows/apple-sdks.yml | 20 +- .github/workflows/ci.yml | 23 +- .gitignore | 4 + .../docs/getting-started/installation.mdx | 23 +- .../docs/integrations/react-native-skia.mdx | 2 +- apps/docs/package.json | 1 - apps/example-macos/README.md | 4 +- apps/example-macos/macos/Podfile.lock | 36 +- apps/example-macos/package.json | 1 - apps/example/ios/Podfile.lock | 31 +- apps/example/package.json | 1 - apps/example/src/App.tsx | 14 +- apps/example/src/Home.tsx | 18 +- apps/example/src/Tests.tsx | 15 +- apps/example/tsconfig.json | 13 +- packages/webgpu/CONTRIBUTING.md | 96 ++++-- packages/webgpu/Package.swift | 147 +-------- .../cpp/dawn/common/ExternalTextureParams.h | 6 +- packages/webgpu/cpp/rnwgpu/SurfaceRegistry.h | 4 +- packages/webgpu/cpp/rnwgpu/api/GPUAdapter.cpp | 2 +- packages/webgpu/package.json | 13 +- packages/webgpu/react-native-webgpu.podspec | 139 +++----- packages/webgpu/react-native.config.js | 15 +- .../webgpu/scripts/apple-binaries-utils.sh | 262 +++++++++++++++ packages/webgpu/scripts/check-apple-sdks.sh | 9 +- packages/webgpu/scripts/check-dawn.ts | 75 +++-- .../webgpu/scripts/prepare-apple-binaries.sh | 309 ++++++++++++++++++ .../webgpu/scripts/prepare-dawn-headers.mjs | 172 ++++++++++ packages/webgpu/scripts/spm-plugin.js | 130 ++++++++ .../webgpu/src/__tests__/FeatureNames.spec.ts | 7 +- packages/webgpu/tests/cpp/CMakeLists.txt | 15 +- spm-example/README.md | 23 +- spm-example/ios/SpmExample/AppDelegate.swift | 35 +- spm-example/ios/SpmExample/Info.plist | 18 + yarn.lock | 88 ----- 36 files changed, 1232 insertions(+), 560 deletions(-) create mode 100644 packages/webgpu/scripts/apple-binaries-utils.sh create mode 100644 packages/webgpu/scripts/prepare-apple-binaries.sh create mode 100644 packages/webgpu/scripts/prepare-dawn-headers.mjs create mode 100644 packages/webgpu/scripts/spm-plugin.js diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index f5b52dc3d..052ecded9 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -26,8 +26,25 @@ runs: fi shell: bash - # Dawn comes with the react-native-webgpu-dawn dependency; this only checks - # it against the C++ workarounds pinned to a Dawn commit. + # Cache only the pinned header ZIP. Apple SDK archives stay in the runner's + # shared local cache; this avoids uploading them in every setup job. + # Header copying verifies the cached ZIP, including when Yarn install is skipped. + - name: Cache Dawn header archive + uses: actions/cache@v4 + with: + path: | + ~/Library/Caches/react-native-skia/*/*/dawn-headers.zip + ~/.cache/react-native-skia/*/*/dawn-headers.zip + ~/AppData/Local/react-native-skia/*/*/dawn-headers.zip + key: ${{ runner.os }}-${{ runner.arch }}-dawn-headers-${{ hashFiles('packages/webgpu/binaries.json') }} + + # Populate cpp/dawn/include before checks, compilation, and npm publishing. + # Checkout omits these source/generated headers; no native build runs here. + - name: Copy Dawn headers + working-directory: packages/webgpu + shell: bash + run: yarn copy-dawn-headers + - name: Check Dawn working-directory: packages/webgpu shell: bash diff --git a/.github/workflows/apple-sdks.yml b/.github/workflows/apple-sdks.yml index 64acb7295..af2942180 100644 --- a/.github/workflows/apple-sdks.yml +++ b/.github/workflows/apple-sdks.yml @@ -8,21 +8,25 @@ on: - "packages/webgpu/apple/**" - "packages/webgpu/cpp/**" - "packages/webgpu/package.json" + - "packages/webgpu/binaries.json" + - "packages/webgpu/scripts/*apple*binaries.sh" + - "packages/webgpu/scripts/apple-binaries-utils.sh" - "packages/webgpu/scripts/check-apple-sdks.sh" + - "packages/webgpu/scripts/prepare-dawn-headers.mjs" - ".github/workflows/apple-sdks.yml" jobs: apple-sdks: # Syntax-check only: no yarn install, no pods, no simulator. Only the Dawn - # headers are downloaded (about 1 MB out of the package's tarball). + # headers archive is downloaded from the pinned Skia binaries release. runs-on: macos-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - - name: Download Dawn headers - run: | - VERSION=$(node -p 'require("./packages/webgpu/package.json").dependencies["react-native-webgpu-dawn"]') - mkdir -p "$RUNNER_TEMP/dawn" - curl -sfL "https://registry.npmjs.org/react-native-webgpu-dawn/-/react-native-webgpu-dawn-$VERSION.tgz" \ - | tar xz -C "$RUNNER_TEMP/dawn" package/include + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version-file: .nvmrc + - name: Prepare Dawn headers + run: node packages/webgpu/scripts/prepare-dawn-headers.mjs - name: Check Apple sources against every SDK - run: packages/webgpu/scripts/check-apple-sdks.sh "$RUNNER_TEMP/dawn/package/include" + run: packages/webgpu/scripts/check-apple-sdks.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index afa3c1010..90cba4b3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -201,8 +201,8 @@ jobs: # packages/webgpu/Package.swift resolves and compiles, so a pull request # pays for it only when its diff touches what can change the outcome: the # manifest and the autolinking config, the Apple and C++ sources it - # compiles, the scripts behind the Dawn check, the dependencies that pin - # react-native-webgpu-dawn, the example that links it, or CI itself. Pushes + # compiles, preparation/check scripts, the Dawn release pin, + # the example that links it, or CI itself. Pushes # to main, the merge queue and manual runs always build SwiftPM. macOS builds # on main, manual runs and relevant PRs; shared JavaScript is checked by # bundle-macos on every PR. @@ -237,7 +237,7 @@ jobs: macos=false while IFS= read -r file; do case "$file" in - packages/webgpu/Package.swift|packages/webgpu/package.json|packages/webgpu/react-native.config.js|\ + packages/webgpu/Package.swift|packages/webgpu/*.podspec|packages/webgpu/package.json|packages/webgpu/binaries.json|packages/webgpu/react-native.config.js|\ packages/webgpu/apple/*|packages/webgpu/cpp/*|packages/webgpu/scripts/*|\ spm-example/*|package.json|yarn.lock|\ .github/workflows/ci.yml|.github/actions/setup/*) @@ -246,7 +246,7 @@ jobs: ;; esac case "$file" in - apps/example-macos/*|packages/webgpu/*.podspec|packages/webgpu/package.json|\ + apps/example-macos/*|packages/webgpu/*.podspec|packages/webgpu/package.json|packages/webgpu/binaries.json|\ packages/webgpu/react-native.config.js|packages/webgpu/apple/*|packages/webgpu/cpp/*|\ packages/webgpu/scripts/*|package.json|yarn.lock|.yarn/patches/*|turbo.json|\ .github/workflows/ci.yml|.github/actions/setup/*) @@ -292,15 +292,15 @@ jobs: # The SwiftPM example gets its own job on a GitHub-hosted Mac. It needs no # Metro, simulator or CocoaPods, so nothing ties it to the self-hosted - # machine, and a fresh runner is the strictest check that the WebGPUDawn - # binaryTarget resolves from the release zip + checksum with nothing cached. + # machine. The Xcode phase selects the simulator SDK archive and verifies + # its checksum, independently of SwiftPM package resolution. # It used to be a step of `build`: a hung xcodebuild there blocked the iOS # e2e result and held the self-hosted runner, which has no slack for that. build-spm-ios: needs: changes if: needs.changes.outputs.spm == 'true' runs-on: macos-latest - # Cold run: yarn install, Dawn download, RN artifacts, then one xcodebuild. + # Install JS/headers, resolve RN artifacts, then prepare Dawn during Xcode. timeout-minutes: 25 steps: - name: Checkout @@ -320,7 +320,7 @@ jobs: # spm-example sits outside the yarn workspace so its React Native can # differ from the one apps/example pins: SwiftPM autolinking needs - # React Native 0.87+. It ships no lockfile; react and react-native are + # React Native 0.87.1+. It ships no lockfile; react and react-native are # pinned exactly in its package.json. - name: Install spm-example dependencies working-directory: spm-example @@ -333,11 +333,8 @@ jobs: working-directory: spm-example/ios run: npx react-native spm update - # No CocoaPods and no -disableAutomaticPackageResolution here (unlike - # the example app build above): react-native-webgpu is linked through - # its own Package.swift, and its WebGPUDawn binaryTarget resolves to a - # remote release zip + checksum with nothing cached ahead of time: this - # build's whole point is exercising that download-and-verify step. + # No CocoaPods: the package compiles from bundled headers, and its Xcode + # phase prepares only the selected SDK's Dawn before the app links. - name: Build spm-example for iOS working-directory: spm-example/ios run: | diff --git a/.gitignore b/.gitignore index d12cf476e..f02d2dcff 100644 --- a/.gitignore +++ b/.gitignore @@ -71,3 +71,7 @@ apps/vendor/ Package.resolved .turbo + +# Prepared release inputs and local Apple SDK overrides +packages/webgpu/cpp/dawn/include/ +packages/webgpu/libs/ diff --git a/apps/docs/content/docs/getting-started/installation.mdx b/apps/docs/content/docs/getting-started/installation.mdx index 4cbd550b3..eccf70146 100644 --- a/apps/docs/content/docs/getting-started/installation.mdx +++ b/apps/docs/content/docs/getting-started/installation.mdx @@ -24,6 +24,17 @@ npm i react-native-webgpu An Android app with a lower `minSdkVersion` fails to build; on Expo, the [config plugin](/docs/getting-started/expo#config-plugin) raises it for you. +## Prebuilt binaries + +Both platforms use the [React Native Skia binaries release](https://github.com/wcandillon/react-native-skia/releases) pinned by this package's `binaries.json`: + +- **Android:** Gradle downloads only the ABIs being built and caches them as Gradle dependencies. +- **Apple:** + - **CocoaPods:** `pod install` registers an Xcode phase; it downloads only the selected SDK's Dawn archive during compilation. + - **SwiftPM (optional):** The autolinking plugin registers the same phase. Package resolution uses bundled headers and a local link-settings package, without downloading Dawn. + +Apple archives share Skia's `~/Library/Caches/react-native-skia` cache; set `RNSKIA_CACHE_DIR` to override it. + ## Setup Once installed, the global `navigator.gpu` API is available, the same entry point as in Chrome or Safari: @@ -63,16 +74,16 @@ This replaces the package with a JS-only stand-in: `` renders as a plain By default, `react-native-webgpu` links on iOS/macOS through CocoaPods autolinking, with no extra setup. The long-term plan is to move the Apple platforms to Swift Package Manager. It is available today as an alternative: the package also ships a `Package.swift` for React Native's SwiftPM autolinking, which needs no CocoaPods at all: -1. Use **React Native 0.87 or newer**. Earlier releases have no SwiftPM autolinking, so keep CocoaPods there. +1. Use **React Native 0.87.1 or newer**, with the autolinking plugin's `scriptPhases` hook. Keep CocoaPods on earlier releases. 2. From your app's `ios` directory, run `npx react-native spm add --deintegrate` once. It removes CocoaPods from the project and adds the Swift packages to the `.xcodeproj`. Then build the project (not a workspace) as usual. 3. Do not run `pod install` in that app: it would re-integrate CocoaPods and break the Swift packages. -Dawn comes as a prebuilt binary that Xcode downloads the first time it resolves packages. +Set **User Script Sandboxing** to **NO** on the app target. The Xcode phase needs access to the shared cache and build products. After upgrading the package, run `npx react-native spm update` again. -With React Native Skia v3 installed alongside, package resolution checks that both packages link the same Dawn release, and fails if they are not at [compatible versions](/docs/integrations/react-native-skia#compatibility). After changing either version, reset the package caches in Xcode (File > Packages > Reset Package Caches) if the error persists. +With a compatible React Native Skia integration installed, WebGPU supplies the single Dawn copy. Both packages must pin the same release version and Dawn commit; mismatches fail before linking. See [compatible versions](/docs/integrations/react-native-skia#compatibility). -The Swift package targets iOS only: tvOS, macOS and Android still require the CocoaPods/Gradle autolinked path. See `spm-example` at the root of the [React Native WebGPU repo](https://github.com/wcandillon/react-native-webgpu) for a working reference project, and its README for the gotchas (stale `Package.resolved`, the stub `Podfile`). +The Swift package targets iOS only: tvOS, macOS and Android still require the CocoaPods/Gradle autolinked path. See `spm-example` at the root of the [React Native WebGPU repo](https://github.com/wcandillon/react-native-webgpu) for a working reference project, and its README for setup notes and the stub `Podfile`. ## Troubleshooting @@ -101,8 +112,8 @@ The simulator's Metal stack is not identical to real hardware, and validation ca Learn more in [Apple's documentation on validating Metal API usage](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-api-usage/). - -Gradle downloads the prebuilt Dawn from the [GitHub releases of React Native Skia](https://github.com/wcandillon/react-native-skia/releases), which builds it, the first time it builds, only for the architectures being built, and caches it like any other Gradle dependency. To download it from a mirror or a local directory instead, set the `reactNativeSkiaBinariesUrl` Gradle property (or the `REACT_NATIVE_SKIA_BINARIES_URL` environment variable) to a URL or a `file:///` directory that holds the release assets under `binaries-/`. + +To use a mirror or local release directory on either platform, set `REACT_NATIVE_SKIA_BINARIES_URL` to a URL or `file:///` path holding `binaries-/`. Android also accepts the `reactNativeSkiaBinariesUrl` Gradle property. ## Next steps diff --git a/apps/docs/content/docs/integrations/react-native-skia.mdx b/apps/docs/content/docs/integrations/react-native-skia.mdx index 3d4e09476..9746c15d9 100644 --- a/apps/docs/content/docs/integrations/react-native-skia.mdx +++ b/apps/docs/content/docs/integrations/react-native-skia.mdx @@ -26,7 +26,7 @@ Because the two packages share Dawn, React Native Skia v3 and React Native WebGP | 0.12.1 | 3.0.6 to 3.0.8, or 3.1.0 and later | | 0.10.0 to 0.11.2 | 3.0.0 to 3.0.5 | -If the versions don't match, the native build fails with a `Dawn version mismatch` error rather than misbehaving at runtime. Both packages get Dawn from the `react-native-webgpu-dawn` npm package: make sure a single version of it is installed (`npm ls react-native-webgpu-dawn`, or `yarn why react-native-webgpu-dawn`). +For SDK-archive integration, both packages must pin the same release version and `dawn.commit` in `binaries.json`. WebGPU supplies Dawn; Skia must use its compatible external-Dawn integration so the app links one copy. A mismatch fails with `Dawn version mismatch`. The older binary-npm integrations follow their release-specific installation instructions. The Graphite previews of v2 (`@shopify/react-native-skia@next`) follow the same rule. Regular v2 releases don't use Dawn, so they work alongside any version of React Native WebGPU. diff --git a/apps/docs/package.json b/apps/docs/package.json index 9a6c4884b..85b655e21 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -40,7 +40,6 @@ "eslint": "9.35.0", "fumadocs-twoslash": "^3.2.0", "fumadocs-typescript": "^4.0.4", - "react-native-skia": "3.10.0", "react-native-vision-camera": "5.0.10", "tailwindcss": "^4.1.8", "twoslash": "^0.3.9", diff --git a/apps/example-macos/README.md b/apps/example-macos/README.md index 5c5275be2..0657fb7b1 100644 --- a/apps/example-macos/README.md +++ b/apps/example-macos/README.md @@ -16,8 +16,8 @@ yarn workspace example-macos pod:install:macos yarn workspace example-macos build:macos ``` -The app targets macOS 14.0. Dawn comes from `react-native-webgpu-dawn`; nothing -is built from Dawn sources. For development, run these in separate terminals: +The app targets macOS 14.0. Dawn is prepared from the pinned SDK archive during Xcode compilation; +nothing is built from Dawn sources. For development, run these in separate terminals: ```sh yarn workspace example-macos start diff --git a/apps/example-macos/macos/Podfile.lock b/apps/example-macos/macos/Podfile.lock index 4788c2e2d..468ac5aaa 100644 --- a/apps/example-macos/macos/Podfile.lock +++ b/apps/example-macos/macos/Podfile.lock @@ -2021,36 +2021,6 @@ PODS: - ReactCommon/turbomodule/core - SocketRocket - Yoga - - react-native-skia (3.10.0): - - boost - - DoubleConversion - - fast_float - - fmt - - glog - - hermes-engine - - RCT-Folly - - RCT-Folly/Fabric - - RCTRequired - - RCTTypeSafety - - React - - React-callinvoker - - React-Core - - React-debug - - React-Fabric - - React-featureflags - - React-graphics - - React-ImageManager - - React-jsi - - React-NativeModulesApple - - React-RCTFabric - - React-renderercss - - React-rendererdebug - - React-utils - - ReactCodegen - - ReactCommon/turbomodule/bridging - - ReactCommon/turbomodule/core - - SocketRocket - - Yoga - react-native-webgpu (0.0.0): - boost - DoubleConversion @@ -2965,7 +2935,6 @@ DEPENDENCIES: - React-microtasksnativemodule (from `../node_modules/react-native-macos/ReactCommon/react/nativemodule/microtasks`) - React-mutationobservernativemodule (from `../node_modules/react-native-macos/ReactCommon/react/nativemodule/mutationobserver`) - react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`) - - react-native-skia (from `../node_modules/react-native-skia`) - react-native-webgpu (from `../node_modules/react-native-webgpu`) - React-NativeModulesApple (from `../node_modules/react-native-macos/ReactCommon/react/nativemodule/core/platform/ios`) - React-networking (from `../node_modules/react-native-macos/ReactCommon/react/networking`) @@ -3106,8 +3075,6 @@ EXTERNAL SOURCES: :path: "../node_modules/react-native-macos/ReactCommon/react/nativemodule/mutationobserver" react-native-safe-area-context: :path: "../node_modules/react-native-safe-area-context" - react-native-skia: - :path: "../node_modules/react-native-skia" react-native-webgpu: :path: "../node_modules/react-native-webgpu" React-NativeModulesApple: @@ -3239,8 +3206,7 @@ SPEC CHECKSUMS: React-microtasksnativemodule: 19a679c33c2a30339ded09015f3b150d17741dd9 React-mutationobservernativemodule: fd162222cbf7aa9f00ceaddcfcf3af472dd84db0 react-native-safe-area-context: 6cf08f4151132f9cf2adb948dc6c4ac387f8d30f - react-native-skia: 2a2e368f129a7c029b5dd22e06395eac4fe94c3f - react-native-webgpu: a038711df350957d325a322211216bb73dac7a10 + react-native-webgpu: 7f9b1b83788339356f7567add013bef85f1cf117 React-NativeModulesApple: 5ead5f7c62cdc951f5090c3f736f4da36c1807b5 React-networking: d61cd2aed6bd3ef10baef7b327219f7c12a6969b React-oscompat: 7551cbe14bc1ff01314e9cf119a985abe3e70344 diff --git a/apps/example-macos/package.json b/apps/example-macos/package.json index cd13cd6f8..66618d91b 100644 --- a/apps/example-macos/package.json +++ b/apps/example-macos/package.json @@ -26,7 +26,6 @@ "react-native-reanimated": "4.6.0", "react-native-safe-area-context": "^5.4.0", "react-native-screens": "4.19.0", - "react-native-skia": "3.10.0", "react-native-webgpu": "workspace:*", "react-native-worklets": "0.12.2", "teapot": "^1.0.0", diff --git a/apps/example/ios/Podfile.lock b/apps/example/ios/Podfile.lock index 00145b6b9..680ac4cd2 100644 --- a/apps/example/ios/Podfile.lock +++ b/apps/example/ios/Podfile.lock @@ -1470,31 +1470,6 @@ PODS: - ReactCommon/turbomodule/core - ReactNativeDependencies - Yoga - - react-native-skia (3.10.0): - - hermes-engine - - RCTRequired - - RCTTypeSafety - - React - - React-bridging - - React-callinvoker - - React-Core - - React-Core-prebuilt - - React-cxxstableapi - - React-debug - - React-Fabric - - React-featureflags - - React-graphics - - React-ImageManager - - React-jsi - - React-NativeModulesApple - - React-RCTFabric - - React-renderercss - - React-rendererdebug - - React-utils - - ReactCodegen - - ReactCommon/turbomodule/core - - ReactNativeDependencies - - Yoga - react-native-webgpu (0.0.0): - hermes-engine - RCTRequired @@ -2298,7 +2273,6 @@ DEPENDENCIES: - React-microtasksnativemodule (from `../../../node_modules/react-native/ReactCommon/react/nativemodule/microtasks`) - React-mutationobservernativemodule (from `../../../node_modules/react-native/ReactCommon/react/nativemodule/mutationobserver`) - react-native-safe-area-context (from `../../../node_modules/react-native-safe-area-context`) - - react-native-skia (from `../../../node_modules/react-native-skia`) - react-native-webgpu (from `../../../node_modules/react-native-webgpu`) - React-NativeModulesApple (from `../../../node_modules/react-native/ReactCommon/react/nativemodule/core/platform/ios`) - React-networking (from `../../../node_modules/react-native/ReactCommon/react/networking`) @@ -2451,8 +2425,6 @@ EXTERNAL SOURCES: :path: "../../../node_modules/react-native/ReactCommon/react/nativemodule/mutationobserver" react-native-safe-area-context: :path: "../../../node_modules/react-native-safe-area-context" - react-native-skia: - :path: "../../../node_modules/react-native-skia" react-native-webgpu: :path: "../../../node_modules/react-native-webgpu" React-NativeModulesApple: @@ -2603,8 +2575,7 @@ SPEC CHECKSUMS: React-microtasksnativemodule: 0207d6133274a7cbfc3d0dae326e3055c8cfcf9e React-mutationobservernativemodule: b97a67c29f724d18a92379e7390f24350acb433a react-native-safe-area-context: 949375a80dca43886b96574e6c97a0c5b37a479c - react-native-skia: 8bc263ce99daef1d357c65681e5085b1d3d95157 - react-native-webgpu: 27abd5e7a0af033bc91767a338cea31f441f58af + react-native-webgpu: 8999dd037f25c37339f8fafa937855561f322f5a React-NativeModulesApple: 8cfb2f308f48c48068c96b932e7f0e4297c23342 React-networking: 3325cf73ecbdaacab0da91260b094baf36061a56 React-oscompat: a776760fdfa152e12114f8c30d833963daac27e1 diff --git a/apps/example/package.json b/apps/example/package.json index 99beb5976..01891a695 100644 --- a/apps/example/package.json +++ b/apps/example/package.json @@ -36,7 +36,6 @@ "react-native-reanimated": "4.7.1", "react-native-safe-area-context": "^5.4.0", "react-native-screens": "^4.30.1", - "react-native-skia": "3.10.0", "react-native-vision-camera": "5.0.10", "react-native-vision-camera-worklets": "5.0.10", "react-native-web": "^0.21.2", diff --git a/apps/example/src/App.tsx b/apps/example/src/App.tsx index 4fa329c64..d2aa9ddd6 100644 --- a/apps/example/src/App.tsx +++ b/apps/example/src/App.tsx @@ -22,7 +22,8 @@ import { RenderBundles } from "./RenderBundles"; import { ABuffer } from "./ABuffer"; import { OcclusionQuery } from "./OcclusionQuery"; import { ComputeBoids } from "./ComputeBoids"; -import { MNISTInference } from "./MNISTInference"; +// TODO: Restore MNIST when Skia supports SDK-based Dawn preparation. +// import { MNISTInference } from "./MNISTInference"; import { Wireframe } from "./Wireframe"; import { Resize } from "./Resize"; import { Particules } from "./Particles"; @@ -55,7 +56,8 @@ import { VisionCamera } from "./VisionCamera"; import { SixteenBitTextures } from "./SixteenBitTextures"; import { ViewSnapshot } from "./ViewSnapshot"; import { NativeBufferView } from "./NativeBufferView"; -import { IconBenchmark } from "./IconBenchmark"; +// TODO: Restore this demo when Skia supports SDK-based Dawn preparation. +// import { IconBenchmark } from "./IconBenchmark"; // The two lines below are needed by three.js import "fast-text-encoding"; @@ -88,7 +90,7 @@ const linking: LinkingOptions = { ReversedZ: "reversed-z", ABuffer: "a-buffer", OcclusionQuery: "occlusion-query", - MNISTInference: "mnist-inference", + // MNISTInference: "mnist-inference", ComputeBoids: "compute-boids", ShadowMapping: "shadow-mapping", DeferedRendering: "deferred-rendering", @@ -118,7 +120,7 @@ const linking: LinkingOptions = { SixteenBitTextures: "sixteen-bit-textures", ViewSnapshot: "view-snapshot", NativeBufferView: "native-buffer-view", - IconBenchmark: "icon-benchmark", + // IconBenchmark: "icon-benchmark", }, }, // react-native-test-app registers its bundle id as the iOS URL scheme, and @@ -168,7 +170,7 @@ function App() { - + {/* */} @@ -232,7 +234,7 @@ function App() { /> - + {/* */} diff --git a/apps/example/src/Home.tsx b/apps/example/src/Home.tsx index e476a7f98..022a2ad1c 100644 --- a/apps/example/src/Home.tsx +++ b/apps/example/src/Home.tsx @@ -93,10 +93,11 @@ export const examples = [ screen: "ComputeBoids", title: "๐Ÿฆโ€โฌ› Compute Boids", }, - { - screen: "MNISTInference", - title: "1๏ธโƒฃ MNIST Inference", - }, + // TODO: Restore MNIST when Skia supports SDK-based Dawn preparation. + // { + // screen: "MNISTInference", + // title: "1๏ธโƒฃ MNIST Inference", + // }, ...(Platform.OS !== "ios" ? ([ { @@ -163,10 +164,11 @@ export const examples = [ screen: "NativeBufferView", title: "๐Ÿ–ผ๏ธ Native Buffer View", }, - { - screen: "IconBenchmark", - title: "โฑ๏ธ 200 Icons: Skia Canvas vs NativeBufferView", - }, + // TODO: Restore this demo when Skia supports SDK-based Dawn preparation. + // { + // screen: "IconBenchmark", + // title: "โฑ๏ธ 200 Icons: Skia Canvas vs NativeBufferView", + // }, ] as const; const styles = StyleSheet.create({ diff --git a/apps/example/src/Tests.tsx b/apps/example/src/Tests.tsx index c1ffbf3fa..657965607 100644 --- a/apps/example/src/Tests.tsx +++ b/apps/example/src/Tests.tsx @@ -9,7 +9,7 @@ import { } from "react-native"; import { GPUOffscreenCanvas, - importDevice, + // importDevice, // The flags as the package exports them, not the globals of the same name // (see the `exportedFlags` spec in Constants.spec.ts). GPUBufferUsage as exportedBufferUsage, @@ -23,7 +23,7 @@ import { // loaded yet. On Android, Skia's device then lives on a second instance, and // ImportDevice.spec.ts relies on that split to cover importDevice() across // instances. -import { Skia } from "react-native-skia"; +// import { Skia } from "react-native-skia"; import { mat4, vec3, mat3 } from "wgpu-matrix"; import { serve } from "./serve"; @@ -139,10 +139,13 @@ export const Tests = ({ assets: { di3D, saturn, moon } }: AssetProps) => { }, workletDeviceStress, workletSerialization, - importSkiaDevice: () => - Skia.gpu.isAvailable - ? importDevice(Skia.getNativeDevice()) - : null, + // TODO: Restore Skia interop after SDK-based Dawn preparation is + // supported there. Returning null skips ImportDevice.spec.ts. + // importSkiaDevice: () => + // Skia.gpu.isAvailable + // ? importDevice(Skia.getNativeDevice()) + // : null, + importSkiaDevice: () => null, exportedFlags: { GPUBufferUsage: exportedBufferUsage, GPUColorWrite: exportedColorWrite, diff --git a/apps/example/tsconfig.json b/apps/example/tsconfig.json index 99e0d6c75..f870bb7d9 100644 --- a/apps/example/tsconfig.json +++ b/apps/example/tsconfig.json @@ -7,5 +7,16 @@ "three/addons/*": ["../../node_modules/@types/three/examples/jsm/*"] }, "types": ["@webgpu/types", "@types/node"] - } + }, + // Exclude the dormant Skia demo until SDK-based Dawn integration is available. + // TypeScript replaces inherited exclude arrays, so keep the shared entries. + "exclude": [ + "node_modules", + "**/Pods/**", + "babel.config.js", + "metro.config.js", + "jest.config.js", + "src/MNISTInference", + "src/IconBenchmark" + ] } diff --git a/packages/webgpu/CONTRIBUTING.md b/packages/webgpu/CONTRIBUTING.md index b64b6fef5..6aa5089d4 100644 --- a/packages/webgpu/CONTRIBUTING.md +++ b/packages/webgpu/CONTRIBUTING.md @@ -8,12 +8,19 @@ We happily accept contributions made with coding agents. Our ask is simple: if y ```sh yarn +yarn workspace react-native-webgpu copy-dawn-headers ``` -Dawn, the WebGPU implementation, is prebuilt; there is nothing to build: +### Using pre-built binaries -- On Android, Gradle downloads it at build time from the GitHub release `binaries-` of [wcandillon/react-native-skia](https://github.com/wcandillon/react-native-skia/releases): the shared library of each ABI being built, and the headers. `packages/webgpu/binaries.json` pins the version and the sha256 of every archive. They are resolved as Gradle dependencies, so they are cached in the Gradle user home and later builds work offline; the `prepareDawnBinaries` task verifies them and extracts them into `android/build/binaries`. To download from a mirror, or from a directory with `file:///...`, set the `reactNativeSkiaBinariesUrl` Gradle property or the `REACT_NATIVE_SKIA_BINARIES_URL` environment variable (the ones react-native-skia reads) to a location holding `binaries-/`. -- On Apple platforms it comes with the `react-native-webgpu-dawn` dependency of `packages/webgpu`: the xcframework and the headers. +Dawn, the WebGPU implementation, comes from the shared [React Native Skia binaries release](https://github.com/wcandillon/react-native-skia/releases) pinned by `packages/webgpu/binaries.json`. There is no `postinstall` step: + +- On Android, Gradle downloads one Dawn archive per ABI being built, plus the headers. They are resolved as Gradle dependencies, cached in the Gradle user home, and available offline on later builds. The `prepareDawnBinaries` task verifies the pinned sha256 checksums and extracts them into `android/build/binaries`. +- On Apple platforms, an Xcode build phase prepares the selected SDK's Dawn archive from that same pinned release. CocoaPods adds the phase during `pod install`; optional SwiftPM integration adds it during `react-native spm update`. Headers ship in the main `react-native-webgpu` package, without binary npm dependencies. See [Apple binary preparation](#how-apple-binaries-are-prepared) for caching, local builds, and errors. + +See [installation](../../apps/docs/content/docs/getting-started/installation.mdx#prebuilt-binaries) for downloads and mirrors on both platforms. + +### Examples and tests Example app (from `apps/example/`): `yarn start` ยท `yarn ios` ยท `yarn android` @@ -25,7 +32,7 @@ Tests (from `packages/webgpu/`): `yarn test:ref` (Chrome reference) ยท `yarn tes `yarn test` needs the example app open on its "Tests" screen and connected to Metro first: start Metro with `CI=true yarn start` (from `apps/example/`) โ€” `initialRouteName` in `apps/example/src/App.tsx` is `"Tests"` when `process.env.CI === "true"`, inlined at bundle time via the `transform-inline-environment-variables` babel plugin โ€” then launch the app (`yarn ios` / `yarn android`, or install+launch an existing build). The screen shows "Connecting to localhost..." once it's ready; `yarn test` then picks it up automatically. If a run fails mid-suite, reload the app (`curl -X POST http://localhost:8081/reload`) before the next run โ€” a broken `GPUDevice` from the failed run makes unrelated later tests fail too. The app and the test server talk over port 4242 by default; set `E2E_PORT` for both Metro (it is inlined into the bundle, so start Metro with `--reset-cache` after changing it) and `yarn test` to use another one, as CI does to keep clear of the other projects sharing its runner. -Other `packages/webgpu` scripts: `yarn check-dawn` (checks the installed Dawn against the C++ workarounds pinned to a Dawn commit; CI runs it after `yarn install`) +Other `packages/webgpu` scripts: `yarn copy-dawn-headers` runs the cross-platform `scripts/prepare-dawn-headers.mjs` to prepare source/generated release headers in `cpp/dawn/include`; `yarn check-dawn` checks the pinned Dawn commit against the C++ workarounds. CI prepares headers before these checks and before publishing npm. ## Expo config plugin @@ -33,15 +40,13 @@ The Expo config plugin lives in `plugin/src` and is compiled to `plugin/build` b ## Upgrading Dawn -Dawn ships in the `react-native-webgpu-dawn` npm package, which react-native-skia builds and publishes together with its own Skia Graphite binaries (the **Build and publish binaries** workflow of [wcandillon/react-native-skia](https://github.com/wcandillon/react-native-skia), see its `packages/skia/CONTRIBUTING.md`). It is built from the Dawn commit the Skia release pins in its DEPS, with the patches that release needs, so the two libraries always link the same Dawn. The package records that commit in its `package.json` (`dawn.commit`) and its version follows the Skia one (`154.3.0` for Skia `m154_8037_58c`). - -`packages/webgpu/package.json` pins it exactly (`dependencies`), and keeps the `dawn` label (`chrome-m154a`) that react-native-skia 3.0.x compares against its own Dawn at `pod install` time; it goes away once react-native-skia depends on the package too. +Dawn comes from the `binaries-` release built by react-native-skia from its pinned Dawn commit. `packages/webgpu/binaries.json` records the version, commit, and asset checksums for both Android and Apple. Steps to bump to a new Dawn (new Skia milestone `m`): -1. **Wait for the binaries.** react-native-skia publishes `react-native-webgpu-dawn` at the new version, and the GitHub release `binaries-` that Gradle downloads Dawn from on Android. +1. **Wait for the binaries.** react-native-skia publishes the GitHub release `binaries-`, including the SDK-grouped Apple ZIPs and `dawn-headers.zip`. -2. **Bump the dependency** in `packages/webgpu/package.json` and run `yarn`, and replace `packages/webgpu/binaries.json` with the `checksums.json` of the new release (`curl -fL https://github.com/wcandillon/react-native-skia/releases/download/binaries-/checksums.json -o packages/webgpu/binaries.json`). Both must name the same version: react-native-skia compares it with its own to refuse an app that would link two different Dawns. +2. **Update the pin and headers.** Replace `packages/webgpu/binaries.json` with that release's `checksums.json`, then run `yarn copy-dawn-headers`. Both native integrations read this pin; there is no binary npm dependency to bump. 3. **Review the workarounds.** `yarn check-dawn` fails when the Dawn commit changed while a workaround in `scripts/check-dawn.ts` is still pinned to the previous one: check whether the new Dawn carries the upstream fix, then drop the workaround or move its pin. @@ -51,16 +56,17 @@ Steps to bump to a new Dawn (new Skia milestone `m`): 6. **Build both platforms.** A milestone can also change Dawn's C++ API surface, not just add features โ€” e.g. `chrome-m154` turned `SharedTextureMemory::BeginAccess`/`EndAccess`, `Adapter::GetLimits`, `Device::GetLimits`, and `SharedTextureMemory::GetProperties` from a bool-ish return into `wgpu::Status` (no implicit bool conversion), breaking every `if (!result)` / `if (result)` call site in `cpp/rnwgpu/api/*.cpp`. Building iOS and Android is the way these surface; fix by comparing explicitly (`result == wgpu::Status::Success`). -7. **Verify and commit.** Build and run the example app (see "Development workflow" above for reaching the Tests screen), then commit the dependency bump. +7. **Verify and commit.** Build and run the example app (see "Development workflow" above for reaching the Tests screen), then commit the release-pin update. + ## Swift Package Manager (preview) CocoaPods stays the default. `Package.swift` is additive: SwiftPM ignores the podspec, and CocoaPods ignores `Package.swift`. -SwiftPM support requires **React Native 0.87 or newer**; earlier releases ship -no `scripts/spm`. `apps/example` is on an older version, so it cannot exercise -this path. The harness is `spm-example/` at the repo root, deliberately outside -the yarn workspace so its React Native does not collide with the workspace's. +Automatic SwiftPM preparation requires **React Native 0.87.1 or newer**, whose +plugin contract includes `scriptPhases`. Keep CocoaPods on earlier versions. +The `spm-example/` harness keeps its React Native dependencies separate from +the workspace. Prepare headers with the command above before setting it up. Its [README](../../spm-example/README.md) covers the details; the short form is: ```sh @@ -76,13 +82,15 @@ on purpose: same relative paths to React Native's header products, same `.iOS(.v15)` floor, same `RCT_NEW_ARCH_ENABLED` / `RCT_REMOVE_LEGACY_ARCH` and `DEBUG` / `NDEBUG` defines. When one changes, change the other. -Autolinking references the library through a symlink at +`spm-plugin.js` explicitly registers the package and product with RN's +`Autolinked` aggregate. It references the installed package through a symlink at `/ios/build/generated/autolinking/libs/ReactNativeWebGPU`, and SwiftPM resolves the manifest's relative paths against that symlink rather than against `packages/webgpu`. The two React Native package paths are therefore identical for every standard app. The target name is pinned in `react-native.config.js`; without it a future React Native release would derive it from the podspec -instead and change the header import prefix. +instead and change the header import prefix. Autolinking recreates this +generated symlink; after moving a checkout, rerun `spm update` from `ios/`. The platform floor must not exceed the one in React Native's generated `Autolinked` aggregate, which is hardcoded to iOS 15.0 on 0.87.1: SwiftPM @@ -92,23 +100,39 @@ ships, `.iOS(.v15)` is the only value that links. #### Dawn -The manifest depends on the `react-native-webgpu-dawn` package by path (a -sibling in `node_modules`, or this monorepo's root) and links its -`libwebgpu_dawn.xcframework`, whose slices embed the `webgpu/` and `dawn/` -headers, so no header search path is needed for them. A Graphite build of -react-native-skia installed alongside must link the same Dawn, which the -manifest checks at evaluation time: a react-native-skia that depends on -`react-native-webgpu-dawn` must resolve the same version (the copy nested under -it, else the one next to it, as its podspec resolves it; a workspace that -resolves the package to one version for both passes while react-native-skia's -own pin lags behind a Dawn bump), and the 3.0.x line, which -vendors its own Dawn, must record this package's `dawn` tag at -`react-native-skia-graphite-apple-ios/libs/.dawn-version` (hoisted or nested -under `react-native-skia/node_modules`, also checked for macOS and for the v2 -Graphite previews at `@shopify/react-native-skia/libs/.dawn-version`). SwiftPM -caches manifest evaluations, so after changing either package's Dawn reset the -package caches if the check does not re-run. - -After changing which binaries a checkout uses, delete -`ios/.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved`: -a stale pin silently keeps the previous source. +The plugin generates `build/generated/autolinking/ReactNativeWebGPUBinaries`, +a local C package carrying the static library link settings, and adds an app +phase before compilation. The native manifest uses bundled headers, so package +resolution downloads no Dawn binary or all-platform XCFramework. + +The Xcode phase follows the same steps as CocoaPods; see [Apple binary preparation](#how-apple-binaries-are-prepared). +Set **User Script Sandboxing** to **NO** on the app target. CocoaPods configures +this on its pod target automatically. Refresh `spm update` after changing the +package or pin so generated settings match the installed package. + +### How Apple binaries are prepared + +This section explains what the scripts do automatically during setup and app builds (both CocoaPods and SwiftPM). No extra manual steps are required. + +0. `pod install` or `react-native spm update` registers the Xcode build phase. + + CocoaPods or the RN 0.87.1+ SwiftPM plugin (`spm-plugin.js`) adds the phase automatically. + The phase runs `prepare-apple-binaries.sh`, which sources `apple-binaries-utils.sh`. + No binaries are downloaded during setup. + +During each Apple app build, the script: + +1. Selects the SDK, platform variant, and required architectures from Xcode. +2. Uses local overrides or downloads the selected SDK's Dawn archive. +3. Verifies pinned checksums and SDK metadata before use. +4. Updates the selected XCFramework slice under `$OBJROOT/ReactNativeWebGPUBinaries`. +5. Stages `librnwgpu_webgpu_dawn.a` in build products for static linking. +6. Reuses unchanged downloads, slices, and libraries on later builds. + +- Downloads share `~/Library/Caches/react-native-skia`, similar to React Native and Hermes handling. +- Set `RNSKIA_CACHE_DIR` to change the cache location. +- Local overrides use `libs/apple/` with `.a` libraries and `metadata.json`; symlink `libs/apple` to Skia's `libs/dawn/apple` to test local Dawn builds. +- WebGPU always supplies Dawn; shared Skia integration requires matching release versions and Dawn commits in both packages' `binaries.json`. +- Expand **Prepare React Native WebGPU binaries** in Xcode's report navigator for errors. + +See [SwiftPM Dawn](#dawn) for SwiftPM integration. diff --git a/packages/webgpu/Package.swift b/packages/webgpu/Package.swift index 54780446f..661dd023d 100644 --- a/packages/webgpu/Package.swift +++ b/packages/webgpu/Package.swift @@ -1,134 +1,21 @@ // swift-tools-version: 6.0 -// -// SwiftPM manifest for react-native-webgpu. iOS only. -// Additive: the CocoaPods podspec remains the supported default. -// -// React Native 0.87+ references a library that ships its own Package.swift -// through a symlink at /ios/build/generated/autolinking/libs/, and -// resolves the relative paths below against that symlink. They are the same -// for every standard app, because the symlink location is. Earlier React -// Native releases have no SwiftPM autolinking: keep CocoaPods there. - +// Optional RN 0.87.1+ SwiftPM integration; CocoaPods remains the default. +// The autolinking plugin registers this manifest through libs/ReactNativeWebGPU +// and creates a neighboring link-settings package. Headers ship in npm; an +// Xcode phase prepares only the selected SDK's Dawn archive before app linking. import Foundation import PackageDescription -// Absolute location of this package. Xcode passes the autolinking symlink as -// the package directory, so resolve it before deriving sibling paths. -let packageRoot = URL(fileURLWithPath: Context.packageDirectory) - .resolvingSymlinksInPath().path -let sibling = { (relative: String) -> String in - URL(fileURLWithPath: "\(packageRoot)/\(relative)").standardized.path -} -// A node package next to this one: a sibling in the consumer's node_modules, -// or under this monorepo's root. -let nodePackage = { (name: String) -> String? in - ["../\(name)", "../../node_modules/\(name)"] - .map(sibling) - .first { FileManager.default.fileExists(atPath: "\($0)/package.json") } -} -let readJSON = { (path: String) -> [String: Any]? in - guard let data = FileManager.default.contents(atPath: path) else { return nil } - return try? JSONSerialization.jsonObject(with: data) as? [String: Any] -} - -// Dawn, the WebGPU implementation, comes from the react-native-webgpu-dawn npm -// package this package depends on: an xcframework with the `webgpu/` and -// `dawn/` headers embedded in every slice, which SwiftPM exposes to dependents -// without any search path. react-native-skia's Graphite backend links the -// same package, so an app installing both contains exactly one Dawn. -guard let dawnPath = nodePackage("react-native-webgpu-dawn") else { - // Reached when the dependency was skipped at install time, which SwiftPM - // would otherwise report as an unresolvable dependency path. - fatalError( - """ - react-native-webgpu-dawn was not found next to react-native-webgpu. It ships \ - the Dawn binaries this package links against. Reinstall dependencies. - """) -} -let ownPackage = readJSON("\(packageRoot)/package.json") ?? [:] -let dawnVersion = - (readJSON("\(dawnPath)/package.json")?["version"] as? String) ?? "unknown" - -// Skia Graphite and WebGPU must link the exact same Dawn, or the pair links -// fine and crashes at runtime. react-native-skia's podspec enforces this at -// `pod install` time; a Swift package has no install hook, so the same check -// runs here, at manifest evaluation. SwiftPM caches evaluations, so after -// changing either package's Dawn reset the package caches (File > Packages > -// Reset Package Caches) if this does not re-run. -// -// A react-native-skia that depends on react-native-webgpu-dawn itself must -// resolve the same version as this package: the copy nested under it when the -// package manager could not hoist it, else the one next to it (Node's -// resolution, which react-native-skia's podspec compares too). A workspace -// that resolves the package to one version for both (yarn `resolutions`, npm -// `overrides`) passes while react-native-skia's own pin lags behind a Dawn -// bump: the app then contains that one Dawn. Older Graphite builds -// (react-native-skia 3.0.x) vendor their own Dawn and record its release tag -// at libs/.dawn-version in their binary packages; this package's `dawn` field -// names the release that Dawn is interchangeable with. -if let skiaPath = nodePackage("react-native-skia"), - let skiaPackage = readJSON("\(skiaPath)/package.json"), - let skiaDawnPin = (skiaPackage["dependencies"] as? [String: String])?["react-native-webgpu-dawn"] -{ - let skiaDawnPath = [ - "\(skiaPath)/node_modules/react-native-webgpu-dawn", - "\(skiaPath)/../react-native-webgpu-dawn", - ].first { FileManager.default.fileExists(atPath: "\($0)/package.json") } - let skiaDawn = - skiaDawnPath.flatMap { readJSON("\($0)/package.json")?["version"] as? String } ?? skiaDawnPin - if skiaDawn != dawnVersion { - fatalError( - """ - react-native-webgpu: Dawn version mismatch. This package links \ - react-native-webgpu-dawn \(dawnVersion) but react-native-skia resolves \ - \(skiaDawn) (it depends on \(skiaDawnPin)). Align the two packages so the \ - app contains exactly one Dawn. - """) - } -} else { - let dawnReleaseTag = - "dawn-\((ownPackage["dawn"] as? String ?? "").replacingOccurrences(of: "/", with: "-"))" - // The graphite packages are normally hoisted next to this package, but may - // be nested under react-native-skia when the package manager cannot hoist - // them. The v2 Graphite previews (e.g. @shopify/react-native-skia@2.12.0-next.1) - // keep the marker in their own libs/. Every marker found is checked. - let skiaDawnMarkers = [ - "react-native-skia-graphite-apple-ios/libs/.dawn-version", - "react-native-skia-graphite-apple-macos/libs/.dawn-version", - "react-native-skia/node_modules/react-native-skia-graphite-apple-ios/libs/.dawn-version", - "react-native-skia/node_modules/react-native-skia-graphite-apple-macos/libs/.dawn-version", - "@shopify/react-native-skia/libs/.dawn-version", - ].flatMap { marker in - [ - sibling("../\(marker)"), // consumer: sibling in node_modules - sibling("../../node_modules/\(marker)"), // this monorepo - ] - } - for marker in skiaDawnMarkers { - guard let data = FileManager.default.contents(atPath: marker), - let skiaDawn = String(data: data, encoding: .utf8)? - .trimmingCharacters(in: .whitespacesAndNewlines) - else { continue } - if skiaDawn != dawnReleaseTag { - fatalError( - """ - react-native-webgpu: Dawn version mismatch. This package links \ - react-native-webgpu-dawn \(dawnVersion) (\(dawnReleaseTag)) but the \ - react-native-skia Graphite binaries (\(marker)) link \(skiaDawn). Align \ - the two packages so the app contains exactly one Dawn. - """) - } - } +// SwiftPM discovers resources even with explicit sources. Limit discovery to +// native directories, excluding JS dependencies and build products automatically. +let packageDirectory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() +let nativeDirectories: Set = ["apple", "cpp"] +let excludedPaths = try FileManager.default.contentsOfDirectory(atPath: packageDirectory.path).filter { + !nativeDirectories.contains($0) } -// Unlike a native Xcode target, SwiftPM doesn't generate an implicit -// per-target header map, so quoted includes only resolve within the -// including file's own directory. The sources use bare cross-directory -// includes (e.g. apple/WebGPUModule.h includes "RNWebGPUManager.h" from -// cpp/rnwgpu), so every directory that's the target of one of those bare -// includes has to be listed explicitly here. The "webgpu/..." and "dawn/..." -// includes resolve through the Dawn xcframework's embedded headers. -// Keep in sync with header_dirs in react-native-webgpu.podspec. +// Bare includes need each internal directory explicitly, including the bundled +// source/generated Dawn headers. Keep this catalog aligned with the podspec. let internalHeaderDirs = [ "apple", "cpp", @@ -137,6 +24,7 @@ let internalHeaderDirs = [ "cpp/rnwgpu/api", "cpp/rnwgpu/api/descriptors", "cpp/rnwgpu/async", + "cpp/dawn/include", ] let package = Package( @@ -145,7 +33,7 @@ let package = Package( // target's. React Native's generated Autolinked aggregate hardcodes iOS 15.0 // (react-native#58379 derives it from the app instead), so this must not // exceed 15.0; a lower floor is always accepted. - platforms: [.iOS(.v15)], + platforms: [.iOS(.v15), .tvOS(.v15), .macOS(.v14)], products: [ // Autolinking looks this name up verbatim; react-native.config.js pins it. .library(name: "ReactNativeWebGPU", targets: ["ReactNativeWebGPU"]) @@ -153,7 +41,7 @@ let package = Package( dependencies: [ .package(name: "React-GeneratedCode", path: "../../../ios"), .package(name: "ReactNative", path: "../../../../xcframeworks"), - .package(path: dawnPath), + .package(name: "ReactNativeWebGPUBinaries", path: "../../ReactNativeWebGPUBinaries"), ], targets: [ .target( @@ -164,12 +52,13 @@ let package = Package( .product(name: "ReactNativeDependenciesHeaders", package: "ReactNative"), // RNWgpuViewSpec, generated by the app's codegen run. .product(name: "ReactAppHeaders", package: "React-GeneratedCode"), - .product(name: "react-native-webgpu-dawn", package: "react-native-webgpu-dawn"), + .product(name: "ReactNativeWebGPUBinaries", package: "ReactNativeWebGPUBinaries"), ], // apple/ and cpp/ have no common ancestor below the package root, and // .headerSearchPath cannot escape the target path. path: ".", - // Explicit, so SwiftPM never walks node_modules, lib or android. + exclude: excludedPaths, + // Compile only native implementations; Dawn itself is already prebuilt. sources: ["apple", "cpp/jsi", "cpp/rnwgpu"], // SwiftPM requires a public headers directory inside the target and // defaults to "include", which this package does not have. diff --git a/packages/webgpu/cpp/dawn/common/ExternalTextureParams.h b/packages/webgpu/cpp/dawn/common/ExternalTextureParams.h index 2dadadd22..259e01dca 100644 --- a/packages/webgpu/cpp/dawn/common/ExternalTextureParams.h +++ b/packages/webgpu/cpp/dawn/common/ExternalTextureParams.h @@ -29,9 +29,9 @@ // // Vendored from Dawn's src/dawn/common/ExternalTextureParams.h, unchanged. The // functions it declares are compiled into the Dawn binaries that -// react-native-webgpu-dawn ships (libwebgpu_dawn.so, libwebgpu_dawn.a), which -// export them, but the package only ships Dawn's public headers. The copy is -// pinned to the Dawn commit of the package in scripts/check-dawn.ts: on a Dawn +// the pinned release ships (libwebgpu_dawn.so, libwebgpu_dawn.a), which +// export them, but the released include/ tree has only public headers. The copy +// is pinned to the release commit in scripts/check-dawn.ts: on a Dawn // bump, diff it against the new commit's file and re-sync it. #ifndef SRC_DAWN_COMMON_EXTERNALTEXTUREPARAMS_H_ diff --git a/packages/webgpu/cpp/rnwgpu/SurfaceRegistry.h b/packages/webgpu/cpp/rnwgpu/SurfaceRegistry.h index f6ee192ee..e87b7676c 100644 --- a/packages/webgpu/cpp/rnwgpu/SurfaceRegistry.h +++ b/packages/webgpu/cpp/rnwgpu/SurfaceRegistry.h @@ -442,8 +442,8 @@ class SurfaceInfo { // not touch the device, and this must not change behaviour there. // // Remove once the pinned Dawn contains the upstream fix; the check in - // scripts/check-dawn.ts fails when the Dawn the react-native-webgpu-dawn - // package was built from changes, so that decision is not forgotten. + // scripts/check-dawn.ts fails when binaries.json selects another Dawn + // commit, so that decision is not forgotten. void releaseSurfaceForDevice(const wgpu::Device &device) { #if defined(__ANDROID__) std::unique_lock lock(_mutex); diff --git a/packages/webgpu/cpp/rnwgpu/api/GPUAdapter.cpp b/packages/webgpu/cpp/rnwgpu/api/GPUAdapter.cpp index cf2dcd997..102203d3a 100644 --- a/packages/webgpu/cpp/rnwgpu/api/GPUAdapter.cpp +++ b/packages/webgpu/cpp/rnwgpu/api/GPUAdapter.cpp @@ -295,7 +295,7 @@ async::AsyncTaskHandle GPUAdapter::requestDevice( // held work settles once the app is back (the same toggle Skia // requests on the device it shares, see react-native-skia's // DawnUtils::requestDevice). Dawn applies it on iOS and tvOS only, and - // a Dawn without it (react-native-webgpu-dawn before 157.1.0) drops + // a Dawn without it (Dawn binaries releases before 157.1.0) drops // the name. The caller opts out through disabledToggles. { static const char *const kName = diff --git a/packages/webgpu/package.json b/packages/webgpu/package.json index ba1c01cac..e93f9942c 100644 --- a/packages/webgpu/package.json +++ b/packages/webgpu/package.json @@ -20,6 +20,9 @@ "apple/**", "*.podspec", "Package.swift", + "scripts/apple-binaries-utils.sh", + "scripts/prepare-apple-binaries.sh", + "scripts/spm-plugin.js", "binaries.json", "react-native.config.js", "app.plugin.js", @@ -43,7 +46,8 @@ "clang-format-android": "find android/cpp/ -iname \"*.h\" -o -iname \"*.m\" -o -iname \"*.cpp\" | xargs clang-format -i", "clang-format-common": "find cpp/rnwgpu -iname \"*.h\" -o -iname \"*.m\" -o -iname \"*.cpp\" | xargs clang-format -i", "cpplint": "cpplint --linelength=230 --filter=-legal/copyright,-whitespace/indent,-whitespace/comments,-whitespace/ending_newline,-build/include_order,-runtime/references,-readability/todo,-whitespace/blank_line,-whitespace/todo,-runtime/int,-build/c++11,-whitespace/parens --exclude=android/.cxx --exclude=cpp/dawn --exclude=libs --exclude=android/build --exclude=node_modules --recursive .", - "check-dawn": "tsx scripts/check-dawn.ts" + "check-dawn": "tsx scripts/check-dawn.ts", + "copy-dawn-headers": "node scripts/prepare-dawn-headers.mjs" }, "keywords": [ "react-native", @@ -113,9 +117,6 @@ "wgpu-matrix": "^3.0.2", "ws": "^8.18.0" }, - "dependencies": { - "react-native-webgpu-dawn": "158.0.0" - }, "peerDependencies": { "react": "*", "react-native": ">=0.81.0", @@ -157,5 +158,9 @@ "WebGPUNativeBufferView": "WebGPUNativeBufferView" } } + }, + "swiftpmConfig": { + "name": "ReactNativeWebGPU", + "autolinkingPlugin": "./scripts/spm-plugin.js" } } diff --git a/packages/webgpu/react-native-webgpu.podspec b/packages/webgpu/react-native-webgpu.podspec index 6704db317..2c5310932 100644 --- a/packages/webgpu/react-native-webgpu.podspec +++ b/packages/webgpu/react-native-webgpu.podspec @@ -1,43 +1,17 @@ require "json" -require "fileutils" +require "open3" package = JSON.parse(File.read(File.join(__dir__, "package.json"))) -folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' -# Resolve a node package directory using Node's own module resolution -# (mirrors `require.resolve(pkg/package.json)`). A lambda rather than a `def`: -# CocoaPods evaluates the podspec inside the `Pod` module, where top-level -# methods are not reachable at the call site. -resolve_node_package = lambda do |name, base_dir| - script = "process.stdout.write(require('path').dirname(require.resolve('#{name}/package.json')))" - dir = Dir.chdir(base_dir) { `node -e "#{script}" 2>/dev/null`.strip } - dir.empty? ? nil : dir -end - -# Dawn, the WebGPU implementation, ships in the react-native-webgpu-dawn npm -# package this package depends on (react-native-skia's Graphite backend links -# the same one, so an app installing both contains exactly one Dawn). Its -# headers are used in place, but CocoaPods only vendors frameworks from inside -# the pod, so the xcframework is copied into libs/apple at `pod install` time. -# The copy is stamped with the package version and skipped when it already -# matches, which keeps CocoaPods' cache intact across installs. -dawn_dir = resolve_node_package.call('react-native-webgpu-dawn', __dir__) -if dawn_dir.nil? - raise "react-native-webgpu: the react-native-webgpu-dawn package was not found. " \ - "It ships the Dawn binaries this package links against; make sure " \ - "dependencies are installed (yarn install / npm install), then run `pod install` again." -end -dawn_version = JSON.parse(File.read(File.join(dawn_dir, 'package.json')))['version'].to_s -dawn_include = File.join(dawn_dir, 'include') -dawn_libs = File.join(__dir__, 'libs', 'apple') -dawn_marker = File.join(dawn_libs, '.version') -unless File.exist?(dawn_marker) && File.read(dawn_marker).strip == dawn_version - Pod::UI.puts "react-native-webgpu: installing Dawn (react-native-webgpu-dawn #{dawn_version})" - FileUtils.rm_rf(dawn_libs) - FileUtils.mkdir_p(dawn_libs) - FileUtils.cp_r(File.join(dawn_dir, 'libs', 'apple', 'libwebgpu_dawn.xcframework'), dawn_libs) - File.write(dawn_marker, dawn_version) -end +# Configuration reads the installed release pin only. SDK downloads wait for +# Xcode's platform/architecture settings; headers already ship in this package. +stdout, stderr, status = Open3.capture3( + '/bin/bash', File.join(__dir__, 'scripts', 'prepare-apple-binaries.sh'), + '--config' +) +raise "react-native-webgpu: #{stderr.strip}" unless status.success? +binary_config = JSON.parse(stdout) +binary_search_path = '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeWebGPUBinaries"' Pod::Spec.new do |s| s.name = "react-native-webgpu" @@ -47,12 +21,8 @@ Pod::Spec.new do |s| s.license = package["license"] s.authors = package["author"] - # React Native's CocoaPods autolinking drops any pod whose podspec does not - # declare the Podfile target's platform (#608), so every platform the Dawn - # xcframework ships a slice for is listed. react-native-tvos keeps the tvOS - # floor equal to the iOS one (its min_supported_versions helper). visionOS - # is not listed: react-native-webgpu-dawn ships no xros slice, so a visionOS - # target would autolink the pod and then fail to link it. + # CocoaPods autolinks only declared native platforms. Knowing a release SDK + # in the preparer alone does not establish WebGPU runtime support there. s.platforms = { :ios => min_ios_version_supported, :tvos => min_ios_version_supported, @@ -60,49 +30,46 @@ Pod::Spec.new do |s| } s.source = { :git => "https://github.com/wcandillon/react-native-webgpu.git", :tag => "#{s.version}" } - # CocoaPods is the supported default. Package.swift (React Native 0.87+ - # SwiftPM autolinking) is additive: SwiftPM ignores this podspec, and - # CocoaPods ignores Package.swift. An app links through one or the other, - # never both, so set RNWGPU_USE_SPM=1 before `pod install` when linking - # through the Swift package instead: RN's autolinking and codegen both key - # off this podspec being present, so it still needs to exist, but it must - # not compile or vendor anything itself or the app gets the native module - # twice. - if ENV['RNWGPU_USE_SPM'] - # The Swift package resolves React Native's headers from the - # static-library Pods layout (Pods/Headers/Public). With `use_frameworks!` - # CocoaPods keeps headers inside each framework instead, so none of those - # paths exist and the package fails to compile with header-not-found - # errors that don't point back here. Refuse the combination up front. - # The React Native template drives `use_frameworks!` from USE_FRAMEWORKS. - if ENV['USE_FRAMEWORKS'] - raise "react-native-webgpu: RNWGPU_USE_SPM needs the static-library Pods layout. " \ - "Unset USE_FRAMEWORKS (or drop use_frameworks! from the Podfile) to link " \ - "react-native-webgpu through its Swift package." - end - s.source_files = "apple/RNWGUIKit.h" - else - s.source_files = [ - "apple/**/*.{h,c,cc,cpp,m,mm,swift}", - "cpp/**/*.{h,cpp}" - ] + # CocoaPods and SwiftPM compile these sources independently; an app chooses + # one native integration. Neither downloads binaries during package setup. + s.source_files = [ + "apple/**/*.{h,c,cc,cpp,m,mm,swift}", + "cpp/**/*.{h,cpp}" + ] - s.vendored_frameworks = 'libs/apple/libwebgpu_dawn.xcframework' + # Retain nested paths: Dawn's forwarding and generated headers share basenames. + s.header_mappings_dir = "." + s.libraries = ['c++'] + binary_config['linkNames'] + s.preserve_paths = ['scripts/*.{js,sh}', 'libs/apple/**/*'] + s.user_target_xcconfig = { 'LIBRARY_SEARCH_PATHS' => binary_search_path } + s.script_phase = { + :name => 'Prepare React Native WebGPU binaries', + :shell_path => '/bin/bash', + :execution_position => :before_compile, + :always_out_of_date => '1', + :script => <<-SCRIPT + /bin/bash "${PODS_TARGET_SRCROOT}/scripts/prepare-apple-binaries.sh" \ + --output "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeWebGPUBinaries" \ + --assembly-root "${OBJROOT}/ReactNativeWebGPUBinaries" + SCRIPT + } - # The VideoPlayer API uses AVFoundation / CoreMedia, and shared-texture - # surfaces use CoreVideo (CVPixelBuffer). Link them so their symbols resolve. - # ImageIO provides CGImageSource, the image decoder behind createImageBitmap. - s.frameworks = "AVFoundation", "CoreMedia", "CoreVideo", "ImageIO" - end + # The VideoPlayer API uses AVFoundation / CoreMedia, and shared-texture + # surfaces use CoreVideo (CVPixelBuffer). Link them so their symbols resolve. + # ImageIO provides CGImageSource, the image decoder behind createImageBitmap. + s.frameworks = "AVFoundation", "CoreMedia", "CoreVideo", "ImageIO" # Under use_frameworks!, bare includes across folders (e.g. "GPU.h") # resolve only through these paths. Keep in sync with internalHeaderDirs # in Package.swift. - header_dirs = %w[apple cpp cpp/jsi cpp/rnwgpu cpp/rnwgpu/api cpp/rnwgpu/api/descriptors cpp/rnwgpu/async] + header_dirs = %w[apple cpp cpp/jsi cpp/rnwgpu cpp/rnwgpu/api cpp/rnwgpu/api/descriptors cpp/rnwgpu/async cpp/dawn/include] header_search_paths = header_dirs.map { |dir| "\"$(PODS_TARGET_SRCROOT)/#{dir}\"" } s.pod_target_xcconfig = { - 'HEADER_SEARCH_PATHS' => (header_search_paths + ["\"#{dawn_include}\""]).join(' '), + 'HEADER_SEARCH_PATHS' => header_search_paths.join(' '), + # Preparation needs access to the shared release cache and build products. + 'ENABLE_USER_SCRIPT_SANDBOXING' => 'NO', + 'LIBRARY_SEARCH_PATHS' => binary_search_path, # Xcode's all-target headermaps let same-named headers leak across pods # (e.g. @shopify/react-native-skia keeps a jsi/ helper layer with # identical relative header paths). Resolve includes strictly through our @@ -110,23 +77,5 @@ Pod::Spec.new do |s| 'USE_HEADERMAP' => 'NO', } - # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0. - # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79. - if respond_to?(:install_modules_dependencies, true) - install_modules_dependencies(s) - else - s.dependency "React-Core" - s.compiler_flags = folly_compiler_flags - s.pod_target_xcconfig = { - "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\" \"$(PODS_TARGET_SRCROOT)/cpp\" \"#{dawn_include}\"", - "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1", - "CLANG_CXX_LANGUAGE_STANDARD" => "c++20" - } - s.dependency "React-RCTFabric" - s.dependency "React-Codegen" - s.dependency "RCT-Folly" - s.dependency "RCTRequired" - s.dependency "RCTTypeSafety" - s.dependency "ReactCommon/turbomodule/core" - end + install_modules_dependencies(s) end diff --git a/packages/webgpu/react-native.config.js b/packages/webgpu/react-native.config.js index 014e78f80..99d8b6eb0 100644 --- a/packages/webgpu/react-native.config.js +++ b/packages/webgpu/react-native.config.js @@ -1,6 +1,9 @@ -// Pins the SwiftPM target name. Without it the name is derived: today from the -// npm name (ReactNativeWebgpu), but an in-flight React Native change derives it -// from the podspec instead. The name is also the header import prefix, so it -// must not move. Package.swift declares the same name for its package, product -// and target; scripts/package-swift-template.ts carries it as SWIFT_PACKAGE_NAME. -module.exports = { spm: { name: "ReactNativeWebGPU" } }; +// RN 0.87.1 reads this block; RN 0.88+ also reads package.json swiftpmConfig. +// Keep the native product and hook identical in both discovery paths. +// The plugin registers the package/product and the Node-free Xcode phase. +module.exports = { + spm: { + name: "ReactNativeWebGPU", + autolinkingPlugin: "./scripts/spm-plugin.js", + }, +}; diff --git a/packages/webgpu/scripts/apple-binaries-utils.sh b/packages/webgpu/scripts/apple-binaries-utils.sh new file mode 100644 index 000000000..48ca68dcb --- /dev/null +++ b/packages/webgpu/scripts/apple-binaries-utils.sh @@ -0,0 +1,262 @@ +#!/bin/bash +# Shared Apple preparation helpers. Bash 3.2 and macOS system tools only. +# +# Sourced by prepare-apple-binaries.sh; does not download or write files on load. +# The caller owns WORK_DIR, LOCKS, TEMP_PATHS, and cleanup traps. Helpers return +# resolved paths/metadata through globals so lock ownership stays in one shell. + +# MARK: Supported SDKs and linked libraries + +# The release metadata supplies architectures; SDK groups can change their archs +# without changing this list or hardcoding XCFramework slice identifiers. +RNWGPU_SDKS=( + iphoneos iphonesimulator maccatalyst + appletvos appletvsimulator macos +) +RNWGPU_DAWN_LIBRARY=libwebgpu_dawn.a + +# MARK: Release and cache policy + +# Cache path, asset layout and locks intentionally match react-native-skia. +# Overrides are resolved when loading the installed manifest, not while sourcing. +RNWGPU_RELEASE_BASE_URL=https://github.com/wcandillon/react-native-skia/releases/download +RNWGPU_LOCK_TIMEOUT_SECONDS=600 +RNWGPU_LOCK_POLL_SECONDS=0.1 + +# Bound retries and transfer time so an unavailable mirror fails the build phase +# with a useful error. A failed transfer never replaces a verified cache entry. +RNWGPU_CURL_OPTIONS=( + --fail --location --silent --show-error + --retry 2 --retry-delay 1 --retry-max-time 300 + --connect-timeout 20 --max-time 300 +) + +# MARK: Diagnostics and metadata readers + +# Diagnostics stay on stderr so --config can return machine-readable JSON. +# The marker suppresses a second generic diagnostic from the caller's ERR trap. +fail() { + printf 'error: [react-native-webgpu] %s\n' "$*" >&2 + : > "$WORK_DIR/failed" + exit 1 +} + +note() { + printf 'note: [react-native-webgpu] %s\n' "$*" >&2 +} + +# Read typed JSON values without Node or an optional package such as jq. +json_string() { + if ! plutil -extract "$2" raw -expect string -o - "$1"; then + printf 'error: [react-native-webgpu] Cannot read string %s in %s. Check the package/SDK metadata.\n' "$2" "$1" >&2 + return 1 + fi +} + +# json_strings FILE KEY: emit one array element per line, preserving JSON types. +json_strings() { + local file="$1" key="$2" count index + count=$(plutil -extract "$key" raw -expect array -o - "$file") || return 1 + for ((index = 0; index < count; index++)); do + json_string "$file" "$key.$index" || return 1 + done +} + +# Hash downloaded archives and small manifests, not each large extracted library. +hash_file() { + shasum -a 256 "$1" | cut -d ' ' -f 1 +} + +# MARK: Platform and dependency resolution + +# PLATFORM_NAME=macosx needs its Catalyst variant to select iOS-compatible code. +# Each row is SDK|binary platform|variant|deployment setting. +sdk_descriptor() { + case "$1" in + iphoneos) echo 'iphoneos|ios||IPHONEOS_DEPLOYMENT_TARGET' ;; + iphonesimulator) echo 'iphonesimulator|ios|simulator|IPHONEOS_DEPLOYMENT_TARGET' ;; + maccatalyst) echo 'maccatalyst|ios|maccatalyst|IPHONEOS_DEPLOYMENT_TARGET' ;; + appletvos) echo 'appletvos|tvos||TVOS_DEPLOYMENT_TARGET' ;; + appletvsimulator) echo 'appletvsimulator|tvos|simulator|TVOS_DEPLOYMENT_TARGET' ;; + macos) echo 'macos|macos||MACOSX_DEPLOYMENT_TARGET' ;; + *) return 1 ;; + esac +} + +# The installed manifest pins immutable release assets; never fetch a remote pin. +# Sets MANIFEST, VERSION, RELEASE_TAG, CACHE_ROOT, and RELEASE_URL. Cache entries +# are shared across projects and isolated by release tag and pinned SHA-256. +load_release() { + MANIFEST="$PACKAGE_ROOT/binaries.json" + VERSION=$(json_string "$MANIFEST" version) || fail "Cannot read version from $MANIFEST. Reinstall the package." + RELEASE_TAG=$(json_string "$MANIFEST" tag) || fail "Cannot read tag from $MANIFEST. Reinstall the package." + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ && "$RELEASE_TAG" == "binaries-$VERSION" ]] || + fail "Invalid version/tag in $MANIFEST. Refresh the release manifest." + CACHE_ROOT="${RNSKIA_CACHE_DIR:-$HOME/Library/Caches/react-native-skia}/$RELEASE_TAG" + [[ "$CACHE_ROOT" == /* ]] || fail 'RNSKIA_CACHE_DIR must be an absolute path.' + RELEASE_URL="${REACT_NATIVE_SKIA_BINARIES_URL:-$RNWGPU_RELEASE_BASE_URL}" + RELEASE_URL="${RELEASE_URL%/}/$RELEASE_TAG" +} + +# MARK: Shared cache synchronization + +# acquire_lock DIRECTORY: mkdir serializes writers across app/build processes. +# Locks cover writers only. Recover an owner terminated during another build. +# LOCKS is owned by the caller's EXIT trap, including interrupted downloads. +acquire_lock() { + local directory="$1" started=$SECONDS pid + mkdir -p "$(dirname "$directory")" + until mkdir "$directory" 2>/dev/null; do + pid=$(cat "$directory/pid" 2>/dev/null) || pid='' + if [[ "$pid" =~ ^[1-9][0-9]*$ ]] && ! kill -0 "$pid" 2>/dev/null; then + rm -rf "$directory" + continue + fi + (( SECONDS - started < RNWGPU_LOCK_TIMEOUT_SECONDS )) || + fail "Timed out waiting for $directory. Check for another running build before removing this lock." + sleep "$RNWGPU_LOCK_POLL_SECONDS" + done + LOCKS+=("$directory") + printf '%s\n' "$$" > "$directory/pid" +} + +# Completed writes release early; the caller's cleanup ignores locks now absent. +release_lock() { + rm -rf "$1" +} + +# Keep a previous complete directory if replacing it fails. +replace_directory() { + local source="$1" destination="$2" backup="$2.previous-$$" + rm -rf "$backup" + if [[ -e "$destination" ]]; then mv "$destination" "$backup"; fi + if ! mv "$source" "$destination"; then + if [[ -e "$backup" ]]; then mv "$backup" "$destination"; fi + fail "Cannot replace $destination. Check build/cache permissions and free disk space." + fi + rm -rf "$backup" +} + +# MARK: Verified release downloads + +# cached_asset NAME: resolve one pinned ZIP into ASSET_DIRECTORY and set its +# SHA-256 as SOURCE_SIGNATURE. Only that SDK/module is downloaded. +# Verify every reused ZIP. Downloads/extractions are staged before replacing cache +# entries; a failed network request or checksum cannot become a cache hit. +# Returns ASSET_DIRECTORY, without capturing lock state in a subshell. +cached_asset() { + local name="$1" expected escaped archive temporary marker entry actual + escaped=${name//./\\.} + expected=$(json_string "$MANIFEST" "assets.$escaped.sha256" 2>/dev/null) || expected='' + [[ "$expected" =~ ^[a-f0-9]{64}$ ]] || + fail "Release $VERSION has no pinned asset '$name'. Publish/select SDK archives or build this SDK locally." + ASSET_DIRECTORY="$CACHE_ROOT/$expected/${name%.zip}" + archive="$ASSET_DIRECTORY.zip" + acquire_lock "$ASSET_DIRECTORY.lock" + actual='' + if [[ -f "$archive" ]]; then actual=$(hash_file "$archive"); fi + if [[ "$actual" != "$expected" ]]; then + temporary="$archive.$$.download" + TEMP_PATHS+=("$temporary") + note "Downloading $name ($VERSION)" + curl "${RNWGPU_CURL_OPTIONS[@]}" \ + --output "$temporary" "$RELEASE_URL/$name" || + fail "Cannot download $name. Check the release URL/network or REACT_NATIVE_SKIA_BINARIES_URL, then retry." + actual=$(hash_file "$temporary") + [[ "$actual" == "$expected" ]] || + fail "SHA-256 mismatch for $name. Expected $expected; received $actual. Unverified data was discarded." + mv "$temporary" "$archive" + fi + marker="$ASSET_DIRECTORY/.verified" + # Reuse extracted files only after the ZIP passed verification above. The + # marker avoids extracting the same immutable archive on every app build. + if [[ ! -f "$marker" || "$(cat "$marker")" != "$expected" ]]; then + temporary="$ASSET_DIRECTORY.$$.extract" + TEMP_PATHS+=("$temporary") + mkdir -p "$temporary" + # Archive members must remain inside the extraction directory. + unzip -Z1 "$archive" > "$WORK_DIR/zip-entries" + while IFS= read -r entry; do + case "$entry" in + ''|/*|*\\*|..|../*|*/../*|*/..) fail "Unsafe path in $name: $entry" ;; + esac + done < "$WORK_DIR/zip-entries" + unzip -q "$archive" -d "$temporary" + printf '%s\n' "$expected" > "$temporary/.verified" + replace_directory "$temporary" "$ASSET_DIRECTORY" + fi + release_lock "$ASSET_DIRECTORY.lock" + SOURCE_SIGNATURE="$expected" +} + +# MARK: SDK metadata and local overrides + +# validate_metadata DIRECTORY SDK: sets META_ARCHS and META_IDENTIFIER. +# Validate all requested architectures and every linked library against metadata. +# Metadata also determines future slice identifiers; no hardcoded arch sets. +# Release builds verify Mach-O members before publishing; consumers check the +# pinned archive and its descriptor without scanning every object at build time. +validate_metadata() { + local directory="$1" sdk="$2" file platform variant ignored deployment + local actual_sdk actual_platform actual_variant arch seen='' library libraries minimum + file="$directory/metadata.json" + [[ -f "$file" ]] || fail "Missing SDK metadata: $file. Rebuild local $MODULE '$sdk' or refresh the pinned SDK archive/cache." + IFS='|' read -r ignored platform variant deployment <<< "$(sdk_descriptor "$sdk")" + actual_sdk=$(json_string "$file" sdk) + actual_platform=$(json_string "$file" platform) + # Device/native macOS metadata omits variant. Catch absence inside the + # substitution so Bash 3.2 does not inherit ERR for this optional value. + actual_variant=$(json_string "$file" variant 2>/dev/null || true) + [[ "$actual_sdk" == "$sdk" && "$actual_platform" == "$platform" && "$actual_variant" == "$variant" ]] || + fail "Incorrect SDK metadata in $directory; expected $sdk. Rebuild locally or refresh the pinned release." + META_ARCHS=$(json_strings "$file" architectures) || fail "Invalid architecture array in $file." + [[ -n "$META_ARCHS" ]] || fail "No architectures recorded in $file." + while IFS= read -r arch; do + [[ "$arch" =~ ^[A-Za-z0-9_]+$ && " $seen " != *" $arch "* ]] || fail "Invalid/duplicate architecture in $file: $arch" + seen="$seen $arch" + done <<< "$META_ARCHS" + for arch in "${REQUESTED_ARCHS[@]}"; do + [[ " $seen " == *" $arch "* ]] || fail "$sdk binaries in $directory do not contain $arch. Build that architecture or select a compatible release." + done + libraries=$(json_strings "$file" libraries) || fail "Invalid library array in $file." + for library in "${MODULE_LIBRARIES[@]}"; do + [[ -f "$directory/$library" ]] || fail "Incomplete $sdk binaries: $directory/$library is missing. Rebuild locally or remove the incomplete cache." + [[ $'\n'"$libraries"$'\n' == *$'\n'"$library"$'\n'* ]] || fail "$file does not declare $library." + done + minimum=$(json_string "$file" minimumDeploymentTarget) + if [[ -n "$minimum" ]]; then + [[ "$minimum" =~ ^[0-9]+(\.[0-9]+){0,2}$ ]] || fail "Invalid deployment target in $file: $minimum" + # Numeric comparison handles both major-only and dotted deployment versions. + if [[ -n "${!deployment:-}" ]] && ! awk -v actual="${!deployment}" -v minimum="$minimum" ' + BEGIN { split(actual, a, "."); split(minimum, m, "."); + for (i = 1; i <= 3; i++) { if (a[i]+0 > m[i]+0) exit 0; if (a[i]+0 < m[i]+0) exit 1; } }'; then + fail "$sdk binaries require deployment target $minimum, but $deployment=${!deployment}. Raise the app deployment target." + fi + fi + META_IDENTIFIER="$platform-$(printf '%s\n' "$META_ARCHS" | LC_ALL=C sort | paste -sd _ -)${variant:+-$variant}" +} + +# An existing SDK tree is a read-only local override. Missing SDKs fail rather +# than mixing local and released Dawn. Symlink libs/apple to a local Skia Dawn +# build's libs/dawn/apple directory to consume those same SDK libraries. +resolve_libraries() { + local sdk="$1" local_root="$PACKAGE_ROOT/libs/apple" library + if [[ -d "$local_root" ]]; then + SOURCE_DIRECTORY="$local_root/$sdk" + [[ -f "$SOURCE_DIRECTORY/metadata.json" ]] || + fail "Local Dawn overrides are enabled, but $SOURCE_DIRECTORY/metadata.json is missing. Build '$sdk' locally or remove that override directory." + note "Using local Dawn: $SOURCE_DIRECTORY" + validate_metadata "$SOURCE_DIRECTORY" "$sdk" + SOURCE_SIGNATURE=$({ + cat "$SOURCE_DIRECTORY/metadata.json" + for library in "${MODULE_LIBRARIES[@]}"; do + # Detect rapid local rebuilds without hashing large archives each time. + stat -f '%N %z %.9Fm %.9Fc' "$SOURCE_DIRECTORY/$library" + done + } | shasum -a 256 | cut -d ' ' -f 1) + else + cached_asset "dawn-apple-$sdk.zip" + SOURCE_DIRECTORY="$ASSET_DIRECTORY" + validate_metadata "$SOURCE_DIRECTORY" "$sdk" + fi +} diff --git a/packages/webgpu/scripts/check-apple-sdks.sh b/packages/webgpu/scripts/check-apple-sdks.sh index 6b85e52bc..de6f72eef 100755 --- a/packages/webgpu/scripts/check-apple-sdks.sh +++ b/packages/webgpu/scripts/check-apple-sdks.sh @@ -6,14 +6,15 @@ # else in CI builds for tvOS or visionOS. # # Usage: check-apple-sdks.sh [dawn-include-dir] -# Defaults to the Dawn headers installed in node_modules. +# Defaults to the prepared Dawn headers bundled in this package. set -euo pipefail cd "$(dirname "$0")/.." -DAWN_INCLUDE="${1:-}" -if [ -z "$DAWN_INCLUDE" ]; then - DAWN_INCLUDE="$(dirname "$(node -p 'require.resolve("react-native-webgpu-dawn/package.json")')")/include" +DAWN_INCLUDE="${1:-$PWD/cpp/dawn/include}" +if [ ! -f "$DAWN_INCLUDE/webgpu/webgpu.h" ]; then + echo "error: [react-native-webgpu] Dawn headers are missing. Run yarn copy-dawn-headers." >&2 + exit 1 fi # The other files under apple/ need React and codegen headers, which only diff --git a/packages/webgpu/scripts/check-dawn.ts b/packages/webgpu/scripts/check-dawn.ts index 43065362f..4175d0923 100644 --- a/packages/webgpu/scripts/check-dawn.ts +++ b/packages/webgpu/scripts/check-dawn.ts @@ -1,10 +1,10 @@ #!/usr/bin/env tsx -// Dawn ships in the react-native-webgpu-dawn package, built by react-native-skia -// from the Dawn commit its Skia release pins. This checks the installed one +// Dawn is pinned in binaries.json and published by react-native-skia. +// Headers are prepared from that release before building/publishing. This checks it // against the C++ workarounds below, which exist for Dawn bugs that an upstream // fix makes obsolete. Each entry names the Dawn commit it was validated against. -// Bumping the dependency to a package built from another commit fails here +// Selecting a release built from another commit fails here // until whoever does the bump checks whether the upstream fix is included: if // it is, delete the marked code and the entry; if it is not, update `commit` // (and re-verify the diagnostic screen). @@ -12,15 +12,18 @@ // Runs from `yarn check-dawn`, in CI right after `yarn install`. import { existsSync, readFileSync, readdirSync } from "fs"; -import { dirname, join } from "path"; +import { join } from "path"; -const dawnPackageJson = - require.resolve("react-native-webgpu-dawn/package.json"); -const dawnPackage = JSON.parse(readFileSync(dawnPackageJson, "utf-8")); -const installedCommit: string | undefined = dawnPackage.dawn?.commit; +const root = join(__dirname, ".."); +const binaries = JSON.parse(readFileSync(join(root, "binaries.json"), "utf-8")); +const installedCommit: string | undefined = binaries.dawn?.commit; if (!installedCommit) { + console.error("โŒ binaries.json must record dawn.commit"); + process.exit(1); +} +if (!existsSync(join(root, "cpp/dawn/include/webgpu/webgpu.h"))) { console.error( - `โŒ ${dawnPackageJson} does not record the Dawn commit it was built from (dawn.commit)`, + "โŒ Dawn headers are missing. Run yarn copy-dawn-headers before building or checking Dawn." ); process.exit(1); } @@ -37,7 +40,7 @@ const dawnWorkarounds = [ upstream: "Dawn CL pending (see the workaround comment in the files)", }, { - // Not a workaround: a copy of a Dawn header the package does not ship. + // Not a workaround: an internal Dawn header absent from the public headers. // The functions it declares are exported by the Dawn binaries; the header // has to match the Dawn the binaries were built from. marker: "DAWN_VENDORED_EXTERNAL_TEXTURE_PARAMS", @@ -48,39 +51,25 @@ const dawnWorkarounds = [ }, ]; -const root = join(__dirname, ".."); - -// On Android, Gradle downloads Dawn from the binaries- release that -// binaries.json pins, while the Apple builds link the package, and -// react-native-skia pairs the two libraries on the package's version: the two -// pins must name the same Dawn. -const binaries = JSON.parse(readFileSync(join(root, "binaries.json"), "utf-8")); -if ( - binaries.version !== dawnPackage.version || - binaries.dawn?.commit !== installedCommit -) { - console.error( - `โŒ binaries.json pins binaries ${binaries.version} (Dawn ${String(binaries.dawn?.commit).slice(0, 10)}) but react-native-webgpu-dawn is ${dawnPackage.version} (Dawn ${installedCommit.slice(0, 10)}). Bump both together, see "Upgrading Dawn" in CONTRIBUTING.md.`, - ); - process.exit(1); -} - // Until #507 the build copied Dawn's headers into cpp/webgpu and cpp/dawn. -// Both come before the package's include directory on every include path -// (podspec HEADER_SEARCH_PATHS, android/CMakeLists.txt), so a copy left over -// from that build silently shadows the headers the binaries were built from. -// cpp/dawn/common is vendored on purpose (see the entry above). +// Both can shadow the prepared include directory. cpp/dawn/common is vendored +// on purpose; cpp/dawn/include holds the current release headers. const staleHeaderDirs = [ "cpp/webgpu", ...(existsSync(join(root, "cpp/dawn")) ? readdirSync(join(root, "cpp/dawn")) - .filter((entry) => entry !== "common" && !entry.startsWith(".")) + .filter( + (entry) => + entry !== "common" && entry !== "include" && !entry.startsWith(".") + ) .map((entry) => `cpp/dawn/${entry}`) : []), ].filter((dir) => existsSync(join(root, dir))); if (staleHeaderDirs.length > 0) { console.error( - `โŒ Stale Dawn header copies shadow react-native-webgpu-dawn's include directory: ${staleHeaderDirs.join(", ")}. Delete them; Dawn's headers come from the package since #507.`, + `โŒ Stale Dawn header copies shadow cpp/dawn/include: ${staleHeaderDirs.join( + ", " + )}. Delete them and run yarn copy-dawn-headers.` ); process.exit(1); } @@ -96,21 +85,28 @@ for (const workaround of dawnWorkarounds) { }); if (present.length === 0) { console.error( - `โŒ Workaround ${workaround.marker} is gone from the sources; remove its entry from scripts/check-dawn.ts`, + `โŒ Workaround ${workaround.marker} is gone from the sources; remove its entry from scripts/check-dawn.ts` ); failed = true; } else if (present.length !== workaround.files.length) { const missing = workaround.files.filter((file) => !present.includes(file)); console.error( - `โŒ Workaround ${workaround.marker} is only partially applied: missing from ${missing.join(", ")}`, + `โŒ Workaround ${ + workaround.marker + } is only partially applied: missing from ${missing.join(", ")}` ); failed = true; } else if (installedCommit !== workaround.commit) { console.error( - `โŒ Dawn changed (${workaround.commit.slice(0, 10)} -> ${installedCommit.slice(0, 10)}, react-native-webgpu-dawn ${dawnPackage.version}) but ${workaround.marker} is still in ${present.join(", ")}`, + `โŒ Dawn changed (${workaround.commit.slice( + 0, + 10 + )} -> ${installedCommit.slice(0, 10)}, binaries ${ + binaries.version + }) but ${workaround.marker} is still in ${present.join(", ")}` ); console.error( - ` Check whether this Dawn contains the upstream fix (${workaround.upstream}). If it does, remove the marked code and this entry; if not, update the commit in scripts/check-dawn.ts`, + ` Check whether this Dawn contains the upstream fix (${workaround.upstream}). If it does, remove the marked code and this entry; if not, update the commit in scripts/check-dawn.ts` ); failed = true; } @@ -120,5 +116,8 @@ if (failed) { } console.log( - `โœ… react-native-webgpu-dawn ${dawnPackage.version} (Dawn ${installedCommit.slice(0, 10)}) at ${dirname(dawnPackageJson)}`, + `โœ… binaries ${binaries.version} (Dawn ${installedCommit.slice( + 0, + 10 + )}) at ${join(root, "cpp/dawn/include")}` ); diff --git a/packages/webgpu/scripts/prepare-apple-binaries.sh b/packages/webgpu/scripts/prepare-apple-binaries.sh new file mode 100644 index 000000000..2f2484f55 --- /dev/null +++ b/packages/webgpu/scripts/prepare-apple-binaries.sh @@ -0,0 +1,309 @@ +#!/bin/bash +# +# CocoaPods and RN SwiftPM share this Node-free preparation phase. +# SDK archives contain static libraries; headers already ship in react-native-webgpu. +# Nothing compiles here: resolve libraries, update XCFramework slices, then copy +# the selected SDK's archives into Xcode's library search path. +# +# Usage: +# /bin/bash prepare-apple-binaries.sh --config +# /bin/bash prepare-apple-binaries.sh --config --spm-package +# /bin/bash prepare-apple-binaries.sh --output --assembly-root +# +# Xcode environment: +# PLATFORM_NAME, EFFECTIVE_PLATFORM_NAME, SDK_VARIANT select the SDK/variant. +# ARCHS, EXCLUDED_ARCHS, ONLY_ACTIVE_ARCH, CURRENT_ARCH, NATIVE_ARCH_ACTUAL +# select required architectures; metadata may contain additional ones. +# IPHONEOS_DEPLOYMENT_TARGET, TVOS_DEPLOYMENT_TARGET, MACOSX_DEPLOYMENT_TARGET +# must meet the selected archive's deployment floor. +# BUILT_PRODUCTS_DIR and OBJROOT supply default output/assembly directories. +# ENABLE_USER_SCRIPT_SANDBOXING must be NO on the target running this phase. +# +# Overrides: +# RNSKIA_CACHE_DIR changes the shared download cache (default: +# ~/Library/Caches/react-native-skia). Version/checksum subdirectories remain. +# REACT_NATIVE_SKIA_BINARIES_URL changes the release base URL; the installed +# binaries.json still pins the tag and checksums, including for mirrors. +# libs/apple, when present, is a read-only local Dawn override. +set -Eeuo pipefail + +# MARK: Package paths and shared constants + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PACKAGE_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +source "$SCRIPT_DIR/apple-binaries-utils.sh" + +# MARK: Failure reporting and cleanup + +# Report the actual command failure before Xcode's generic PhaseScriptExecution error. +report_failure() { + local status="$1" line="$2" command="$3" + if [[ ! -f "$WORK_DIR/failed" ]]; then + printf 'error: [react-native-webgpu] Preparation failed at line %s (exit %s): %s. Check the diagnostic above, permissions, and free disk space.\n' "$line" "$status" "$command" >&2 + : > "$WORK_DIR/failed" + fi + exit "$status" +} + +# Release only locks still owned by this process, never a later cache writer. +cleanup() { + # Missing pid files are expected for locks released before EXIT. Bash 3.2 + # otherwise inherits ERR into their reads and reports a successful run as failed. + trap - ERR + local directory owner entry + for directory in ${LOCKS[@]+"${LOCKS[@]}"}; do + owner=$(cat "$directory/pid" 2>/dev/null) || owner='' + if [[ "$owner" == "$$" ]]; then rm -rf "$directory"; fi + done + # Interrupted downloads/copies are temporary. Keep verified cache entries, + # local overrides, and complete XCFramework slices from earlier builds. + for entry in ${TEMP_PATHS[@]+"${TEMP_PATHS[@]}"}; do rm -rf "$entry"; done + rm -rf "$WORK_DIR" +} + +# MARK: Xcode target selection + +# Sets SDK and REQUESTED_ARCHS from Xcode's expanded architecture settings. +# Catalyst uses the macOS SDK, but must select iOS/macabi libraries. Exclusions +# apply before ONLY_ACTIVE_ARCH reduces the request to the current architecture. +detect_target() { + SDK="${PLATFORM_NAME:-}" + if [[ "$SDK" == macosx ]]; then + SDK=macos + if [[ "${EFFECTIVE_PLATFORM_NAME:-}" == -maccatalyst || "${SDK_VARIANT:-}" == maccatalyst || "${SDK_VARIANT:-}" == iosmac ]]; then + SDK=maccatalyst + fi + fi + sdk_descriptor "$SDK" >/dev/null || + fail "Unsupported Apple platform '${PLATFORM_NAME:-unset}' (EFFECTIVE_PLATFORM_NAME='${EFFECTIVE_PLATFORM_NAME:-}'). Supported SDKs: ${RNWGPU_SDKS[*]}. Build an Apple target in Xcode." + local arch excluded skip seen='' active="${CURRENT_ARCH:-}" + if [[ -z "$active" || "$active" == undefined_arch ]]; then active="${NATIVE_ARCH_ACTUAL:-}"; fi + REQUESTED_ARCHS=() + for arch in ${ARCHS:-}; do + [[ "$arch" =~ ^[A-Za-z0-9_]+$ ]] || fail "Invalid architecture in ARCHS: $arch" + skip=false + for excluded in ${EXCLUDED_ARCHS:-}; do + if [[ "$arch" == "$excluded" ]]; then skip=true; fi + done + if [[ "$skip" == false && " $seen " != *" $arch "* ]]; then + REQUESTED_ARCHS+=("$arch") + seen="$seen $arch" + fi + done + ((${#REQUESTED_ARCHS[@]} > 0)) || fail "Cannot determine Apple architectures from ARCHS='${ARCHS:-}'. Run preparation from an Xcode target." + if [[ "${ONLY_ACTIVE_ARCH:-NO}" == YES && -n "$active" && " $seen " == *" $active "* ]]; then + REQUESTED_ARCHS=("$active") + fi +} + +# MARK: CocoaPods and SwiftPM configuration + +# Plain JSON is consumed by the podspec and the mandatory RN JavaScript adapter. +# Names are prefixed at staging so they cannot collide with another dependency's +# libwebgpu_dawn.a in the shared build-products directory. +print_configuration() { + local name="${RNWGPU_DAWN_LIBRARY#lib}" + printf '{"linkNames":["rnwgpu_%s"]}\n' "${name%.a}" +} + +# Keep generated files stable across repeated SwiftPM autolinking synchronizations. +write_if_changed() { + local source="$1" destination="$2" + if ! cmp -s "$source" "$destination"; then + mkdir -p "$(dirname "$destination")" + cp "$source" "$destination" + fi +} + +# write_spm_package DIRECTORY: generate a link-settings target, not binaryTargets. +# SwiftPM resolves this small local package before Xcode knows the selected SDK; +# the build phase provides its libraries later. Headers stay in react-native-webgpu. +# Only the RN hook is JavaScript. Package generation and the native phase use shell. +write_spm_package() { + local directory="$1" library name + printf '// Link settings only; Dawn headers ship in react-native-webgpu.\n' > "$WORK_DIR/ReactNativeWebGPUBinaries.h" + printf '// Propagates static binary link settings to the app.\n' > "$WORK_DIR/link.c" + cat > "$WORK_DIR/Package.swift" <<'SWIFT' +// swift-tools-version: 6.0 +// Generated by react-native-webgpu; SDK binaries are prepared by its Xcode phase. +import PackageDescription + +let package = Package( + name: "ReactNativeWebGPUBinaries", + platforms: [.iOS(.v15), .tvOS(.v15), .macOS(.v14)], + products: [.library(name: "ReactNativeWebGPUBinaries", targets: ["ReactNativeWebGPUBinaries"])], + targets: [ + .target( + name: "ReactNativeWebGPUBinaries", + path: ".", + sources: ["link.c"], + publicHeadersPath: "include", + linkerSettings: [ +SWIFT + for library in "${ALL_LIBRARIES[@]}"; do + name="${library#lib}" + printf ' .linkedLibrary("rnwgpu_%s"),\n' "${name%.a}" >> "$WORK_DIR/Package.swift" + done + cat >> "$WORK_DIR/Package.swift" <<'SWIFT' + ] + ) + ] +) +SWIFT + write_if_changed "$WORK_DIR/Package.swift" "$directory/Package.swift" + write_if_changed "$WORK_DIR/link.c" "$directory/link.c" + write_if_changed "$WORK_DIR/ReactNativeWebGPUBinaries.h" "$directory/include/ReactNativeWebGPUBinaries.h" +} + +# MARK: Incremental XCFramework assembly + +# write_xcframework_plist CONTAINER LIBRARY METADATA_ROOT: describe only SDKs +# already prepared in this build folder. A later SDK appends its own slice. +# All values written to XML are fixed library/platform names or validated archs. +# The descriptors come from saved SDK metadata, rather than hardcoded slice names. +write_xcframework_plist() { + local container="$1" library="$2" metadata_root="$3" sdk file identifier archs arch + local ignored platform variant deployment + { + cat <<'PLIST' + + + +CFBundlePackageTypeXFWK +XCFrameworkFormatVersion1.0 +AvailableLibraries +PLIST + for sdk in "${RNWGPU_SDKS[@]}"; do + file="$metadata_root/$sdk.json" + [[ -f "$file" ]] || continue + IFS='|' read -r ignored platform variant deployment <<< "$(sdk_descriptor "$sdk")" + archs=$(json_strings "$file" architectures) + identifier="$platform-$(printf '%s\n' "$archs" | LC_ALL=C sort | paste -sd _ -)${variant:+-$variant}" + printf 'LibraryIdentifier%s\n' "$identifier" + printf 'LibraryPath%s\n' "$library" + printf 'SupportedPlatform%s\n' "$platform" + if [[ -n "$variant" ]]; then printf 'SupportedPlatformVariant%s\n' "$variant"; fi + printf 'SupportedArchitectures\n' + while IFS= read -r arch; do printf '%s\n' "$arch"; done <<< "$archs" + printf '\n' + done + printf '\n' + } > "$container/Info.plist" +} + +# Clone on APFS where possible; fall back to an ordinary copy on other volumes. +copy_library() { + cp -c "$1" "$2" 2>/dev/null || cp -p "$1" "$2" +} + +# Update one SDK atomically and retain other SDKs already prepared in this build. +# Returns the module's CONTAINER_ROOT for the linker staging step. +# The caller holds the assembly lock across both assembly and linker staging. +assemble_module() { + local root="$CONTAINERS/$MODULE" library existing=true temporary previous='' old_archs platform variant ignored deployment + local signature_file="$CONTAINERS/$MODULE/.slices/$SDK.signature" + CONTAINER_ROOT="$root" + for library in "${MODULE_LIBRARIES[@]}"; do + if [[ ! -f "$root/${library%.a}.xcframework/$META_IDENTIFIER/$library" || ! -f "$root/${library%.a}.xcframework/Info.plist" ]]; then existing=false; fi + done + if [[ -f "$signature_file" && "$(cat "$signature_file")" == "$SOURCE_SIGNATURE" && "$existing" == true ]]; then return; fi + temporary="$root.$$.assemble" + TEMP_PATHS+=("$temporary") + mkdir -p "$temporary" + if [[ -d "$root" ]]; then ditto "$root" "$temporary"; fi + if [[ -f "$temporary/.slices/$SDK.json" ]]; then + old_archs=$(json_strings "$temporary/.slices/$SDK.json" architectures) + IFS='|' read -r ignored platform variant deployment <<< "$(sdk_descriptor "$SDK")" + previous="$platform-$(printf '%s\n' "$old_archs" | LC_ALL=C sort | paste -sd _ -)${variant:+-$variant}" + fi + mkdir -p "$temporary/.slices" + cp "$SOURCE_DIRECTORY/metadata.json" "$temporary/.slices/$SDK.json" + for library in "${MODULE_LIBRARIES[@]}"; do + local container="$temporary/${library%.a}.xcframework" + if [[ -n "$previous" && "$previous" != "$META_IDENTIFIER" ]]; then rm -rf "$container/$previous"; fi + mkdir -p "$container/$META_IDENTIFIER" + copy_library "$SOURCE_DIRECTORY/$library" "$container/$META_IDENTIFIER/$library" + write_xcframework_plist "$container" "$library" "$temporary/.slices" + done + printf '%s\n' "$SOURCE_SIGNATURE" > "$temporary/.slices/$SDK.signature" + replace_directory "$temporary" "$root" + note "Prepared $SDK XCFramework slices ($(printf '%s' "$META_ARCHS" | tr '\n' ' '))" +} + +# MARK: Linker inputs + +# stage_module: expose the selected slice as librnwgpu_.a in OUTPUT. +# Static libraries link into the app; XCFramework containers are build inputs, +# rather than dynamic frameworks copied into the app's Frameworks directory. +# Build-product stamps include SDK/version/source identity, avoiding equal-size +# archives from another platform and unnecessary copies on incremental builds. +stage_module() { + local library destination temporary stamp="$OUTPUT/.rnwgpu-$MODULE.signature" + local signature="$SDK:$VERSION:$SOURCE_SIGNATURE" name + mkdir -p "$OUTPUT" + for library in "${MODULE_LIBRARIES[@]}"; do + name="${library#lib}" + destination="$OUTPUT/librnwgpu_$name" + if [[ -f "$stamp" && "$(cat "$stamp")" == "$signature" && -f "$destination" ]]; then continue; fi + temporary="$destination.$$.tmp" + TEMP_PATHS+=("$temporary") + copy_library "$CONTAINER_ROOT/${library%.a}.xcframework/$META_IDENTIFIER/$library" "$temporary" + mv "$temporary" "$destination" + done + printf '%s\n' "$signature" > "$stamp" +} + +# MARK: Entry point + +# Configuration mode performs no downloads; native mode requires Xcode settings. +# Global state is shared with helpers; initialize cleanup ownership before any +# operation that may fail. CLI arguments override the Xcode directory defaults. +main() { + WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/rnwgpu-apple.XXXXXX") + LOCKS=() + TEMP_PATHS=() + trap 'report_failure "$?" "$LINENO" "$BASH_COMMAND"' ERR + trap cleanup EXIT + trap 'exit 130' INT + trap 'exit 143' TERM + local config=false spm_package='' manifest_hash + OUTPUT="${BUILT_PRODUCTS_DIR:-}" + ASSEMBLY_ROOT="${OBJROOT:+$OBJROOT/ReactNativeWebGPUBinaries}" + while (($# > 0)); do + case "$1" in + --config) config=true; shift ;; + --output|--assembly-root|--spm-package) + (($# > 1)) && [[ -n "$2" ]] || fail "Missing value for $1." + case "$1" in + --output) OUTPUT="$2" ;; + --assembly-root) ASSEMBLY_ROOT="$2" ;; + --spm-package) spm_package="$2" ;; + esac + shift 2 ;; + *) fail "Unknown preparation option '$1'." ;; + esac + done + if [[ "$config" != true ]]; then detect_target; fi + load_release + ALL_LIBRARIES=("$RNWGPU_DAWN_LIBRARY") + if [[ -n "$spm_package" ]]; then write_spm_package "$spm_package"; fi + if [[ "$config" == true ]]; then print_configuration; return; fi + [[ "$OUTPUT" == /* && "$ASSEMBLY_ROOT" == /* ]] || fail 'Missing absolute binary output/build directory. Run preparation from the installed Xcode phase.' + [[ "${ENABLE_USER_SCRIPT_SANDBOXING:-NO}" != YES ]] || fail 'Binary preparation needs release-cache/build-product access. Set User Script Sandboxing to No on this app target.' + [[ -f "$PACKAGE_ROOT/cpp/dawn/include/webgpu/webgpu.h" ]] || + fail 'Dawn headers are missing from react-native-webgpu. Reinstall it; contributors must run yarn copy-dawn-headers.' + # Isolate assembly by manifest while retaining other SDKs of the same release. + manifest_hash=$(hash_file "$MANIFEST") + CONTAINERS="$ASSEMBLY_ROOT/$VERSION-${manifest_hash:0:16}" + MODULE=dawn + MODULE_LIBRARIES=("$RNWGPU_DAWN_LIBRARY") + resolve_libraries "$SDK" + acquire_lock "$ASSEMBLY_ROOT.lock" + assemble_module + stage_module + release_lock "$ASSEMBLY_ROOT.lock" + note "Ready: $SDK (${REQUESTED_ARCHS[*]}); Dawn own" +} + +# Sourcing exposes helpers for verification; direct execution prepares binaries. +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then main "$@"; fi diff --git a/packages/webgpu/scripts/prepare-dawn-headers.mjs b/packages/webgpu/scripts/prepare-dawn-headers.mjs new file mode 100644 index 000000000..90f5f041e --- /dev/null +++ b/packages/webgpu/scripts/prepare-dawn-headers.mjs @@ -0,0 +1,172 @@ +/** + * Prepares source/generated Dawn headers for contributors and npm publishing. + * Reads only binaries.json and shares Skia's OS-specific release cache. + * Requires Node plus unzip (macOS/Linux) or PowerShell (Windows); no Yarn install. + * Apple Xcode preparation is separate and never invokes this script. + */ +import crypto from "node:crypto"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const PackageRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + ".." +); +const AssetName = "dawn-headers.zip"; +const ReleaseBaseURL = + "https://github.com/wcandillon/react-native-skia/releases/download"; + +/** Hash the small header archive before extracting or reusing it. + * @param {string} file + */ +const sha256 = (file) => + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + +/** Match Skia's user-cache location and respect the shared override. */ +const cacheDirectory = () => { + if (process.env.RNSKIA_CACHE_DIR) { + if (!path.isAbsolute(process.env.RNSKIA_CACHE_DIR)) { + throw new Error("RNSKIA_CACHE_DIR must be an absolute path."); + } + return process.env.RNSKIA_CACHE_DIR; + } + let root = process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"); + if (process.platform === "darwin") { + root = path.join(os.homedir(), "Library", "Caches"); + } else if (process.platform === "win32") { + root = + process.env.LOCALAPPDATA ?? path.join(os.homedir(), "AppData", "Local"); + } + return path.join(root, "react-native-skia"); +}; + +/** Fetch one pinned asset; mirrors may also use file:/// URLs. + * @param {URL} url + * @param {string} destination + */ +const download = async (url, destination) => { + if (url.protocol === "file:") { + fs.copyFileSync(fileURLToPath(url), destination); + return; + } + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + if (!response.ok) { + throw new Error(`Cannot download ${url}: HTTP ${response.status}.`); + } + fs.writeFileSync(destination, Buffer.from(await response.arrayBuffer())); +}; + +/** Use system ZIP extraction so the SDK syntax job needs no npm dependencies. + * @param {string} archive + * @param {string} destination + */ +const extract = (archive, destination) => { + if (process.platform === "win32") { + // Environment values preserve spaces/apostrophes without PowerShell quoting. + execFileSync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "Expand-Archive -LiteralPath $env:RNWGPU_HEADERS_ARCHIVE -DestinationPath $env:RNWGPU_HEADERS_DESTINATION -ErrorAction Stop", + ], + { + env: { + ...process.env, + RNWGPU_HEADERS_ARCHIVE: archive, + RNWGPU_HEADERS_DESTINATION: destination, + }, + } + ); + return; + } + execFileSync("unzip", ["-q", archive, "-d", destination]); +}; + +/** Verify the release archive before replacing cpp/dawn/include. */ +const prepare = async () => { + const binaries = JSON.parse( + fs.readFileSync(path.join(PackageRoot, "binaries.json"), "utf8") + ); + const { version, tag } = binaries; + const expected = binaries.assets?.[AssetName]?.sha256; + if ( + !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version) || + tag !== `binaries-${version}` || + !/^[a-f0-9]{64}$/.test(expected) + ) { + throw new Error( + "Invalid release or Dawn header checksum in binaries.json." + ); + } + + const cache = path.join(cacheDirectory(), tag, expected); + const archive = path.join(cache, AssetName); + fs.mkdirSync(cache, { recursive: true }); + if (!fs.existsSync(archive) || sha256(archive) !== expected) { + const url = new URL( + `${tag}/${AssetName}`, + `${(process.env.REACT_NATIVE_SKIA_BINARIES_URL ?? ReleaseBaseURL).replace( + /\/$/, + "" + )}/` + ); + // Publish complete verified ZIPs atomically; other projects share this cache. + const temporary = fs.mkdtempSync(path.join(cache, ".headers-")); + try { + const candidate = path.join(temporary, AssetName); + console.log(`Downloading ${url}`); + await download(url, candidate); + if (sha256(candidate) !== expected) { + throw new Error( + `SHA-256 mismatch for ${AssetName}; download discarded.` + ); + } + fs.renameSync(candidate, archive); + } finally { + fs.rmSync(temporary, { recursive: true, force: true }); + } + } else { + console.log(`Verified cached ${AssetName} (${version}).`); + } + + const dawnRoot = path.join(PackageRoot, "cpp", "dawn"); + fs.mkdirSync(dawnRoot, { recursive: true }); + const temporary = fs.mkdtempSync(path.join(dawnRoot, ".headers-")); + const destination = path.join(dawnRoot, "include"); + const previous = path.join(temporary, "previous"); + try { + extract(archive, temporary); + const include = path.join(temporary, "include"); + if (!fs.existsSync(path.join(include, "webgpu", "webgpu.h"))) { + throw new Error(`${AssetName} has no include/webgpu/webgpu.h.`); + } + // Keep existing headers if download/extraction fails. Leave vendored common/ + // untouched: only the generated/source include tree is replaced. + if (fs.existsSync(destination)) { + fs.renameSync(destination, previous); + } + try { + fs.renameSync(include, destination); + } catch (error) { + if (fs.existsSync(previous)) { + fs.renameSync(previous, destination); + } + throw error; + } + console.log(`Prepared Dawn headers ${version}: ${destination}`); + } finally { + fs.rmSync(temporary, { recursive: true, force: true }); + } +}; + +prepare().catch((error) => { + console.error( + `Dawn header preparation failed: ${error.message}\nCheck binaries.json, the published release, and REACT_NATIVE_SKIA_BINARIES_URL, then retry.` + ); + process.exitCode = 1; +}); diff --git a/packages/webgpu/scripts/spm-plugin.js b/packages/webgpu/scripts/spm-plugin.js new file mode 100644 index 000000000..86f5687ce --- /dev/null +++ b/packages/webgpu/scripts/spm-plugin.js @@ -0,0 +1,130 @@ +"use strict"; + +// MARK: Autolinking helpers + +const fs = require("fs"); +const path = require("path"); +const { execFileSync } = require("child_process"); + +/** Quote a generated path as one shell argument, including spaces/apostrophes. */ +const shellQuote = (value) => `'${value.replace(/'/g, "'\\''")}'`; + +/** + * RN requires a JavaScript autolinking entry point. It delegates configuration + * and package generation to Bash; the installed Xcode phase never invokes Node. + * RN invokes this hook again when it regenerates the autolinked package graph. + * Configuration reads the installed release pin; binary downloads wait for Xcode + * to supply the SDK and architecture build settings. + */ +module.exports = function webgpuSwiftPM(context) { + const packageRoot = path.join(__dirname, ".."); + const scriptPath = path.join(__dirname, "prepare-apple-binaries.sh"); + + // MARK: RN hook compatibility + + // Check the installed hook's capability, rather than assuming a semver string + // describes it: local RN checkouts and prereleases may carry different tooling. + // Without scriptPhases, libraries would be linked before they were prepared. + const contract = path.join( + context.reactNativeRoot, + "scripts/spm/autolinking-plugins.js" + ); + if ( + !fs.existsSync(contract) || + !fs.readFileSync(contract, "utf8").includes("scriptPhases") + ) { + throw new Error( + "react-native-webgpu: automatic SwiftPM binary preparation requires React Native 0.87.1 or newer. Upgrade React Native or use CocoaPods." + ); + } + + // MARK: Generated Dawn link settings + + // WebGPU always supplies Dawn. Skia's integration opts out of its own copy + // when this native module is linked; both packages validate the same pin. + // Configuration writes a local link-settings package, without downloading SDKs. + execFileSync( + "/bin/bash", + [ + scriptPath, + "--config", + "--spm-package", + path.join(context.outputDir, "ReactNativeWebGPUBinaries"), + ], + { encoding: "utf8" } + ); + + // MARK: Xcode preparation phase + + // RN already resolved the package during autolinking. A project-relative path + // handles hoisting/pnpm and relocation without Node lookups inside Xcode. + // Resolve symlinks on both sides before computing the path so workspace package + // aliases do not produce a different path after Xcode expands SRCROOT. + const relativeScript = shellQuote( + path.relative(fs.realpathSync(context.appRoot), fs.realpathSync(scriptPath)) + ); + + // Xcode expands SDK/architecture variables when this phase runs. Cache and + // assembly logic stays in the shared shell scripts used by CocoaPods too. + // exec preserves their exit status and error diagnostics in Xcode's build log. + const script = `set -eo pipefail +# Check before reading package files, which script sandboxing may already deny. +if [ "\${ENABLE_USER_SCRIPT_SANDBOXING:-NO}" = YES ]; then + echo "error: [react-native-webgpu] Set User Script Sandboxing to No on this app target; preparation needs release-cache and build-product access." >&2 + exit 1 +fi +PREPARE_SCRIPT="$SRCROOT"/${relativeScript} +if [ ! -f "$PREPARE_SCRIPT" ]; then + echo "error: [react-native-webgpu] Binary preparation script is missing. Reinstall dependencies and rerun react-native spm update." >&2 + exit 1 +fi +exec /bin/bash "$PREPARE_SCRIPT" --output "$BUILT_PRODUCTS_DIR" --assembly-root "$OBJROOT/ReactNativeWebGPUBinaries" +`; + + // MARK: Native package registration + + // RN delegates the plugin host's native contribution entirely to this hook. + // Recreate its usual libs/ alias so Package.swift's relative React and + // generated-code dependencies resolve within this app's autolinking tree. + const packageAlias = path.join( + context.outputDir, + "libs", + "ReactNativeWebGPU" + ); + fs.mkdirSync(path.dirname(packageAlias), { recursive: true }); + if (!fs.existsSync(packageAlias)) { + fs.symlinkSync(packageRoot, packageAlias, "dir"); + } + + // MARK: RN phase reconciliation and synchronization + + return { + packageDependencies: [{ name: "ReactNativeWebGPU", path: packageAlias }], + productDependencies: [ + { name: "ReactNativeWebGPU", package: "ReactNativeWebGPU" }, + ], + scriptPhases: [ + { + // RN uses this stable id to update the phase instead of adding duplicates. + id: "react-native-webgpu.prepare-binaries", + name: "Prepare React Native WebGPU binaries", + script, + // Bundled headers allow package compilation without downloading binaries; + // prepare libraries before the app's compile/link steps consume them. + position: "beforeCompile", + // SDK selection and local overrides are not fixed Xcode input files. + // Run every build; shell signatures skip unchanged assembly and copies. + alwaysOutOfDate: true, + }, + ], + // These trigger RN autolinking regeneration when the pin or adapter changes. + // They are separate from the preparation phase's own binary/cache checks. + watchPaths: [ + path.join(packageRoot, "binaries.json"), + path.join(packageRoot, "Package.swift"), + __filename, + scriptPath, + path.join(__dirname, "apple-binaries-utils.sh"), + ], + }; +}; diff --git a/packages/webgpu/src/__tests__/FeatureNames.spec.ts b/packages/webgpu/src/__tests__/FeatureNames.spec.ts index 546859351..e3de1816c 100644 --- a/packages/webgpu/src/__tests__/FeatureNames.spec.ts +++ b/packages/webgpu/src/__tests__/FeatureNames.spec.ts @@ -7,11 +7,8 @@ const cppDir = path.resolve(__dirname, "..", "..", "cpp"); const read = (...segments: string[]) => fs.readFileSync(path.join(cppDir, ...segments), "utf-8"); -// The Dawn headers of the installed react-native-webgpu-dawn package. -const dawnInclude = path.join( - path.dirname(require.resolve("react-native-webgpu-dawn/package.json")), - "include", -); +// Read the same prepared release headers bundled for native consumers. +const dawnInclude = path.join(cppDir, "dawn", "include"); // Every value of wgpu::FeatureName, straight from the Dawn headers (the // webgpu/ header is a shim onto the generated dawn/ one). A milestone upgrade diff --git a/packages/webgpu/tests/cpp/CMakeLists.txt b/packages/webgpu/tests/cpp/CMakeLists.txt index 55b423784..f4ce00bfe 100644 --- a/packages/webgpu/tests/cpp/CMakeLists.txt +++ b/packages/webgpu/tests/cpp/CMakeLists.txt @@ -4,16 +4,11 @@ project(react_native_webgpu_cpp_tests LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED True) -# Dawn's headers come from the react-native-webgpu-dawn package, as in the -# Android and iOS builds. The code under test needs only its headers. -execute_process( - COMMAND node -e "process.stdout.write(require('path').dirname(require.resolve('react-native-webgpu-dawn/package.json')))" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - OUTPUT_VARIABLE DAWN_DIR - RESULT_VARIABLE DAWN_DIR_RESULT -) -if(NOT DAWN_DIR_RESULT EQUAL 0) - message(FATAL_ERROR "react-native-webgpu: the react-native-webgpu-dawn package was not found. Install dependencies (yarn install) first.") +# Use the same prepared headers shipped to CocoaPods and SwiftPM consumers. +# Unit tests need no Dawn library and perform no binary download here. +set(DAWN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../cpp/dawn") +if(NOT EXISTS "${DAWN_DIR}/include/webgpu/webgpu.h") + message(FATAL_ERROR "react-native-webgpu: Dawn headers are missing. Run yarn copy-dawn-headers first.") endif() include(FetchContent) diff --git a/spm-example/README.md b/spm-example/README.md index 589dc9e50..c984221dd 100644 --- a/spm-example/README.md +++ b/spm-example/README.md @@ -14,20 +14,24 @@ same way. ## Why it sits outside the yarn workspace -Swift Package Manager support requires **React Native 0.87 or newer**; earlier -releases ship no `scripts/spm`. `apps/example` is pinned to an older version, so -this app keeps its own `node_modules` and installs with npm. It ships no +Automatic SwiftPM binary preparation requires **React Native 0.87.1 or newer**, +with the autolinking plugin's `scriptPhases` hook. This harness keeps its pinned +React Native separate from the workspace, with its own `node_modules` installed +using npm. It ships no lockfile: `react` and `react-native` are pinned exactly in `package.json`. `react-native-webgpu` is linked from the workspace with -`file:../packages/webgpu`, so it builds the working tree, not a published release. +`file:../packages/webgpu`, so it builds the working tree, not a published release. Install the workspace +and run `yarn workspace react-native-webgpu copy-dawn-headers` first; published +packages already include those headers. Xcode prepares only the selected SDK +from the pinned release, using the same cache as react-native-skia. ## Build and run ```sh npm install cd ios -npx react-native spm add --deintegrate # injects the Swift packages into the .xcodeproj +npx react-native spm update # refreshes the committed project and preparation phase xcodebuild -project SpmExample.xcodeproj -scheme SpmExample \ -configuration Release -sdk iphonesimulator \ @@ -40,10 +44,11 @@ Release embeds its own JS bundle, so it needs no Metro. For Debug, run ## Gotchas -- **Stale `Package.resolved`.** Xcode caches package pins in - `ios/SpmExample.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved`. - After changing the `react-native-webgpu-dawn` version, delete it first or the - old pin is silently kept. +- **Binary preparation.** The app phase downloads only the selected SDK's Dawn + archive and stages its static library. Failures print `error: [react-native-webgpu]`; + expand **Prepare React Native WebGPU binaries** in Xcode's report navigator. + Set **User Script Sandboxing** to **NO** on the app target. See + [cache/local-build details](../packages/webgpu/CONTRIBUTING.md#how-apple-binaries-are-prepared). - **`spm update` re-adds an absolute `HERMES_CLI_PATH`.** On React Native 0.87.1 the injector writes this machine's own path to `hermesc` into `project.pbxproj` and `.spm-injected.json`. The build does not need it, so it diff --git a/spm-example/ios/SpmExample/AppDelegate.swift b/spm-example/ios/SpmExample/AppDelegate.swift index eefddcb3b..99870d7af 100644 --- a/spm-example/ios/SpmExample/AppDelegate.swift +++ b/spm-example/ios/SpmExample/AppDelegate.swift @@ -5,11 +5,11 @@ import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? - var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? + // MARK: - Application setup + func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil @@ -21,18 +21,35 @@ class AppDelegate: UIResponder, UIApplicationDelegate { reactNativeDelegate = delegate reactNativeFactory = factory - window = UIWindow(frame: UIScreen.main.bounds) + return true + } +} - factory.startReactNative( - withModuleName: "SpmExample", - in: window, - launchOptions: launchOptions - ) +// MARK: - Scene lifecycle - return true +// Scene-owned windows are required when building with the iOS 27 SDK. +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions + ) { + guard let windowScene = scene as? UIWindowScene, + let appDelegate = UIApplication.shared.delegate as? AppDelegate, + let factory = appDelegate.reactNativeFactory else { + return + } + + let window = UIWindow(windowScene: windowScene) + self.window = window + factory.startReactNative(withModuleName: "SpmExample", in: window) } } +// MARK: - React Native bundle + class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() diff --git a/spm-example/ios/SpmExample/Info.plist b/spm-example/ios/SpmExample/Info.plist index 9065468f9..88971e1f1 100644 --- a/spm-example/ios/SpmExample/Info.plist +++ b/spm-example/ios/SpmExample/Info.plist @@ -36,6 +36,24 @@ NSLocationWhenInUseUsageDescription + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + + + + UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities diff --git a/yarn.lock b/yarn.lock index b11a520ea..01ff9e36b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8134,7 +8134,6 @@ __metadata: react-native-reanimated: 4.7.1 react-native-safe-area-context: ^5.4.0 react-native-screens: ^4.30.1 - react-native-skia: 3.10.0 react-native-test-app: 5.4.17 react-native-vision-camera: 5.0.10 react-native-vision-camera-worklets: 5.0.10 @@ -9330,15 +9329,6 @@ __metadata: languageName: node linkType: hard -"canvaskit-wasm@npm:0.41.1": - version: 0.41.1 - resolution: "canvaskit-wasm@npm:0.41.1" - dependencies: - "@webgpu/types": 0.1.21 - checksum: d8d673497e41f07b843766234dd89d73d95d5da3bbc2befa1e67d399c4a54ff2196126391f110b985ac2cadce6928a0a2880b00843c06d61ba747a1b5b8b3b90 - languageName: node - linkType: hard - "ccount@npm:^2.0.0": version: 2.0.1 resolution: "ccount@npm:2.0.1" @@ -11110,7 +11100,6 @@ __metadata: next: ^16.2.7 react: 19.3.0 react-dom: 19.3.0 - react-native-skia: 3.10.0 react-native-vision-camera: 5.0.10 react-native-web: ^0.21.2 react-native-webgpu: "workspace:*" @@ -12254,7 +12243,6 @@ __metadata: react-native-reanimated: 4.6.0 react-native-safe-area-context: ^5.4.0 react-native-screens: 4.19.0 - react-native-skia: 3.10.0 react-native-test-app: 5.4.17 react-native-webgpu: "workspace:*" react-native-worklets: 0.12.2 @@ -20769,63 +20757,6 @@ __metadata: languageName: node linkType: hard -"react-native-skia-graphite-android@npm:158.0.0": - version: 158.0.0 - resolution: "react-native-skia-graphite-android@npm:158.0.0" - checksum: b8306f52ce35761df064f4f0103f977802fc48cfe43d3b354ece441a34c7d4841ce3626186d9ffb53e6f1d62ba4d10845d71d87b9aa4c923228d4c410390d3c0 - languageName: node - linkType: hard - -"react-native-skia-graphite-apple-ios@npm:158.0.0": - version: 158.0.0 - resolution: "react-native-skia-graphite-apple-ios@npm:158.0.0" - checksum: be8cea926a20756cf48088cdc75ca9b4b4b4c328e4cd7ad846c6d31d4fbdf6114dbfa00d546b83541a86534160e2bf3ae53bc1d378dfee57e7d44e09d7a0542b - languageName: node - linkType: hard - -"react-native-skia-graphite-apple-macos@npm:158.0.0": - version: 158.0.0 - resolution: "react-native-skia-graphite-apple-macos@npm:158.0.0" - checksum: 61b14ad117919ce1215c1e44ba5f478cd97ebabead39df71a069e06992e6385fb1d85406fcc898c5d189e665e899ccd02b816cd34a389607ea765a7f47bc129a - languageName: node - linkType: hard - -"react-native-skia-graphite-apple-tvos@npm:158.0.0": - version: 158.0.0 - resolution: "react-native-skia-graphite-apple-tvos@npm:158.0.0" - checksum: eb4191148323277e0a4c5c0ef9fc38afc8b55ff629badf7c7c23cddb2c6fb9ef328e976c3758c7637e76ab0122155365cebad9fad0587aefc06a0fa3898711b9 - languageName: node - linkType: hard - -"react-native-skia@npm:3.10.0": - version: 3.10.0 - resolution: "react-native-skia@npm:3.10.0" - dependencies: - canvaskit-wasm: 0.41.1 - react-native-skia-graphite-android: 158.0.0 - react-native-skia-graphite-apple-ios: 158.0.0 - react-native-skia-graphite-apple-macos: 158.0.0 - react-native-skia-graphite-apple-tvos: 158.0.0 - react-native-webgpu-dawn: 158.0.0 - react-reconciler: 0.33.0 - peerDependencies: - react: ">=19.0" - react-native: ">=0.79" - react-native-reanimated: ">=4.0.0" - react-native-worklets: ">=0.7.0" - peerDependenciesMeta: - react-native: - optional: true - react-native-reanimated: - optional: true - react-native-worklets: - optional: true - bin: - setup-skia-web: scripts/setup-canvaskit.js - checksum: 1827e9b8af63d0d5c2b08dbc1348f449d6e3590e765efdd517c32f90b15e1673cd760c13a35b645827c91ceb4c8c2d00ad34ca551b7a72c1ee4dfd1a1ce00305 - languageName: node - linkType: hard - "react-native-test-app@npm:5.4.17": version: 5.4.17 resolution: "react-native-test-app@npm:5.4.17" @@ -20906,13 +20837,6 @@ __metadata: languageName: node linkType: hard -"react-native-webgpu-dawn@npm:158.0.0": - version: 158.0.0 - resolution: "react-native-webgpu-dawn@npm:158.0.0" - checksum: 91affe20aa3a65cb2f33861c501cf56bb2d59b148fa159f4dc8bbdf232e995db42ae499ea86f131cb107106b55eaa747ec42f36565db7e43a823a9d4f64ec9dd - languageName: node - linkType: hard - "react-native-webgpu-monorepo@workspace:.": version: 0.0.0-use.local resolution: "react-native-webgpu-monorepo@workspace:." @@ -20973,7 +20897,6 @@ __metadata: react-native-builder-bob: ^0.23.2 react-native-reanimated: 4.7.1 react-native-web: ^0.21.2 - react-native-webgpu-dawn: 158.0.0 react-native-worklets: 0.13.1 seedrandom: ^3.0.5 semantic-release: ^25.0.9 @@ -21271,17 +21194,6 @@ __metadata: languageName: node linkType: hard -"react-reconciler@npm:0.33.0": - version: 0.33.0 - resolution: "react-reconciler@npm:0.33.0" - dependencies: - scheduler: ^0.27.0 - peerDependencies: - react: ^19.2.0 - checksum: 88181988a66e092c393ed5b9b8d1bdc96bfebbd973c39f0d44ed51e011869d9e344122c89d0971f175c4b533bb614b1eddae9eaea8d4d37bd69e609923888015 - languageName: node - linkType: hard - "react-reconciler@npm:^0.31.0": version: 0.31.0 resolution: "react-reconciler@npm:0.31.0"