From e596307f70cc3e3e86e9f24f6d561da4b5b040ea Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 13 Aug 2026 11:21:13 +0200 Subject: [PATCH 1/2] refactor: run action steps through the harness CLI Move the GitHub Action's four bundled Node scripts into @react-native-harness/cli as `harness ci ` and delete the committed bundles. The action now invokes the project's own installed react-native-harness binary instead of prebuilt .cjs files checked into the repository, so changes to config, cache, or platform-android no longer require rebuilding and committing ~628KB of bundled output. --- .../version-plan-1786612420017.md | 12 + action.yml | 142 +- actions/android/action.yml | 174 - actions/android/index.cjs | 1 - actions/ios/action.yml | 103 - actions/ios/index.cjs | 1 - actions/shared/index.cjs | 4747 --------------- actions/shared/plan-restore.cjs | 5045 ---------------- actions/shared/plan-save.cjs | 5093 ----------------- actions/shared/snapshot-metro.cjs | 4916 ---------------- actions/web/action.yml | 131 - actions/web/index.cjs | 1 - .../README.md => docs/github-action.md | 30 +- packages/cli/eslint.config.mjs | 17 +- packages/cli/package.json | 1 + .../cli/src/ci/__tests__/load-config.test.ts | 113 + .../ci}/__tests__/metro-cache-inputs.test.ts | 0 .../ci/__tests__/plan-metro-restore.test.ts} | 6 +- .../src/ci/__tests__/plan-metro-save.test.ts} | 18 +- .../src/ci}/__tests__/snapshot-metro.test.ts | 8 +- .../src/shared => cli/src/ci}/format-bytes.ts | 0 .../index.ts => cli/src/ci/load-config.ts} | 52 +- .../src/ci}/metro-cache-inputs.ts | 3 + .../src/ci/plan-metro-restore.ts} | 10 +- .../src/ci/plan-metro-save.ts} | 10 +- .../shared => cli/src/ci}/snapshot-metro.ts | 10 +- packages/cli/src/ci/workspace-root.ts | 39 + packages/cli/src/index.ts | 62 + packages/cli/tsconfig.json | 11 +- packages/cli/tsconfig.lib.json | 11 +- .../{github-action => cli}/vite.config.ts | 2 +- packages/github-action/eslint.config.mjs | 34 - packages/github-action/package.json | 22 - packages/github-action/project.json | 18 - packages/github-action/src/action.yml | 301 - packages/github-action/src/android/action.yml | 174 - packages/github-action/src/android/index.ts | 1 - packages/github-action/src/ios/action.yml | 103 - packages/github-action/src/ios/index.ts | 1 - packages/github-action/src/web/action.yml | 131 - packages/github-action/src/web/index.ts | 1 - packages/github-action/tsconfig.json | 25 - packages/github-action/tsconfig.lib.json | 30 - packages/github-action/tsup.config.mts | 42 - .../src/__tests__/ci-action.test.ts | 100 +- pnpm-lock.yaml | 503 +- tsconfig.json | 3 - website/src/docs/guides/ci-cd.md | 2 +- 48 files changed, 467 insertions(+), 21793 deletions(-) create mode 100644 .nx/version-plans/version-plan-1786612420017.md delete mode 100644 actions/android/action.yml delete mode 100644 actions/android/index.cjs delete mode 100644 actions/ios/action.yml delete mode 100644 actions/ios/index.cjs delete mode 100644 actions/shared/index.cjs delete mode 100644 actions/shared/plan-restore.cjs delete mode 100644 actions/shared/plan-save.cjs delete mode 100644 actions/shared/snapshot-metro.cjs delete mode 100644 actions/web/action.yml delete mode 100644 actions/web/index.cjs rename packages/github-action/README.md => docs/github-action.md (73%) create mode 100644 packages/cli/src/ci/__tests__/load-config.test.ts rename packages/{github-action/src/shared => cli/src/ci}/__tests__/metro-cache-inputs.test.ts (100%) rename packages/{github-action/src/shared/__tests__/plan-restore.test.ts => cli/src/ci/__tests__/plan-metro-restore.test.ts} (94%) rename packages/{github-action/src/shared/__tests__/plan-save.test.ts => cli/src/ci/__tests__/plan-metro-save.test.ts} (91%) rename packages/{github-action/src/shared => cli/src/ci}/__tests__/snapshot-metro.test.ts (92%) rename packages/{github-action/src/shared => cli/src/ci}/format-bytes.ts (100%) rename packages/{github-action/src/shared/index.ts => cli/src/ci/load-config.ts} (67%) rename packages/{github-action/src/shared => cli/src/ci}/metro-cache-inputs.ts (97%) rename packages/{github-action/src/shared/plan-restore.ts => cli/src/ci/plan-metro-restore.ts} (91%) rename packages/{github-action/src/shared/plan-save.ts => cli/src/ci/plan-metro-save.ts} (95%) rename packages/{github-action/src/shared => cli/src/ci}/snapshot-metro.ts (92%) create mode 100644 packages/cli/src/ci/workspace-root.ts rename packages/{github-action => cli}/vite.config.ts (87%) delete mode 100644 packages/github-action/eslint.config.mjs delete mode 100644 packages/github-action/package.json delete mode 100644 packages/github-action/project.json delete mode 100644 packages/github-action/src/action.yml delete mode 100644 packages/github-action/src/android/action.yml delete mode 100644 packages/github-action/src/android/index.ts delete mode 100644 packages/github-action/src/ios/action.yml delete mode 100644 packages/github-action/src/ios/index.ts delete mode 100644 packages/github-action/src/web/action.yml delete mode 100644 packages/github-action/src/web/index.ts delete mode 100644 packages/github-action/tsconfig.json delete mode 100644 packages/github-action/tsconfig.lib.json delete mode 100644 packages/github-action/tsup.config.mts diff --git a/.nx/version-plans/version-plan-1786612420017.md b/.nx/version-plans/version-plan-1786612420017.md new file mode 100644 index 00000000..cd44002b --- /dev/null +++ b/.nx/version-plans/version-plan-1786612420017.md @@ -0,0 +1,12 @@ +--- +__default__: minor +--- + +The `react-native-harness` CLI now exposes `harness ci ` +(`load-config`, `plan-metro-restore`, `snapshot-metro`, `plan-metro-save`), +which the official GitHub Action uses to run its configuration and Metro +caching steps through your project's own installed CLI instead of bundled +scripts checked into the action. As a result, the action now requires a +compatible `react-native-harness` version to be installed in the project it +runs against — keep the action ref and the `react-native-harness` package +version in sync, as already recommended. diff --git a/action.yml b/action.yml index 0a6fe34b..0f945366 100644 --- a/action.yml +++ b/action.yml @@ -51,15 +51,97 @@ inputs: runs: using: 'composite' steps: + - name: Detect Package Manager + id: detect-pm + shell: bash + working-directory: ${{ inputs.projectRoot || '.' }} + run: | + if [ -n "${{ inputs.packageManager }}" ]; then + case "${{ inputs.packageManager }}" in + pnpm) + echo "manager=pnpm" >> $GITHUB_OUTPUT + echo "runner=pnpm exec " >> $GITHUB_OUTPUT + ;; + yarn) + echo "manager=yarn" >> $GITHUB_OUTPUT + echo "runner=yarn " >> $GITHUB_OUTPUT + ;; + bun) + echo "manager=bun" >> $GITHUB_OUTPUT + echo "runner=bunx " >> $GITHUB_OUTPUT + ;; + deno) + echo "manager=deno" >> $GITHUB_OUTPUT + echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT + ;; + npm) + echo "manager=npm" >> $GITHUB_OUTPUT + echo "runner=npx " >> $GITHUB_OUTPUT + ;; + *) + echo "Error: Unsupported packageManager '${{ inputs.packageManager }}'" + echo "Supported values: npm, yarn, pnpm, bun, deno" + exit 1 + ;; + esac + elif [ -f "pnpm-lock.yaml" ]; then + echo "manager=pnpm" >> $GITHUB_OUTPUT + echo "runner=pnpm exec " >> $GITHUB_OUTPUT + elif [ -f "yarn.lock" ]; then + echo "manager=yarn" >> $GITHUB_OUTPUT + echo "runner=yarn " >> $GITHUB_OUTPUT + elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then + echo "manager=bun" >> $GITHUB_OUTPUT + echo "runner=bunx " >> $GITHUB_OUTPUT + elif [ -f "deno.lock" ]; then + echo "manager=deno" >> $GITHUB_OUTPUT + echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT + else + echo "manager=npm" >> $GITHUB_OUTPUT + echo "runner=npx " >> $GITHUB_OUTPUT + fi + # This action invokes the project's own installed react-native-harness CLI + # (via `harness ci ...`) instead of shipping bundled scripts, so the + # action ref and the installed package version must be compatible. On an + # older, pre-`ci`-subcommand CLI, `harness ci load-config` falls through + # to the Jest CLI and treats `ci` as a test path pattern -- silently + # running (zero) tests instead of failing -- so this guard must run + # before any `harness ci ...` step is invoked. + - name: Verify react-native-harness CLI version + shell: bash + working-directory: ${{ inputs.projectRoot || '.' }} + run: | + # The `harness ci ` interface this action relies on ships + # starting with 1.5.0 (see the version plan for this change). On an + # older CLI, `harness ci load-config` falls through to the Jest CLI + # instead of failing, so this floor must match the exact release + # that introduced `ci`, not the release this action.yml happens to + # be edited in. + MIN_VERSION="1.5.0" + INSTALLED_VERSION=$(node -p "require(require.resolve('react-native-harness/package.json',{paths:[process.cwd()]})).version" 2>/dev/null) + if [ -z "$INSTALLED_VERSION" ]; then + echo "Error: could not resolve the 'react-native-harness' package in this project." + echo "This action requires react-native-harness >= $MIN_VERSION to be installed. Pin the action ref to the same release as the installed package." + exit 1 + fi + # Note: `sort -V` ranks a prerelease like "1.5.0-beta.1" below + # "1.5.0", so a prerelease of the very release that introduces `ci` + # would be (correctly, if conservatively) rejected here. + LOWEST=$(printf '%s\n%s\n' "$MIN_VERSION" "$INSTALLED_VERSION" | sort -V | head -n1) + if [ "$LOWEST" != "$MIN_VERSION" ]; then + echo "Error: This action requires react-native-harness >= $MIN_VERSION (found $INSTALLED_VERSION). Pin the action ref to the same release as the installed package." + exit 1 + fi - name: Load React Native Harness configuration id: load-config shell: bash + working-directory: ${{ inputs.projectRoot || '.' }} env: INPUT_RUNNER: ${{ inputs.runner }} INPUT_PROJECTROOT: ${{ inputs.projectRoot }} HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} run: | - node ${{ github.action_path }}/actions/shared/index.cjs + ${{ steps.detect-pm.outputs.runner }}react-native-harness ci load-config - name: Verify native app input if: fromJson(steps.load-config.outputs.config).platformId != 'web' shell: bash @@ -72,10 +154,11 @@ runs: - name: Plan Metro cache restore id: plan-metro-restore shell: bash + working-directory: ${{ steps.load-config.outputs.projectRoot }} env: INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} run: | - node ${{ github.action_path }}/actions/shared/plan-restore.cjs + ${{ steps.detect-pm.outputs.runner }}react-native-harness ci plan-metro-restore - name: Restore Metro cache (.harness/cache/metro) id: restore-metro uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -95,13 +178,14 @@ runs: - name: Snapshot Metro cache id: snapshot-metro-restore shell: bash + working-directory: ${{ steps.load-config.outputs.projectRoot }} env: INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} # Empty on a cache miss; snapshot-metro.cjs uses it to report whether # the Metro cache was actually restored and from which key. METRO_RESTORED_KEY: ${{ steps.restore-metro.outputs.cache-matched-key }} run: | - node ${{ github.action_path }}/actions/shared/snapshot-metro.cjs + ${{ steps.detect-pm.outputs.runner }}react-native-harness ci snapshot-metro - name: Restore Harness cache id: cache-harness-restore if: fromJson(steps.load-config.outputs.config).platformId == 'ios' @@ -178,55 +262,6 @@ runs: run: npx playwright install --with-deps chromium # ── Shared ─────────────────────────────────────────────────────────────── - - name: Detect Package Manager - id: detect-pm - shell: bash - working-directory: ${{ steps.load-config.outputs.projectRoot }} - run: | - if [ -n "${{ inputs.packageManager }}" ]; then - case "${{ inputs.packageManager }}" in - pnpm) - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - ;; - yarn) - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - ;; - bun) - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - ;; - deno) - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - ;; - npm) - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - ;; - *) - echo "Error: Unsupported packageManager '${{ inputs.packageManager }}'" - echo "Supported values: npm, yarn, pnpm, bun, deno" - exit 1 - ;; - esac - elif [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - name: Run E2E tests id: run-tests shell: bash @@ -277,13 +312,14 @@ runs: id: plan-metro-save if: always() shell: bash + working-directory: ${{ steps.load-config.outputs.projectRoot }} env: INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} INPUT_METRO_SNAPSHOT: ${{ steps.snapshot-metro-restore.outputs.metroSnapshot }} INPUT_CACHESAVEPOLICY: ${{ inputs.cacheSavePolicy }} IS_DEFAULT_BRANCH: ${{ github.ref_name == github.event.repository.default_branch }} run: | - node ${{ github.action_path }}/actions/shared/plan-save.cjs + ${{ steps.detect-pm.outputs.runner }}react-native-harness ci plan-metro-save - name: Save Metro cache if: always() && steps.plan-metro-save.outputs.metroShouldSave == 'true' uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 diff --git a/actions/android/action.yml b/actions/android/action.yml deleted file mode 100644 index b650943f..00000000 --- a/actions/android/action.yml +++ /dev/null @@ -1,174 +0,0 @@ -name: React Native Harness for Android -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on Android' -inputs: - app: - description: The path to the Android app (.apk) - required: true - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - cacheAvd: - description: Whether to cache the AVD - required: false - type: boolean - default: 'true' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Verify Android config - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - if [ '${{ fromJson(steps.load-config.outputs.config).config.device.avd }}' = 'null' ]; then - echo "Error: AVD config is required for Android emulators" - echo "Please define the 'avd' property in the runner config" - exit 1 - fi - - name: Get architecture of the runner - id: arch - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - case "${{ runner.arch }}" in - X64) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - ARM64) - echo "arch=arm64-v8a" >> $GITHUB_OUTPUT - ;; - ARM32) - echo "arch=armeabi-v7a" >> $GITHUB_OUTPUT - ;; - *) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - esac - - name: Enable KVM group perms - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules - sudo udevadm control --reload-rules - sudo udevadm trigger --name-match=kvm - ls /dev/kvm - - name: Compute AVD cache key - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - id: avd-key - shell: bash - run: | - CACHE_CONFIG='${{ toJson(fromJson(steps.load-config.outputs.config).action.avdCacheConfig) }}' - AVD_CONFIG_HASH=$(printf '%s' "$CACHE_CONFIG" | sha256sum | cut -d' ' -f1) - AVD_NAME='${{ fromJson(steps.load-config.outputs.config).config.device.name }}' - ARCH="${{ steps.arch.outputs.arch }}" - CACHE_KEY="avd-$AVD_NAME-$ARCH-$AVD_CONFIG_HASH" - echo "key=$CACHE_KEY" >> $GITHUB_OUTPUT - - name: Restore AVD cache - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - id: avd-cache - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - HARNESS_APP_PATH: ${{ inputs.app }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-android - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Save AVD cache - if: ${{ always() && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled && steps.avd-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-android - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/actions/android/index.cjs b/actions/android/index.cjs deleted file mode 100644 index 3918c74e..00000000 --- a/actions/android/index.cjs +++ /dev/null @@ -1 +0,0 @@ -"use strict"; diff --git a/actions/ios/action.yml b/actions/ios/action.yml deleted file mode 100644 index 79772e43..00000000 --- a/actions/ios/action.yml +++ /dev/null @@ -1,103 +0,0 @@ -name: React Native Harness for iOS -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on iOS' -inputs: - app: - description: The path to the iOS app (.app) - required: true - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - HARNESS_APP_PATH: ${{ inputs.app }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-ios - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-ios - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/actions/ios/index.cjs b/actions/ios/index.cjs deleted file mode 100644 index 3918c74e..00000000 --- a/actions/ios/index.cjs +++ /dev/null @@ -1 +0,0 @@ -"use strict"; diff --git a/actions/shared/index.cjs b/actions/shared/index.cjs deleted file mode 100644 index cee93346..00000000 --- a/actions/shared/index.cjs +++ /dev/null @@ -1,4747 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// ../../node_modules/picocolors/picocolors.js -var require_picocolors = __commonJS({ - "../../node_modules/picocolors/picocolors.js"(exports2, module2) { - "use strict"; - var p = process || {}; - var argv = p.argv || []; - var env = p.env || {}; - var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI); - var formatter = (open, close, replace = open) => (input) => { - let string = "" + input, index = string.indexOf(close, open.length); - return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; - }; - var replaceClose = (string, close, replace, index) => { - let result = "", cursor = 0; - do { - result += string.substring(cursor, index) + replace; - cursor = index + close.length; - index = string.indexOf(close, cursor); - } while (~index); - return result + string.substring(cursor); - }; - var createColors = (enabled = isColorSupported) => { - let f = enabled ? formatter : () => String; - return { - isColorSupported: enabled, - reset: f("\x1B[0m", "\x1B[0m"), - bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), - dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), - italic: f("\x1B[3m", "\x1B[23m"), - underline: f("\x1B[4m", "\x1B[24m"), - inverse: f("\x1B[7m", "\x1B[27m"), - hidden: f("\x1B[8m", "\x1B[28m"), - strikethrough: f("\x1B[9m", "\x1B[29m"), - black: f("\x1B[30m", "\x1B[39m"), - red: f("\x1B[31m", "\x1B[39m"), - green: f("\x1B[32m", "\x1B[39m"), - yellow: f("\x1B[33m", "\x1B[39m"), - blue: f("\x1B[34m", "\x1B[39m"), - magenta: f("\x1B[35m", "\x1B[39m"), - cyan: f("\x1B[36m", "\x1B[39m"), - white: f("\x1B[37m", "\x1B[39m"), - gray: f("\x1B[90m", "\x1B[39m"), - bgBlack: f("\x1B[40m", "\x1B[49m"), - bgRed: f("\x1B[41m", "\x1B[49m"), - bgGreen: f("\x1B[42m", "\x1B[49m"), - bgYellow: f("\x1B[43m", "\x1B[49m"), - bgBlue: f("\x1B[44m", "\x1B[49m"), - bgMagenta: f("\x1B[45m", "\x1B[49m"), - bgCyan: f("\x1B[46m", "\x1B[49m"), - bgWhite: f("\x1B[47m", "\x1B[49m"), - blackBright: f("\x1B[90m", "\x1B[39m"), - redBright: f("\x1B[91m", "\x1B[39m"), - greenBright: f("\x1B[92m", "\x1B[39m"), - yellowBright: f("\x1B[93m", "\x1B[39m"), - blueBright: f("\x1B[94m", "\x1B[39m"), - magentaBright: f("\x1B[95m", "\x1B[39m"), - cyanBright: f("\x1B[96m", "\x1B[39m"), - whiteBright: f("\x1B[97m", "\x1B[39m"), - bgBlackBright: f("\x1B[100m", "\x1B[49m"), - bgRedBright: f("\x1B[101m", "\x1B[49m"), - bgGreenBright: f("\x1B[102m", "\x1B[49m"), - bgYellowBright: f("\x1B[103m", "\x1B[49m"), - bgBlueBright: f("\x1B[104m", "\x1B[49m"), - bgMagentaBright: f("\x1B[105m", "\x1B[49m"), - bgCyanBright: f("\x1B[106m", "\x1B[49m"), - bgWhiteBright: f("\x1B[107m", "\x1B[49m") - }; - }; - module2.exports = createColors(); - module2.exports.createColors = createColors; - } -}); - -// ../../node_modules/sisteransi/src/index.js -var require_src = __commonJS({ - "../../node_modules/sisteransi/src/index.js"(exports2, module2) { - "use strict"; - var ESC = "\x1B"; - var CSI = `${ESC}[`; - var beep = "\x07"; - var cursor = { - to(x2, y) { - if (!y) return `${CSI}${x2 + 1}G`; - return `${CSI}${y + 1};${x2 + 1}H`; - }, - move(x2, y) { - let ret = ""; - if (x2 < 0) ret += `${CSI}${-x2}D`; - else if (x2 > 0) ret += `${CSI}${x2}C`; - if (y < 0) ret += `${CSI}${-y}A`; - else if (y > 0) ret += `${CSI}${y}B`; - return ret; - }, - up: (count = 1) => `${CSI}${count}A`, - down: (count = 1) => `${CSI}${count}B`, - forward: (count = 1) => `${CSI}${count}C`, - backward: (count = 1) => `${CSI}${count}D`, - nextLine: (count = 1) => `${CSI}E`.repeat(count), - prevLine: (count = 1) => `${CSI}F`.repeat(count), - left: `${CSI}G`, - hide: `${CSI}?25l`, - show: `${CSI}?25h`, - save: `${ESC}7`, - restore: `${ESC}8` - }; - var scroll = { - up: (count = 1) => `${CSI}S`.repeat(count), - down: (count = 1) => `${CSI}T`.repeat(count) - }; - var erase = { - screen: `${CSI}2J`, - up: (count = 1) => `${CSI}1J`.repeat(count), - down: (count = 1) => `${CSI}J`.repeat(count), - line: `${CSI}2K`, - lineEnd: `${CSI}K`, - lineStart: `${CSI}1K`, - lines(count) { - let clear = ""; - for (let i = 0; i < count; i++) - clear += this.line + (i < count - 1 ? cursor.up() : ""); - if (count) - clear += cursor.left; - return clear; - } - }; - module2.exports = { cursor, scroll, erase, beep }; - } -}); - -// ../../node_modules/zod/dist/esm/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util, - void: () => voidType -}); - -// ../../node_modules/zod/dist/esm/v3/helpers/util.js -var util; -(function(util3) { - util3.assertEqual = (_2) => { - }; - function assertIs(_arg) { - } - util3.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util3.assertNever = assertNever; - util3.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util3.getValidEnumValues = (obj) => { - const validKeys = util3.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); - const filtered = {}; - for (const k3 of validKeys) { - filtered[k3] = obj[k3]; - } - return util3.objectValues(filtered); - }; - util3.objectValues = (obj) => { - return util3.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util3.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util3.joinValues = joinValues; - util3.jsonStringifyReplacer = (_2, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t2 = typeof data; - switch (t2) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// ../../node_modules/zod/dist/esm/v3/ZodError.js -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -// ../../node_modules/zod/dist/esm/v3/locales/en.js -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; -var en_default = errorMap; - -// ../../node_modules/zod/dist/esm/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -// ../../node_modules/zod/dist/esm/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data, path: path9, errorMaps, issueData } = params; - const fullPath = [...path9, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x2) => !!x2) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x2) => x2.status === "aborted"; -var isDirty = (x2) => x2.status === "dirty"; -var isValid = (x2) => x2.status === "valid"; -var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; - -// ../../node_modules/zod/dist/esm/v3/helpers/errorUtil.js -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -// ../../node_modules/zod/dist/esm/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path9, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path9; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new _ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x2) => !!x2); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me2 = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me2 = this; - return OK(function(...args) { - const parsedArgs = me2._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me2._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = /* @__PURE__ */ Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })) -}; -var NEVER = INVALID; - -// ../tools/dist/net.js -var import_node_net = __toESM(require("net"), 1); - -// ../tools/dist/logger.js -var import_node_util = __toESM(require("util"), 1); -var import_picocolors = __toESM(require_picocolors(), 1); -var verbose = !!process.env.HARNESS_DEBUG; -var BASE_TAG = "[harness]"; -var INFO_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.magenta(" HARNESS ")))) : "HARNESS"; -var ERROR_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.red(" HARNESS ")))) : "HARNESS"; -var getTimestamp = () => (/* @__PURE__ */ new Date()).toISOString(); -var normalizeScope = (scope) => scope.trim().replace(/^\[+|\]+$/g, "").replace(/\]\[/g, "]["); -var formatPrefix = (scopes) => { - const suffix = scopes.map((scope) => `[${normalizeScope(scope)}]`).join(""); - return `${BASE_TAG}${suffix}`; -}; -var mapLines = (text, prefix) => text.split("\n").map((line) => `${prefix} ${line}`).join("\n"); -var writeLog = (level, scopes, messages) => { - if (!verbose && (level === "info" || level === "log" || level === "success")) { - const output2 = import_node_util.default.format(...messages); - const tag = INFO_TAG; - process.stderr.write(`${tag} ${output2} -`); - return; - } - if (!verbose && level === "error") { - const output2 = import_node_util.default.format(...messages); - process.stderr.write(`${ERROR_TAG} ${output2} -`); - return; - } - const method = level === "warn" ? console.warn : console.debug; - const output = import_node_util.default.format(...messages); - const prefix = `${getTimestamp()} ${formatPrefix(scopes)}`; - method(mapLines(output, prefix)); -}; -var setVerbose = (level) => { - verbose = level; -}; -var isVerbose = () => { - return verbose; -}; -var createScopedLogger = (scopes = []) => ({ - debug: (...messages) => { - if (!verbose) { - return; - } - writeLog("debug", scopes, messages); - }, - info: (...messages) => { - writeLog("info", scopes, messages); - }, - warn: (...messages) => { - writeLog("warn", scopes, messages); - }, - error: (...messages) => { - writeLog("error", scopes, messages); - }, - log: (...messages) => { - writeLog("log", scopes, messages); - }, - success: (...messages) => { - writeLog("success", scopes, messages); - }, - child: (scope) => createScopedLogger([...scopes, scope]), - setVerbose, - isVerbose -}); -var logger = createScopedLogger(); - -// ../../node_modules/@clack/core/dist/index.mjs -var import_node_process = require("process"); -var k = __toESM(require("readline"), 1); -var import_node_readline = __toESM(require("readline"), 1); -var import_sisteransi = __toESM(require_src(), 1); -var import_node_tty = require("tty"); -var Ft = { limit: 1 / 0, ellipsis: "" }; -var ft = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var j = "\x07"; -var Q = "["; -var dt = "]"; -var U = `${dt}8;;`; -var et = new RegExp(`(?:\\${Q}(?\\d+)m|\\${U}(?.*)${j})`, "y"); -var At = ["up", "down", "left", "right", "space", "enter", "cancel"]; -var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true }; -var bt = globalThis.process.platform.startsWith("win"); - -// ../../node_modules/@clack/prompts/dist/index.mjs -var import_picocolors2 = __toESM(require_picocolors(), 1); -var import_node_process2 = __toESM(require("process"), 1); -var import_node_fs = require("fs"); -var import_node_path = require("path"); -var import_sisteransi2 = __toESM(require_src(), 1); -var import_node_util2 = require("util"); -function ht() { - return import_node_process2.default.platform !== "win32" ? import_node_process2.default.env.TERM !== "linux" : !!import_node_process2.default.env.CI || !!import_node_process2.default.env.WT_SESSION || !!import_node_process2.default.env.TERMINUS_SUBLIME || import_node_process2.default.env.ConEmuTask === "{cmd::Cmder}" || import_node_process2.default.env.TERM_PROGRAM === "Terminus-Sublime" || import_node_process2.default.env.TERM_PROGRAM === "vscode" || import_node_process2.default.env.TERM === "xterm-256color" || import_node_process2.default.env.TERM === "alacritty" || import_node_process2.default.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; -} -var ee = ht(); -var w = (e, r) => ee ? e : r; -var Me = w("\u25C6", "*"); -var ce = w("\u25A0", "x"); -var de = w("\u25B2", "x"); -var V = w("\u25C7", "o"); -var $e = w("\u250C", "T"); -var h = w("\u2502", "|"); -var x = w("\u2514", "\u2014"); -var Re = w("\u2510", "T"); -var Oe = w("\u2518", "\u2014"); -var Y = w("\u25CF", ">"); -var K = w("\u25CB", " "); -var te = w("\u25FB", "[\u2022]"); -var k2 = w("\u25FC", "[+]"); -var z = w("\u25FB", "[ ]"); -var Pe = w("\u25AA", "\u2022"); -var se = w("\u2500", "-"); -var he = w("\u256E", "+"); -var Ne = w("\u251C", "+"); -var me = w("\u256F", "+"); -var pe = w("\u2570", "+"); -var We = w("\u256D", "+"); -var ge = w("\u25CF", "\u2022"); -var fe = w("\u25C6", "*"); -var Fe = w("\u25B2", "!"); -var ye = w("\u25A0", "x"); -var Ft2 = { limit: 1 / 0, ellipsis: "" }; -var yt2 = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var Ce = "\x07"; -var Ve = "["; -var vt = "]"; -var we = `${vt}8;;`; -var Ge = new RegExp(`(?:\\${Ve}(?\\d+)m|\\${we}(?.*)${Ce})`, "y"); -var Ut = import_picocolors2.default.magenta; -var Ye = { light: w("\u2500", "-"), heavy: w("\u2501", "="), block: w("\u2588", "#") }; -var ze = `${import_picocolors2.default.gray(h)} `; - -// ../tools/dist/spawn.js -var spawnLogger = logger.child("spawn"); - -// ../tools/dist/react-native.js -var import_node_module = require("module"); -var import_node_path2 = __toESM(require("path"), 1); -var import_node_fs2 = __toESM(require("fs"), 1); - -// ../tools/dist/error.js -var HarnessError = class extends Error { -}; - -// ../tools/dist/packages.js -var import_node_path3 = __toESM(require("path"), 1); -var import_node_fs3 = __toESM(require("fs"), 1); - -// ../tools/dist/path.js -var import_node_path4 = __toESM(require("path"), 1); - -// ../tools/dist/crash-artifacts.js -var import_node_fs4 = __toESM(require("fs"), 1); -var import_node_path5 = __toESM(require("path"), 1); -var DEFAULT_ARTIFACT_ROOT = import_node_path5.default.join(process.cwd(), ".harness", "crash-reports"); - -// ../tools/dist/harness-artifacts.js -var import_node_fs5 = __toESM(require("fs"), 1); -var import_node_path6 = __toESM(require("path"), 1); - -// ../tools/dist/diagnostics.js -var noop = () => void 0; -var noopSpan = { - end: noop, - fail: noop -}; -var createNoopDiagnostics = () => { - const diagnostics = { - enabled: false, - start: () => noopSpan, - measure: async (_label, fn) => fn(), - mark: noop, - record: noop, - child: () => diagnostics, - flush: () => [] - }; - return diagnostics; -}; -var noopDiagnostics = createNoopDiagnostics(); - -// ../tools/dist/device-core-budget.js -var MIN_DEVICE_CORE_BUDGET = 2; -var MAX_DEVICE_CORE_BUDGET = 4; -var getDeviceCoreBudget = (hostParallelism) => { - return Math.min(Math.max(Math.floor(hostParallelism / 2), MIN_DEVICE_CORE_BUDGET), MAX_DEVICE_CORE_BUDGET); -}; - -// ../tools/dist/host-capabilities.js -var import_node_os = __toESM(require("os"), 1); - -// ../plugins/dist/utils.js -var isHookTree = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - for (const child of Object.values(value)) { - if (child === void 0) { - continue; - } - if (typeof child === "function") { - continue; - } - if (child == null || typeof child !== "object" || Array.isArray(child) || !isHookTree(child)) { - return false; - } - } - return true; -}; - -// ../plugins/dist/plugin.js -var isHarnessPlugin = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const candidate = value; - if (typeof candidate.name !== "string" || candidate.name.length === 0) { - return false; - } - if (candidate.createState != null && typeof candidate.createState !== "function") { - return false; - } - if (candidate.hooks != null && !isHookTree(candidate.hooks)) { - return false; - } - return true; -}; - -// ../plugins/dist/manager.js -var pluginsLogger = logger.child("plugins"); - -// ../config/dist/types.js -var DEFAULT_METRO_PORT = 8081; -var configLogger = logger.child("config"); -var RunnerSchema = external_exports.object({ - name: external_exports.string().min(1, "Runner name is required").regex(/^[a-zA-Z0-9._-]+$/, "Runner name can only contain alphanumeric characters, dots, underscores, and hyphens"), - config: external_exports.record(external_exports.any()), - runner: external_exports.string(), - cli: external_exports.string().optional(), - platformId: external_exports.string() -}); -var PluginSchema = external_exports.custom((value) => isHarnessPlugin(value), "Invalid Harness plugin"); -var ConfigSchema = external_exports.object({ - entryPoint: external_exports.string().min(1, "Entry point is required"), - appRegistryComponentName: external_exports.string().min(1, "App registry component name is required"), - runners: external_exports.array(RunnerSchema).min(1, "At least one runner is required"), - plugins: external_exports.array(PluginSchema).optional().default([]), - defaultRunner: external_exports.string().optional(), - host: external_exports.string().min(1, "Host is required").optional(), - metroPort: external_exports.number().int("Metro port must be an integer").min(1, "Metro port must be at least 1").max(65535, "Metro port must be at most 65535").optional().default(DEFAULT_METRO_PORT), - webSocketPort: external_exports.number().optional().describe("Deprecated. Bridge traffic now uses metroPort and this value is ignored."), - bridgeTimeout: external_exports.number().min(1e3, "Bridge timeout must be at least 1 second").default(6e4), - testTimeout: external_exports.number().min(1e3, "Test timeout must be at least 1 second").default(5e3), - platformReadyTimeout: external_exports.number().min(1e3, "Platform ready timeout must be at least 1 second").default(3e5), - bundleStartTimeout: external_exports.number().min(1e3, "Bundle start timeout must be at least 1 second").default(6e4), - maxAppRestarts: external_exports.number().min(0, "Max app restarts must be at least 0").default(2), - eagerPrewarm: external_exports.boolean().optional().default(true).describe("Start building the Metro bundle while the platform (emulator, simulator, or browser) is still booting, so the first bundle is ready sooner. Disable to defer the first bundle build until app startup."), - resetEnvironmentBetweenTestFiles: external_exports.union([external_exports.boolean(), external_exports.enum(["process", "runtime"])]).optional().default(true).describe("Controls how the environment is reset between test files. `true` (default) and `'process'` kill and cold-restart the app process. `'runtime'` reloads the JS runtime in place (DevSettings.reload() / window.location.reload()), which is cheaper but escalates to a process restart if the reload fails or the app does not reconnect in time. `false` disables resetting the environment between test files entirely."), - skipAlreadyIncludedModules: external_exports.boolean().optional().describe('Skip re-sending modules already served in the main app bundle when Metro serves a per-test-file bundle. Defaults to true; set to false as an escape hatch if it causes issues. Left undefined (rather than defaulted here) so `resolveSkipAlreadyIncludedModules` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__skipAlreadyIncludedModules` alias.'), - // Deprecated alias for `skipAlreadyIncludedModules` -- see - // `resolveSkipAlreadyIncludedModules`. Left without a `.default()` for the - // same reason: a default value would be indistinguishable from the user - // never having set it, which would break alias-vs-explicit-flag precedence. - unstable__skipAlreadyIncludedModules: external_exports.boolean().optional().describe("Deprecated. Use `skipAlreadyIncludedModules` instead."), - cache: external_exports.object({ - metro: external_exports.boolean().optional().describe('Enable persistent Metro transform and file-map caching under the .harness cache directory. Defaults to true; set to false to always start with a cold Metro cache. Left undefined (rather than defaulted here) so `resolveMetroCacheEnabled` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__enableMetroCache` alias.'), - version: external_exports.string().optional().describe("User-controlled salt folded into the Metro cacheVersion. Bump it to force-invalidate previously cached transforms.") - }).optional(), - // Deprecated alias for `cache.metro` -- see `resolveMetroCacheEnabled`. - // Left without a `.default()` for the same reason as - // `unstable__skipAlreadyIncludedModules`: a default value would be - // indistinguishable from the user never having set it, which would break - // alias-vs-explicit-flag precedence. - unstable__enableMetroCache: external_exports.boolean().optional().describe("Deprecated. Use `cache.metro` instead."), - permissions: external_exports.boolean().optional().default(false).describe("Enable platform-specific permission prompt automation. When false, Harness does not start permission-handling helpers such as the iOS XCTest agent."), - detectNativeCrashes: external_exports.boolean().optional().default(true), - crashDetectionInterval: external_exports.number().min(100, "Crash detection interval must be at least 100ms").default(500), - disableViewFlattening: external_exports.boolean().optional().default(false).describe("Disable view flattening in React Native. This will set collapsable={true} for all View components to ensure they are not flattened by the native layout engine."), - coverage: external_exports.object({ - root: external_exports.string().optional().describe(`Root directory for coverage instrumentation in monorepo setups. Specifies the directory from which coverage data should be collected. Use ".." for create-react-native-library projects where tests run from example/ but source files are in parent directory. Passed to babel-plugin-istanbul's cwd option.`), - native: external_exports.object({ - ios: external_exports.object({ - pods: external_exports.array(external_exports.string()).min(1, "At least one pod name is required").describe("Pod names to instrument for native code coverage. Coverage flags are injected at pod install time via a CocoaPods hook. After tests, profraw data is collected and converted to lcov format.") - }).optional() - }).optional().describe("Native code coverage configuration.") - }).optional(), - forwardClientLogs: external_exports.boolean().optional().default(false).describe("Enable forwarding of console.log, console.warn, console.error, and other console method calls from the React Native app during the active test run. When enabled, app console output is attached to the active test result's console output."), - diagnostics: external_exports.boolean().optional().default(false).describe("Enable diagnostics tracing for the harness session. Records spans for session setup, Metro bundling, bridge/client events, and per-file test runs, then writes a Chrome Trace Event JSON file and prints a summary after each run. Can also be enabled via the RN_HARNESS_DIAGNOSTICS environment variable."), - // Deprecated property - used for migration detection - include: external_exports.array(external_exports.string()).optional() -}).refine((config) => { - if (config.defaultRunner) { - return config.runners.some((runner) => runner.name === config.defaultRunner); - } - return true; -}, { - message: "Default runner must match one of the configured runner names", - path: ["defaultRunner"] -}); - -// ../config/dist/errors.js -var ConfigValidationError = class extends HarnessError { - filePath; - validationErrors; - constructor(filePath, validationErrors) { - const lines = [ - `Configuration validation failed in ${filePath}`, - "", - "The following issues were found:", - "" - ]; - validationErrors.forEach((error, index) => { - lines.push(` ${index + 1}. ${error}`); - }); - lines.push("", "Please fix these issues and try again.", "For more information, visit: https://react-native-harness.dev/docs/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.validationErrors = validationErrors; - this.name = "ConfigValidationError"; - } -}; -var ConfigNotFoundError = class extends HarnessError { - searchPath; - constructor(searchPath) { - const lines = [ - "Configuration file not found", - "", - `Searched for configuration files in: ${searchPath}`, - "and all parent directories.", - "", - "React Native Harness looks for one of these files:", - " \u2022 rn-harness.config.js", - " \u2022 rn-harness.config.mjs", - " \u2022 rn-harness.config.cjs", - " \u2022 rn-harness.config.json", - "", - "For more information, visit: https://www.react-native-harness.dev/docs/getting-started/configuration" - ]; - super(lines.join("\n")); - this.searchPath = searchPath; - this.name = "ConfigNotFoundError"; - } -}; -var ConfigLoadError = class extends HarnessError { - filePath; - cause; - constructor(filePath, cause) { - const lines = [ - "Failed to load configuration file", - "", - `File: ${filePath}`, - "" - ]; - if (cause) { - lines.push("Error details:"); - lines.push(` ${cause.message}`); - lines.push(""); - } - lines.push("This could be due to:", " \u2022 Syntax errors in your configuration file", " \u2022 Missing dependencies or modules", " \u2022 Invalid file format or encoding", " \u2022 File permissions issues", "", "Troubleshooting steps:", " 1. Check the file syntax and format", " 2. Ensure all required dependencies are installed", " 3. Verify file permissions", " 4. Try creating a new configuration file", "", "For more help, visit: https://www.react-native-harness.dev/docs/getting-started/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.name = "ConfigLoadError"; - this.cause = cause; - } -}; - -// ../config/dist/reader.js -var import_node_path7 = __toESM(require("path"), 1); -var import_node_fs6 = __toESM(require("fs"), 1); -var import_node_module2 = require("module"); -var import_meta = {}; -var extensions = [".js", ".mjs", ".cjs", ".json"]; -var importUp = async (dir, name) => { - const filePath = import_node_path7.default.join(dir, name); - for (const ext of extensions) { - const filePathWithExt = `${filePath}${ext}`; - if (import_node_fs6.default.existsSync(filePathWithExt)) { - let rawConfig; - try { - if (ext === ".mjs") { - rawConfig = await import(filePathWithExt).then((module2) => module2.default); - } else { - const require2 = (0, import_node_module2.createRequire)(import_meta.url); - rawConfig = require2(filePathWithExt); - } - } catch (error) { - throw new ConfigLoadError(filePathWithExt, error instanceof Error ? error : void 0); - } - try { - const config = ConfigSchema.parse(rawConfig); - return { config, filePathWithExt, configDir: dir }; - } catch (error) { - if (error instanceof ZodError) { - const validationErrors = error.errors.map((err) => { - const path9 = err.path.length > 0 ? ` at "${err.path.join(".")}"` : ""; - return `${err.message}${path9}`; - }); - throw new ConfigValidationError(filePathWithExt, validationErrors); - } - throw error; - } - } - } - const parentDir = import_node_path7.default.dirname(dir); - if (parentDir === dir) { - throw new ConfigNotFoundError(dir); - } - return importUp(parentDir, name); -}; -var getConfig = async (dir) => { - const { config, configDir } = await importUp(dir, "rn-harness.config"); - return { - config, - projectRoot: configDir - }; -}; - -// ../platform-android/dist/avd-config.js -var import_promises3 = require("fs/promises"); - -// ../platform-android/dist/emulator-startup.js -var import_node_os3 = __toESM(require("os"), 1); - -// ../platform-android/dist/environment.js -var import_node_fs7 = require("fs"); -var import_promises = require("fs/promises"); -var import_node_os2 = __toESM(require("os"), 1); -var import_node_path8 = __toESM(require("path"), 1); -var import_promises2 = require("stream/promises"); -var import_node_https = __toESM(require("https"), 1); -var androidEnvironmentLogger = logger.child("android-environment"); -var getHostAndroidSystemImageArch = (architecture = process.arch) => { - switch (architecture) { - case "arm64": - return "arm64-v8a"; - case "arm": - return "armeabi-v7a"; - case "x64": - default: - return "x86_64"; - } -}; - -// ../platform-android/dist/emulator-startup.js -var emulatorStartupLogger = logger.child("android-emulator-startup"); -var getEmulatorCpuCores = () => { - return getDeviceCoreBudget(import_node_os3.default.availableParallelism()); -}; - -// ../platform-android/dist/adb.js -var import_node_child_process = require("child_process"); -var import_promises4 = require("fs/promises"); -var EMULATOR_OUTPUT_BUFFER_LIMIT = 16 * 1024; -var androidAdbLogger = logger.child("android-adb"); - -// src/shared/index.ts -var import_node_path9 = __toESM(require("path")); -var import_node_fs8 = __toESM(require("fs")); -var resolveAvdCachingEnabled2 = ({ - snapshotEnabled -}) => { - const override = process.env.HARNESS_AVD_CACHING; - const requestedValue = override == null ? snapshotEnabled : override.toLowerCase() === "true"; - return requestedValue === true; -}; -var getNormalizedAvdCacheConfig2 = ({ - emulator, - hostArch -}) => { - const avd = emulator.avd; - if (!avd) { - return null; - } - return { - name: emulator.name, - apiLevel: avd.apiLevel, - arch: hostArch, - profile: avd.profile.trim().toLowerCase(), - diskSize: avd.diskSize.trim().toLowerCase(), - heapSize: avd.heapSize.trim().toLowerCase(), - // Roll the AVD cache key whenever the baked-in vCPU count changes, so a - // cached AVD built before this constant existed regenerates once instead - // of failing the compatibility check on every run. - cpuCores: getEmulatorCpuCores() - }; -}; -var getResolvedRunner = (runner) => { - if (runner.platformId !== "android" || runner.config.device.type !== "emulator") { - return runner; - } - const avdCachingEnabled = resolveAvdCachingEnabled2({ - snapshotEnabled: runner.config.device.avd?.snapshot?.enabled - }); - return { - ...runner, - config: { - ...runner.config, - device: { - ...runner.config.device, - avd: runner.config.device.avd - } - }, - action: { - avdCachingEnabled, - avdCacheConfig: getNormalizedAvdCacheConfig2({ - emulator: runner.config.device, - hostArch: getHostAndroidSystemImageArch() - }) - } - }; -}; -var run = async () => { - try { - const projectRootInput = process.env.INPUT_PROJECTROOT; - const runnerInput = process.env.INPUT_RUNNER; - if (!runnerInput) { - throw new Error("Runner input is required"); - } - const projectRoot = projectRootInput ? import_node_path9.default.resolve(projectRootInput) : process.cwd(); - console.info(`Loading React Native Harness config from: ${projectRoot}`); - const { config, projectRoot: resolvedProjectRoot } = await getConfig( - projectRoot - ); - const runner = config.runners.find((runner2) => runner2.name === runnerInput); - if (!runner) { - throw new Error(`Runner ${runnerInput} not found in config`); - } - const githubOutput = process.env.GITHUB_OUTPUT; - if (!githubOutput) { - throw new Error("GITHUB_OUTPUT environment variable is not set"); - } - const resolvedRunner = getResolvedRunner(runner); - const relativeProjectRoot = import_node_path9.default.relative(process.cwd(), resolvedProjectRoot) || "."; - const output = `config=${JSON.stringify( - resolvedRunner - )} -projectRoot=${relativeProjectRoot} -`; - import_node_fs8.default.appendFileSync(githubOutput, output); - } catch (error) { - if (error instanceof Error) { - console.error(error.message); - } else { - console.error("Failed to load Harness configuration"); - } - process.exit(1); - } -}; -run(); diff --git a/actions/shared/plan-restore.cjs b/actions/shared/plan-restore.cjs deleted file mode 100644 index 3525d74c..00000000 --- a/actions/shared/plan-restore.cjs +++ /dev/null @@ -1,5045 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// ../../node_modules/picocolors/picocolors.js -var require_picocolors = __commonJS({ - "../../node_modules/picocolors/picocolors.js"(exports2, module2) { - "use strict"; - var p = process || {}; - var argv = p.argv || []; - var env = p.env || {}; - var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI); - var formatter = (open, close, replace = open) => (input) => { - let string = "" + input, index = string.indexOf(close, open.length); - return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; - }; - var replaceClose = (string, close, replace, index) => { - let result = "", cursor = 0; - do { - result += string.substring(cursor, index) + replace; - cursor = index + close.length; - index = string.indexOf(close, cursor); - } while (~index); - return result + string.substring(cursor); - }; - var createColors = (enabled = isColorSupported) => { - let f = enabled ? formatter : () => String; - return { - isColorSupported: enabled, - reset: f("\x1B[0m", "\x1B[0m"), - bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), - dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), - italic: f("\x1B[3m", "\x1B[23m"), - underline: f("\x1B[4m", "\x1B[24m"), - inverse: f("\x1B[7m", "\x1B[27m"), - hidden: f("\x1B[8m", "\x1B[28m"), - strikethrough: f("\x1B[9m", "\x1B[29m"), - black: f("\x1B[30m", "\x1B[39m"), - red: f("\x1B[31m", "\x1B[39m"), - green: f("\x1B[32m", "\x1B[39m"), - yellow: f("\x1B[33m", "\x1B[39m"), - blue: f("\x1B[34m", "\x1B[39m"), - magenta: f("\x1B[35m", "\x1B[39m"), - cyan: f("\x1B[36m", "\x1B[39m"), - white: f("\x1B[37m", "\x1B[39m"), - gray: f("\x1B[90m", "\x1B[39m"), - bgBlack: f("\x1B[40m", "\x1B[49m"), - bgRed: f("\x1B[41m", "\x1B[49m"), - bgGreen: f("\x1B[42m", "\x1B[49m"), - bgYellow: f("\x1B[43m", "\x1B[49m"), - bgBlue: f("\x1B[44m", "\x1B[49m"), - bgMagenta: f("\x1B[45m", "\x1B[49m"), - bgCyan: f("\x1B[46m", "\x1B[49m"), - bgWhite: f("\x1B[47m", "\x1B[49m"), - blackBright: f("\x1B[90m", "\x1B[39m"), - redBright: f("\x1B[91m", "\x1B[39m"), - greenBright: f("\x1B[92m", "\x1B[39m"), - yellowBright: f("\x1B[93m", "\x1B[39m"), - blueBright: f("\x1B[94m", "\x1B[39m"), - magentaBright: f("\x1B[95m", "\x1B[39m"), - cyanBright: f("\x1B[96m", "\x1B[39m"), - whiteBright: f("\x1B[97m", "\x1B[39m"), - bgBlackBright: f("\x1B[100m", "\x1B[49m"), - bgRedBright: f("\x1B[101m", "\x1B[49m"), - bgGreenBright: f("\x1B[102m", "\x1B[49m"), - bgYellowBright: f("\x1B[103m", "\x1B[49m"), - bgBlueBright: f("\x1B[104m", "\x1B[49m"), - bgMagentaBright: f("\x1B[105m", "\x1B[49m"), - bgCyanBright: f("\x1B[106m", "\x1B[49m"), - bgWhiteBright: f("\x1B[107m", "\x1B[49m") - }; - }; - module2.exports = createColors(); - module2.exports.createColors = createColors; - } -}); - -// ../../node_modules/sisteransi/src/index.js -var require_src = __commonJS({ - "../../node_modules/sisteransi/src/index.js"(exports2, module2) { - "use strict"; - var ESC = "\x1B"; - var CSI = `${ESC}[`; - var beep = "\x07"; - var cursor = { - to(x2, y) { - if (!y) return `${CSI}${x2 + 1}G`; - return `${CSI}${y + 1};${x2 + 1}H`; - }, - move(x2, y) { - let ret = ""; - if (x2 < 0) ret += `${CSI}${-x2}D`; - else if (x2 > 0) ret += `${CSI}${x2}C`; - if (y < 0) ret += `${CSI}${-y}A`; - else if (y > 0) ret += `${CSI}${y}B`; - return ret; - }, - up: (count = 1) => `${CSI}${count}A`, - down: (count = 1) => `${CSI}${count}B`, - forward: (count = 1) => `${CSI}${count}C`, - backward: (count = 1) => `${CSI}${count}D`, - nextLine: (count = 1) => `${CSI}E`.repeat(count), - prevLine: (count = 1) => `${CSI}F`.repeat(count), - left: `${CSI}G`, - hide: `${CSI}?25l`, - show: `${CSI}?25h`, - save: `${ESC}7`, - restore: `${ESC}8` - }; - var scroll = { - up: (count = 1) => `${CSI}S`.repeat(count), - down: (count = 1) => `${CSI}T`.repeat(count) - }; - var erase = { - screen: `${CSI}2J`, - up: (count = 1) => `${CSI}1J`.repeat(count), - down: (count = 1) => `${CSI}J`.repeat(count), - line: `${CSI}2K`, - lineEnd: `${CSI}K`, - lineStart: `${CSI}1K`, - lines(count) { - let clear = ""; - for (let i = 0; i < count; i++) - clear += this.line + (i < count - 1 ? cursor.up() : ""); - if (count) - clear += cursor.left; - return clear; - } - }; - module2.exports = { cursor, scroll, erase, beep }; - } -}); - -// src/shared/plan-restore.ts -var import_node_fs12 = __toESM(require("fs")); -var import_node_path12 = __toESM(require("path")); - -// ../cache/dist/index.js -var import_node_fs9 = __toESM(require("fs"), 1); - -// ../tools/dist/net.js -var import_node_net = __toESM(require("net"), 1); - -// ../tools/dist/logger.js -var import_node_util = __toESM(require("util"), 1); -var import_picocolors = __toESM(require_picocolors(), 1); -var verbose = !!process.env.HARNESS_DEBUG; -var BASE_TAG = "[harness]"; -var INFO_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.magenta(" HARNESS ")))) : "HARNESS"; -var ERROR_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.red(" HARNESS ")))) : "HARNESS"; -var getTimestamp = () => (/* @__PURE__ */ new Date()).toISOString(); -var normalizeScope = (scope) => scope.trim().replace(/^\[+|\]+$/g, "").replace(/\]\[/g, "]["); -var formatPrefix = (scopes) => { - const suffix = scopes.map((scope) => `[${normalizeScope(scope)}]`).join(""); - return `${BASE_TAG}${suffix}`; -}; -var mapLines = (text, prefix) => text.split("\n").map((line) => `${prefix} ${line}`).join("\n"); -var writeLog = (level, scopes, messages) => { - if (!verbose && (level === "info" || level === "log" || level === "success")) { - const output2 = import_node_util.default.format(...messages); - const tag = INFO_TAG; - process.stderr.write(`${tag} ${output2} -`); - return; - } - if (!verbose && level === "error") { - const output2 = import_node_util.default.format(...messages); - process.stderr.write(`${ERROR_TAG} ${output2} -`); - return; - } - const method = level === "warn" ? console.warn : console.debug; - const output = import_node_util.default.format(...messages); - const prefix = `${getTimestamp()} ${formatPrefix(scopes)}`; - method(mapLines(output, prefix)); -}; -var setVerbose = (level) => { - verbose = level; -}; -var isVerbose = () => { - return verbose; -}; -var createScopedLogger = (scopes = []) => ({ - debug: (...messages) => { - if (!verbose) { - return; - } - writeLog("debug", scopes, messages); - }, - info: (...messages) => { - writeLog("info", scopes, messages); - }, - warn: (...messages) => { - writeLog("warn", scopes, messages); - }, - error: (...messages) => { - writeLog("error", scopes, messages); - }, - log: (...messages) => { - writeLog("log", scopes, messages); - }, - success: (...messages) => { - writeLog("success", scopes, messages); - }, - child: (scope) => createScopedLogger([...scopes, scope]), - setVerbose, - isVerbose -}); -var logger = createScopedLogger(); - -// ../../node_modules/@clack/core/dist/index.mjs -var import_node_process = require("process"); -var k = __toESM(require("readline"), 1); -var import_node_readline = __toESM(require("readline"), 1); -var import_sisteransi = __toESM(require_src(), 1); -var import_node_tty = require("tty"); -var Ft = { limit: 1 / 0, ellipsis: "" }; -var ft = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var j = "\x07"; -var Q = "["; -var dt = "]"; -var U = `${dt}8;;`; -var et = new RegExp(`(?:\\${Q}(?\\d+)m|\\${U}(?.*)${j})`, "y"); -var At = ["up", "down", "left", "right", "space", "enter", "cancel"]; -var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true }; -var bt = globalThis.process.platform.startsWith("win"); - -// ../../node_modules/@clack/prompts/dist/index.mjs -var import_picocolors2 = __toESM(require_picocolors(), 1); -var import_node_process2 = __toESM(require("process"), 1); -var import_node_fs = require("fs"); -var import_node_path = require("path"); -var import_sisteransi2 = __toESM(require_src(), 1); -var import_node_util2 = require("util"); -function ht() { - return import_node_process2.default.platform !== "win32" ? import_node_process2.default.env.TERM !== "linux" : !!import_node_process2.default.env.CI || !!import_node_process2.default.env.WT_SESSION || !!import_node_process2.default.env.TERMINUS_SUBLIME || import_node_process2.default.env.ConEmuTask === "{cmd::Cmder}" || import_node_process2.default.env.TERM_PROGRAM === "Terminus-Sublime" || import_node_process2.default.env.TERM_PROGRAM === "vscode" || import_node_process2.default.env.TERM === "xterm-256color" || import_node_process2.default.env.TERM === "alacritty" || import_node_process2.default.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; -} -var ee = ht(); -var w = (e, r) => ee ? e : r; -var Me = w("\u25C6", "*"); -var ce = w("\u25A0", "x"); -var de = w("\u25B2", "x"); -var V = w("\u25C7", "o"); -var $e = w("\u250C", "T"); -var h = w("\u2502", "|"); -var x = w("\u2514", "\u2014"); -var Re = w("\u2510", "T"); -var Oe = w("\u2518", "\u2014"); -var Y = w("\u25CF", ">"); -var K = w("\u25CB", " "); -var te = w("\u25FB", "[\u2022]"); -var k2 = w("\u25FC", "[+]"); -var z = w("\u25FB", "[ ]"); -var Pe = w("\u25AA", "\u2022"); -var se = w("\u2500", "-"); -var he = w("\u256E", "+"); -var Ne = w("\u251C", "+"); -var me = w("\u256F", "+"); -var pe = w("\u2570", "+"); -var We = w("\u256D", "+"); -var ge = w("\u25CF", "\u2022"); -var fe = w("\u25C6", "*"); -var Fe = w("\u25B2", "!"); -var ye = w("\u25A0", "x"); -var Ft2 = { limit: 1 / 0, ellipsis: "" }; -var yt2 = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var Ce = "\x07"; -var Ve = "["; -var vt = "]"; -var we = `${vt}8;;`; -var Ge = new RegExp(`(?:\\${Ve}(?\\d+)m|\\${we}(?.*)${Ce})`, "y"); -var Ut = import_picocolors2.default.magenta; -var Ye = { light: w("\u2500", "-"), heavy: w("\u2501", "="), block: w("\u2588", "#") }; -var ze = `${import_picocolors2.default.gray(h)} `; - -// ../tools/dist/spawn.js -var spawnLogger = logger.child("spawn"); - -// ../tools/dist/react-native.js -var import_node_module = require("module"); -var import_node_path2 = __toESM(require("path"), 1); -var import_node_fs2 = __toESM(require("fs"), 1); - -// ../tools/dist/error.js -var HarnessError = class extends Error { -}; - -// ../tools/dist/packages.js -var import_node_path3 = __toESM(require("path"), 1); -var import_node_fs3 = __toESM(require("fs"), 1); - -// ../tools/dist/path.js -var import_node_path4 = __toESM(require("path"), 1); - -// ../tools/dist/crash-artifacts.js -var import_node_fs4 = __toESM(require("fs"), 1); -var import_node_path5 = __toESM(require("path"), 1); -var DEFAULT_ARTIFACT_ROOT = import_node_path5.default.join(process.cwd(), ".harness", "crash-reports"); - -// ../tools/dist/harness-artifacts.js -var import_node_fs5 = __toESM(require("fs"), 1); -var import_node_path6 = __toESM(require("path"), 1); - -// ../tools/dist/diagnostics.js -var noop = () => void 0; -var noopSpan = { - end: noop, - fail: noop -}; -var createNoopDiagnostics = () => { - const diagnostics = { - enabled: false, - start: () => noopSpan, - measure: async (_label, fn) => fn(), - mark: noop, - record: noop, - child: () => diagnostics, - flush: () => [] - }; - return diagnostics; -}; -var noopDiagnostics = createNoopDiagnostics(); - -// ../tools/dist/host-capabilities.js -var import_node_os = __toESM(require("os"), 1); - -// ../cache/dist/paths.js -var import_node_path7 = __toESM(require("path"), 1); -var HARNESS_DIRNAME = ".harness"; -var CACHE_DIRNAME = "cache"; -var METRO_TRANSFORM_DIRNAME = "metro"; -var METRO_FILE_MAP_DIRNAME = "metro-file-map"; -var createHarnessCachePaths = (projectRoot) => { - const root = import_node_path7.default.join(projectRoot, HARNESS_DIRNAME, CACHE_DIRNAME); - return { - root, - metroTransform: import_node_path7.default.join(root, METRO_TRANSFORM_DIRNAME), - metroFileMap: import_node_path7.default.join(root, METRO_FILE_MAP_DIRNAME) - }; -}; -var getDomainDirectories = (domain, paths) => { - switch (domain) { - case "metro": - return [paths.metroTransform, paths.metroFileMap]; - default: - return []; - } -}; - -// ../cache/dist/plan.js -var import_node_crypto = require("crypto"); -var import_node_fs6 = __toESM(require("fs"), 1); -var import_node_path8 = __toESM(require("path"), 1); -var cacheLogger = logger.child("cache"); -var KEYS_FILENAME = "keys.json"; -var HASH_LENGTH = 16; -var ALL_DOMAINS = ["metro"]; -var isAccretiveDomain = (domain) => { - switch (domain) { - case "metro": - return true; - default: - return false; - } -}; -var hashSortedEntries = (entries) => (0, import_node_crypto.createHash)("sha256").update(entries.slice().sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => `${key}=${value}`).join("\n")).digest("hex").slice(0, HASH_LENGTH); -var buildStaticHashKey = (domain, inputs) => { - const hash = hashSortedEntries(Object.entries(inputs.staticInputs)); - return `harness-${domain}-${inputs.os}-${hash}`; -}; -var buildContentHash = (entries) => hashSortedEntries(entries.map((entry) => [entry.path, String(entry.sizeBytes)])); -var walkDirectory = (root, directory, entries) => { - let dirents; - try { - dirents = import_node_fs6.default.readdirSync(directory, { withFileTypes: true }); - } catch { - return; - } - for (const dirent of dirents) { - const fullPath = import_node_path8.default.join(directory, dirent.name); - if (dirent.isDirectory()) { - walkDirectory(root, fullPath, entries); - } else if (dirent.isFile()) { - const stat = import_node_fs6.default.statSync(fullPath); - entries.push({ - path: import_node_path8.default.relative(root, fullPath), - sizeBytes: stat.size, - mtimeMs: stat.mtimeMs - }); - } - } -}; -var planRestore = (paths, inputs) => { - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const restoreKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - paths: [...getDomainDirectories(domain, paths)], - restoreKey, - restorePrefixes: accretive ? [`${restoreKey}-`] : [], - accretive - }; - } - return { version: 1, domains }; -}; -var snapshot = (paths) => { - const result = {}; - for (const domain of ALL_DOMAINS) { - try { - const entries = []; - for (const directory of getDomainDirectories(domain, paths)) { - walkDirectory(paths.root, directory, entries); - } - result[domain] = entries; - } catch (error) { - cacheLogger.warn(`Failed to snapshot cache domain "${domain}". Treating as empty.`, error); - result[domain] = []; - } - } - return result; -}; -var diffSnapshots = (before, after) => { - const beforeByPath = new Map(before.map((entry) => [entry.path, entry])); - const afterByPath = new Map(after.map((entry) => [entry.path, entry])); - let addedEntries = 0; - let removedEntries = 0; - let addedBytes = 0; - for (const [entryPath, afterEntry] of afterByPath) { - const beforeEntry = beforeByPath.get(entryPath); - if (!beforeEntry || beforeEntry.sizeBytes !== afterEntry.sizeBytes) { - addedEntries += 1; - addedBytes += afterEntry.sizeBytes; - } - } - for (const entryPath of beforeByPath.keys()) { - if (!afterByPath.has(entryPath)) { - removedEntries += 1; - } - } - return { addedEntries, removedEntries, addedBytes }; -}; -var shouldSaveForPolicy = (policy, delta) => { - if (delta.addedEntries + delta.removedEntries === 0) { - return false; - } - switch (policy.mode) { - case "always": - return true; - case "default-branch": - return policy.isDefaultBranch; - case "never": - return false; - } -}; -var planSave = (paths, before, policy, inputs) => { - const after = snapshot(paths); - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const beforeEntries = before[domain] ?? []; - const afterEntries = after[domain] ?? []; - const delta = diffSnapshots(beforeEntries, afterEntries); - const staticHashKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - shouldSave: shouldSaveForPolicy(policy, delta), - saveKey: accretive ? `${staticHashKey}-${buildContentHash(afterEntries)}` : staticHashKey, - delta - }; - } - return { version: 1, domains }; -}; -var writeKeysFile = (paths, plan) => { - const filePath = import_node_path8.default.join(paths.root, KEYS_FILENAME); - try { - import_node_fs6.default.mkdirSync(paths.root, { recursive: true }); - import_node_fs6.default.writeFileSync(filePath, JSON.stringify(plan, null, 2)); - } catch (error) { - cacheLogger.warn(`Failed to write cache keys file "${filePath}".`, error); - } -}; - -// ../cache/dist/warmth.js -var import_node_fs7 = __toESM(require("fs"), 1); -var cacheLogger2 = logger.child("cache"); -var isDomainWarm = (domain, paths) => { - const directory = getWarmthDirectory(domain, paths); - if (!directory) { - return false; - } - try { - const stat = import_node_fs7.default.statSync(directory); - if (!stat.isDirectory()) { - return false; - } - return import_node_fs7.default.readdirSync(directory).length > 0; - } catch (error) { - if (isMissingPathError(error)) { - return false; - } - cacheLogger2.warn(`Failed to check cache warmth for "${domain}" at "${directory}". Treating as cold.`, error); - return false; - } -}; -var getWarmthDirectory = (domain, paths) => { - switch (domain) { - case "metro": - return paths.metroTransform; - default: - return void 0; - } -}; -var isMissingPathError = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; - -// ../cache/dist/domains/metro.js -var import_node_crypto2 = require("crypto"); -var import_node_fs8 = __toESM(require("fs"), 1); -var import_node_path9 = __toESM(require("path"), 1); -var cacheLogger3 = logger.child("cache"); -var LOCKFILE_NAMES = [ - "bun.lock", - "bun.lockb", - "package-lock.json", - "npm-shrinkwrap.json", - "pnpm-lock.yaml", - "yarn.lock" -]; -var METRO_CONFIG_EXTENSIONS = [ - "js", - "cjs", - "mjs", - "ts", - "cts", - "mts", - "json" -]; -var METRO_CONFIG_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `metro.config.${extension}`); -var METRO_CONFIG_DIR_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `.config/metro.${extension}`); -var BABEL_CONFIG_NAMES = [ - "babel.config.json", - "babel.config.js", - "babel.config.cjs", - "babel.config.mjs", - "babel.config.cts" -]; -var METRO_KEY_FILENAMES = [ - ...LOCKFILE_NAMES, - ...METRO_CONFIG_NAMES, - ...METRO_CONFIG_DIR_NAMES, - ...BABEL_CONFIG_NAMES -]; -var collectAncestorDirectories = (projectRoot, repoRoot) => { - const resolvedProjectRoot = import_node_path9.default.resolve(projectRoot); - const resolvedRepoRoot = import_node_path9.default.resolve(repoRoot); - if (resolvedProjectRoot === resolvedRepoRoot) { - return [resolvedProjectRoot]; - } - const relative = import_node_path9.default.relative(resolvedRepoRoot, resolvedProjectRoot); - const isProjectRootInsideRepoRoot = relative !== "" && !relative.startsWith(`..${import_node_path9.default.sep}`) && relative !== ".." && !import_node_path9.default.isAbsolute(relative); - if (!isProjectRootInsideRepoRoot) { - return [resolvedProjectRoot]; - } - const directories = []; - let current = resolvedProjectRoot; - for (; ; ) { - directories.push(current); - if (current === resolvedRepoRoot) { - break; - } - const parent = import_node_path9.default.dirname(current); - if (parent === current) { - break; - } - current = parent; - } - return directories; -}; -var collectKeyFiles = (directories, repoRoot) => { - const matches = []; - for (const directory of directories) { - for (const candidate of METRO_KEY_FILENAMES) { - const fullPath = import_node_path9.default.join(directory, candidate); - if (!import_node_fs8.default.existsSync(fullPath) || !import_node_fs8.default.statSync(fullPath).isFile()) { - continue; - } - matches.push({ - relativePath: import_node_path9.default.relative(repoRoot, fullPath).split(import_node_path9.default.sep).join("/"), - content: import_node_fs8.default.readFileSync(fullPath) - }); - } - } - return matches; -}; -var hashKeyFiles = (matches) => { - const hash = (0, import_node_crypto2.createHash)("sha256"); - for (const match of matches.slice().sort((a, b) => a.relativePath < b.relativePath ? -1 : 1)) { - hash.update(match.relativePath); - hash.update("\0"); - hash.update(match.content); - hash.update("\0"); - } - return hash.digest("hex"); -}; -var computeMetroStaticInputs = (options) => { - try { - const resolvedProjectRoot = import_node_path9.default.resolve(options.projectRoot); - const resolvedRepoRoot = import_node_path9.default.resolve(options.repoRoot); - if (!import_node_fs8.default.statSync(resolvedProjectRoot).isDirectory()) { - throw new Error(`projectRoot "${resolvedProjectRoot}" is not a directory`); - } - if (!import_node_fs8.default.statSync(resolvedRepoRoot).isDirectory()) { - throw new Error(`repoRoot "${resolvedRepoRoot}" is not a directory`); - } - const directories = collectAncestorDirectories(resolvedProjectRoot, resolvedRepoRoot); - const matches = collectKeyFiles(directories, resolvedRepoRoot); - return { - lockfileHash: hashKeyFiles(matches), - bundlerMetroVersion: options.bundlerMetroVersion, - ...options.salt ? { salt: options.salt } : {} - }; - } catch (error) { - cacheLogger3.warn(`Failed to compute Metro cache key inputs for "${options.projectRoot}". Falling back to an always-miss key.`, error); - return { - lockfileHash: "unavailable", - bundlerMetroVersion: options.bundlerMetroVersion - }; - } -}; - -// ../cache/dist/index.js -var cacheLogger4 = logger.child("cache"); -var createHarnessCache = (options) => { - const paths = createHarnessCachePaths(options.projectRoot); - return { - paths, - isWarm: (domain) => isDomainWarm(domain, paths), - ensureDomainDirectories: (domain) => { - for (const directory of getDomainDirectories(domain, paths)) { - try { - import_node_fs9.default.mkdirSync(directory, { recursive: true }); - } catch (error) { - cacheLogger4.warn(`Failed to create cache directory "${directory}". Continuing with a cold cache.`, error); - } - } - }, - planRestore: (inputs) => planRestore(paths, inputs), - snapshot: () => snapshot(paths), - planSave: (before, policy, inputs) => planSave(paths, before, policy, inputs), - writeKeysFile: (plan) => writeKeysFile(paths, plan) - }; -}; - -// ../../node_modules/zod/dist/esm/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util2, - void: () => voidType -}); - -// ../../node_modules/zod/dist/esm/v3/helpers/util.js -var util2; -(function(util3) { - util3.assertEqual = (_2) => { - }; - function assertIs(_arg) { - } - util3.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util3.assertNever = assertNever; - util3.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util3.getValidEnumValues = (obj) => { - const validKeys = util3.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); - const filtered = {}; - for (const k3 of validKeys) { - filtered[k3] = obj[k3]; - } - return util3.objectValues(filtered); - }; - util3.objectValues = (obj) => { - return util3.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util3.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util3.joinValues = joinValues; - util3.jsonStringifyReplacer = (_2, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t2 = typeof data; - switch (t2) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// ../../node_modules/zod/dist/esm/v3/ZodError.js -var ZodIssueCode = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -// ../../node_modules/zod/dist/esm/v3/locales/en.js -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util2.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue); - } - return { message }; -}; -var en_default = errorMap; - -// ../../node_modules/zod/dist/esm/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -// ../../node_modules/zod/dist/esm/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data, path: path12, errorMaps, issueData } = params; - const fullPath = [...path12, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x2) => !!x2) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x2) => x2.status === "aborted"; -var isDirty = (x2) => x2.status === "dirty"; -var isValid = (x2) => x2.status === "valid"; -var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; - -// ../../node_modules/zod/dist/esm/v3/helpers/errorUtil.js -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -// ../../node_modules/zod/dist/esm/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path12, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path12; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new _ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util2.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x2) => !!x2); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me2 = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me2 = this; - return OK(function(...args) { - const parsedArgs = me2._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me2._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = /* @__PURE__ */ Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })) -}; -var NEVER = INVALID; - -// ../plugins/dist/utils.js -var isHookTree = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - for (const child of Object.values(value)) { - if (child === void 0) { - continue; - } - if (typeof child === "function") { - continue; - } - if (child == null || typeof child !== "object" || Array.isArray(child) || !isHookTree(child)) { - return false; - } - } - return true; -}; - -// ../plugins/dist/plugin.js -var isHarnessPlugin = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const candidate = value; - if (typeof candidate.name !== "string" || candidate.name.length === 0) { - return false; - } - if (candidate.createState != null && typeof candidate.createState !== "function") { - return false; - } - if (candidate.hooks != null && !isHookTree(candidate.hooks)) { - return false; - } - return true; -}; - -// ../plugins/dist/manager.js -var pluginsLogger = logger.child("plugins"); - -// ../config/dist/types.js -var DEFAULT_METRO_PORT = 8081; -var configLogger = logger.child("config"); -var RunnerSchema = external_exports.object({ - name: external_exports.string().min(1, "Runner name is required").regex(/^[a-zA-Z0-9._-]+$/, "Runner name can only contain alphanumeric characters, dots, underscores, and hyphens"), - config: external_exports.record(external_exports.any()), - runner: external_exports.string(), - cli: external_exports.string().optional(), - platformId: external_exports.string() -}); -var PluginSchema = external_exports.custom((value) => isHarnessPlugin(value), "Invalid Harness plugin"); -var ConfigSchema = external_exports.object({ - entryPoint: external_exports.string().min(1, "Entry point is required"), - appRegistryComponentName: external_exports.string().min(1, "App registry component name is required"), - runners: external_exports.array(RunnerSchema).min(1, "At least one runner is required"), - plugins: external_exports.array(PluginSchema).optional().default([]), - defaultRunner: external_exports.string().optional(), - host: external_exports.string().min(1, "Host is required").optional(), - metroPort: external_exports.number().int("Metro port must be an integer").min(1, "Metro port must be at least 1").max(65535, "Metro port must be at most 65535").optional().default(DEFAULT_METRO_PORT), - webSocketPort: external_exports.number().optional().describe("Deprecated. Bridge traffic now uses metroPort and this value is ignored."), - bridgeTimeout: external_exports.number().min(1e3, "Bridge timeout must be at least 1 second").default(6e4), - testTimeout: external_exports.number().min(1e3, "Test timeout must be at least 1 second").default(5e3), - platformReadyTimeout: external_exports.number().min(1e3, "Platform ready timeout must be at least 1 second").default(3e5), - bundleStartTimeout: external_exports.number().min(1e3, "Bundle start timeout must be at least 1 second").default(6e4), - maxAppRestarts: external_exports.number().min(0, "Max app restarts must be at least 0").default(2), - eagerPrewarm: external_exports.boolean().optional().default(true).describe("Start building the Metro bundle while the platform (emulator, simulator, or browser) is still booting, so the first bundle is ready sooner. Disable to defer the first bundle build until app startup."), - resetEnvironmentBetweenTestFiles: external_exports.union([external_exports.boolean(), external_exports.enum(["process", "runtime"])]).optional().default(true).describe("Controls how the environment is reset between test files. `true` (default) and `'process'` kill and cold-restart the app process. `'runtime'` reloads the JS runtime in place (DevSettings.reload() / window.location.reload()), which is cheaper but escalates to a process restart if the reload fails or the app does not reconnect in time. `false` disables resetting the environment between test files entirely."), - skipAlreadyIncludedModules: external_exports.boolean().optional().describe('Skip re-sending modules already served in the main app bundle when Metro serves a per-test-file bundle. Defaults to true; set to false as an escape hatch if it causes issues. Left undefined (rather than defaulted here) so `resolveSkipAlreadyIncludedModules` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__skipAlreadyIncludedModules` alias.'), - // Deprecated alias for `skipAlreadyIncludedModules` -- see - // `resolveSkipAlreadyIncludedModules`. Left without a `.default()` for the - // same reason: a default value would be indistinguishable from the user - // never having set it, which would break alias-vs-explicit-flag precedence. - unstable__skipAlreadyIncludedModules: external_exports.boolean().optional().describe("Deprecated. Use `skipAlreadyIncludedModules` instead."), - cache: external_exports.object({ - metro: external_exports.boolean().optional().describe('Enable persistent Metro transform and file-map caching under the .harness cache directory. Defaults to true; set to false to always start with a cold Metro cache. Left undefined (rather than defaulted here) so `resolveMetroCacheEnabled` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__enableMetroCache` alias.'), - version: external_exports.string().optional().describe("User-controlled salt folded into the Metro cacheVersion. Bump it to force-invalidate previously cached transforms.") - }).optional(), - // Deprecated alias for `cache.metro` -- see `resolveMetroCacheEnabled`. - // Left without a `.default()` for the same reason as - // `unstable__skipAlreadyIncludedModules`: a default value would be - // indistinguishable from the user never having set it, which would break - // alias-vs-explicit-flag precedence. - unstable__enableMetroCache: external_exports.boolean().optional().describe("Deprecated. Use `cache.metro` instead."), - permissions: external_exports.boolean().optional().default(false).describe("Enable platform-specific permission prompt automation. When false, Harness does not start permission-handling helpers such as the iOS XCTest agent."), - detectNativeCrashes: external_exports.boolean().optional().default(true), - crashDetectionInterval: external_exports.number().min(100, "Crash detection interval must be at least 100ms").default(500), - disableViewFlattening: external_exports.boolean().optional().default(false).describe("Disable view flattening in React Native. This will set collapsable={true} for all View components to ensure they are not flattened by the native layout engine."), - coverage: external_exports.object({ - root: external_exports.string().optional().describe(`Root directory for coverage instrumentation in monorepo setups. Specifies the directory from which coverage data should be collected. Use ".." for create-react-native-library projects where tests run from example/ but source files are in parent directory. Passed to babel-plugin-istanbul's cwd option.`), - native: external_exports.object({ - ios: external_exports.object({ - pods: external_exports.array(external_exports.string()).min(1, "At least one pod name is required").describe("Pod names to instrument for native code coverage. Coverage flags are injected at pod install time via a CocoaPods hook. After tests, profraw data is collected and converted to lcov format.") - }).optional() - }).optional().describe("Native code coverage configuration.") - }).optional(), - forwardClientLogs: external_exports.boolean().optional().default(false).describe("Enable forwarding of console.log, console.warn, console.error, and other console method calls from the React Native app during the active test run. When enabled, app console output is attached to the active test result's console output."), - diagnostics: external_exports.boolean().optional().default(false).describe("Enable diagnostics tracing for the harness session. Records spans for session setup, Metro bundling, bridge/client events, and per-file test runs, then writes a Chrome Trace Event JSON file and prints a summary after each run. Can also be enabled via the RN_HARNESS_DIAGNOSTICS environment variable."), - // Deprecated property - used for migration detection - include: external_exports.array(external_exports.string()).optional() -}).refine((config) => { - if (config.defaultRunner) { - return config.runners.some((runner) => runner.name === config.defaultRunner); - } - return true; -}, { - message: "Default runner must match one of the configured runner names", - path: ["defaultRunner"] -}); - -// ../config/dist/errors.js -var ConfigValidationError = class extends HarnessError { - filePath; - validationErrors; - constructor(filePath, validationErrors) { - const lines = [ - `Configuration validation failed in ${filePath}`, - "", - "The following issues were found:", - "" - ]; - validationErrors.forEach((error, index) => { - lines.push(` ${index + 1}. ${error}`); - }); - lines.push("", "Please fix these issues and try again.", "For more information, visit: https://react-native-harness.dev/docs/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.validationErrors = validationErrors; - this.name = "ConfigValidationError"; - } -}; -var ConfigNotFoundError = class extends HarnessError { - searchPath; - constructor(searchPath) { - const lines = [ - "Configuration file not found", - "", - `Searched for configuration files in: ${searchPath}`, - "and all parent directories.", - "", - "React Native Harness looks for one of these files:", - " \u2022 rn-harness.config.js", - " \u2022 rn-harness.config.mjs", - " \u2022 rn-harness.config.cjs", - " \u2022 rn-harness.config.json", - "", - "For more information, visit: https://www.react-native-harness.dev/docs/getting-started/configuration" - ]; - super(lines.join("\n")); - this.searchPath = searchPath; - this.name = "ConfigNotFoundError"; - } -}; -var ConfigLoadError = class extends HarnessError { - filePath; - cause; - constructor(filePath, cause) { - const lines = [ - "Failed to load configuration file", - "", - `File: ${filePath}`, - "" - ]; - if (cause) { - lines.push("Error details:"); - lines.push(` ${cause.message}`); - lines.push(""); - } - lines.push("This could be due to:", " \u2022 Syntax errors in your configuration file", " \u2022 Missing dependencies or modules", " \u2022 Invalid file format or encoding", " \u2022 File permissions issues", "", "Troubleshooting steps:", " 1. Check the file syntax and format", " 2. Ensure all required dependencies are installed", " 3. Verify file permissions", " 4. Try creating a new configuration file", "", "For more help, visit: https://www.react-native-harness.dev/docs/getting-started/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.name = "ConfigLoadError"; - this.cause = cause; - } -}; - -// ../config/dist/reader.js -var import_node_path10 = __toESM(require("path"), 1); -var import_node_fs10 = __toESM(require("fs"), 1); -var import_node_module2 = require("module"); -var import_meta = {}; -var extensions = [".js", ".mjs", ".cjs", ".json"]; -var importUp = async (dir, name) => { - const filePath = import_node_path10.default.join(dir, name); - for (const ext of extensions) { - const filePathWithExt = `${filePath}${ext}`; - if (import_node_fs10.default.existsSync(filePathWithExt)) { - let rawConfig; - try { - if (ext === ".mjs") { - rawConfig = await import(filePathWithExt).then((module2) => module2.default); - } else { - const require2 = (0, import_node_module2.createRequire)(import_meta.url); - rawConfig = require2(filePathWithExt); - } - } catch (error) { - throw new ConfigLoadError(filePathWithExt, error instanceof Error ? error : void 0); - } - try { - const config = ConfigSchema.parse(rawConfig); - return { config, filePathWithExt, configDir: dir }; - } catch (error) { - if (error instanceof ZodError) { - const validationErrors = error.errors.map((err) => { - const path12 = err.path.length > 0 ? ` at "${err.path.join(".")}"` : ""; - return `${err.message}${path12}`; - }); - throw new ConfigValidationError(filePathWithExt, validationErrors); - } - throw error; - } - } - } - const parentDir = import_node_path10.default.dirname(dir); - if (parentDir === dir) { - throw new ConfigNotFoundError(dir); - } - return importUp(parentDir, name); -}; -var getConfig = async (dir) => { - const { config, configDir } = await importUp(dir, "rn-harness.config"); - return { - config, - projectRoot: configDir - }; -}; - -// src/shared/metro-cache-inputs.ts -var import_node_fs11 = __toESM(require("fs")); -var import_node_path11 = __toESM(require("path")); -var FALLBACK_BUNDLER_METRO_VERSION = "unknown"; -var resolveRepoRoot = (projectRoot) => { - let dir = projectRoot; - while (true) { - if (import_node_fs11.default.existsSync(import_node_path11.default.join(dir, ".git"))) { - return dir; - } - const parent = import_node_path11.default.dirname(dir); - if (parent === dir) { - return projectRoot; - } - dir = parent; - } -}; -var resolveBundlerMetroPackageJson = (projectRoot) => { - try { - return require.resolve( - "@react-native-harness/bundler-metro/package.json", - { paths: [projectRoot] } - ); - } catch { - const jestPackageJsonPath = require.resolve( - "@react-native-harness/jest/package.json", - { paths: [projectRoot] } - ); - return require.resolve("@react-native-harness/bundler-metro/package.json", { - paths: [import_node_path11.default.dirname(jestPackageJsonPath)] - }); - } -}; -var resolveBundlerMetroVersion = (projectRoot) => { - try { - const packageJsonPath = resolveBundlerMetroPackageJson(projectRoot); - const packageJson = JSON.parse(import_node_fs11.default.readFileSync(packageJsonPath, "utf8")); - if (typeof packageJson.version !== "string") { - throw new Error('"version" field is missing or not a string'); - } - return packageJson.version; - } catch (error) { - console.warn( - `Failed to resolve @react-native-harness/bundler-metro's version from "${projectRoot}". Falling back to "${FALLBACK_BUNDLER_METRO_VERSION}".`, - error - ); - return FALLBACK_BUNDLER_METRO_VERSION; - } -}; -var resolveMetroStaticInputs = (options) => computeMetroStaticInputs({ - projectRoot: options.projectRoot, - repoRoot: resolveRepoRoot(options.projectRoot), - bundlerMetroVersion: resolveBundlerMetroVersion(options.projectRoot), - salt: options.cacheVersionSalt -}); - -// src/shared/plan-restore.ts -var run = async () => { - try { - const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput ? import_node_path12.default.resolve(projectRootInput) : process.cwd(); - console.info(`Planning Metro cache restore for: ${projectRoot}`); - const { config, projectRoot: resolvedProjectRoot } = await getConfig( - projectRoot - ); - const githubOutput = process.env.GITHUB_OUTPUT; - if (!githubOutput) { - throw new Error("GITHUB_OUTPUT environment variable is not set"); - } - const staticInputs = resolveMetroStaticInputs({ - projectRoot: resolvedProjectRoot, - cacheVersionSalt: config.cache?.version - }); - const cache = createHarnessCache({ projectRoot: resolvedProjectRoot }); - const os2 = process.env.RUNNER_OS ?? process.platform; - const restorePlan = cache.planRestore({ - metro: { os: os2, staticInputs } - }); - cache.writeKeysFile(restorePlan); - const metroPlan = restorePlan.domains.metro; - const output = `metroRestoreKey=${metroPlan?.restoreKey ?? ""} -metroRestorePrefixes=${JSON.stringify( - metroPlan?.restorePrefixes ?? [] - )} -`; - import_node_fs12.default.appendFileSync(githubOutput, output); - } catch (error) { - if (error instanceof Error) { - console.error(error.message); - } else { - console.error("Failed to plan Metro cache restore"); - } - process.exit(1); - } -}; -run(); diff --git a/actions/shared/plan-save.cjs b/actions/shared/plan-save.cjs deleted file mode 100644 index 5e69267e..00000000 --- a/actions/shared/plan-save.cjs +++ /dev/null @@ -1,5093 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// ../../node_modules/picocolors/picocolors.js -var require_picocolors = __commonJS({ - "../../node_modules/picocolors/picocolors.js"(exports2, module2) { - "use strict"; - var p = process || {}; - var argv = p.argv || []; - var env = p.env || {}; - var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI); - var formatter = (open, close, replace = open) => (input) => { - let string = "" + input, index = string.indexOf(close, open.length); - return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; - }; - var replaceClose = (string, close, replace, index) => { - let result = "", cursor = 0; - do { - result += string.substring(cursor, index) + replace; - cursor = index + close.length; - index = string.indexOf(close, cursor); - } while (~index); - return result + string.substring(cursor); - }; - var createColors = (enabled = isColorSupported) => { - let f = enabled ? formatter : () => String; - return { - isColorSupported: enabled, - reset: f("\x1B[0m", "\x1B[0m"), - bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), - dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), - italic: f("\x1B[3m", "\x1B[23m"), - underline: f("\x1B[4m", "\x1B[24m"), - inverse: f("\x1B[7m", "\x1B[27m"), - hidden: f("\x1B[8m", "\x1B[28m"), - strikethrough: f("\x1B[9m", "\x1B[29m"), - black: f("\x1B[30m", "\x1B[39m"), - red: f("\x1B[31m", "\x1B[39m"), - green: f("\x1B[32m", "\x1B[39m"), - yellow: f("\x1B[33m", "\x1B[39m"), - blue: f("\x1B[34m", "\x1B[39m"), - magenta: f("\x1B[35m", "\x1B[39m"), - cyan: f("\x1B[36m", "\x1B[39m"), - white: f("\x1B[37m", "\x1B[39m"), - gray: f("\x1B[90m", "\x1B[39m"), - bgBlack: f("\x1B[40m", "\x1B[49m"), - bgRed: f("\x1B[41m", "\x1B[49m"), - bgGreen: f("\x1B[42m", "\x1B[49m"), - bgYellow: f("\x1B[43m", "\x1B[49m"), - bgBlue: f("\x1B[44m", "\x1B[49m"), - bgMagenta: f("\x1B[45m", "\x1B[49m"), - bgCyan: f("\x1B[46m", "\x1B[49m"), - bgWhite: f("\x1B[47m", "\x1B[49m"), - blackBright: f("\x1B[90m", "\x1B[39m"), - redBright: f("\x1B[91m", "\x1B[39m"), - greenBright: f("\x1B[92m", "\x1B[39m"), - yellowBright: f("\x1B[93m", "\x1B[39m"), - blueBright: f("\x1B[94m", "\x1B[39m"), - magentaBright: f("\x1B[95m", "\x1B[39m"), - cyanBright: f("\x1B[96m", "\x1B[39m"), - whiteBright: f("\x1B[97m", "\x1B[39m"), - bgBlackBright: f("\x1B[100m", "\x1B[49m"), - bgRedBright: f("\x1B[101m", "\x1B[49m"), - bgGreenBright: f("\x1B[102m", "\x1B[49m"), - bgYellowBright: f("\x1B[103m", "\x1B[49m"), - bgBlueBright: f("\x1B[104m", "\x1B[49m"), - bgMagentaBright: f("\x1B[105m", "\x1B[49m"), - bgCyanBright: f("\x1B[106m", "\x1B[49m"), - bgWhiteBright: f("\x1B[107m", "\x1B[49m") - }; - }; - module2.exports = createColors(); - module2.exports.createColors = createColors; - } -}); - -// ../../node_modules/sisteransi/src/index.js -var require_src = __commonJS({ - "../../node_modules/sisteransi/src/index.js"(exports2, module2) { - "use strict"; - var ESC = "\x1B"; - var CSI = `${ESC}[`; - var beep = "\x07"; - var cursor = { - to(x2, y) { - if (!y) return `${CSI}${x2 + 1}G`; - return `${CSI}${y + 1};${x2 + 1}H`; - }, - move(x2, y) { - let ret = ""; - if (x2 < 0) ret += `${CSI}${-x2}D`; - else if (x2 > 0) ret += `${CSI}${x2}C`; - if (y < 0) ret += `${CSI}${-y}A`; - else if (y > 0) ret += `${CSI}${y}B`; - return ret; - }, - up: (count = 1) => `${CSI}${count}A`, - down: (count = 1) => `${CSI}${count}B`, - forward: (count = 1) => `${CSI}${count}C`, - backward: (count = 1) => `${CSI}${count}D`, - nextLine: (count = 1) => `${CSI}E`.repeat(count), - prevLine: (count = 1) => `${CSI}F`.repeat(count), - left: `${CSI}G`, - hide: `${CSI}?25l`, - show: `${CSI}?25h`, - save: `${ESC}7`, - restore: `${ESC}8` - }; - var scroll = { - up: (count = 1) => `${CSI}S`.repeat(count), - down: (count = 1) => `${CSI}T`.repeat(count) - }; - var erase = { - screen: `${CSI}2J`, - up: (count = 1) => `${CSI}1J`.repeat(count), - down: (count = 1) => `${CSI}J`.repeat(count), - line: `${CSI}2K`, - lineEnd: `${CSI}K`, - lineStart: `${CSI}1K`, - lines(count) { - let clear = ""; - for (let i = 0; i < count; i++) - clear += this.line + (i < count - 1 ? cursor.up() : ""); - if (count) - clear += cursor.left; - return clear; - } - }; - module2.exports = { cursor, scroll, erase, beep }; - } -}); - -// src/shared/plan-save.ts -var import_node_fs12 = __toESM(require("fs")); -var import_node_path12 = __toESM(require("path")); - -// ../cache/dist/index.js -var import_node_fs9 = __toESM(require("fs"), 1); - -// ../tools/dist/net.js -var import_node_net = __toESM(require("net"), 1); - -// ../tools/dist/logger.js -var import_node_util = __toESM(require("util"), 1); -var import_picocolors = __toESM(require_picocolors(), 1); -var verbose = !!process.env.HARNESS_DEBUG; -var BASE_TAG = "[harness]"; -var INFO_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.magenta(" HARNESS ")))) : "HARNESS"; -var ERROR_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.red(" HARNESS ")))) : "HARNESS"; -var getTimestamp = () => (/* @__PURE__ */ new Date()).toISOString(); -var normalizeScope = (scope) => scope.trim().replace(/^\[+|\]+$/g, "").replace(/\]\[/g, "]["); -var formatPrefix = (scopes) => { - const suffix = scopes.map((scope) => `[${normalizeScope(scope)}]`).join(""); - return `${BASE_TAG}${suffix}`; -}; -var mapLines = (text, prefix) => text.split("\n").map((line) => `${prefix} ${line}`).join("\n"); -var writeLog = (level, scopes, messages) => { - if (!verbose && (level === "info" || level === "log" || level === "success")) { - const output2 = import_node_util.default.format(...messages); - const tag = INFO_TAG; - process.stderr.write(`${tag} ${output2} -`); - return; - } - if (!verbose && level === "error") { - const output2 = import_node_util.default.format(...messages); - process.stderr.write(`${ERROR_TAG} ${output2} -`); - return; - } - const method = level === "warn" ? console.warn : console.debug; - const output = import_node_util.default.format(...messages); - const prefix = `${getTimestamp()} ${formatPrefix(scopes)}`; - method(mapLines(output, prefix)); -}; -var setVerbose = (level) => { - verbose = level; -}; -var isVerbose = () => { - return verbose; -}; -var createScopedLogger = (scopes = []) => ({ - debug: (...messages) => { - if (!verbose) { - return; - } - writeLog("debug", scopes, messages); - }, - info: (...messages) => { - writeLog("info", scopes, messages); - }, - warn: (...messages) => { - writeLog("warn", scopes, messages); - }, - error: (...messages) => { - writeLog("error", scopes, messages); - }, - log: (...messages) => { - writeLog("log", scopes, messages); - }, - success: (...messages) => { - writeLog("success", scopes, messages); - }, - child: (scope) => createScopedLogger([...scopes, scope]), - setVerbose, - isVerbose -}); -var logger = createScopedLogger(); - -// ../../node_modules/@clack/core/dist/index.mjs -var import_node_process = require("process"); -var k = __toESM(require("readline"), 1); -var import_node_readline = __toESM(require("readline"), 1); -var import_sisteransi = __toESM(require_src(), 1); -var import_node_tty = require("tty"); -var Ft = { limit: 1 / 0, ellipsis: "" }; -var ft = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var j = "\x07"; -var Q = "["; -var dt = "]"; -var U = `${dt}8;;`; -var et = new RegExp(`(?:\\${Q}(?\\d+)m|\\${U}(?.*)${j})`, "y"); -var At = ["up", "down", "left", "right", "space", "enter", "cancel"]; -var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true }; -var bt = globalThis.process.platform.startsWith("win"); - -// ../../node_modules/@clack/prompts/dist/index.mjs -var import_picocolors2 = __toESM(require_picocolors(), 1); -var import_node_process2 = __toESM(require("process"), 1); -var import_node_fs = require("fs"); -var import_node_path = require("path"); -var import_sisteransi2 = __toESM(require_src(), 1); -var import_node_util2 = require("util"); -function ht() { - return import_node_process2.default.platform !== "win32" ? import_node_process2.default.env.TERM !== "linux" : !!import_node_process2.default.env.CI || !!import_node_process2.default.env.WT_SESSION || !!import_node_process2.default.env.TERMINUS_SUBLIME || import_node_process2.default.env.ConEmuTask === "{cmd::Cmder}" || import_node_process2.default.env.TERM_PROGRAM === "Terminus-Sublime" || import_node_process2.default.env.TERM_PROGRAM === "vscode" || import_node_process2.default.env.TERM === "xterm-256color" || import_node_process2.default.env.TERM === "alacritty" || import_node_process2.default.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; -} -var ee = ht(); -var w = (e, r) => ee ? e : r; -var Me = w("\u25C6", "*"); -var ce = w("\u25A0", "x"); -var de = w("\u25B2", "x"); -var V = w("\u25C7", "o"); -var $e = w("\u250C", "T"); -var h = w("\u2502", "|"); -var x = w("\u2514", "\u2014"); -var Re = w("\u2510", "T"); -var Oe = w("\u2518", "\u2014"); -var Y = w("\u25CF", ">"); -var K = w("\u25CB", " "); -var te = w("\u25FB", "[\u2022]"); -var k2 = w("\u25FC", "[+]"); -var z = w("\u25FB", "[ ]"); -var Pe = w("\u25AA", "\u2022"); -var se = w("\u2500", "-"); -var he = w("\u256E", "+"); -var Ne = w("\u251C", "+"); -var me = w("\u256F", "+"); -var pe = w("\u2570", "+"); -var We = w("\u256D", "+"); -var ge = w("\u25CF", "\u2022"); -var fe = w("\u25C6", "*"); -var Fe = w("\u25B2", "!"); -var ye = w("\u25A0", "x"); -var Ft2 = { limit: 1 / 0, ellipsis: "" }; -var yt2 = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var Ce = "\x07"; -var Ve = "["; -var vt = "]"; -var we = `${vt}8;;`; -var Ge = new RegExp(`(?:\\${Ve}(?\\d+)m|\\${we}(?.*)${Ce})`, "y"); -var Ut = import_picocolors2.default.magenta; -var Ye = { light: w("\u2500", "-"), heavy: w("\u2501", "="), block: w("\u2588", "#") }; -var ze = `${import_picocolors2.default.gray(h)} `; - -// ../tools/dist/spawn.js -var spawnLogger = logger.child("spawn"); - -// ../tools/dist/react-native.js -var import_node_module = require("module"); -var import_node_path2 = __toESM(require("path"), 1); -var import_node_fs2 = __toESM(require("fs"), 1); - -// ../tools/dist/error.js -var HarnessError = class extends Error { -}; - -// ../tools/dist/packages.js -var import_node_path3 = __toESM(require("path"), 1); -var import_node_fs3 = __toESM(require("fs"), 1); - -// ../tools/dist/path.js -var import_node_path4 = __toESM(require("path"), 1); - -// ../tools/dist/crash-artifacts.js -var import_node_fs4 = __toESM(require("fs"), 1); -var import_node_path5 = __toESM(require("path"), 1); -var DEFAULT_ARTIFACT_ROOT = import_node_path5.default.join(process.cwd(), ".harness", "crash-reports"); - -// ../tools/dist/harness-artifacts.js -var import_node_fs5 = __toESM(require("fs"), 1); -var import_node_path6 = __toESM(require("path"), 1); - -// ../tools/dist/diagnostics.js -var noop = () => void 0; -var noopSpan = { - end: noop, - fail: noop -}; -var createNoopDiagnostics = () => { - const diagnostics = { - enabled: false, - start: () => noopSpan, - measure: async (_label, fn) => fn(), - mark: noop, - record: noop, - child: () => diagnostics, - flush: () => [] - }; - return diagnostics; -}; -var noopDiagnostics = createNoopDiagnostics(); - -// ../tools/dist/host-capabilities.js -var import_node_os = __toESM(require("os"), 1); - -// ../cache/dist/paths.js -var import_node_path7 = __toESM(require("path"), 1); -var HARNESS_DIRNAME = ".harness"; -var CACHE_DIRNAME = "cache"; -var METRO_TRANSFORM_DIRNAME = "metro"; -var METRO_FILE_MAP_DIRNAME = "metro-file-map"; -var createHarnessCachePaths = (projectRoot) => { - const root = import_node_path7.default.join(projectRoot, HARNESS_DIRNAME, CACHE_DIRNAME); - return { - root, - metroTransform: import_node_path7.default.join(root, METRO_TRANSFORM_DIRNAME), - metroFileMap: import_node_path7.default.join(root, METRO_FILE_MAP_DIRNAME) - }; -}; -var getDomainDirectories = (domain, paths) => { - switch (domain) { - case "metro": - return [paths.metroTransform, paths.metroFileMap]; - default: - return []; - } -}; - -// ../cache/dist/plan.js -var import_node_crypto = require("crypto"); -var import_node_fs6 = __toESM(require("fs"), 1); -var import_node_path8 = __toESM(require("path"), 1); -var cacheLogger = logger.child("cache"); -var KEYS_FILENAME = "keys.json"; -var HASH_LENGTH = 16; -var ALL_DOMAINS = ["metro"]; -var isAccretiveDomain = (domain) => { - switch (domain) { - case "metro": - return true; - default: - return false; - } -}; -var hashSortedEntries = (entries) => (0, import_node_crypto.createHash)("sha256").update(entries.slice().sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => `${key}=${value}`).join("\n")).digest("hex").slice(0, HASH_LENGTH); -var buildStaticHashKey = (domain, inputs) => { - const hash = hashSortedEntries(Object.entries(inputs.staticInputs)); - return `harness-${domain}-${inputs.os}-${hash}`; -}; -var buildContentHash = (entries) => hashSortedEntries(entries.map((entry) => [entry.path, String(entry.sizeBytes)])); -var walkDirectory = (root, directory, entries) => { - let dirents; - try { - dirents = import_node_fs6.default.readdirSync(directory, { withFileTypes: true }); - } catch { - return; - } - for (const dirent of dirents) { - const fullPath = import_node_path8.default.join(directory, dirent.name); - if (dirent.isDirectory()) { - walkDirectory(root, fullPath, entries); - } else if (dirent.isFile()) { - const stat = import_node_fs6.default.statSync(fullPath); - entries.push({ - path: import_node_path8.default.relative(root, fullPath), - sizeBytes: stat.size, - mtimeMs: stat.mtimeMs - }); - } - } -}; -var planRestore = (paths, inputs) => { - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const restoreKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - paths: [...getDomainDirectories(domain, paths)], - restoreKey, - restorePrefixes: accretive ? [`${restoreKey}-`] : [], - accretive - }; - } - return { version: 1, domains }; -}; -var snapshot = (paths) => { - const result = {}; - for (const domain of ALL_DOMAINS) { - try { - const entries = []; - for (const directory of getDomainDirectories(domain, paths)) { - walkDirectory(paths.root, directory, entries); - } - result[domain] = entries; - } catch (error) { - cacheLogger.warn(`Failed to snapshot cache domain "${domain}". Treating as empty.`, error); - result[domain] = []; - } - } - return result; -}; -var diffSnapshots = (before, after) => { - const beforeByPath = new Map(before.map((entry) => [entry.path, entry])); - const afterByPath = new Map(after.map((entry) => [entry.path, entry])); - let addedEntries = 0; - let removedEntries = 0; - let addedBytes = 0; - for (const [entryPath, afterEntry] of afterByPath) { - const beforeEntry = beforeByPath.get(entryPath); - if (!beforeEntry || beforeEntry.sizeBytes !== afterEntry.sizeBytes) { - addedEntries += 1; - addedBytes += afterEntry.sizeBytes; - } - } - for (const entryPath of beforeByPath.keys()) { - if (!afterByPath.has(entryPath)) { - removedEntries += 1; - } - } - return { addedEntries, removedEntries, addedBytes }; -}; -var shouldSaveForPolicy = (policy, delta) => { - if (delta.addedEntries + delta.removedEntries === 0) { - return false; - } - switch (policy.mode) { - case "always": - return true; - case "default-branch": - return policy.isDefaultBranch; - case "never": - return false; - } -}; -var planSave = (paths, before, policy, inputs) => { - const after = snapshot(paths); - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const beforeEntries = before[domain] ?? []; - const afterEntries = after[domain] ?? []; - const delta = diffSnapshots(beforeEntries, afterEntries); - const staticHashKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - shouldSave: shouldSaveForPolicy(policy, delta), - saveKey: accretive ? `${staticHashKey}-${buildContentHash(afterEntries)}` : staticHashKey, - delta - }; - } - return { version: 1, domains }; -}; -var writeKeysFile = (paths, plan) => { - const filePath = import_node_path8.default.join(paths.root, KEYS_FILENAME); - try { - import_node_fs6.default.mkdirSync(paths.root, { recursive: true }); - import_node_fs6.default.writeFileSync(filePath, JSON.stringify(plan, null, 2)); - } catch (error) { - cacheLogger.warn(`Failed to write cache keys file "${filePath}".`, error); - } -}; - -// ../cache/dist/warmth.js -var import_node_fs7 = __toESM(require("fs"), 1); -var cacheLogger2 = logger.child("cache"); -var isDomainWarm = (domain, paths) => { - const directory = getWarmthDirectory(domain, paths); - if (!directory) { - return false; - } - try { - const stat = import_node_fs7.default.statSync(directory); - if (!stat.isDirectory()) { - return false; - } - return import_node_fs7.default.readdirSync(directory).length > 0; - } catch (error) { - if (isMissingPathError(error)) { - return false; - } - cacheLogger2.warn(`Failed to check cache warmth for "${domain}" at "${directory}". Treating as cold.`, error); - return false; - } -}; -var getWarmthDirectory = (domain, paths) => { - switch (domain) { - case "metro": - return paths.metroTransform; - default: - return void 0; - } -}; -var isMissingPathError = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; - -// ../cache/dist/domains/metro.js -var import_node_crypto2 = require("crypto"); -var import_node_fs8 = __toESM(require("fs"), 1); -var import_node_path9 = __toESM(require("path"), 1); -var cacheLogger3 = logger.child("cache"); -var LOCKFILE_NAMES = [ - "bun.lock", - "bun.lockb", - "package-lock.json", - "npm-shrinkwrap.json", - "pnpm-lock.yaml", - "yarn.lock" -]; -var METRO_CONFIG_EXTENSIONS = [ - "js", - "cjs", - "mjs", - "ts", - "cts", - "mts", - "json" -]; -var METRO_CONFIG_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `metro.config.${extension}`); -var METRO_CONFIG_DIR_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `.config/metro.${extension}`); -var BABEL_CONFIG_NAMES = [ - "babel.config.json", - "babel.config.js", - "babel.config.cjs", - "babel.config.mjs", - "babel.config.cts" -]; -var METRO_KEY_FILENAMES = [ - ...LOCKFILE_NAMES, - ...METRO_CONFIG_NAMES, - ...METRO_CONFIG_DIR_NAMES, - ...BABEL_CONFIG_NAMES -]; -var collectAncestorDirectories = (projectRoot, repoRoot) => { - const resolvedProjectRoot = import_node_path9.default.resolve(projectRoot); - const resolvedRepoRoot = import_node_path9.default.resolve(repoRoot); - if (resolvedProjectRoot === resolvedRepoRoot) { - return [resolvedProjectRoot]; - } - const relative = import_node_path9.default.relative(resolvedRepoRoot, resolvedProjectRoot); - const isProjectRootInsideRepoRoot = relative !== "" && !relative.startsWith(`..${import_node_path9.default.sep}`) && relative !== ".." && !import_node_path9.default.isAbsolute(relative); - if (!isProjectRootInsideRepoRoot) { - return [resolvedProjectRoot]; - } - const directories = []; - let current = resolvedProjectRoot; - for (; ; ) { - directories.push(current); - if (current === resolvedRepoRoot) { - break; - } - const parent = import_node_path9.default.dirname(current); - if (parent === current) { - break; - } - current = parent; - } - return directories; -}; -var collectKeyFiles = (directories, repoRoot) => { - const matches = []; - for (const directory of directories) { - for (const candidate of METRO_KEY_FILENAMES) { - const fullPath = import_node_path9.default.join(directory, candidate); - if (!import_node_fs8.default.existsSync(fullPath) || !import_node_fs8.default.statSync(fullPath).isFile()) { - continue; - } - matches.push({ - relativePath: import_node_path9.default.relative(repoRoot, fullPath).split(import_node_path9.default.sep).join("/"), - content: import_node_fs8.default.readFileSync(fullPath) - }); - } - } - return matches; -}; -var hashKeyFiles = (matches) => { - const hash = (0, import_node_crypto2.createHash)("sha256"); - for (const match of matches.slice().sort((a, b) => a.relativePath < b.relativePath ? -1 : 1)) { - hash.update(match.relativePath); - hash.update("\0"); - hash.update(match.content); - hash.update("\0"); - } - return hash.digest("hex"); -}; -var computeMetroStaticInputs = (options) => { - try { - const resolvedProjectRoot = import_node_path9.default.resolve(options.projectRoot); - const resolvedRepoRoot = import_node_path9.default.resolve(options.repoRoot); - if (!import_node_fs8.default.statSync(resolvedProjectRoot).isDirectory()) { - throw new Error(`projectRoot "${resolvedProjectRoot}" is not a directory`); - } - if (!import_node_fs8.default.statSync(resolvedRepoRoot).isDirectory()) { - throw new Error(`repoRoot "${resolvedRepoRoot}" is not a directory`); - } - const directories = collectAncestorDirectories(resolvedProjectRoot, resolvedRepoRoot); - const matches = collectKeyFiles(directories, resolvedRepoRoot); - return { - lockfileHash: hashKeyFiles(matches), - bundlerMetroVersion: options.bundlerMetroVersion, - ...options.salt ? { salt: options.salt } : {} - }; - } catch (error) { - cacheLogger3.warn(`Failed to compute Metro cache key inputs for "${options.projectRoot}". Falling back to an always-miss key.`, error); - return { - lockfileHash: "unavailable", - bundlerMetroVersion: options.bundlerMetroVersion - }; - } -}; - -// ../cache/dist/index.js -var cacheLogger4 = logger.child("cache"); -var createHarnessCache = (options) => { - const paths = createHarnessCachePaths(options.projectRoot); - return { - paths, - isWarm: (domain) => isDomainWarm(domain, paths), - ensureDomainDirectories: (domain) => { - for (const directory of getDomainDirectories(domain, paths)) { - try { - import_node_fs9.default.mkdirSync(directory, { recursive: true }); - } catch (error) { - cacheLogger4.warn(`Failed to create cache directory "${directory}". Continuing with a cold cache.`, error); - } - } - }, - planRestore: (inputs) => planRestore(paths, inputs), - snapshot: () => snapshot(paths), - planSave: (before, policy, inputs) => planSave(paths, before, policy, inputs), - writeKeysFile: (plan) => writeKeysFile(paths, plan) - }; -}; - -// ../../node_modules/zod/dist/esm/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util2, - void: () => voidType -}); - -// ../../node_modules/zod/dist/esm/v3/helpers/util.js -var util2; -(function(util3) { - util3.assertEqual = (_2) => { - }; - function assertIs(_arg) { - } - util3.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util3.assertNever = assertNever; - util3.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util3.getValidEnumValues = (obj) => { - const validKeys = util3.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); - const filtered = {}; - for (const k3 of validKeys) { - filtered[k3] = obj[k3]; - } - return util3.objectValues(filtered); - }; - util3.objectValues = (obj) => { - return util3.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util3.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util3.joinValues = joinValues; - util3.jsonStringifyReplacer = (_2, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t2 = typeof data; - switch (t2) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// ../../node_modules/zod/dist/esm/v3/ZodError.js -var ZodIssueCode = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -// ../../node_modules/zod/dist/esm/v3/locales/en.js -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util2.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue); - } - return { message }; -}; -var en_default = errorMap; - -// ../../node_modules/zod/dist/esm/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -// ../../node_modules/zod/dist/esm/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data, path: path12, errorMaps, issueData } = params; - const fullPath = [...path12, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x2) => !!x2) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x2) => x2.status === "aborted"; -var isDirty = (x2) => x2.status === "dirty"; -var isValid = (x2) => x2.status === "valid"; -var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; - -// ../../node_modules/zod/dist/esm/v3/helpers/errorUtil.js -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -// ../../node_modules/zod/dist/esm/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path12, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path12; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new _ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util2.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x2) => !!x2); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me2 = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me2 = this; - return OK(function(...args) { - const parsedArgs = me2._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me2._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = /* @__PURE__ */ Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })) -}; -var NEVER = INVALID; - -// ../plugins/dist/utils.js -var isHookTree = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - for (const child of Object.values(value)) { - if (child === void 0) { - continue; - } - if (typeof child === "function") { - continue; - } - if (child == null || typeof child !== "object" || Array.isArray(child) || !isHookTree(child)) { - return false; - } - } - return true; -}; - -// ../plugins/dist/plugin.js -var isHarnessPlugin = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const candidate = value; - if (typeof candidate.name !== "string" || candidate.name.length === 0) { - return false; - } - if (candidate.createState != null && typeof candidate.createState !== "function") { - return false; - } - if (candidate.hooks != null && !isHookTree(candidate.hooks)) { - return false; - } - return true; -}; - -// ../plugins/dist/manager.js -var pluginsLogger = logger.child("plugins"); - -// ../config/dist/types.js -var DEFAULT_METRO_PORT = 8081; -var configLogger = logger.child("config"); -var RunnerSchema = external_exports.object({ - name: external_exports.string().min(1, "Runner name is required").regex(/^[a-zA-Z0-9._-]+$/, "Runner name can only contain alphanumeric characters, dots, underscores, and hyphens"), - config: external_exports.record(external_exports.any()), - runner: external_exports.string(), - cli: external_exports.string().optional(), - platformId: external_exports.string() -}); -var PluginSchema = external_exports.custom((value) => isHarnessPlugin(value), "Invalid Harness plugin"); -var ConfigSchema = external_exports.object({ - entryPoint: external_exports.string().min(1, "Entry point is required"), - appRegistryComponentName: external_exports.string().min(1, "App registry component name is required"), - runners: external_exports.array(RunnerSchema).min(1, "At least one runner is required"), - plugins: external_exports.array(PluginSchema).optional().default([]), - defaultRunner: external_exports.string().optional(), - host: external_exports.string().min(1, "Host is required").optional(), - metroPort: external_exports.number().int("Metro port must be an integer").min(1, "Metro port must be at least 1").max(65535, "Metro port must be at most 65535").optional().default(DEFAULT_METRO_PORT), - webSocketPort: external_exports.number().optional().describe("Deprecated. Bridge traffic now uses metroPort and this value is ignored."), - bridgeTimeout: external_exports.number().min(1e3, "Bridge timeout must be at least 1 second").default(6e4), - testTimeout: external_exports.number().min(1e3, "Test timeout must be at least 1 second").default(5e3), - platformReadyTimeout: external_exports.number().min(1e3, "Platform ready timeout must be at least 1 second").default(3e5), - bundleStartTimeout: external_exports.number().min(1e3, "Bundle start timeout must be at least 1 second").default(6e4), - maxAppRestarts: external_exports.number().min(0, "Max app restarts must be at least 0").default(2), - eagerPrewarm: external_exports.boolean().optional().default(true).describe("Start building the Metro bundle while the platform (emulator, simulator, or browser) is still booting, so the first bundle is ready sooner. Disable to defer the first bundle build until app startup."), - resetEnvironmentBetweenTestFiles: external_exports.union([external_exports.boolean(), external_exports.enum(["process", "runtime"])]).optional().default(true).describe("Controls how the environment is reset between test files. `true` (default) and `'process'` kill and cold-restart the app process. `'runtime'` reloads the JS runtime in place (DevSettings.reload() / window.location.reload()), which is cheaper but escalates to a process restart if the reload fails or the app does not reconnect in time. `false` disables resetting the environment between test files entirely."), - skipAlreadyIncludedModules: external_exports.boolean().optional().describe('Skip re-sending modules already served in the main app bundle when Metro serves a per-test-file bundle. Defaults to true; set to false as an escape hatch if it causes issues. Left undefined (rather than defaulted here) so `resolveSkipAlreadyIncludedModules` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__skipAlreadyIncludedModules` alias.'), - // Deprecated alias for `skipAlreadyIncludedModules` -- see - // `resolveSkipAlreadyIncludedModules`. Left without a `.default()` for the - // same reason: a default value would be indistinguishable from the user - // never having set it, which would break alias-vs-explicit-flag precedence. - unstable__skipAlreadyIncludedModules: external_exports.boolean().optional().describe("Deprecated. Use `skipAlreadyIncludedModules` instead."), - cache: external_exports.object({ - metro: external_exports.boolean().optional().describe('Enable persistent Metro transform and file-map caching under the .harness cache directory. Defaults to true; set to false to always start with a cold Metro cache. Left undefined (rather than defaulted here) so `resolveMetroCacheEnabled` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__enableMetroCache` alias.'), - version: external_exports.string().optional().describe("User-controlled salt folded into the Metro cacheVersion. Bump it to force-invalidate previously cached transforms.") - }).optional(), - // Deprecated alias for `cache.metro` -- see `resolveMetroCacheEnabled`. - // Left without a `.default()` for the same reason as - // `unstable__skipAlreadyIncludedModules`: a default value would be - // indistinguishable from the user never having set it, which would break - // alias-vs-explicit-flag precedence. - unstable__enableMetroCache: external_exports.boolean().optional().describe("Deprecated. Use `cache.metro` instead."), - permissions: external_exports.boolean().optional().default(false).describe("Enable platform-specific permission prompt automation. When false, Harness does not start permission-handling helpers such as the iOS XCTest agent."), - detectNativeCrashes: external_exports.boolean().optional().default(true), - crashDetectionInterval: external_exports.number().min(100, "Crash detection interval must be at least 100ms").default(500), - disableViewFlattening: external_exports.boolean().optional().default(false).describe("Disable view flattening in React Native. This will set collapsable={true} for all View components to ensure they are not flattened by the native layout engine."), - coverage: external_exports.object({ - root: external_exports.string().optional().describe(`Root directory for coverage instrumentation in monorepo setups. Specifies the directory from which coverage data should be collected. Use ".." for create-react-native-library projects where tests run from example/ but source files are in parent directory. Passed to babel-plugin-istanbul's cwd option.`), - native: external_exports.object({ - ios: external_exports.object({ - pods: external_exports.array(external_exports.string()).min(1, "At least one pod name is required").describe("Pod names to instrument for native code coverage. Coverage flags are injected at pod install time via a CocoaPods hook. After tests, profraw data is collected and converted to lcov format.") - }).optional() - }).optional().describe("Native code coverage configuration.") - }).optional(), - forwardClientLogs: external_exports.boolean().optional().default(false).describe("Enable forwarding of console.log, console.warn, console.error, and other console method calls from the React Native app during the active test run. When enabled, app console output is attached to the active test result's console output."), - diagnostics: external_exports.boolean().optional().default(false).describe("Enable diagnostics tracing for the harness session. Records spans for session setup, Metro bundling, bridge/client events, and per-file test runs, then writes a Chrome Trace Event JSON file and prints a summary after each run. Can also be enabled via the RN_HARNESS_DIAGNOSTICS environment variable."), - // Deprecated property - used for migration detection - include: external_exports.array(external_exports.string()).optional() -}).refine((config) => { - if (config.defaultRunner) { - return config.runners.some((runner) => runner.name === config.defaultRunner); - } - return true; -}, { - message: "Default runner must match one of the configured runner names", - path: ["defaultRunner"] -}); - -// ../config/dist/errors.js -var ConfigValidationError = class extends HarnessError { - filePath; - validationErrors; - constructor(filePath, validationErrors) { - const lines = [ - `Configuration validation failed in ${filePath}`, - "", - "The following issues were found:", - "" - ]; - validationErrors.forEach((error, index) => { - lines.push(` ${index + 1}. ${error}`); - }); - lines.push("", "Please fix these issues and try again.", "For more information, visit: https://react-native-harness.dev/docs/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.validationErrors = validationErrors; - this.name = "ConfigValidationError"; - } -}; -var ConfigNotFoundError = class extends HarnessError { - searchPath; - constructor(searchPath) { - const lines = [ - "Configuration file not found", - "", - `Searched for configuration files in: ${searchPath}`, - "and all parent directories.", - "", - "React Native Harness looks for one of these files:", - " \u2022 rn-harness.config.js", - " \u2022 rn-harness.config.mjs", - " \u2022 rn-harness.config.cjs", - " \u2022 rn-harness.config.json", - "", - "For more information, visit: https://www.react-native-harness.dev/docs/getting-started/configuration" - ]; - super(lines.join("\n")); - this.searchPath = searchPath; - this.name = "ConfigNotFoundError"; - } -}; -var ConfigLoadError = class extends HarnessError { - filePath; - cause; - constructor(filePath, cause) { - const lines = [ - "Failed to load configuration file", - "", - `File: ${filePath}`, - "" - ]; - if (cause) { - lines.push("Error details:"); - lines.push(` ${cause.message}`); - lines.push(""); - } - lines.push("This could be due to:", " \u2022 Syntax errors in your configuration file", " \u2022 Missing dependencies or modules", " \u2022 Invalid file format or encoding", " \u2022 File permissions issues", "", "Troubleshooting steps:", " 1. Check the file syntax and format", " 2. Ensure all required dependencies are installed", " 3. Verify file permissions", " 4. Try creating a new configuration file", "", "For more help, visit: https://www.react-native-harness.dev/docs/getting-started/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.name = "ConfigLoadError"; - this.cause = cause; - } -}; - -// ../config/dist/reader.js -var import_node_path10 = __toESM(require("path"), 1); -var import_node_fs10 = __toESM(require("fs"), 1); -var import_node_module2 = require("module"); -var import_meta = {}; -var extensions = [".js", ".mjs", ".cjs", ".json"]; -var importUp = async (dir, name) => { - const filePath = import_node_path10.default.join(dir, name); - for (const ext of extensions) { - const filePathWithExt = `${filePath}${ext}`; - if (import_node_fs10.default.existsSync(filePathWithExt)) { - let rawConfig; - try { - if (ext === ".mjs") { - rawConfig = await import(filePathWithExt).then((module2) => module2.default); - } else { - const require2 = (0, import_node_module2.createRequire)(import_meta.url); - rawConfig = require2(filePathWithExt); - } - } catch (error) { - throw new ConfigLoadError(filePathWithExt, error instanceof Error ? error : void 0); - } - try { - const config = ConfigSchema.parse(rawConfig); - return { config, filePathWithExt, configDir: dir }; - } catch (error) { - if (error instanceof ZodError) { - const validationErrors = error.errors.map((err) => { - const path12 = err.path.length > 0 ? ` at "${err.path.join(".")}"` : ""; - return `${err.message}${path12}`; - }); - throw new ConfigValidationError(filePathWithExt, validationErrors); - } - throw error; - } - } - } - const parentDir = import_node_path10.default.dirname(dir); - if (parentDir === dir) { - throw new ConfigNotFoundError(dir); - } - return importUp(parentDir, name); -}; -var getConfig = async (dir) => { - const { config, configDir } = await importUp(dir, "rn-harness.config"); - return { - config, - projectRoot: configDir - }; -}; - -// src/shared/format-bytes.ts -var formatMegabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`; - -// src/shared/metro-cache-inputs.ts -var import_node_fs11 = __toESM(require("fs")); -var import_node_path11 = __toESM(require("path")); -var FALLBACK_BUNDLER_METRO_VERSION = "unknown"; -var resolveRepoRoot = (projectRoot) => { - let dir = projectRoot; - while (true) { - if (import_node_fs11.default.existsSync(import_node_path11.default.join(dir, ".git"))) { - return dir; - } - const parent = import_node_path11.default.dirname(dir); - if (parent === dir) { - return projectRoot; - } - dir = parent; - } -}; -var resolveBundlerMetroPackageJson = (projectRoot) => { - try { - return require.resolve( - "@react-native-harness/bundler-metro/package.json", - { paths: [projectRoot] } - ); - } catch { - const jestPackageJsonPath = require.resolve( - "@react-native-harness/jest/package.json", - { paths: [projectRoot] } - ); - return require.resolve("@react-native-harness/bundler-metro/package.json", { - paths: [import_node_path11.default.dirname(jestPackageJsonPath)] - }); - } -}; -var resolveBundlerMetroVersion = (projectRoot) => { - try { - const packageJsonPath = resolveBundlerMetroPackageJson(projectRoot); - const packageJson = JSON.parse(import_node_fs11.default.readFileSync(packageJsonPath, "utf8")); - if (typeof packageJson.version !== "string") { - throw new Error('"version" field is missing or not a string'); - } - return packageJson.version; - } catch (error) { - console.warn( - `Failed to resolve @react-native-harness/bundler-metro's version from "${projectRoot}". Falling back to "${FALLBACK_BUNDLER_METRO_VERSION}".`, - error - ); - return FALLBACK_BUNDLER_METRO_VERSION; - } -}; -var resolveMetroStaticInputs = (options) => computeMetroStaticInputs({ - projectRoot: options.projectRoot, - repoRoot: resolveRepoRoot(options.projectRoot), - bundlerMetroVersion: resolveBundlerMetroVersion(options.projectRoot), - salt: options.cacheVersionSalt -}); - -// src/shared/plan-save.ts -var parseSnapshot = (raw) => { - if (!raw) { - return {}; - } - try { - return JSON.parse(raw); - } catch (error) { - console.warn( - "Failed to parse the metroSnapshot input. Treating the pre-run cache state as empty.", - error - ); - return {}; - } -}; -var parseSavePolicyMode = (raw) => { - if (raw === "always" || raw === "never" || raw === "default-branch") { - return raw; - } - return "default-branch"; -}; -var logMetroSaveDecision = (plan, policy) => { - if (!plan) { - return; - } - const { delta, shouldSave, saveKey } = plan; - if (delta.addedEntries + delta.removedEntries === 0) { - console.info("Metro cache: unchanged \u2014 skipping save."); - return; - } - const change = `+${delta.addedEntries} files / ${formatMegabytes(delta.addedBytes)} added, ${delta.removedEntries} removed`; - if (shouldSave) { - console.info( - `Metro cache: changed (${change}) \u2014 saving new entry with key "${saveKey}".` - ); - return; - } - const reason = policy.mode === "default-branch" ? 'policy "default-branch" (current branch is not the default branch)' : `policy "${policy.mode}"`; - console.info( - `Metro cache: changed (${change}) but save skipped by ${reason}.` - ); -}; -var run = async () => { - try { - const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput ? import_node_path12.default.resolve(projectRootInput) : process.cwd(); - console.info(`Planning Metro cache save for: ${projectRoot}`); - const { config, projectRoot: resolvedProjectRoot } = await getConfig( - projectRoot - ); - const githubOutput = process.env.GITHUB_OUTPUT; - if (!githubOutput) { - throw new Error("GITHUB_OUTPUT environment variable is not set"); - } - const staticInputs = resolveMetroStaticInputs({ - projectRoot: resolvedProjectRoot, - cacheVersionSalt: config.cache?.version - }); - const before = parseSnapshot(process.env.INPUT_METRO_SNAPSHOT); - const policy = { - mode: parseSavePolicyMode(process.env.INPUT_CACHESAVEPOLICY), - isDefaultBranch: process.env.IS_DEFAULT_BRANCH === "true" - }; - const cache = createHarnessCache({ projectRoot: resolvedProjectRoot }); - const os2 = process.env.RUNNER_OS ?? process.platform; - const savePlan = cache.planSave(before, policy, { - metro: { os: os2, staticInputs } - }); - cache.writeKeysFile(savePlan); - const metroPlan = savePlan.domains.metro; - logMetroSaveDecision(metroPlan, policy); - const output = `metroShouldSave=${metroPlan?.shouldSave ? "true" : "false"} -metroSaveKey=${metroPlan?.saveKey ?? ""} -`; - import_node_fs12.default.appendFileSync(githubOutput, output); - } catch (error) { - if (error instanceof Error) { - console.error(error.message); - } else { - console.error("Failed to plan Metro cache save"); - } - process.exit(1); - } -}; -run(); diff --git a/actions/shared/snapshot-metro.cjs b/actions/shared/snapshot-metro.cjs deleted file mode 100644 index c39358e8..00000000 --- a/actions/shared/snapshot-metro.cjs +++ /dev/null @@ -1,4916 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// ../../node_modules/picocolors/picocolors.js -var require_picocolors = __commonJS({ - "../../node_modules/picocolors/picocolors.js"(exports2, module2) { - "use strict"; - var p = process || {}; - var argv = p.argv || []; - var env = p.env || {}; - var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI); - var formatter = (open, close, replace = open) => (input) => { - let string = "" + input, index = string.indexOf(close, open.length); - return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; - }; - var replaceClose = (string, close, replace, index) => { - let result = "", cursor = 0; - do { - result += string.substring(cursor, index) + replace; - cursor = index + close.length; - index = string.indexOf(close, cursor); - } while (~index); - return result + string.substring(cursor); - }; - var createColors = (enabled = isColorSupported) => { - let f = enabled ? formatter : () => String; - return { - isColorSupported: enabled, - reset: f("\x1B[0m", "\x1B[0m"), - bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), - dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), - italic: f("\x1B[3m", "\x1B[23m"), - underline: f("\x1B[4m", "\x1B[24m"), - inverse: f("\x1B[7m", "\x1B[27m"), - hidden: f("\x1B[8m", "\x1B[28m"), - strikethrough: f("\x1B[9m", "\x1B[29m"), - black: f("\x1B[30m", "\x1B[39m"), - red: f("\x1B[31m", "\x1B[39m"), - green: f("\x1B[32m", "\x1B[39m"), - yellow: f("\x1B[33m", "\x1B[39m"), - blue: f("\x1B[34m", "\x1B[39m"), - magenta: f("\x1B[35m", "\x1B[39m"), - cyan: f("\x1B[36m", "\x1B[39m"), - white: f("\x1B[37m", "\x1B[39m"), - gray: f("\x1B[90m", "\x1B[39m"), - bgBlack: f("\x1B[40m", "\x1B[49m"), - bgRed: f("\x1B[41m", "\x1B[49m"), - bgGreen: f("\x1B[42m", "\x1B[49m"), - bgYellow: f("\x1B[43m", "\x1B[49m"), - bgBlue: f("\x1B[44m", "\x1B[49m"), - bgMagenta: f("\x1B[45m", "\x1B[49m"), - bgCyan: f("\x1B[46m", "\x1B[49m"), - bgWhite: f("\x1B[47m", "\x1B[49m"), - blackBright: f("\x1B[90m", "\x1B[39m"), - redBright: f("\x1B[91m", "\x1B[39m"), - greenBright: f("\x1B[92m", "\x1B[39m"), - yellowBright: f("\x1B[93m", "\x1B[39m"), - blueBright: f("\x1B[94m", "\x1B[39m"), - magentaBright: f("\x1B[95m", "\x1B[39m"), - cyanBright: f("\x1B[96m", "\x1B[39m"), - whiteBright: f("\x1B[97m", "\x1B[39m"), - bgBlackBright: f("\x1B[100m", "\x1B[49m"), - bgRedBright: f("\x1B[101m", "\x1B[49m"), - bgGreenBright: f("\x1B[102m", "\x1B[49m"), - bgYellowBright: f("\x1B[103m", "\x1B[49m"), - bgBlueBright: f("\x1B[104m", "\x1B[49m"), - bgMagentaBright: f("\x1B[105m", "\x1B[49m"), - bgCyanBright: f("\x1B[106m", "\x1B[49m"), - bgWhiteBright: f("\x1B[107m", "\x1B[49m") - }; - }; - module2.exports = createColors(); - module2.exports.createColors = createColors; - } -}); - -// ../../node_modules/sisteransi/src/index.js -var require_src = __commonJS({ - "../../node_modules/sisteransi/src/index.js"(exports2, module2) { - "use strict"; - var ESC = "\x1B"; - var CSI = `${ESC}[`; - var beep = "\x07"; - var cursor = { - to(x2, y) { - if (!y) return `${CSI}${x2 + 1}G`; - return `${CSI}${y + 1};${x2 + 1}H`; - }, - move(x2, y) { - let ret = ""; - if (x2 < 0) ret += `${CSI}${-x2}D`; - else if (x2 > 0) ret += `${CSI}${x2}C`; - if (y < 0) ret += `${CSI}${-y}A`; - else if (y > 0) ret += `${CSI}${y}B`; - return ret; - }, - up: (count = 1) => `${CSI}${count}A`, - down: (count = 1) => `${CSI}${count}B`, - forward: (count = 1) => `${CSI}${count}C`, - backward: (count = 1) => `${CSI}${count}D`, - nextLine: (count = 1) => `${CSI}E`.repeat(count), - prevLine: (count = 1) => `${CSI}F`.repeat(count), - left: `${CSI}G`, - hide: `${CSI}?25l`, - show: `${CSI}?25h`, - save: `${ESC}7`, - restore: `${ESC}8` - }; - var scroll = { - up: (count = 1) => `${CSI}S`.repeat(count), - down: (count = 1) => `${CSI}T`.repeat(count) - }; - var erase = { - screen: `${CSI}2J`, - up: (count = 1) => `${CSI}1J`.repeat(count), - down: (count = 1) => `${CSI}J`.repeat(count), - line: `${CSI}2K`, - lineEnd: `${CSI}K`, - lineStart: `${CSI}1K`, - lines(count) { - let clear = ""; - for (let i = 0; i < count; i++) - clear += this.line + (i < count - 1 ? cursor.up() : ""); - if (count) - clear += cursor.left; - return clear; - } - }; - module2.exports = { cursor, scroll, erase, beep }; - } -}); - -// src/shared/snapshot-metro.ts -var import_node_fs11 = __toESM(require("fs")); -var import_node_path11 = __toESM(require("path")); - -// ../cache/dist/index.js -var import_node_fs9 = __toESM(require("fs"), 1); - -// ../tools/dist/net.js -var import_node_net = __toESM(require("net"), 1); - -// ../tools/dist/logger.js -var import_node_util = __toESM(require("util"), 1); -var import_picocolors = __toESM(require_picocolors(), 1); -var verbose = !!process.env.HARNESS_DEBUG; -var BASE_TAG = "[harness]"; -var INFO_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.magenta(" HARNESS ")))) : "HARNESS"; -var ERROR_TAG = import_picocolors.default.isColorSupported ? import_picocolors.default.reset(import_picocolors.default.inverse(import_picocolors.default.bold(import_picocolors.default.red(" HARNESS ")))) : "HARNESS"; -var getTimestamp = () => (/* @__PURE__ */ new Date()).toISOString(); -var normalizeScope = (scope) => scope.trim().replace(/^\[+|\]+$/g, "").replace(/\]\[/g, "]["); -var formatPrefix = (scopes) => { - const suffix = scopes.map((scope) => `[${normalizeScope(scope)}]`).join(""); - return `${BASE_TAG}${suffix}`; -}; -var mapLines = (text, prefix) => text.split("\n").map((line) => `${prefix} ${line}`).join("\n"); -var writeLog = (level, scopes, messages) => { - if (!verbose && (level === "info" || level === "log" || level === "success")) { - const output2 = import_node_util.default.format(...messages); - const tag = INFO_TAG; - process.stderr.write(`${tag} ${output2} -`); - return; - } - if (!verbose && level === "error") { - const output2 = import_node_util.default.format(...messages); - process.stderr.write(`${ERROR_TAG} ${output2} -`); - return; - } - const method = level === "warn" ? console.warn : console.debug; - const output = import_node_util.default.format(...messages); - const prefix = `${getTimestamp()} ${formatPrefix(scopes)}`; - method(mapLines(output, prefix)); -}; -var setVerbose = (level) => { - verbose = level; -}; -var isVerbose = () => { - return verbose; -}; -var createScopedLogger = (scopes = []) => ({ - debug: (...messages) => { - if (!verbose) { - return; - } - writeLog("debug", scopes, messages); - }, - info: (...messages) => { - writeLog("info", scopes, messages); - }, - warn: (...messages) => { - writeLog("warn", scopes, messages); - }, - error: (...messages) => { - writeLog("error", scopes, messages); - }, - log: (...messages) => { - writeLog("log", scopes, messages); - }, - success: (...messages) => { - writeLog("success", scopes, messages); - }, - child: (scope) => createScopedLogger([...scopes, scope]), - setVerbose, - isVerbose -}); -var logger = createScopedLogger(); - -// ../../node_modules/@clack/core/dist/index.mjs -var import_node_process = require("process"); -var k = __toESM(require("readline"), 1); -var import_node_readline = __toESM(require("readline"), 1); -var import_sisteransi = __toESM(require_src(), 1); -var import_node_tty = require("tty"); -var Ft = { limit: 1 / 0, ellipsis: "" }; -var ft = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var j = "\x07"; -var Q = "["; -var dt = "]"; -var U = `${dt}8;;`; -var et = new RegExp(`(?:\\${Q}(?\\d+)m|\\${U}(?.*)${j})`, "y"); -var At = ["up", "down", "left", "right", "space", "enter", "cancel"]; -var _ = { actions: new Set(At), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true }; -var bt = globalThis.process.platform.startsWith("win"); - -// ../../node_modules/@clack/prompts/dist/index.mjs -var import_picocolors2 = __toESM(require_picocolors(), 1); -var import_node_process2 = __toESM(require("process"), 1); -var import_node_fs = require("fs"); -var import_node_path = require("path"); -var import_sisteransi2 = __toESM(require_src(), 1); -var import_node_util2 = require("util"); -function ht() { - return import_node_process2.default.platform !== "win32" ? import_node_process2.default.env.TERM !== "linux" : !!import_node_process2.default.env.CI || !!import_node_process2.default.env.WT_SESSION || !!import_node_process2.default.env.TERMINUS_SUBLIME || import_node_process2.default.env.ConEmuTask === "{cmd::Cmder}" || import_node_process2.default.env.TERM_PROGRAM === "Terminus-Sublime" || import_node_process2.default.env.TERM_PROGRAM === "vscode" || import_node_process2.default.env.TERM === "xterm-256color" || import_node_process2.default.env.TERM === "alacritty" || import_node_process2.default.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; -} -var ee = ht(); -var w = (e, r) => ee ? e : r; -var Me = w("\u25C6", "*"); -var ce = w("\u25A0", "x"); -var de = w("\u25B2", "x"); -var V = w("\u25C7", "o"); -var $e = w("\u250C", "T"); -var h = w("\u2502", "|"); -var x = w("\u2514", "\u2014"); -var Re = w("\u2510", "T"); -var Oe = w("\u2518", "\u2014"); -var Y = w("\u25CF", ">"); -var K = w("\u25CB", " "); -var te = w("\u25FB", "[\u2022]"); -var k2 = w("\u25FC", "[+]"); -var z = w("\u25FB", "[ ]"); -var Pe = w("\u25AA", "\u2022"); -var se = w("\u2500", "-"); -var he = w("\u256E", "+"); -var Ne = w("\u251C", "+"); -var me = w("\u256F", "+"); -var pe = w("\u2570", "+"); -var We = w("\u256D", "+"); -var ge = w("\u25CF", "\u2022"); -var fe = w("\u25C6", "*"); -var Fe = w("\u25B2", "!"); -var ye = w("\u25A0", "x"); -var Ft2 = { limit: 1 / 0, ellipsis: "" }; -var yt2 = { limit: 1 / 0, ellipsis: "", ellipsisWidth: 0 }; -var Ce = "\x07"; -var Ve = "["; -var vt = "]"; -var we = `${vt}8;;`; -var Ge = new RegExp(`(?:\\${Ve}(?\\d+)m|\\${we}(?.*)${Ce})`, "y"); -var Ut = import_picocolors2.default.magenta; -var Ye = { light: w("\u2500", "-"), heavy: w("\u2501", "="), block: w("\u2588", "#") }; -var ze = `${import_picocolors2.default.gray(h)} `; - -// ../tools/dist/spawn.js -var spawnLogger = logger.child("spawn"); - -// ../tools/dist/react-native.js -var import_node_module = require("module"); -var import_node_path2 = __toESM(require("path"), 1); -var import_node_fs2 = __toESM(require("fs"), 1); - -// ../tools/dist/error.js -var HarnessError = class extends Error { -}; - -// ../tools/dist/packages.js -var import_node_path3 = __toESM(require("path"), 1); -var import_node_fs3 = __toESM(require("fs"), 1); - -// ../tools/dist/path.js -var import_node_path4 = __toESM(require("path"), 1); - -// ../tools/dist/crash-artifacts.js -var import_node_fs4 = __toESM(require("fs"), 1); -var import_node_path5 = __toESM(require("path"), 1); -var DEFAULT_ARTIFACT_ROOT = import_node_path5.default.join(process.cwd(), ".harness", "crash-reports"); - -// ../tools/dist/harness-artifacts.js -var import_node_fs5 = __toESM(require("fs"), 1); -var import_node_path6 = __toESM(require("path"), 1); - -// ../tools/dist/diagnostics.js -var noop = () => void 0; -var noopSpan = { - end: noop, - fail: noop -}; -var createNoopDiagnostics = () => { - const diagnostics = { - enabled: false, - start: () => noopSpan, - measure: async (_label, fn) => fn(), - mark: noop, - record: noop, - child: () => diagnostics, - flush: () => [] - }; - return diagnostics; -}; -var noopDiagnostics = createNoopDiagnostics(); - -// ../tools/dist/host-capabilities.js -var import_node_os = __toESM(require("os"), 1); - -// ../cache/dist/paths.js -var import_node_path7 = __toESM(require("path"), 1); -var HARNESS_DIRNAME = ".harness"; -var CACHE_DIRNAME = "cache"; -var METRO_TRANSFORM_DIRNAME = "metro"; -var METRO_FILE_MAP_DIRNAME = "metro-file-map"; -var createHarnessCachePaths = (projectRoot) => { - const root = import_node_path7.default.join(projectRoot, HARNESS_DIRNAME, CACHE_DIRNAME); - return { - root, - metroTransform: import_node_path7.default.join(root, METRO_TRANSFORM_DIRNAME), - metroFileMap: import_node_path7.default.join(root, METRO_FILE_MAP_DIRNAME) - }; -}; -var getDomainDirectories = (domain, paths) => { - switch (domain) { - case "metro": - return [paths.metroTransform, paths.metroFileMap]; - default: - return []; - } -}; - -// ../cache/dist/plan.js -var import_node_crypto = require("crypto"); -var import_node_fs6 = __toESM(require("fs"), 1); -var import_node_path8 = __toESM(require("path"), 1); -var cacheLogger = logger.child("cache"); -var KEYS_FILENAME = "keys.json"; -var HASH_LENGTH = 16; -var ALL_DOMAINS = ["metro"]; -var isAccretiveDomain = (domain) => { - switch (domain) { - case "metro": - return true; - default: - return false; - } -}; -var hashSortedEntries = (entries) => (0, import_node_crypto.createHash)("sha256").update(entries.slice().sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => `${key}=${value}`).join("\n")).digest("hex").slice(0, HASH_LENGTH); -var buildStaticHashKey = (domain, inputs) => { - const hash = hashSortedEntries(Object.entries(inputs.staticInputs)); - return `harness-${domain}-${inputs.os}-${hash}`; -}; -var buildContentHash = (entries) => hashSortedEntries(entries.map((entry) => [entry.path, String(entry.sizeBytes)])); -var walkDirectory = (root, directory, entries) => { - let dirents; - try { - dirents = import_node_fs6.default.readdirSync(directory, { withFileTypes: true }); - } catch { - return; - } - for (const dirent of dirents) { - const fullPath = import_node_path8.default.join(directory, dirent.name); - if (dirent.isDirectory()) { - walkDirectory(root, fullPath, entries); - } else if (dirent.isFile()) { - const stat = import_node_fs6.default.statSync(fullPath); - entries.push({ - path: import_node_path8.default.relative(root, fullPath), - sizeBytes: stat.size, - mtimeMs: stat.mtimeMs - }); - } - } -}; -var planRestore = (paths, inputs) => { - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const restoreKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - paths: [...getDomainDirectories(domain, paths)], - restoreKey, - restorePrefixes: accretive ? [`${restoreKey}-`] : [], - accretive - }; - } - return { version: 1, domains }; -}; -var snapshot = (paths) => { - const result = {}; - for (const domain of ALL_DOMAINS) { - try { - const entries = []; - for (const directory of getDomainDirectories(domain, paths)) { - walkDirectory(paths.root, directory, entries); - } - result[domain] = entries; - } catch (error) { - cacheLogger.warn(`Failed to snapshot cache domain "${domain}". Treating as empty.`, error); - result[domain] = []; - } - } - return result; -}; -var diffSnapshots = (before, after) => { - const beforeByPath = new Map(before.map((entry) => [entry.path, entry])); - const afterByPath = new Map(after.map((entry) => [entry.path, entry])); - let addedEntries = 0; - let removedEntries = 0; - let addedBytes = 0; - for (const [entryPath, afterEntry] of afterByPath) { - const beforeEntry = beforeByPath.get(entryPath); - if (!beforeEntry || beforeEntry.sizeBytes !== afterEntry.sizeBytes) { - addedEntries += 1; - addedBytes += afterEntry.sizeBytes; - } - } - for (const entryPath of beforeByPath.keys()) { - if (!afterByPath.has(entryPath)) { - removedEntries += 1; - } - } - return { addedEntries, removedEntries, addedBytes }; -}; -var shouldSaveForPolicy = (policy, delta) => { - if (delta.addedEntries + delta.removedEntries === 0) { - return false; - } - switch (policy.mode) { - case "always": - return true; - case "default-branch": - return policy.isDefaultBranch; - case "never": - return false; - } -}; -var planSave = (paths, before, policy, inputs) => { - const after = snapshot(paths); - const domains = {}; - for (const domain of ALL_DOMAINS) { - const domainInputs = inputs[domain]; - if (!domainInputs) { - continue; - } - const beforeEntries = before[domain] ?? []; - const afterEntries = after[domain] ?? []; - const delta = diffSnapshots(beforeEntries, afterEntries); - const staticHashKey = buildStaticHashKey(domain, domainInputs); - const accretive = isAccretiveDomain(domain); - domains[domain] = { - shouldSave: shouldSaveForPolicy(policy, delta), - saveKey: accretive ? `${staticHashKey}-${buildContentHash(afterEntries)}` : staticHashKey, - delta - }; - } - return { version: 1, domains }; -}; -var writeKeysFile = (paths, plan) => { - const filePath = import_node_path8.default.join(paths.root, KEYS_FILENAME); - try { - import_node_fs6.default.mkdirSync(paths.root, { recursive: true }); - import_node_fs6.default.writeFileSync(filePath, JSON.stringify(plan, null, 2)); - } catch (error) { - cacheLogger.warn(`Failed to write cache keys file "${filePath}".`, error); - } -}; - -// ../cache/dist/warmth.js -var import_node_fs7 = __toESM(require("fs"), 1); -var cacheLogger2 = logger.child("cache"); -var isDomainWarm = (domain, paths) => { - const directory = getWarmthDirectory(domain, paths); - if (!directory) { - return false; - } - try { - const stat = import_node_fs7.default.statSync(directory); - if (!stat.isDirectory()) { - return false; - } - return import_node_fs7.default.readdirSync(directory).length > 0; - } catch (error) { - if (isMissingPathError(error)) { - return false; - } - cacheLogger2.warn(`Failed to check cache warmth for "${domain}" at "${directory}". Treating as cold.`, error); - return false; - } -}; -var getWarmthDirectory = (domain, paths) => { - switch (domain) { - case "metro": - return paths.metroTransform; - default: - return void 0; - } -}; -var isMissingPathError = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; - -// ../cache/dist/domains/metro.js -var import_node_crypto2 = require("crypto"); -var import_node_fs8 = __toESM(require("fs"), 1); -var import_node_path9 = __toESM(require("path"), 1); -var cacheLogger3 = logger.child("cache"); -var LOCKFILE_NAMES = [ - "bun.lock", - "bun.lockb", - "package-lock.json", - "npm-shrinkwrap.json", - "pnpm-lock.yaml", - "yarn.lock" -]; -var METRO_CONFIG_EXTENSIONS = [ - "js", - "cjs", - "mjs", - "ts", - "cts", - "mts", - "json" -]; -var METRO_CONFIG_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `metro.config.${extension}`); -var METRO_CONFIG_DIR_NAMES = METRO_CONFIG_EXTENSIONS.map((extension) => `.config/metro.${extension}`); -var BABEL_CONFIG_NAMES = [ - "babel.config.json", - "babel.config.js", - "babel.config.cjs", - "babel.config.mjs", - "babel.config.cts" -]; -var METRO_KEY_FILENAMES = [ - ...LOCKFILE_NAMES, - ...METRO_CONFIG_NAMES, - ...METRO_CONFIG_DIR_NAMES, - ...BABEL_CONFIG_NAMES -]; - -// ../cache/dist/index.js -var cacheLogger4 = logger.child("cache"); -var createHarnessCache = (options) => { - const paths = createHarnessCachePaths(options.projectRoot); - return { - paths, - isWarm: (domain) => isDomainWarm(domain, paths), - ensureDomainDirectories: (domain) => { - for (const directory of getDomainDirectories(domain, paths)) { - try { - import_node_fs9.default.mkdirSync(directory, { recursive: true }); - } catch (error) { - cacheLogger4.warn(`Failed to create cache directory "${directory}". Continuing with a cold cache.`, error); - } - } - }, - planRestore: (inputs) => planRestore(paths, inputs), - snapshot: () => snapshot(paths), - planSave: (before, policy, inputs) => planSave(paths, before, policy, inputs), - writeKeysFile: (plan) => writeKeysFile(paths, plan) - }; -}; - -// ../../node_modules/zod/dist/esm/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util2, - void: () => voidType -}); - -// ../../node_modules/zod/dist/esm/v3/helpers/util.js -var util2; -(function(util3) { - util3.assertEqual = (_2) => { - }; - function assertIs(_arg) { - } - util3.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util3.assertNever = assertNever; - util3.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util3.getValidEnumValues = (obj) => { - const validKeys = util3.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number"); - const filtered = {}; - for (const k3 of validKeys) { - filtered[k3] = obj[k3]; - } - return util3.objectValues(filtered); - }; - util3.objectValues = (obj) => { - return util3.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util3.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util3.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util3.joinValues = joinValues; - util3.jsonStringifyReplacer = (_2, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util2 || (util2 = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t2 = typeof data; - switch (t2) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// ../../node_modules/zod/dist/esm/v3/ZodError.js -var ZodIssueCode = util2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -// ../../node_modules/zod/dist/esm/v3/locales/en.js -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util2.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util2.assertNever(issue); - } - return { message }; -}; -var en_default = errorMap; - -// ../../node_modules/zod/dist/esm/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -// ../../node_modules/zod/dist/esm/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data, path: path11, errorMaps, issueData } = params; - const fullPath = [...path11, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x2) => !!x2) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x2) => x2.status === "aborted"; -var isDirty = (x2) => x2.status === "dirty"; -var isValid = (x2) => x2.status === "valid"; -var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; - -// ../../node_modules/zod/dist/esm/v3/helpers/errorUtil.js -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -// ../../node_modules/zod/dist/esm/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path11, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path11; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new _ZodObject({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util2.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util2.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util2.objectKeys(b); - const sharedKeys = util2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x2) => !!x2); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me2 = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me2._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me2 = this; - return OK(function(...args) { - const parsedArgs = me2._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me2._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util2.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = /* @__PURE__ */ Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })) -}; -var NEVER = INVALID; - -// ../plugins/dist/utils.js -var isHookTree = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - for (const child of Object.values(value)) { - if (child === void 0) { - continue; - } - if (typeof child === "function") { - continue; - } - if (child == null || typeof child !== "object" || Array.isArray(child) || !isHookTree(child)) { - return false; - } - } - return true; -}; - -// ../plugins/dist/plugin.js -var isHarnessPlugin = (value) => { - if (value == null || typeof value !== "object" || Array.isArray(value)) { - return false; - } - const candidate = value; - if (typeof candidate.name !== "string" || candidate.name.length === 0) { - return false; - } - if (candidate.createState != null && typeof candidate.createState !== "function") { - return false; - } - if (candidate.hooks != null && !isHookTree(candidate.hooks)) { - return false; - } - return true; -}; - -// ../plugins/dist/manager.js -var pluginsLogger = logger.child("plugins"); - -// ../config/dist/types.js -var DEFAULT_METRO_PORT = 8081; -var configLogger = logger.child("config"); -var RunnerSchema = external_exports.object({ - name: external_exports.string().min(1, "Runner name is required").regex(/^[a-zA-Z0-9._-]+$/, "Runner name can only contain alphanumeric characters, dots, underscores, and hyphens"), - config: external_exports.record(external_exports.any()), - runner: external_exports.string(), - cli: external_exports.string().optional(), - platformId: external_exports.string() -}); -var PluginSchema = external_exports.custom((value) => isHarnessPlugin(value), "Invalid Harness plugin"); -var ConfigSchema = external_exports.object({ - entryPoint: external_exports.string().min(1, "Entry point is required"), - appRegistryComponentName: external_exports.string().min(1, "App registry component name is required"), - runners: external_exports.array(RunnerSchema).min(1, "At least one runner is required"), - plugins: external_exports.array(PluginSchema).optional().default([]), - defaultRunner: external_exports.string().optional(), - host: external_exports.string().min(1, "Host is required").optional(), - metroPort: external_exports.number().int("Metro port must be an integer").min(1, "Metro port must be at least 1").max(65535, "Metro port must be at most 65535").optional().default(DEFAULT_METRO_PORT), - webSocketPort: external_exports.number().optional().describe("Deprecated. Bridge traffic now uses metroPort and this value is ignored."), - bridgeTimeout: external_exports.number().min(1e3, "Bridge timeout must be at least 1 second").default(6e4), - testTimeout: external_exports.number().min(1e3, "Test timeout must be at least 1 second").default(5e3), - platformReadyTimeout: external_exports.number().min(1e3, "Platform ready timeout must be at least 1 second").default(3e5), - bundleStartTimeout: external_exports.number().min(1e3, "Bundle start timeout must be at least 1 second").default(6e4), - maxAppRestarts: external_exports.number().min(0, "Max app restarts must be at least 0").default(2), - eagerPrewarm: external_exports.boolean().optional().default(true).describe("Start building the Metro bundle while the platform (emulator, simulator, or browser) is still booting, so the first bundle is ready sooner. Disable to defer the first bundle build until app startup."), - resetEnvironmentBetweenTestFiles: external_exports.union([external_exports.boolean(), external_exports.enum(["process", "runtime"])]).optional().default(true).describe("Controls how the environment is reset between test files. `true` (default) and `'process'` kill and cold-restart the app process. `'runtime'` reloads the JS runtime in place (DevSettings.reload() / window.location.reload()), which is cheaper but escalates to a process restart if the reload fails or the app does not reconnect in time. `false` disables resetting the environment between test files entirely."), - skipAlreadyIncludedModules: external_exports.boolean().optional().describe('Skip re-sending modules already served in the main app bundle when Metro serves a per-test-file bundle. Defaults to true; set to false as an escape hatch if it causes issues. Left undefined (rather than defaulted here) so `resolveSkipAlreadyIncludedModules` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__skipAlreadyIncludedModules` alias.'), - // Deprecated alias for `skipAlreadyIncludedModules` -- see - // `resolveSkipAlreadyIncludedModules`. Left without a `.default()` for the - // same reason: a default value would be indistinguishable from the user - // never having set it, which would break alias-vs-explicit-flag precedence. - unstable__skipAlreadyIncludedModules: external_exports.boolean().optional().describe("Deprecated. Use `skipAlreadyIncludedModules` instead."), - cache: external_exports.object({ - metro: external_exports.boolean().optional().describe('Enable persistent Metro transform and file-map caching under the .harness cache directory. Defaults to true; set to false to always start with a cold Metro cache. Left undefined (rather than defaulted here) so `resolveMetroCacheEnabled` can tell "not set" apart from "explicitly set" when reconciling with the deprecated `unstable__enableMetroCache` alias.'), - version: external_exports.string().optional().describe("User-controlled salt folded into the Metro cacheVersion. Bump it to force-invalidate previously cached transforms.") - }).optional(), - // Deprecated alias for `cache.metro` -- see `resolveMetroCacheEnabled`. - // Left without a `.default()` for the same reason as - // `unstable__skipAlreadyIncludedModules`: a default value would be - // indistinguishable from the user never having set it, which would break - // alias-vs-explicit-flag precedence. - unstable__enableMetroCache: external_exports.boolean().optional().describe("Deprecated. Use `cache.metro` instead."), - permissions: external_exports.boolean().optional().default(false).describe("Enable platform-specific permission prompt automation. When false, Harness does not start permission-handling helpers such as the iOS XCTest agent."), - detectNativeCrashes: external_exports.boolean().optional().default(true), - crashDetectionInterval: external_exports.number().min(100, "Crash detection interval must be at least 100ms").default(500), - disableViewFlattening: external_exports.boolean().optional().default(false).describe("Disable view flattening in React Native. This will set collapsable={true} for all View components to ensure they are not flattened by the native layout engine."), - coverage: external_exports.object({ - root: external_exports.string().optional().describe(`Root directory for coverage instrumentation in monorepo setups. Specifies the directory from which coverage data should be collected. Use ".." for create-react-native-library projects where tests run from example/ but source files are in parent directory. Passed to babel-plugin-istanbul's cwd option.`), - native: external_exports.object({ - ios: external_exports.object({ - pods: external_exports.array(external_exports.string()).min(1, "At least one pod name is required").describe("Pod names to instrument for native code coverage. Coverage flags are injected at pod install time via a CocoaPods hook. After tests, profraw data is collected and converted to lcov format.") - }).optional() - }).optional().describe("Native code coverage configuration.") - }).optional(), - forwardClientLogs: external_exports.boolean().optional().default(false).describe("Enable forwarding of console.log, console.warn, console.error, and other console method calls from the React Native app during the active test run. When enabled, app console output is attached to the active test result's console output."), - diagnostics: external_exports.boolean().optional().default(false).describe("Enable diagnostics tracing for the harness session. Records spans for session setup, Metro bundling, bridge/client events, and per-file test runs, then writes a Chrome Trace Event JSON file and prints a summary after each run. Can also be enabled via the RN_HARNESS_DIAGNOSTICS environment variable."), - // Deprecated property - used for migration detection - include: external_exports.array(external_exports.string()).optional() -}).refine((config) => { - if (config.defaultRunner) { - return config.runners.some((runner) => runner.name === config.defaultRunner); - } - return true; -}, { - message: "Default runner must match one of the configured runner names", - path: ["defaultRunner"] -}); - -// ../config/dist/errors.js -var ConfigValidationError = class extends HarnessError { - filePath; - validationErrors; - constructor(filePath, validationErrors) { - const lines = [ - `Configuration validation failed in ${filePath}`, - "", - "The following issues were found:", - "" - ]; - validationErrors.forEach((error, index) => { - lines.push(` ${index + 1}. ${error}`); - }); - lines.push("", "Please fix these issues and try again.", "For more information, visit: https://react-native-harness.dev/docs/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.validationErrors = validationErrors; - this.name = "ConfigValidationError"; - } -}; -var ConfigNotFoundError = class extends HarnessError { - searchPath; - constructor(searchPath) { - const lines = [ - "Configuration file not found", - "", - `Searched for configuration files in: ${searchPath}`, - "and all parent directories.", - "", - "React Native Harness looks for one of these files:", - " \u2022 rn-harness.config.js", - " \u2022 rn-harness.config.mjs", - " \u2022 rn-harness.config.cjs", - " \u2022 rn-harness.config.json", - "", - "For more information, visit: https://www.react-native-harness.dev/docs/getting-started/configuration" - ]; - super(lines.join("\n")); - this.searchPath = searchPath; - this.name = "ConfigNotFoundError"; - } -}; -var ConfigLoadError = class extends HarnessError { - filePath; - cause; - constructor(filePath, cause) { - const lines = [ - "Failed to load configuration file", - "", - `File: ${filePath}`, - "" - ]; - if (cause) { - lines.push("Error details:"); - lines.push(` ${cause.message}`); - lines.push(""); - } - lines.push("This could be due to:", " \u2022 Syntax errors in your configuration file", " \u2022 Missing dependencies or modules", " \u2022 Invalid file format or encoding", " \u2022 File permissions issues", "", "Troubleshooting steps:", " 1. Check the file syntax and format", " 2. Ensure all required dependencies are installed", " 3. Verify file permissions", " 4. Try creating a new configuration file", "", "For more help, visit: https://www.react-native-harness.dev/docs/getting-started/configuration"); - super(lines.join("\n")); - this.filePath = filePath; - this.name = "ConfigLoadError"; - this.cause = cause; - } -}; - -// ../config/dist/reader.js -var import_node_path10 = __toESM(require("path"), 1); -var import_node_fs10 = __toESM(require("fs"), 1); -var import_node_module2 = require("module"); -var import_meta = {}; -var extensions = [".js", ".mjs", ".cjs", ".json"]; -var importUp = async (dir, name) => { - const filePath = import_node_path10.default.join(dir, name); - for (const ext of extensions) { - const filePathWithExt = `${filePath}${ext}`; - if (import_node_fs10.default.existsSync(filePathWithExt)) { - let rawConfig; - try { - if (ext === ".mjs") { - rawConfig = await import(filePathWithExt).then((module2) => module2.default); - } else { - const require2 = (0, import_node_module2.createRequire)(import_meta.url); - rawConfig = require2(filePathWithExt); - } - } catch (error) { - throw new ConfigLoadError(filePathWithExt, error instanceof Error ? error : void 0); - } - try { - const config = ConfigSchema.parse(rawConfig); - return { config, filePathWithExt, configDir: dir }; - } catch (error) { - if (error instanceof ZodError) { - const validationErrors = error.errors.map((err) => { - const path11 = err.path.length > 0 ? ` at "${err.path.join(".")}"` : ""; - return `${err.message}${path11}`; - }); - throw new ConfigValidationError(filePathWithExt, validationErrors); - } - throw error; - } - } - } - const parentDir = import_node_path10.default.dirname(dir); - if (parentDir === dir) { - throw new ConfigNotFoundError(dir); - } - return importUp(parentDir, name); -}; -var getConfig = async (dir) => { - const { config, configDir } = await importUp(dir, "rn-harness.config"); - return { - config, - projectRoot: configDir - }; -}; - -// src/shared/format-bytes.ts -var formatMegabytes = (bytes) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`; - -// src/shared/snapshot-metro.ts -var run = async () => { - try { - const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput ? import_node_path11.default.resolve(projectRootInput) : process.cwd(); - console.info(`Snapshotting Metro cache for: ${projectRoot}`); - const { projectRoot: resolvedProjectRoot } = await getConfig(projectRoot); - const githubOutput = process.env.GITHUB_OUTPUT; - if (!githubOutput) { - throw new Error("GITHUB_OUTPUT environment variable is not set"); - } - const cache = createHarnessCache({ projectRoot: resolvedProjectRoot }); - const snapshotAfterRestore = cache.snapshot(); - const restoredKey = process.env.METRO_RESTORED_KEY; - if (restoredKey) { - const metroEntries = snapshotAfterRestore.metro ?? []; - const totalBytes = metroEntries.reduce( - (sum, entry) => sum + entry.sizeBytes, - 0 - ); - console.info( - `Metro cache: restored from key "${restoredKey}" (${metroEntries.length} files, ${formatMegabytes(totalBytes)}).` - ); - } else { - console.info( - "Metro cache: no existing cache entry matched \u2014 starting cold." - ); - } - const output = `metroSnapshot=${JSON.stringify(snapshotAfterRestore)} -`; - import_node_fs11.default.appendFileSync(githubOutput, output); - } catch (error) { - if (error instanceof Error) { - console.error(error.message); - } else { - console.error("Failed to snapshot the Metro cache"); - } - process.exit(1); - } -}; -run(); diff --git a/actions/web/action.yml b/actions/web/action.yml deleted file mode 100644 index ff593a4f..00000000 --- a/actions/web/action.yml +++ /dev/null @@ -1,131 +0,0 @@ -name: React Native Harness for Web -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on Web' -inputs: - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Install Playwright Browsers - shell: bash - run: npx playwright install --with-deps chromium - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - if [ -n "$PRE_RUN_HOOK" ]; then - pre_hook_file="$(mktemp "${RUNNER_TEMP:-/tmp}/harness-pre-run.XXXXXX.sh")" - trap 'rm -f "$pre_hook_file"' EXIT - printf '%s\n' "$PRE_RUN_HOOK" > "$pre_hook_file" - chmod +x "$pre_hook_file" - bash "$pre_hook_file" - rm -f "$pre_hook_file" - trap - EXIT - fi - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - export HARNESS_EXIT_CODE="$harness_exit_code" - after_run_exit_code=0 - if [ -n "$AFTER_RUN_HOOK" ]; then - after_hook_file="$(mktemp "${RUNNER_TEMP:-/tmp}/harness-after-run.XXXXXX.sh")" - trap 'rm -f "$after_hook_file"' EXIT - printf '%s\n' "$AFTER_RUN_HOOK" > "$after_hook_file" - chmod +x "$after_hook_file" - set +e - bash "$after_hook_file" - after_run_exit_code=$? - set -e - rm -f "$after_hook_file" - trap - EXIT - fi - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - if [ "$after_run_exit_code" -ne 0 ]; then - exit "$after_run_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-chromium - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-web - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/actions/web/index.cjs b/actions/web/index.cjs deleted file mode 100644 index 3918c74e..00000000 --- a/actions/web/index.cjs +++ /dev/null @@ -1 +0,0 @@ -"use strict"; diff --git a/packages/github-action/README.md b/docs/github-action.md similarity index 73% rename from packages/github-action/README.md rename to docs/github-action.md index 8c4ff783..b0dd956b 100644 --- a/packages/github-action/README.md +++ b/docs/github-action.md @@ -1,16 +1,12 @@ -![harness-banner](https://react-native-harness.dev/harness-banner.jpg) +# GitHub Action for React Native Harness -### GitHub Action for React Native Harness +GitHub Action that simplifies running React Native Harness tests in CI/CD environments. It lives at the repository root (`action.yml`) and handles the setup of emulators, simulators, browsers, and test execution automatically based on the selected Harness runner. -[![mit licence][license-badge]][license] -[![Chat][chat-badge]][chat] -[![PRs Welcome][prs-welcome-badge]][prs-welcome] - -GitHub Action that simplifies running React Native Harness tests in CI/CD environments. It lives at the repository root and handles the setup of emulators, simulators, browsers, and test execution automatically based on the selected Harness runner. +For a narrative walkthrough with a complete example workflow, see the [CI/CD guide](https://react-native-harness.dev/docs/guides/ci-cd) on the docs site. This page is the action's own reference documentation. ## Action -Pin the action ref to the **same release as the `react-native-harness` package** in your project’s `package.json` (for example `1.0.0` in dependencies → `@v1.0.0` on the action). The action and npm releases are cut from the same repo; keeping versions aligned avoids drift between what `pnpm install` / `npm ci` resolves and what the workflow runs. +Pin the action ref to the **same release as the `react-native-harness` package** in your project's `package.json` (for example `1.0.0` in dependencies → `@v1.0.0` on the action). The action and npm releases are cut from the same repo; keeping versions aligned avoids drift between what `pnpm install` / `npm ci` resolves and what the workflow runs. Use a [release tag](https://github.com/callstackincubator/react-native-harness/releases) for normal CI, or `@main` only if you intentionally track the default branch. @@ -21,6 +17,10 @@ Use a [release tag](https://github.com/callstackincubator/react-native-harness/r The action reads your `rn-harness.config.mjs` file, resolves the `runner` you pass in, and uses that runner's `platformId` to decide which platform-specific setup to execute. +### Version coupling + +Starting with this release, the action invokes your project's own installed `react-native-harness` CLI (via `harness ci `) instead of shipping its own bundled scripts. This means action `@vX` requires `react-native-harness >= X` to be installed in the project the workflow runs against. The action verifies this itself as one of its first steps and fails with a clear error (rather than silently misbehaving) when the installed CLI is missing or too old. + ## Inputs - `runner` (required): The runner name from your Harness configuration @@ -110,17 +110,3 @@ Runner configuration requirements: The action is designed to work with your existing React Native Harness configuration. It automatically reads `rn-harness.config.mjs` to determine device and platform settings, so you don't need to hardcode emulator or simulator configuration in workflow files. For complete workflow examples, see the [CI/CD documentation](https://react-native-harness.dev/docs/guides/ci-cd). - -## Made with ❤️ at Callstack - -`@react-native-harness/github-action` is an open source project and will always remain free to use. If you think it's cool, please star it 🌟. [Callstack][callstack-readme-with-love] is a group of React and React Native geeks, contact us at [hello@callstack.com](mailto:hello@callstack.com) if you need any help with these or just want to say hi! - -Like the project? ⚛️ [Join the team](https://callstack.com/careers/?utm_campaign=Senior_RN&utm_source=github&utm_medium=readme) who does amazing stuff for clients and drives React Native Open Source! 🔥 - -[callstack-readme-with-love]: https://callstack.com/?utm_source=github.com&utm_medium=referral&utm_campaign=react-native-harness&utm_term=readme-with-love -[license-badge]: https://img.shields.io/npm/l/@react-native-harness/github-action?style=for-the-badge -[license]: https://github.com/callstackincubator/react-native-harness/blob/main/LICENSE -[prs-welcome-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=for-the-badge -[prs-welcome]: ../../CONTRIBUTING.md -[chat-badge]: https://img.shields.io/discord/426714625279524876.svg?style=for-the-badge -[chat]: https://discord.gg/xgGt7KAjxv diff --git a/packages/cli/eslint.config.mjs b/packages/cli/eslint.config.mjs index 5765a779..ec768514 100644 --- a/packages/cli/eslint.config.mjs +++ b/packages/cli/eslint.config.mjs @@ -9,7 +9,22 @@ export default [ 'error', { ignoredFiles: ['{projectRoot}/eslint.config.{js,cjs,mjs,ts,cts,mts}'], - ignoredDependencies: ['@react-native-harness/bridge', '@react-native-harness/platform-android', '@react-native-harness/platform-apple', '@react-native-harness/platform-web', 'vitest'], + ignoredDependencies: [ + '@react-native-harness/bridge', + '@react-native-harness/platform-android', + '@react-native-harness/platform-apple', + '@react-native-harness/platform-web', + 'vite', + 'vitest', + // Referenced only as a require.resolve() target to read the + // consuming project's own installed version at runtime, not + // imported/bundled by this package. + '@react-native-harness/bundler-metro', + // Referenced only as a require.resolve() fallback root to reach + // bundler-metro when it's nested under jest's own node_modules, + // not imported/bundled by this package. + '@react-native-harness/jest', + ], }, ], }, diff --git a/packages/cli/package.json b/packages/cli/package.json index bca6a108..7312c420 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -22,6 +22,7 @@ }, "dependencies": { "@react-native-harness/bridge": "workspace:*", + "@react-native-harness/cache": "workspace:*", "@react-native-harness/config": "workspace:*", "@react-native-harness/platforms": "workspace:*", "@react-native-harness/tools": "workspace:*", diff --git a/packages/cli/src/ci/__tests__/load-config.test.ts b/packages/cli/src/ci/__tests__/load-config.test.ts new file mode 100644 index 00000000..15bee006 --- /dev/null +++ b/packages/cli/src/ci/__tests__/load-config.test.ts @@ -0,0 +1,113 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + getConfig: vi.fn(), +})); + +vi.mock('@react-native-harness/config', () => ({ + getConfig: mocks.getConfig, +})); + +describe('load-config', () => { + let workspaceRoot: string; + let githubOutputPath: string; + + beforeEach(() => { + vi.resetModules(); + vi.clearAllMocks(); + + workspaceRoot = fs.mkdtempSync( + path.join(os.tmpdir(), 'gha-load-config-workspace-') + ); + githubOutputPath = path.join(workspaceRoot, 'github-output.txt'); + fs.writeFileSync(githubOutputPath, ''); + + process.env.INPUT_RUNNER = 'ios'; + process.env.GITHUB_OUTPUT = githubOutputPath; + + mocks.getConfig.mockImplementation(async (projectRoot: string) => ({ + config: { + runners: [ + { + name: 'ios', + platformId: 'ios', + config: { device: { type: 'simulator' } }, + }, + ], + }, + projectRoot, + })); + + vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + vi.spyOn(console, 'error').mockImplementation(() => undefined); + vi.spyOn(console, 'info').mockImplementation(() => undefined); + }); + + afterEach(() => { + fs.rmSync(workspaceRoot, { recursive: true, force: true }); + delete process.env.INPUT_RUNNER; + delete process.env.INPUT_PROJECTROOT; + delete process.env.GITHUB_OUTPUT; + delete process.env.GITHUB_WORKSPACE; + vi.restoreAllMocks(); + }); + + // Regression test for a bug where INPUT_PROJECTROOT (workspace-relative, + // as the composite action passes it) was resolved against process.cwd() + // instead of GITHUB_WORKSPACE. Since the action also sets a per-step + // `working-directory` equal to the resolved project root, that produced a + // doubled-up path like "/apps/foo/apps/foo" and an emitted + // projectRoot of "." instead of "apps/foo" -- silently pointing + // actions/cache and actions/upload-artifact (which resolve paths against + // the workspace root, not any step's working-directory) at the wrong + // directory. + it('resolves a workspace-relative INPUT_PROJECTROOT against GITHUB_WORKSPACE, not process.cwd()', async () => { + const projectDir = path.join(workspaceRoot, 'apps', 'foo'); + fs.mkdirSync(projectDir, { recursive: true }); + + process.env.GITHUB_WORKSPACE = workspaceRoot; + process.env.INPUT_PROJECTROOT = 'apps/foo'; + // Mirrors the action's `working-directory: ${{ steps.load-config.outputs.projectRoot }}` + // convention on later ci steps: process.cwd() differs from the + // workspace root even though INPUT_PROJECTROOT is workspace-relative. + vi.spyOn(process, 'cwd').mockReturnValue(projectDir); + + const { runLoadConfig } = await import('../load-config.js'); + await runLoadConfig(); + + expect(mocks.getConfig).toHaveBeenCalledWith(projectDir); + expect(mocks.getConfig).not.toHaveBeenCalledWith( + path.join(projectDir, 'apps', 'foo') + ); + + const output = fs.readFileSync(githubOutputPath, 'utf8'); + expect(output).toContain('projectRoot=apps/foo\n'); + expect(output).not.toContain('projectRoot=.\n'); + }); + + it('falls back to GITHUB_WORKSPACE itself when INPUT_PROJECTROOT is unset', async () => { + process.env.GITHUB_WORKSPACE = workspaceRoot; + + const { runLoadConfig } = await import('../load-config.js'); + await runLoadConfig(); + + expect(mocks.getConfig).toHaveBeenCalledWith(workspaceRoot); + + const output = fs.readFileSync(githubOutputPath, 'utf8'); + expect(output).toContain('projectRoot=.\n'); + }); + + it('falls back to process.cwd() when GITHUB_WORKSPACE is unset, for local invocation', async () => { + const cwd = path.join(workspaceRoot, 'local-cwd'); + fs.mkdirSync(cwd, { recursive: true }); + vi.spyOn(process, 'cwd').mockReturnValue(cwd); + + const { runLoadConfig } = await import('../load-config.js'); + await runLoadConfig(); + + expect(mocks.getConfig).toHaveBeenCalledWith(cwd); + }); +}); diff --git a/packages/github-action/src/shared/__tests__/metro-cache-inputs.test.ts b/packages/cli/src/ci/__tests__/metro-cache-inputs.test.ts similarity index 100% rename from packages/github-action/src/shared/__tests__/metro-cache-inputs.test.ts rename to packages/cli/src/ci/__tests__/metro-cache-inputs.test.ts diff --git a/packages/github-action/src/shared/__tests__/plan-restore.test.ts b/packages/cli/src/ci/__tests__/plan-metro-restore.test.ts similarity index 94% rename from packages/github-action/src/shared/__tests__/plan-restore.test.ts rename to packages/cli/src/ci/__tests__/plan-metro-restore.test.ts index e2c89d7f..5e9aaa6d 100644 --- a/packages/github-action/src/shared/__tests__/plan-restore.test.ts +++ b/packages/cli/src/ci/__tests__/plan-metro-restore.test.ts @@ -77,7 +77,7 @@ describe('plan-restore', () => { }); it('writes metroRestoreKey and metroRestorePrefixes (as JSON) to GITHUB_OUTPUT', async () => { - await import('../plan-restore.js'); + await (await import('../plan-metro-restore.js')).runPlanMetroRestore(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -94,7 +94,7 @@ describe('plan-restore', () => { }); it('calls planRestore with the os and staticInputs assembled from the Metro key recipe', async () => { - await import('../plan-restore.js'); + await (await import('../plan-metro-restore.js')).runPlanMetroRestore(); await vi.waitFor(() => { expect(planRestoreMock).toHaveBeenCalled(); @@ -111,7 +111,7 @@ describe('plan-restore', () => { it('fails loudly (process.exit(1)) when GITHUB_OUTPUT is not set', async () => { delete process.env.GITHUB_OUTPUT; - await import('../plan-restore.js'); + await (await import('../plan-metro-restore.js')).runPlanMetroRestore(); await vi.waitFor(() => { expect(process.exit).toHaveBeenCalledWith(1); diff --git a/packages/github-action/src/shared/__tests__/plan-save.test.ts b/packages/cli/src/ci/__tests__/plan-metro-save.test.ts similarity index 91% rename from packages/github-action/src/shared/__tests__/plan-save.test.ts rename to packages/cli/src/ci/__tests__/plan-metro-save.test.ts index 70dc4910..9526debf 100644 --- a/packages/github-action/src/shared/__tests__/plan-save.test.ts +++ b/packages/cli/src/ci/__tests__/plan-metro-save.test.ts @@ -80,7 +80,7 @@ describe('plan-save', () => { }); it('writes metroShouldSave and metroSaveKey to GITHUB_OUTPUT', async () => { - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -94,7 +94,7 @@ describe('plan-save', () => { }); it('parses the metroSnapshot input and builds the SavePolicy from env/input', async () => { - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(planSaveMock).toHaveBeenCalled(); @@ -110,7 +110,7 @@ describe('plan-save', () => { it('treats an unparseable metroSnapshot input as an empty snapshot instead of throwing', async () => { process.env.INPUT_METRO_SNAPSHOT = 'not json'; - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(planSaveMock).toHaveBeenCalled(); @@ -127,7 +127,7 @@ describe('plan-save', () => { it('defaults an unrecognized cacheSavePolicy input to "default-branch"', async () => { process.env.INPUT_CACHESAVEPOLICY = 'bogus'; - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(planSaveMock).toHaveBeenCalled(); @@ -156,7 +156,7 @@ describe('plan-save', () => { }, }); - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -179,7 +179,7 @@ describe('plan-save', () => { }, }); - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -203,7 +203,7 @@ describe('plan-save', () => { }, }); - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -227,7 +227,7 @@ describe('plan-save', () => { }, }); - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(writeKeysFileMock).toHaveBeenCalled(); @@ -241,7 +241,7 @@ describe('plan-save', () => { it('fails loudly (process.exit(1)) when GITHUB_OUTPUT is not set', async () => { delete process.env.GITHUB_OUTPUT; - await import('../plan-save.js'); + await (await import('../plan-metro-save.js')).runPlanMetroSave(); await vi.waitFor(() => { expect(process.exit).toHaveBeenCalledWith(1); diff --git a/packages/github-action/src/shared/__tests__/snapshot-metro.test.ts b/packages/cli/src/ci/__tests__/snapshot-metro.test.ts similarity index 92% rename from packages/github-action/src/shared/__tests__/snapshot-metro.test.ts rename to packages/cli/src/ci/__tests__/snapshot-metro.test.ts index 69b9b11f..0eb44547 100644 --- a/packages/github-action/src/shared/__tests__/snapshot-metro.test.ts +++ b/packages/cli/src/ci/__tests__/snapshot-metro.test.ts @@ -59,7 +59,7 @@ describe('snapshot-metro', () => { }); it('writes the current cache snapshot to GITHUB_OUTPUT as metroSnapshot', async () => { - await import('../snapshot-metro.js'); + await (await import('../snapshot-metro.js')).runSnapshotMetro(); await vi.waitFor(() => { expect(snapshotMock).toHaveBeenCalled(); @@ -80,7 +80,7 @@ describe('snapshot-metro', () => { ], }); - await import('../snapshot-metro.js'); + await (await import('../snapshot-metro.js')).runSnapshotMetro(); await vi.waitFor(() => { expect(snapshotMock).toHaveBeenCalled(); @@ -94,7 +94,7 @@ describe('snapshot-metro', () => { it('reports a cold start when no cache entry matched', async () => { delete process.env.METRO_RESTORED_KEY; - await import('../snapshot-metro.js'); + await (await import('../snapshot-metro.js')).runSnapshotMetro(); await vi.waitFor(() => { expect(snapshotMock).toHaveBeenCalled(); @@ -108,7 +108,7 @@ describe('snapshot-metro', () => { it('fails loudly (process.exit(1)) when GITHUB_OUTPUT is not set', async () => { delete process.env.GITHUB_OUTPUT; - await import('../snapshot-metro.js'); + await (await import('../snapshot-metro.js')).runSnapshotMetro(); await vi.waitFor(() => { expect(process.exit).toHaveBeenCalledWith(1); diff --git a/packages/github-action/src/shared/format-bytes.ts b/packages/cli/src/ci/format-bytes.ts similarity index 100% rename from packages/github-action/src/shared/format-bytes.ts rename to packages/cli/src/ci/format-bytes.ts diff --git a/packages/github-action/src/shared/index.ts b/packages/cli/src/ci/load-config.ts similarity index 67% rename from packages/github-action/src/shared/index.ts rename to packages/cli/src/ci/load-config.ts index c1355e70..3bd2ece1 100644 --- a/packages/github-action/src/shared/index.ts +++ b/packages/cli/src/ci/load-config.ts @@ -1,10 +1,28 @@ import { getConfig } from '@react-native-harness/config'; -import { - getEmulatorCpuCores, - getHostAndroidSystemImageArch, -} from '@react-native-harness/platform-android'; -import path from 'node:path'; import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { relativeToWorkspaceRoot, resolveProjectRoot } from './workspace-root.js'; + +/** + * `@react-native-harness/platform-android` is only a devDependency of this + * package (the published CLI must not crash on Android-less/web-only + * projects), so it's never imported at the top level. It's resolved from the + * consuming project instead -- a project with an Android runner necessarily + * has the package installed -- mirroring how metro-cache-inputs.ts resolves + * @react-native-harness/bundler-metro from the consuming project. + */ +const loadPlatformAndroid = async ( + projectRoot: string +): Promise< + typeof import('@react-native-harness/platform-android') +> => { + const require = createRequire(import.meta.url); + const platformAndroidEntry = require.resolve( + '@react-native-harness/platform-android', + { paths: [projectRoot] } + ); + return import(platformAndroidEntry); +}; const resolveAvdCachingEnabled = ({ snapshotEnabled, @@ -21,6 +39,7 @@ const resolveAvdCachingEnabled = ({ const getNormalizedAvdCacheConfig = ({ emulator, hostArch, + getEmulatorCpuCores, }: { emulator: { name: string; @@ -32,6 +51,7 @@ const getNormalizedAvdCacheConfig = ({ }; }; hostArch: 'x86_64' | 'arm64-v8a' | 'armeabi-v7a'; + getEmulatorCpuCores: () => number; }) => { const avd = emulator.avd; @@ -53,8 +73,9 @@ const getNormalizedAvdCacheConfig = ({ }; }; -const getResolvedRunner = ( - runner: Awaited>['config']['runners'][number] +const getResolvedRunner = async ( + runner: Awaited>['config']['runners'][number], + projectRoot: string ) => { if ( runner.platformId !== 'android' || @@ -67,6 +88,9 @@ const getResolvedRunner = ( snapshotEnabled: runner.config.device.avd?.snapshot?.enabled, }); + const { getEmulatorCpuCores, getHostAndroidSystemImageArch } = + await loadPlatformAndroid(projectRoot); + return { ...runner, config: { @@ -81,12 +105,13 @@ const getResolvedRunner = ( avdCacheConfig: getNormalizedAvdCacheConfig({ emulator: runner.config.device, hostArch: getHostAndroidSystemImageArch(), + getEmulatorCpuCores, }), }, }; }; -const run = async (): Promise => { +export const runLoadConfig = async (): Promise => { try { const projectRootInput = process.env.INPUT_PROJECTROOT; const runnerInput = process.env.INPUT_RUNNER; @@ -95,9 +120,7 @@ const run = async (): Promise => { throw new Error('Runner input is required'); } - const projectRoot = projectRootInput - ? path.resolve(projectRootInput) - : process.cwd(); + const projectRoot = resolveProjectRoot(projectRootInput); console.info(`Loading React Native Harness config from: ${projectRoot}`); @@ -116,9 +139,8 @@ const run = async (): Promise => { throw new Error('GITHUB_OUTPUT environment variable is not set'); } - const resolvedRunner = getResolvedRunner(runner); - const relativeProjectRoot = - path.relative(process.cwd(), resolvedProjectRoot) || '.'; + const resolvedRunner = await getResolvedRunner(runner, resolvedProjectRoot); + const relativeProjectRoot = relativeToWorkspaceRoot(resolvedProjectRoot); const output = `config=${JSON.stringify( resolvedRunner )}\nprojectRoot=${relativeProjectRoot}\n`; @@ -133,5 +155,3 @@ const run = async (): Promise => { process.exit(1); } }; - -run(); diff --git a/packages/github-action/src/shared/metro-cache-inputs.ts b/packages/cli/src/ci/metro-cache-inputs.ts similarity index 97% rename from packages/github-action/src/shared/metro-cache-inputs.ts rename to packages/cli/src/ci/metro-cache-inputs.ts index e03f04f4..46733bf7 100644 --- a/packages/github-action/src/shared/metro-cache-inputs.ts +++ b/packages/cli/src/ci/metro-cache-inputs.ts @@ -1,7 +1,10 @@ import fs from 'node:fs'; import path from 'node:path'; +import { createRequire } from 'node:module'; import { computeMetroStaticInputs } from '@react-native-harness/cache'; +const require = createRequire(import.meta.url); + const FALLBACK_BUNDLER_METRO_VERSION = 'unknown'; /** diff --git a/packages/github-action/src/shared/plan-restore.ts b/packages/cli/src/ci/plan-metro-restore.ts similarity index 91% rename from packages/github-action/src/shared/plan-restore.ts rename to packages/cli/src/ci/plan-metro-restore.ts index 67691bef..aa03b78d 100644 --- a/packages/github-action/src/shared/plan-restore.ts +++ b/packages/cli/src/ci/plan-metro-restore.ts @@ -1,16 +1,14 @@ import fs from 'node:fs'; -import path from 'node:path'; import { createHarnessCache } from '@react-native-harness/cache'; import { getConfig } from '@react-native-harness/config'; import { resolveMetroStaticInputs } from './metro-cache-inputs.js'; +import { resolveProjectRoot } from './workspace-root.js'; -const run = async (): Promise => { +export const runPlanMetroRestore = async (): Promise => { try { const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput - ? path.resolve(projectRootInput) - : process.cwd(); + const projectRoot = resolveProjectRoot(projectRootInput); console.info(`Planning Metro cache restore for: ${projectRoot}`); @@ -65,5 +63,3 @@ const run = async (): Promise => { process.exit(1); } }; - -run(); diff --git a/packages/github-action/src/shared/plan-save.ts b/packages/cli/src/ci/plan-metro-save.ts similarity index 95% rename from packages/github-action/src/shared/plan-save.ts rename to packages/cli/src/ci/plan-metro-save.ts index 8c071987..f509057b 100644 --- a/packages/github-action/src/shared/plan-save.ts +++ b/packages/cli/src/ci/plan-metro-save.ts @@ -1,5 +1,4 @@ import fs from 'node:fs'; -import path from 'node:path'; import { createHarnessCache, type CacheSnapshot, @@ -9,6 +8,7 @@ import { import { getConfig } from '@react-native-harness/config'; import { formatMegabytes } from './format-bytes.js'; import { resolveMetroStaticInputs } from './metro-cache-inputs.js'; +import { resolveProjectRoot } from './workspace-root.js'; const parseSnapshot = (raw: string | undefined): CacheSnapshot => { if (!raw) { @@ -74,13 +74,11 @@ const logMetroSaveDecision = ( ); }; -const run = async (): Promise => { +export const runPlanMetroSave = async (): Promise => { try { const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput - ? path.resolve(projectRootInput) - : process.cwd(); + const projectRoot = resolveProjectRoot(projectRootInput); console.info(`Planning Metro cache save for: ${projectRoot}`); @@ -133,5 +131,3 @@ const run = async (): Promise => { process.exit(1); } }; - -run(); diff --git a/packages/github-action/src/shared/snapshot-metro.ts b/packages/cli/src/ci/snapshot-metro.ts similarity index 92% rename from packages/github-action/src/shared/snapshot-metro.ts rename to packages/cli/src/ci/snapshot-metro.ts index 281ad55c..1f9a721c 100644 --- a/packages/github-action/src/shared/snapshot-metro.ts +++ b/packages/cli/src/ci/snapshot-metro.ts @@ -1,8 +1,8 @@ import fs from 'node:fs'; -import path from 'node:path'; import { createHarnessCache } from '@react-native-harness/cache'; import { getConfig } from '@react-native-harness/config'; import { formatMegabytes } from './format-bytes.js'; +import { resolveProjectRoot } from './workspace-root.js'; /** * Must run AFTER the "Restore Metro cache" step and BEFORE the test run, so @@ -13,13 +13,11 @@ import { formatMegabytes } from './format-bytes.js'; * restored cache, defeating the "only save when content actually changed" * policy. */ -const run = async (): Promise => { +export const runSnapshotMetro = async (): Promise => { try { const projectRootInput = process.env.INPUT_PROJECTROOT; - const projectRoot = projectRootInput - ? path.resolve(projectRootInput) - : process.cwd(); + const projectRoot = resolveProjectRoot(projectRootInput); console.info(`Snapshotting Metro cache for: ${projectRoot}`); @@ -65,5 +63,3 @@ const run = async (): Promise => { process.exit(1); } }; - -run(); diff --git a/packages/cli/src/ci/workspace-root.ts b/packages/cli/src/ci/workspace-root.ts new file mode 100644 index 00000000..4e199c76 --- /dev/null +++ b/packages/cli/src/ci/workspace-root.ts @@ -0,0 +1,39 @@ +import path from 'node:path'; + +/** + * The workspace root that INPUT_PROJECTROOT and the emitted `projectRoot` + * output are resolved against. GitHub Actions sets GITHUB_WORKSPACE to the + * checkout root for every step, regardless of that step's + * `working-directory` -- and the composite action sets `working-directory` + * on these steps so `pnpm exec` / `npx` resolves the project's own installed + * binary. Anchoring path resolution to GITHUB_WORKSPACE (rather than + * process.cwd()) keeps `INPUT_PROJECTROOT` and `projectRoot` consistently + * workspace-root-relative no matter which directory a step actually runs in. + * Falls back to process.cwd() so the CLI still behaves sensibly when + * invoked locally, outside of GitHub Actions. + */ +export const getWorkspaceRoot = (): string => + process.env.GITHUB_WORKSPACE ?? process.cwd(); + +/** + * Resolves the project root from the (possibly relative, possibly unset) + * INPUT_PROJECTROOT value, always against the workspace root -- never + * against process.cwd(), which varies per step via `working-directory`. + */ +export const resolveProjectRoot = ( + projectRootInput: string | undefined +): string => { + const workspaceRoot = getWorkspaceRoot(); + return projectRootInput + ? path.resolve(workspaceRoot, projectRootInput) + : workspaceRoot; +}; + +/** + * Mirrors resolveProjectRoot's base so the `projectRoot` value emitted to + * GITHUB_OUTPUT is relative to the workspace root, matching what + * downstream non-bash steps (actions/cache, actions/upload-artifact, + * hashFiles(...)) resolve paths against. + */ +export const relativeToWorkspaceRoot = (target: string): string => + path.relative(getWorkspaceRoot(), target) || '.'; diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index af488bd4..95fd2c65 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -83,6 +83,63 @@ Examples: harness skill get core`); }; +const CI_SUBCOMMANDS = [ + 'load-config', + 'plan-metro-restore', + 'snapshot-metro', + 'plan-metro-save', +] as const; + +const printCiUsage = () => { + console.error(`Usage: harness ci + +Commands: + load-config Load and resolve the Harness config for a runner + plan-metro-restore Plan a Metro cache restore + snapshot-metro Snapshot the Metro cache after restore + plan-metro-save Plan a Metro cache save + +These commands are invoked by the react-native-harness GitHub Action and are +not intended to be run manually.`); +}; + +const runCiCommand = async () => { + const [, , , subcommand] = process.argv; + + if ( + subcommand === undefined || + !CI_SUBCOMMANDS.includes(subcommand as (typeof CI_SUBCOMMANDS)[number]) + ) { + printCiUsage(); + process.exit(1); + } + + switch (subcommand) { + case 'load-config': { + const { runLoadConfig } = await import('./ci/load-config.js'); + await runLoadConfig(); + return; + } + case 'plan-metro-restore': { + const { runPlanMetroRestore } = await import( + './ci/plan-metro-restore.js' + ); + await runPlanMetroRestore(); + return; + } + case 'snapshot-metro': { + const { runSnapshotMetro } = await import('./ci/snapshot-metro.js'); + await runSnapshotMetro(); + return; + } + case 'plan-metro-save': { + const { runPlanMetroSave } = await import('./ci/plan-metro-save.js'); + await runPlanMetroSave(); + return; + } + } +}; + const getErrorMessage = (error: unknown): string => { if (error instanceof Error) { return error.message; @@ -209,6 +266,11 @@ const main = async () => { return; } + if (process.argv[2] === 'ci') { + await runCiCommand(); + return; + } + if ( await runPlatformCommand({ argv: process.argv.slice(2), diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json index 7e4d9db0..cd0b53f9 100644 --- a/packages/cli/tsconfig.json +++ b/packages/cli/tsconfig.json @@ -4,7 +4,10 @@ "include": [], "references": [ { - "path": "../platform-web" + "path": "../jest" + }, + { + "path": "../bundler-metro" }, { "path": "../tools" @@ -15,9 +18,15 @@ { "path": "../config" }, + { + "path": "../cache" + }, { "path": "../bridge" }, + { + "path": "../platform-web" + }, { "path": "../platform-ios" }, diff --git a/packages/cli/tsconfig.lib.json b/packages/cli/tsconfig.lib.json index 5f756417..04273ff8 100644 --- a/packages/cli/tsconfig.lib.json +++ b/packages/cli/tsconfig.lib.json @@ -13,7 +13,10 @@ "include": ["src/**/*.ts"], "references": [ { - "path": "../platform-web/tsconfig.lib.json" + "path": "../jest/tsconfig.lib.json" + }, + { + "path": "../bundler-metro/tsconfig.lib.json" }, { "path": "../tools/tsconfig.lib.json" @@ -24,9 +27,15 @@ { "path": "../config/tsconfig.lib.json" }, + { + "path": "../cache/tsconfig.lib.json" + }, { "path": "../bridge/tsconfig.lib.json" }, + { + "path": "../platform-web/tsconfig.lib.json" + }, { "path": "../platform-ios/tsconfig.lib.json" }, diff --git a/packages/github-action/vite.config.ts b/packages/cli/vite.config.ts similarity index 87% rename from packages/github-action/vite.config.ts rename to packages/cli/vite.config.ts index 9db8823c..9631ae83 100644 --- a/packages/github-action/vite.config.ts +++ b/packages/cli/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vite'; export default defineConfig(() => ({ root: __dirname, - cacheDir: '../../node_modules/.vite/packages/github-action', + cacheDir: '../../node_modules/.vite/packages/cli', test: { watch: false, globals: true, diff --git a/packages/github-action/eslint.config.mjs b/packages/github-action/eslint.config.mjs deleted file mode 100644 index fabd4248..00000000 --- a/packages/github-action/eslint.config.mjs +++ /dev/null @@ -1,34 +0,0 @@ -import baseConfig from '../../eslint.config.mjs'; - -export default [ - ...baseConfig, - { - files: ['**/*.json'], - rules: { - '@nx/dependency-checks': [ - 'error', - { - ignoredFiles: [ - '{projectRoot}/eslint.config.{js,cjs,mjs,ts,cts,mts}', - '{projectRoot}/tsup.config.{js,cjs,mjs,ts,cts,mts}', - ], - ignoredDependencies: [ - 'vite', - 'vitest', - // Referenced only as a require.resolve() target to read the - // consuming project's own installed version at runtime, not - // imported/bundled by this package. - '@react-native-harness/bundler-metro', - // Referenced only as a require.resolve() fallback root to reach - // bundler-metro when it's nested under jest's own node_modules, - // not imported/bundled by this package. - '@react-native-harness/jest', - ], - }, - ], - }, - languageOptions: { - parser: await import('jsonc-eslint-parser'), - }, - }, -]; diff --git a/packages/github-action/package.json b/packages/github-action/package.json deleted file mode 100644 index b5e46110..00000000 --- a/packages/github-action/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "@react-native-harness/github-action", - "private": true, - "description": "GitHub Actions for React Native Harness", - "version": "1.4.1", - "type": "commonjs", - "exports": { - "./package.json": "./package.json" - }, - "scripts": { - "build": "tsup" - }, - "dependencies": { - "@react-native-harness/cache": "workspace:*", - "@react-native-harness/config": "workspace:*", - "@react-native-harness/platform-android": "workspace:*" - }, - "devDependencies": { - "tsup": "^8.5.1" - }, - "license": "MIT" -} diff --git a/packages/github-action/project.json b/packages/github-action/project.json deleted file mode 100644 index 81d804fe..00000000 --- a/packages/github-action/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@react-native-harness/github-action", - "$schema": "../../node_modules/nx/schemas/project-schema.json", - "targets": { - "build": { - "inputs": [ - "{projectRoot}/src/**/*", - "{projectRoot}/tsup.config.mts", - "{workspaceRoot}/tsconfig.base.json", - "{projectRoot}/tsconfig.json", - "{projectRoot}/tsconfig.lib.json", - "{projectRoot}/package.json" - ], - "dependsOn": ["^build"], - "outputs": ["{projectRoot}/dist"] - } - } -} diff --git a/packages/github-action/src/action.yml b/packages/github-action/src/action.yml deleted file mode 100644 index 0a6fe34b..00000000 --- a/packages/github-action/src/action.yml +++ /dev/null @@ -1,301 +0,0 @@ -name: React Native Harness -description: Run React Native Harness tests on iOS, Android or Web -inputs: - runner: - description: The runner to use (must match a runner name defined in your harness config) - required: true - type: string - app: - description: The path to the app (.app for iOS, .apk for Android). Not required for web. - required: false - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - packageManager: - description: Package manager to use instead of auto-detection (npm, yarn, pnpm, bun, or deno) - required: false - type: string - default: '' - cacheAvd: - description: Whether to cache the AVD - required: false - type: boolean - default: 'true' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' - cacheSavePolicy: - description: When to save a new Metro cache entry ('default-branch', 'always', or 'never') - required: false - type: string - default: 'default-branch' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - node ${{ github.action_path }}/actions/shared/index.cjs - - name: Verify native app input - if: fromJson(steps.load-config.outputs.config).platformId != 'web' - shell: bash - run: | - if [ -z "${{ inputs.app }}" ]; then - echo "Error: app input is required for native runners" - echo "Please provide the path to the built app (.apk for Android, .app for iOS)" - exit 1 - fi - - name: Plan Metro cache restore - id: plan-metro-restore - shell: bash - env: - INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} - run: | - node ${{ github.action_path }}/actions/shared/plan-restore.cjs - - name: Restore Metro cache (.harness/cache/metro) - id: restore-metro - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/metro - ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/metro-file-map - key: ${{ steps.plan-metro-restore.outputs.metroRestoreKey }} - # The '\n' here is a literal newline embedded via YAML double-quote - # escaping (not a GitHub Actions expression escape -- expression - # string literals don't interpret backslash sequences), so join() - # actually separates entries onto their own lines, as actions/cache - # requires for restore-keys. - restore-keys: "${{ join(fromJson(steps.plan-metro-restore.outputs.metroRestorePrefixes), '\n') }}" - # Must run after "Restore Metro cache" so this reflects what was actually - # restored (empty on a cache miss), not the always-empty pre-restore state. - - name: Snapshot Metro cache - id: snapshot-metro-restore - shell: bash - env: - INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} - # Empty on a cache miss; snapshot-metro.cjs uses it to report whether - # the Metro cache was actually restored and from which key. - METRO_RESTORED_KEY: ${{ steps.restore-metro.outputs.cache-matched-key }} - run: | - node ${{ github.action_path }}/actions/shared/snapshot-metro.cjs - - name: Restore Harness cache - id: cache-harness-restore - if: fromJson(steps.load-config.outputs.config).platformId == 'ios' - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/xctest-agent-simulator-* - key: harness-ios-${{ runner.os }}-${{ hashFiles(format('{0}/.harness/cache/**/cache.json', steps.load-config.outputs.projectRoot)) }} - restore-keys: | - harness-ios-${{ runner.os }}- - - # ── iOS ────────────────────────────────────────────────────────────────── - # iOS simulator boot and app installation are handled by Harness itself. - # ── Android ────────────────────────────────────────────────────────────── - - name: Verify Android config - if: ${{ fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - if [ '${{ fromJson(steps.load-config.outputs.config).config.device.avd }}' = 'null' ]; then - echo "Error: AVD config is required for Android emulators" - echo "Please define the 'avd' property in the runner config" - exit 1 - fi - - name: Get architecture of the runner - id: arch - if: ${{ fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - case "${{ runner.arch }}" in - X64) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - ARM64) - echo "arch=arm64-v8a" >> $GITHUB_OUTPUT - ;; - ARM32) - echo "arch=armeabi-v7a" >> $GITHUB_OUTPUT - ;; - *) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - esac - - name: Enable KVM group perms - if: ${{ fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules - sudo udevadm control --reload-rules - sudo udevadm trigger --name-match=kvm - ls /dev/kvm - - name: Compute AVD cache key - id: avd-key - if: ${{ fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - shell: bash - run: | - CACHE_CONFIG='${{ toJson(fromJson(steps.load-config.outputs.config).action.avdCacheConfig) }}' - AVD_CONFIG_HASH=$(printf '%s' "$CACHE_CONFIG" | sha256sum | cut -d' ' -f1) - AVD_NAME='${{ fromJson(steps.load-config.outputs.config).config.device.name }}' - ARCH="${{ steps.arch.outputs.arch }}" - CACHE_KEY="avd-$AVD_NAME-$ARCH-$AVD_CONFIG_HASH" - echo "key=$CACHE_KEY" >> $GITHUB_OUTPUT - - name: Restore AVD cache - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - id: avd-cache - if: ${{ fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - # ── Web ────────────────────────────────────────────────────────────────── - - name: Install Playwright Browsers - if: fromJson(steps.load-config.outputs.config).platformId == 'web' - shell: bash - run: npx playwright install --with-deps chromium - - # ── Shared ─────────────────────────────────────────────────────────────── - - name: Detect Package Manager - id: detect-pm - shell: bash - working-directory: ${{ steps.load-config.outputs.projectRoot }} - run: | - if [ -n "${{ inputs.packageManager }}" ]; then - case "${{ inputs.packageManager }}" in - pnpm) - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - ;; - yarn) - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - ;; - bun) - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - ;; - deno) - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - ;; - npm) - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - ;; - *) - echo "Error: Unsupported packageManager '${{ inputs.packageManager }}'" - echo "Supported values: npm, yarn, pnpm, bun, deno" - exit 1 - ;; - esac - elif [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ steps.load-config.outputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - HARNESS_APP_PATH: ${{ inputs.app }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-${{ fromJson(steps.load-config.outputs.config).platformId }} - path: | - ${{ steps.load-config.outputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ steps.load-config.outputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Save AVD cache - if: ${{ always() && fromJson(steps.load-config.outputs.config).platformId == 'android' && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled && steps.avd-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - - name: Save Harness cache - if: ${{ always() && fromJson(steps.load-config.outputs.config).platformId == 'ios' && steps.cache-harness-restore.outputs.cache-hit != 'true' }} - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/xctest-agent-simulator-* - key: ${{ steps.cache-harness-restore.outputs.cache-primary-key }} - - name: Plan Metro cache save - id: plan-metro-save - if: always() - shell: bash - env: - INPUT_PROJECTROOT: ${{ steps.load-config.outputs.projectRoot }} - INPUT_METRO_SNAPSHOT: ${{ steps.snapshot-metro-restore.outputs.metroSnapshot }} - INPUT_CACHESAVEPOLICY: ${{ inputs.cacheSavePolicy }} - IS_DEFAULT_BRANCH: ${{ github.ref_name == github.event.repository.default_branch }} - run: | - node ${{ github.action_path }}/actions/shared/plan-save.cjs - - name: Save Metro cache - if: always() && steps.plan-metro-save.outputs.metroShouldSave == 'true' - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/metro - ${{ steps.load-config.outputs.projectRoot }}/.harness/cache/metro-file-map - key: ${{ steps.plan-metro-save.outputs.metroSaveKey }} - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-${{ fromJson(steps.load-config.outputs.config).platformId }} - path: ${{ steps.load-config.outputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/packages/github-action/src/android/action.yml b/packages/github-action/src/android/action.yml deleted file mode 100644 index b650943f..00000000 --- a/packages/github-action/src/android/action.yml +++ /dev/null @@ -1,174 +0,0 @@ -name: React Native Harness for Android -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on Android' -inputs: - app: - description: The path to the Android app (.apk) - required: true - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - cacheAvd: - description: Whether to cache the AVD - required: false - type: boolean - default: 'true' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Verify Android config - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - if [ '${{ fromJson(steps.load-config.outputs.config).config.device.avd }}' = 'null' ]; then - echo "Error: AVD config is required for Android emulators" - echo "Please define the 'avd' property in the runner config" - exit 1 - fi - - name: Get architecture of the runner - id: arch - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - case "${{ runner.arch }}" in - X64) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - ARM64) - echo "arch=arm64-v8a" >> $GITHUB_OUTPUT - ;; - ARM32) - echo "arch=armeabi-v7a" >> $GITHUB_OUTPUT - ;; - *) - echo "arch=x86_64" >> $GITHUB_OUTPUT - ;; - esac - - name: Enable KVM group perms - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' }} - shell: bash - run: | - echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules - sudo udevadm control --reload-rules - sudo udevadm trigger --name-match=kvm - ls /dev/kvm - - name: Compute AVD cache key - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - id: avd-key - shell: bash - run: | - CACHE_CONFIG='${{ toJson(fromJson(steps.load-config.outputs.config).action.avdCacheConfig) }}' - AVD_CONFIG_HASH=$(printf '%s' "$CACHE_CONFIG" | sha256sum | cut -d' ' -f1) - AVD_NAME='${{ fromJson(steps.load-config.outputs.config).config.device.name }}' - ARCH="${{ steps.arch.outputs.arch }}" - CACHE_KEY="avd-$AVD_NAME-$ARCH-$AVD_CONFIG_HASH" - echo "key=$CACHE_KEY" >> $GITHUB_OUTPUT - - name: Restore AVD cache - if: ${{ fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled }} - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - id: avd-cache - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - HARNESS_APP_PATH: ${{ inputs.app }} - HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-android - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Save AVD cache - if: ${{ always() && fromJson(steps.load-config.outputs.config).config.device.type == 'emulator' && fromJson(steps.load-config.outputs.config).action.avdCachingEnabled && steps.avd-cache.outputs.cache-hit != 'true' }} - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: | - ~/.android/avd - ~/.android/adb* - key: ${{ steps.avd-key.outputs.key }} - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-android - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/packages/github-action/src/android/index.ts b/packages/github-action/src/android/index.ts deleted file mode 100644 index fcbabe12..00000000 --- a/packages/github-action/src/android/index.ts +++ /dev/null @@ -1 +0,0 @@ -// This file is intentionally empty. diff --git a/packages/github-action/src/ios/action.yml b/packages/github-action/src/ios/action.yml deleted file mode 100644 index 79772e43..00000000 --- a/packages/github-action/src/ios/action.yml +++ /dev/null @@ -1,103 +0,0 @@ -name: React Native Harness for iOS -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on iOS' -inputs: - app: - description: The path to the iOS app (.app) - required: true - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - HARNESS_APP_PATH: ${{ inputs.app }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-ios - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-ios - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/packages/github-action/src/ios/index.ts b/packages/github-action/src/ios/index.ts deleted file mode 100644 index fcbabe12..00000000 --- a/packages/github-action/src/ios/index.ts +++ /dev/null @@ -1 +0,0 @@ -// This file is intentionally empty. diff --git a/packages/github-action/src/web/action.yml b/packages/github-action/src/web/action.yml deleted file mode 100644 index ff593a4f..00000000 --- a/packages/github-action/src/web/action.yml +++ /dev/null @@ -1,131 +0,0 @@ -name: React Native Harness for Web -description: '[Deprecated] Use callstackincubator/react-native-harness instead. Run React Native Harness tests on Web' -inputs: - runner: - description: The runner to use - required: true - type: string - projectRoot: - description: The project root directory - required: false - type: string - uploadVisualTestArtifacts: - description: Whether to upload visual test diff and actual images as artifacts - required: false - type: boolean - default: 'true' - harnessArgs: - description: Additional arguments to pass to the Harness CLI - required: false - type: string - default: '' - preRunHook: - description: Shell script to run in bash immediately before Harness starts - required: false - type: string - default: '' - afterRunHook: - description: Shell script to run in bash immediately after Harness finishes - required: false - type: string - default: '' -runs: - using: 'composite' - steps: - - name: Load React Native Harness configuration - id: load-config - shell: bash - env: - INPUT_RUNNER: ${{ inputs.runner }} - INPUT_PROJECTROOT: ${{ inputs.projectRoot }} - run: | - node ${{ github.action_path }}/../shared/index.cjs - - name: Install Playwright Browsers - shell: bash - run: npx playwright install --with-deps chromium - - name: Detect Package Manager - id: detect-pm - shell: bash - run: | - if [ -f "pnpm-lock.yaml" ]; then - echo "manager=pnpm" >> $GITHUB_OUTPUT - echo "runner=pnpm exec " >> $GITHUB_OUTPUT - elif [ -f "yarn.lock" ]; then - echo "manager=yarn" >> $GITHUB_OUTPUT - echo "runner=yarn " >> $GITHUB_OUTPUT - elif [ -f "bun.lock" ] || [ -f "bun.lockb" ]; then - echo "manager=bun" >> $GITHUB_OUTPUT - echo "runner=bunx " >> $GITHUB_OUTPUT - elif [ -f "deno.lock" ]; then - echo "manager=deno" >> $GITHUB_OUTPUT - echo "runner=deno run -A npm:" >> $GITHUB_OUTPUT - else - echo "manager=npm" >> $GITHUB_OUTPUT - echo "runner=npx " >> $GITHUB_OUTPUT - fi - - name: Run E2E tests - id: run-tests - shell: bash - working-directory: ${{ inputs.projectRoot }} - env: - PRE_RUN_HOOK: ${{ inputs.preRunHook }} - AFTER_RUN_HOOK: ${{ inputs.afterRunHook }} - HARNESS_RUNNER: ${{ inputs.runner }} - run: | - export HARNESS_PROJECT_ROOT="$PWD" - - if [ -n "$PRE_RUN_HOOK" ]; then - pre_hook_file="$(mktemp "${RUNNER_TEMP:-/tmp}/harness-pre-run.XXXXXX.sh")" - trap 'rm -f "$pre_hook_file"' EXIT - printf '%s\n' "$PRE_RUN_HOOK" > "$pre_hook_file" - chmod +x "$pre_hook_file" - bash "$pre_hook_file" - rm -f "$pre_hook_file" - trap - EXIT - fi - - set +e - ${{ steps.detect-pm.outputs.runner }}react-native-harness --harnessRunner ${{ inputs.runner }} ${{ inputs.harnessArgs }} - harness_exit_code=$? - set -e - - export HARNESS_EXIT_CODE="$harness_exit_code" - after_run_exit_code=0 - if [ -n "$AFTER_RUN_HOOK" ]; then - after_hook_file="$(mktemp "${RUNNER_TEMP:-/tmp}/harness-after-run.XXXXXX.sh")" - trap 'rm -f "$after_hook_file"' EXIT - printf '%s\n' "$AFTER_RUN_HOOK" > "$after_hook_file" - chmod +x "$after_hook_file" - set +e - bash "$after_hook_file" - after_run_exit_code=$? - set -e - rm -f "$after_hook_file" - trap - EXIT - fi - - echo "harness_exit_code=$harness_exit_code" >> "$GITHUB_OUTPUT" - - if [ "$harness_exit_code" -ne 0 ]; then - exit "$harness_exit_code" - fi - - if [ "$after_run_exit_code" -ne 0 ]; then - exit "$after_run_exit_code" - fi - - name: Upload visual test artifacts - if: always() && inputs.uploadVisualTestArtifacts == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: visual-test-diffs-chromium - path: | - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-diff.png - ${{ inputs.projectRoot }}/**/__image_snapshots__/**/*-actual.png - if-no-files-found: ignore - - name: Upload crash report artifacts - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: harness-crash-reports-web - path: ${{ inputs.projectRoot }}/.harness/crash-reports/**/* - if-no-files-found: ignore diff --git a/packages/github-action/src/web/index.ts b/packages/github-action/src/web/index.ts deleted file mode 100644 index fcbabe12..00000000 --- a/packages/github-action/src/web/index.ts +++ /dev/null @@ -1 +0,0 @@ -// This file is intentionally empty. diff --git a/packages/github-action/tsconfig.json b/packages/github-action/tsconfig.json deleted file mode 100644 index 0fe47aad..00000000 --- a/packages/github-action/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "files": [], - "include": [], - "references": [ - { - "path": "../jest" - }, - { - "path": "../bundler-metro" - }, - { - "path": "../platform-android" - }, - { - "path": "../config" - }, - { - "path": "../cache" - }, - { - "path": "./tsconfig.lib.json" - } - ] -} diff --git a/packages/github-action/tsconfig.lib.json b/packages/github-action/tsconfig.lib.json deleted file mode 100644 index c497d568..00000000 --- a/packages/github-action/tsconfig.lib.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "baseUrl": ".", - "rootDir": "src", - "outDir": "dist", - "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", - "emitDeclarationOnly": false, - "forceConsistentCasingInFileNames": true, - "types": ["node"] - }, - "include": ["src/**/*.ts"], - "references": [ - { - "path": "../jest/tsconfig.lib.json" - }, - { - "path": "../bundler-metro/tsconfig.lib.json" - }, - { - "path": "../platform-android/tsconfig.lib.json" - }, - { - "path": "../config/tsconfig.lib.json" - }, - { - "path": "../cache/tsconfig.lib.json" - } - ] -} diff --git a/packages/github-action/tsup.config.mts b/packages/github-action/tsup.config.mts deleted file mode 100644 index 47cc3626..00000000 --- a/packages/github-action/tsup.config.mts +++ /dev/null @@ -1,42 +0,0 @@ -import { defineConfig } from 'tsup'; -import fs from 'node:fs'; -import path from 'node:path'; - -const OUT_DIR = path.resolve('../../actions'); -const TARGETS = ['ios', 'android', 'web']; - -const packageJson = JSON.parse( - fs.readFileSync(path.resolve('./package.json'), 'utf8') -); - -export default defineConfig({ - entry: { - ...Object.fromEntries( - TARGETS.map((target) => [`${target}/index`, `src/${target}/index.ts`]) - ), - 'shared/index': 'src/shared/index.ts', - 'shared/plan-restore': 'src/shared/plan-restore.ts', - 'shared/snapshot-metro': 'src/shared/snapshot-metro.ts', - 'shared/plan-save': 'src/shared/plan-save.ts', - }, - outDir: OUT_DIR, - format: 'cjs', - dts: false, - platform: 'node', - clean: true, - bundle: true, - noExternal: Object.keys(packageJson.dependencies || {}), - outExtension: ({ format }) => ({ js: format === 'cjs' ? '.cjs' : '.mjs' }), - onSuccess: async () => { - TARGETS.forEach((target) => { - fs.copyFileSync( - path.resolve(`./src/${target}/action.yml`), - path.resolve(OUT_DIR, `./${target}/action.yml`) - ); - }); - fs.copyFileSync( - path.resolve('./src/action.yml'), - path.resolve(OUT_DIR, '../action.yml') - ); - }, -}); diff --git a/packages/platform-android/src/__tests__/ci-action.test.ts b/packages/platform-android/src/__tests__/ci-action.test.ts index 7647addb..9c520dc7 100644 --- a/packages/platform-android/src/__tests__/ci-action.test.ts +++ b/packages/platform-android/src/__tests__/ci-action.test.ts @@ -6,76 +6,52 @@ const workspaceRoot = path.resolve(import.meta.dirname, '../../../..'); describe('Android GitHub action config', () => { it('does not duplicate Android SDK verification in the action YAML', async () => { - const [rootAction, packageAction] = await Promise.all([ - readFile(path.join(workspaceRoot, 'action.yml'), 'utf8'), - readFile( - path.join(workspaceRoot, 'packages/github-action/src/action.yml'), - 'utf8' - ), - ]); - - for (const actionYaml of [rootAction, packageAction]) { - expect(actionYaml).not.toContain('Verify Android SDK packages'); - expect(actionYaml).toContain( - "steps.avd-cache.outputs.cache-hit != 'true'" - ); - } + const actionYaml = await readFile( + path.join(workspaceRoot, 'action.yml'), + 'utf8' + ); + + expect(actionYaml).not.toContain('Verify Android SDK packages'); + expect(actionYaml).toContain( + "steps.avd-cache.outputs.cache-hit != 'true'" + ); }); it('removes the third-party emulator runner and maps cacheAvd to HARNESS_AVD_CACHING', async () => { - const [rootAction, packageAction] = await Promise.all([ - readFile(path.join(workspaceRoot, 'action.yml'), 'utf8'), - readFile( - path.join(workspaceRoot, 'packages/github-action/src/action.yml'), - 'utf8' - ), - ]); - - for (const actionYaml of [rootAction, packageAction]) { - expect(actionYaml).not.toContain( - 'reactivecircus/android-emulator-runner' - ); - expect(actionYaml).toContain( - 'HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }}' - ); - expect(actionYaml).toContain( - 'fromJson(steps.load-config.outputs.config).action.avdCachingEnabled' - ); - } + const actionYaml = await readFile( + path.join(workspaceRoot, 'action.yml'), + 'utf8' + ); + + expect(actionYaml).not.toContain('reactivecircus/android-emulator-runner'); + expect(actionYaml).toContain('HARNESS_AVD_CACHING: ${{ inputs.cacheAvd }}'); + expect(actionYaml).toContain( + 'fromJson(steps.load-config.outputs.config).action.avdCachingEnabled' + ); }); it('saves the AVD cache after the Harness run step', async () => { - const [rootAction, packageAction] = await Promise.all([ - readFile(path.join(workspaceRoot, 'action.yml'), 'utf8'), - readFile( - path.join(workspaceRoot, 'packages/github-action/src/action.yml'), - 'utf8' - ), - ]); - - for (const actionYaml of [rootAction, packageAction]) { - expect(actionYaml.indexOf('- name: Run E2E tests')).toBeLessThan( - actionYaml.indexOf('- name: Save AVD cache') - ); - } + const actionYaml = await readFile( + path.join(workspaceRoot, 'action.yml'), + 'utf8' + ); + + expect(actionYaml.indexOf('- name: Run E2E tests')).toBeLessThan( + actionYaml.indexOf('- name: Save AVD cache') + ); }); it('uses a cache key that includes the emulator name', async () => { - const [rootAction, packageAction] = await Promise.all([ - readFile(path.join(workspaceRoot, 'action.yml'), 'utf8'), - readFile( - path.join(workspaceRoot, 'packages/github-action/src/action.yml'), - 'utf8' - ), - ]); - - for (const actionYaml of [rootAction, packageAction]) { - expect(actionYaml).toContain( - "AVD_NAME='${{ fromJson(steps.load-config.outputs.config).config.device.name }}'" - ); - expect(actionYaml).toContain( - 'CACHE_KEY="avd-$AVD_NAME-$ARCH-$AVD_CONFIG_HASH"' - ); - } + const actionYaml = await readFile( + path.join(workspaceRoot, 'action.yml'), + 'utf8' + ); + + expect(actionYaml).toContain( + "AVD_NAME='${{ fromJson(steps.load-config.outputs.config).config.device.name }}'" + ); + expect(actionYaml).toContain( + 'CACHE_KEY="avd-$AVD_NAME-$ARCH-$AVD_CONFIG_HASH"' + ); }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ae9b49d..55081f5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -318,6 +318,9 @@ importers: '@react-native-harness/bridge': specifier: workspace:* version: link:../bridge + '@react-native-harness/cache': + specifier: workspace:* + version: link:../cache '@react-native-harness/config': specifier: workspace:* version: link:../config @@ -369,22 +372,6 @@ importers: specifier: '*' version: 0.82.1(@babel/core@7.27.4)(@react-native-community/cli@20.0.0(typescript@5.9.3))(@react-native/metro-config@0.82.1)(@types/react@19.1.13)(react@19.2.3) - packages/github-action: - dependencies: - '@react-native-harness/cache': - specifier: workspace:* - version: link:../cache - '@react-native-harness/config': - specifier: workspace:* - version: link:../config - '@react-native-harness/platform-android': - specifier: workspace:* - version: link:../platform-android - devDependencies: - tsup: - specifier: ^8.5.1 - version: 8.5.1(@swc/core@1.5.29(@swc/helpers@0.5.17))(jiti@2.6.1)(postcss@8.5.6)(typescript@5.9.3)(yaml@2.8.0) - packages/jest: dependencies: '@jest/test-result': @@ -1389,306 +1376,150 @@ packages: cpu: [ppc64] os: [aix] - '@esbuild/aix-ppc64@0.27.2': - resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - '@esbuild/android-arm64@0.25.5': resolution: {integrity: sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==} engines: {node: '>=18'} cpu: [arm64] os: [android] - '@esbuild/android-arm64@0.27.2': - resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - '@esbuild/android-arm@0.25.5': resolution: {integrity: sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==} engines: {node: '>=18'} cpu: [arm] os: [android] - '@esbuild/android-arm@0.27.2': - resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - '@esbuild/android-x64@0.25.5': resolution: {integrity: sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==} engines: {node: '>=18'} cpu: [x64] os: [android] - '@esbuild/android-x64@0.27.2': - resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - '@esbuild/darwin-arm64@0.25.5': resolution: {integrity: sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] - '@esbuild/darwin-arm64@0.27.2': - resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - '@esbuild/darwin-x64@0.25.5': resolution: {integrity: sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==} engines: {node: '>=18'} cpu: [x64] os: [darwin] - '@esbuild/darwin-x64@0.27.2': - resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - '@esbuild/freebsd-arm64@0.25.5': resolution: {integrity: sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-arm64@0.27.2': - resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - '@esbuild/freebsd-x64@0.25.5': resolution: {integrity: sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] - '@esbuild/freebsd-x64@0.27.2': - resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - '@esbuild/linux-arm64@0.25.5': resolution: {integrity: sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==} engines: {node: '>=18'} cpu: [arm64] os: [linux] - '@esbuild/linux-arm64@0.27.2': - resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - '@esbuild/linux-arm@0.25.5': resolution: {integrity: sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==} engines: {node: '>=18'} cpu: [arm] os: [linux] - '@esbuild/linux-arm@0.27.2': - resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - '@esbuild/linux-ia32@0.25.5': resolution: {integrity: sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==} engines: {node: '>=18'} cpu: [ia32] os: [linux] - '@esbuild/linux-ia32@0.27.2': - resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - '@esbuild/linux-loong64@0.25.5': resolution: {integrity: sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==} engines: {node: '>=18'} cpu: [loong64] os: [linux] - '@esbuild/linux-loong64@0.27.2': - resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - '@esbuild/linux-mips64el@0.25.5': resolution: {integrity: sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] - '@esbuild/linux-mips64el@0.27.2': - resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - '@esbuild/linux-ppc64@0.25.5': resolution: {integrity: sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] - '@esbuild/linux-ppc64@0.27.2': - resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - '@esbuild/linux-riscv64@0.25.5': resolution: {integrity: sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] - '@esbuild/linux-riscv64@0.27.2': - resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - '@esbuild/linux-s390x@0.25.5': resolution: {integrity: sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==} engines: {node: '>=18'} cpu: [s390x] os: [linux] - '@esbuild/linux-s390x@0.27.2': - resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - '@esbuild/linux-x64@0.25.5': resolution: {integrity: sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==} engines: {node: '>=18'} cpu: [x64] os: [linux] - '@esbuild/linux-x64@0.27.2': - resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - '@esbuild/netbsd-arm64@0.25.5': resolution: {integrity: sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-arm64@0.27.2': - resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - '@esbuild/netbsd-x64@0.25.5': resolution: {integrity: sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] - '@esbuild/netbsd-x64@0.27.2': - resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - '@esbuild/openbsd-arm64@0.25.5': resolution: {integrity: sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-arm64@0.27.2': - resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - '@esbuild/openbsd-x64@0.25.5': resolution: {integrity: sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] - '@esbuild/openbsd-x64@0.27.2': - resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - - '@esbuild/openharmony-arm64@0.27.2': - resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - '@esbuild/sunos-x64@0.25.5': resolution: {integrity: sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==} engines: {node: '>=18'} cpu: [x64] os: [sunos] - '@esbuild/sunos-x64@0.27.2': - resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - '@esbuild/win32-arm64@0.25.5': resolution: {integrity: sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==} engines: {node: '>=18'} cpu: [arm64] os: [win32] - '@esbuild/win32-arm64@0.27.2': - resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - '@esbuild/win32-ia32@0.25.5': resolution: {integrity: sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==} engines: {node: '>=18'} cpu: [ia32] os: [win32] - '@esbuild/win32-ia32@0.27.2': - resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - '@esbuild/win32-x64@0.25.5': resolution: {integrity: sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==} engines: {node: '>=18'} cpu: [x64] os: [win32] - '@esbuild/win32-x64@0.27.2': - resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - '@eslint-community/eslint-utils@4.7.0': resolution: {integrity: sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -3593,9 +3424,6 @@ packages: resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==} engines: {node: '>=12'} - any-promise@1.3.0: - resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -3870,12 +3698,6 @@ packages: buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} - bundle-require@5.1.0: - resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - peerDependencies: - esbuild: '>=0.18' - bytes@3.1.2: resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} engines: {node: '>= 0.8'} @@ -3960,10 +3782,6 @@ packages: resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} engines: {node: '>= 8.10.0'} - chokidar@4.0.3: - resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} - engines: {node: '>= 14.16.0'} - chrome-launcher@0.15.2: resolution: {integrity: sha512-zdLEwNo3aUVzIhKhTtXfxhdvZhUghrnmkvcAq2NoDd+LeOHKf03H5jwZ8T/STsAlzyALkBVK552iaG1fGf1xVQ==} engines: {node: '>=12.13.0'} @@ -4074,10 +3892,6 @@ packages: commander@2.20.3: resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} - commander@4.1.1: - resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} - engines: {node: '>= 6'} - commander@7.2.0: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} @@ -4106,9 +3920,6 @@ packages: concat-with-sourcemaps@1.1.0: resolution: {integrity: sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg==} - confbox@0.1.8: - resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==} - confusing-browser-globals@1.0.11: resolution: {integrity: sha512-JsPKdmh8ZkmnHxDk55FZ1TqVLvEQTvoByJZRN9jzI0UjxK/QgAmsphz7PGtqgPieQZ/CQcHWXCR7ATDNhGe+YA==} @@ -4116,10 +3927,6 @@ packages: resolution: {integrity: sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==} engines: {node: '>= 0.10.0'} - consola@3.4.2: - resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} - engines: {node: ^14.18.0 || >=16.10.0} - content-disposition@0.5.4: resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} engines: {node: '>= 0.6'} @@ -4574,11 +4381,6 @@ packages: engines: {node: '>=18'} hasBin: true - esbuild@0.27.2: - resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==} - engines: {node: '>=18'} - hasBin: true - escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -4954,9 +4756,6 @@ packages: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} - fix-dts-default-cjs-exports@1.0.1: - resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} - flat-cache@4.0.1: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} @@ -5812,10 +5611,6 @@ packages: joi@17.13.3: resolution: {integrity: sha512-otDA4ldcIx+ZXsKHWmp0YizCweVRZG96J10b0FevjfuncLO1oX59THoAmHkNubYJ+9gWsYsp5k8v4ib6oDv1fA==} - joycon@3.1.1: - resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} - engines: {node: '>=10'} - js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -5998,10 +5793,6 @@ packages: resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==} engines: {node: '>=10'} - lilconfig@3.1.3: - resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} - engines: {node: '>=14'} - lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} @@ -6009,10 +5800,6 @@ packages: resolution: {integrity: sha512-cNOjgCnLB+FnvWWtyRTzmB3POJ+cXxTA81LoW7u8JdmhfXzriropYwpjShnz1QLLWsQwY7nIxoDmcPTwphDK9w==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - load-tsconfig@0.2.5: - resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - loader-runner@4.3.0: resolution: {integrity: sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==} engines: {node: '>=6.11.5'} @@ -6462,9 +6249,6 @@ packages: engines: {node: '>=10'} hasBin: true - mlly@1.8.0: - resolution: {integrity: sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==} - mrmime@2.0.1: resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} engines: {node: '>=10'} @@ -6475,9 +6259,6 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - mz@2.7.0: - resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} - nano-spawn@1.0.2: resolution: {integrity: sha512-21t+ozMQDAL/UGgQVBbZ/xXvNO10++ZPuTmKRO8k9V3AClVRht49ahtDjfY8l1q6nSHOrE5ASfthzH3ol6R/hg==} engines: {node: '>=20.17'} @@ -6814,9 +6595,6 @@ packages: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} - pkg-types@1.3.1: - resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} - pkg-up@3.1.0: resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==} engines: {node: '>=8'} @@ -6896,24 +6674,6 @@ packages: ts-node: optional: true - postcss-load-config@6.0.1: - resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} - engines: {node: '>= 18'} - peerDependencies: - jiti: '>=1.21.0' - postcss: '>=8.0.9' - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - jiti: - optional: true - postcss: - optional: true - tsx: - optional: true - yaml: - optional: true - postcss-merge-longhand@5.1.7: resolution: {integrity: sha512-YCI9gZB+PLNskrK0BB3/2OzPnGhPkBEwmwhfYk1ilBHYVAZB7/tkTHFBAnCrvBBOmeYyMYw3DMjT55SyxMBzjQ==} engines: {node: ^10 || ^12 || >=14.0} @@ -7273,10 +7033,6 @@ packages: resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} engines: {node: '>=8.10.0'} - readdirp@4.1.2: - resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} - engines: {node: '>= 14.18.0'} - recma-build-jsx@1.0.0: resolution: {integrity: sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew==} @@ -7808,11 +7564,6 @@ packages: styleq@0.1.3: resolution: {integrity: sha512-3ZUifmCDCQanjeej1f6kyl/BeP/Vae5EYkQ9iJfUm/QwZvlgnZzyflqAsAWYURdtea8Vkvswu2GrC57h3qffcA==} - sucrase@3.35.0: - resolution: {integrity: sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==} - engines: {node: '>=16 || 14 >=14.17'} - hasBin: true - supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} @@ -7882,13 +7633,6 @@ packages: resolution: {integrity: sha512-pFYqmTw68LXVjeWJMST4+borgQP2AyMNbg1BpZh9LbyhUeNkeaPF9gzfPGUAnSMV3qPYdWUwDIjjCLiSDOl7vg==} engines: {node: '>=18'} - thenify-all@1.6.0: - resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} - engines: {node: '>=0.8'} - - thenify@3.3.1: - resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} - throat@5.0.0: resolution: {integrity: sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==} @@ -7967,9 +7711,6 @@ packages: peerDependencies: typescript: '>=4.8.4' - ts-interface-checker@0.1.13: - resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} - tsconfig-paths@3.15.0: resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==} @@ -7984,25 +7725,6 @@ packages: resolution: {integrity: sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==} engines: {node: '>=0.6.x'} - tsup@8.5.1: - resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==} - engines: {node: '>=18'} - hasBin: true - peerDependencies: - '@microsoft/api-extractor': ^7.36.0 - '@swc/core': ^1 - postcss: ^8.4.12 - typescript: '>=4.5.0' - peerDependenciesMeta: - '@microsoft/api-extractor': - optional: true - '@swc/core': - optional: true - postcss: - optional: true - typescript: - optional: true - type-check@0.4.0: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} @@ -8059,9 +7781,6 @@ packages: resolution: {integrity: sha512-LbBDqdIC5s8iROCUjMbW1f5dJQTEFB1+KO9ogbvlb3nm9n4YHa5p4KTvFPWvh2Hs8gZMBuiB1/8+pdfe/tDPug==} hasBin: true - ufo@1.6.1: - resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==} - unbox-primitive@1.1.0: resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} engines: {node: '>= 0.4'} @@ -9427,156 +9146,78 @@ snapshots: '@esbuild/aix-ppc64@0.25.5': optional: true - '@esbuild/aix-ppc64@0.27.2': - optional: true - '@esbuild/android-arm64@0.25.5': optional: true - '@esbuild/android-arm64@0.27.2': - optional: true - '@esbuild/android-arm@0.25.5': optional: true - '@esbuild/android-arm@0.27.2': - optional: true - '@esbuild/android-x64@0.25.5': optional: true - '@esbuild/android-x64@0.27.2': - optional: true - '@esbuild/darwin-arm64@0.25.5': optional: true - '@esbuild/darwin-arm64@0.27.2': - optional: true - '@esbuild/darwin-x64@0.25.5': optional: true - '@esbuild/darwin-x64@0.27.2': - optional: true - '@esbuild/freebsd-arm64@0.25.5': optional: true - '@esbuild/freebsd-arm64@0.27.2': - optional: true - '@esbuild/freebsd-x64@0.25.5': optional: true - '@esbuild/freebsd-x64@0.27.2': - optional: true - '@esbuild/linux-arm64@0.25.5': optional: true - '@esbuild/linux-arm64@0.27.2': - optional: true - '@esbuild/linux-arm@0.25.5': optional: true - '@esbuild/linux-arm@0.27.2': - optional: true - '@esbuild/linux-ia32@0.25.5': optional: true - '@esbuild/linux-ia32@0.27.2': - optional: true - '@esbuild/linux-loong64@0.25.5': optional: true - '@esbuild/linux-loong64@0.27.2': - optional: true - '@esbuild/linux-mips64el@0.25.5': optional: true - '@esbuild/linux-mips64el@0.27.2': - optional: true - '@esbuild/linux-ppc64@0.25.5': optional: true - '@esbuild/linux-ppc64@0.27.2': - optional: true - '@esbuild/linux-riscv64@0.25.5': optional: true - '@esbuild/linux-riscv64@0.27.2': - optional: true - '@esbuild/linux-s390x@0.25.5': optional: true - '@esbuild/linux-s390x@0.27.2': - optional: true - '@esbuild/linux-x64@0.25.5': optional: true - '@esbuild/linux-x64@0.27.2': - optional: true - '@esbuild/netbsd-arm64@0.25.5': optional: true - '@esbuild/netbsd-arm64@0.27.2': - optional: true - '@esbuild/netbsd-x64@0.25.5': optional: true - '@esbuild/netbsd-x64@0.27.2': - optional: true - '@esbuild/openbsd-arm64@0.25.5': optional: true - '@esbuild/openbsd-arm64@0.27.2': - optional: true - '@esbuild/openbsd-x64@0.25.5': optional: true - '@esbuild/openbsd-x64@0.27.2': - optional: true - - '@esbuild/openharmony-arm64@0.27.2': - optional: true - '@esbuild/sunos-x64@0.25.5': optional: true - '@esbuild/sunos-x64@0.27.2': - optional: true - '@esbuild/win32-arm64@0.25.5': optional: true - '@esbuild/win32-arm64@0.27.2': - optional: true - '@esbuild/win32-ia32@0.25.5': optional: true - '@esbuild/win32-ia32@0.27.2': - optional: true - '@esbuild/win32-x64@0.25.5': optional: true - '@esbuild/win32-x64@0.27.2': - optional: true - '@eslint-community/eslint-utils@4.7.0(eslint@9.29.0(jiti@2.4.2))': dependencies: eslint: 9.29.0(jiti@2.4.2) @@ -12340,8 +11981,6 @@ snapshots: ansi-styles@6.2.1: {} - any-promise@1.3.0: {} - anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -12716,11 +12355,6 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 - bundle-require@5.1.0(esbuild@0.27.2): - dependencies: - esbuild: 0.27.2 - load-tsconfig: 0.2.5 - bytes@3.1.2: {} cac@6.7.14: {} @@ -12805,10 +12439,6 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - chokidar@4.0.3: - dependencies: - readdirp: 4.1.2 - chrome-launcher@0.15.2: dependencies: '@types/node': 20.19.25 @@ -12906,8 +12536,6 @@ snapshots: commander@2.20.3: {} - commander@4.1.1: {} - commander@7.2.0: {} commander@9.5.0: {} @@ -12938,8 +12566,6 @@ snapshots: dependencies: source-map: 0.6.1 - confbox@0.1.8: {} - confusing-browser-globals@1.0.11: {} connect@3.7.0: @@ -12951,8 +12577,6 @@ snapshots: transitivePeerDependencies: - supports-color - consola@3.4.2: {} - content-disposition@0.5.4: dependencies: safe-buffer: 5.2.1 @@ -13504,35 +13128,6 @@ snapshots: '@esbuild/win32-ia32': 0.25.5 '@esbuild/win32-x64': 0.25.5 - esbuild@0.27.2: - optionalDependencies: - '@esbuild/aix-ppc64': 0.27.2 - '@esbuild/android-arm': 0.27.2 - '@esbuild/android-arm64': 0.27.2 - '@esbuild/android-x64': 0.27.2 - '@esbuild/darwin-arm64': 0.27.2 - '@esbuild/darwin-x64': 0.27.2 - '@esbuild/freebsd-arm64': 0.27.2 - '@esbuild/freebsd-x64': 0.27.2 - '@esbuild/linux-arm': 0.27.2 - '@esbuild/linux-arm64': 0.27.2 - '@esbuild/linux-ia32': 0.27.2 - '@esbuild/linux-loong64': 0.27.2 - '@esbuild/linux-mips64el': 0.27.2 - '@esbuild/linux-ppc64': 0.27.2 - '@esbuild/linux-riscv64': 0.27.2 - '@esbuild/linux-s390x': 0.27.2 - '@esbuild/linux-x64': 0.27.2 - '@esbuild/netbsd-arm64': 0.27.2 - '@esbuild/netbsd-x64': 0.27.2 - '@esbuild/openbsd-arm64': 0.27.2 - '@esbuild/openbsd-x64': 0.27.2 - '@esbuild/openharmony-arm64': 0.27.2 - '@esbuild/sunos-x64': 0.27.2 - '@esbuild/win32-arm64': 0.27.2 - '@esbuild/win32-ia32': 0.27.2 - '@esbuild/win32-x64': 0.27.2 - escalade@3.2.0: {} escape-html@1.0.3: {} @@ -14079,12 +13674,6 @@ snapshots: locate-path: 6.0.0 path-exists: 4.0.0 - fix-dts-default-cjs-exports@1.0.1: - dependencies: - magic-string: 0.30.17 - mlly: 1.8.0 - rollup: 4.43.0 - flat-cache@4.0.1: dependencies: flatted: 3.3.3 @@ -15333,8 +14922,6 @@ snapshots: '@sideway/formula': 3.0.1 '@sideway/pinpoint': 2.0.0 - joycon@3.1.1: {} - js-tokens@4.0.0: {} js-tokens@9.0.1: {} @@ -15533,14 +15120,10 @@ snapshots: lilconfig@2.1.0: {} - lilconfig@3.1.3: {} - lines-and-columns@1.2.4: {} lines-and-columns@2.0.3: {} - load-tsconfig@0.2.5: {} - loader-runner@4.3.0: {} loader-utils@2.0.4: @@ -16336,25 +15919,12 @@ snapshots: mkdirp@1.0.4: {} - mlly@1.8.0: - dependencies: - acorn: 8.15.0 - pathe: 2.0.3 - pkg-types: 1.3.1 - ufo: 1.6.1 - mrmime@2.0.1: {} ms@2.0.0: {} ms@2.1.3: {} - mz@2.7.0: - dependencies: - any-promise: 1.3.0 - object-assign: 4.1.1 - thenify-all: 1.6.0 - nano-spawn@1.0.2: {} nanoid@3.3.11: {} @@ -16714,12 +16284,6 @@ snapshots: dependencies: find-up: 4.1.0 - pkg-types@1.3.1: - dependencies: - confbox: 0.1.8 - mlly: 1.8.0 - pathe: 2.0.3 - pkg-up@3.1.0: dependencies: find-up: 3.0.0 @@ -16786,14 +16350,6 @@ snapshots: optionalDependencies: postcss: 8.5.6 - postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(yaml@2.8.0): - dependencies: - lilconfig: 3.1.3 - optionalDependencies: - jiti: 2.6.1 - postcss: 8.5.6 - yaml: 2.8.0 - postcss-merge-longhand@5.1.7(postcss@8.5.6): dependencies: postcss: 8.5.6 @@ -17186,8 +16742,6 @@ snapshots: dependencies: picomatch: 2.3.1 - readdirp@4.1.2: {} - recma-build-jsx@1.0.0: dependencies: '@types/estree': 1.0.8 @@ -17872,16 +17426,6 @@ snapshots: styleq@0.1.3: {} - sucrase@3.35.0: - dependencies: - '@jridgewell/gen-mapping': 0.3.8 - commander: 4.1.1 - glob: 10.4.5 - lines-and-columns: 1.2.4 - mz: 2.7.0 - pirates: 4.0.7 - ts-interface-checker: 0.1.13 - supports-color@7.2.0: dependencies: has-flag: 4.0.0 @@ -17960,14 +17504,6 @@ snapshots: glob: 10.5.0 minimatch: 9.0.5 - thenify-all@1.6.0: - dependencies: - thenify: 3.3.1 - - thenify@3.3.1: - dependencies: - any-promise: 1.3.0 - throat@5.0.0: {} tinybench@2.9.0: {} @@ -18024,8 +17560,6 @@ snapshots: dependencies: typescript: 5.9.3 - ts-interface-checker@0.1.13: {} - tsconfig-paths@3.15.0: dependencies: '@types/json5': 0.0.29 @@ -18043,35 +17577,6 @@ snapshots: tsscmp@1.0.6: {} - tsup@8.5.1(@swc/core@1.5.29(@swc/helpers@0.5.17))(jiti@2.6.1)(postcss@8.5.6)(typescript@5.9.3)(yaml@2.8.0): - dependencies: - bundle-require: 5.1.0(esbuild@0.27.2) - cac: 6.7.14 - chokidar: 4.0.3 - consola: 3.4.2 - debug: 4.4.1 - esbuild: 0.27.2 - fix-dts-default-cjs-exports: 1.0.1 - joycon: 3.1.1 - picocolors: 1.1.1 - postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(yaml@2.8.0) - resolve-from: 5.0.0 - rollup: 4.43.0 - source-map: 0.7.6 - sucrase: 3.35.0 - tinyexec: 0.3.2 - tinyglobby: 0.2.15 - tree-kill: 1.2.2 - optionalDependencies: - '@swc/core': 1.5.29(@swc/helpers@0.5.17) - postcss: 8.5.6 - typescript: 5.9.3 - transitivePeerDependencies: - - jiti - - supports-color - - tsx - - yaml - type-check@0.4.0: dependencies: prelude-ls: 1.2.1 @@ -18141,8 +17646,6 @@ snapshots: ua-parser-js@1.0.41: {} - ufo@1.6.1: {} - unbox-primitive@1.1.0: dependencies: call-bound: 1.0.4 diff --git a/tsconfig.json b/tsconfig.json index acde8899..02cdd5eb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -57,9 +57,6 @@ { "path": "./packages/bundler-metro" }, - { - "path": "./packages/github-action" - }, { "path": "./packages/ui" }, diff --git a/website/src/docs/guides/ci-cd.md b/website/src/docs/guides/ci-cd.md index 982637e4..28889aad 100644 --- a/website/src/docs/guides/ci-cd.md +++ b/website/src/docs/guides/ci-cd.md @@ -19,7 +19,7 @@ React Native Harness provides an official GitHub Action that simplifies running - `callstackincubator/react-native-harness` :::tip Versioning -Pin the action to the **same [release tag](https://github.com/callstackincubator/react-native-harness/releases) as the `react-native-harness` version in your `package.json`** (for example package `1.0.0` → `uses: callstackincubator/react-native-harness@v1.0.0`). The composite action and the npm package are released together; matching them avoids subtle mismatches between CLI behavior and the workflow steps. +Pin the action to the **same [release tag](https://github.com/callstackincubator/react-native-harness/releases) as the `react-native-harness` version in your `package.json`** (for example package `1.0.0` → `uses: callstackincubator/react-native-harness@v1.0.0`). The composite action and the npm package are released together; matching them avoids subtle mismatches between CLI behavior and the workflow steps. The action invokes your project's own installed `react-native-harness` CLI rather than shipping bundled scripts, so action `@vX` requires `react-native-harness >= X` to be installed -- the action checks this itself and fails with a clear error on a mismatch. ::: The action automatically: From 5a100ad65042412d01651b39493185966ba883dd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 13 Aug 2026 12:02:12 +0200 Subject: [PATCH 2/2] fix: gate the action's CLI guard on a capability marker, not a version floor The action's react-native-harness compatibility check used a hard-coded MIN_VERSION compared via `sort -V`. That's unbootstrappable: it rejects the very release that introduces `harness ci` (this repo's own workspace packages carry the pre-release version until the release is cut), and `sort -V` also ranks prereleases of a compatible release below it. Replace the version floor with an explicit `harnessActionProtocol` marker on the `react-native-harness` package.json, which the action reads via the same `require.resolve` call it already makes. The two packages release in lockstep via `workspace:*`, so the marker can't drift from the CLI it describes, and the guard still fails fast (without ever invoking `harness ci` itself) when a project's installed CLI predates the CLI-based action. --- .../version-plan-1786612420017.md | 8 ++-- action.yml | 46 ++++++++++--------- docs/github-action.md | 4 +- .../__tests__/harness-action-protocol.test.ts | 26 +++++++++++ packages/react-native-harness/package.json | 4 ++ website/src/docs/guides/ci-cd.md | 2 +- 6 files changed, 64 insertions(+), 26 deletions(-) create mode 100644 packages/cli/src/ci/__tests__/harness-action-protocol.test.ts diff --git a/.nx/version-plans/version-plan-1786612420017.md b/.nx/version-plans/version-plan-1786612420017.md index cd44002b..106152e3 100644 --- a/.nx/version-plans/version-plan-1786612420017.md +++ b/.nx/version-plans/version-plan-1786612420017.md @@ -7,6 +7,8 @@ The `react-native-harness` CLI now exposes `harness ci ` which the official GitHub Action uses to run its configuration and Metro caching steps through your project's own installed CLI instead of bundled scripts checked into the action. As a result, the action now requires a -compatible `react-native-harness` version to be installed in the project it -runs against — keep the action ref and the `react-native-harness` package -version in sync, as already recommended. +`react-native-harness` install that supports this interface — it checks +this itself via a capability marker on the installed package rather than a +version number, and fails clearly when the installed CLI predates it. Keep +the action ref and the `react-native-harness` package version in sync, as +already recommended. diff --git a/action.yml b/action.yml index 0f945366..1f12e196 100644 --- a/action.yml +++ b/action.yml @@ -101,35 +101,39 @@ runs: echo "runner=npx " >> $GITHUB_OUTPUT fi # This action invokes the project's own installed react-native-harness CLI - # (via `harness ci ...`) instead of shipping bundled scripts, so the - # action ref and the installed package version must be compatible. On an - # older, pre-`ci`-subcommand CLI, `harness ci load-config` falls through - # to the Jest CLI and treats `ci` as a test path pattern -- silently - # running (zero) tests instead of failing -- so this guard must run - # before any `harness ci ...` step is invoked. - - name: Verify react-native-harness CLI version + # (via `harness ci ...`) instead of shipping bundled scripts, so a CLI + # that predates that interface must be rejected before it's ever + # invoked. On such a CLI, `harness ci load-config` falls through to the + # Jest CLI and treats `ci` as a test path pattern -- silently running + # (zero) tests instead of failing -- so this guard must run before any + # `harness ci ...` step, and it must NOT probe support by invoking + # `harness ci` itself and inspecting the result. + - name: Verify react-native-harness supports this action's CLI interface shell: bash working-directory: ${{ inputs.projectRoot || '.' }} run: | - # The `harness ci ` interface this action relies on ships - # starting with 1.5.0 (see the version plan for this change). On an - # older CLI, `harness ci load-config` falls through to the Jest CLI - # instead of failing, so this floor must match the exact release - # that introduced `ci`, not the release this action.yml happens to - # be edited in. - MIN_VERSION="1.5.0" + # Support is detected via an explicit capability marker + # (harnessActionProtocol) on the 'react-native-harness' package.json, + # not by comparing version numbers: a version floor can't be + # satisfied by the very release that introduces the capability it + # requires (this repo's own pre-release CI installs the in-tree + # workspace version), and it would also reject semver-correct + # prereleases of that release. Bump REQUIRED_PROTOCOL only when a + # change to the `harness ci` contract is breaking for this action. + REQUIRED_PROTOCOL=1 INSTALLED_VERSION=$(node -p "require(require.resolve('react-native-harness/package.json',{paths:[process.cwd()]})).version" 2>/dev/null) if [ -z "$INSTALLED_VERSION" ]; then echo "Error: could not resolve the 'react-native-harness' package in this project." - echo "This action requires react-native-harness >= $MIN_VERSION to be installed. Pin the action ref to the same release as the installed package." + echo "Pin the action ref to the same release as the installed react-native-harness package." exit 1 fi - # Note: `sort -V` ranks a prerelease like "1.5.0-beta.1" below - # "1.5.0", so a prerelease of the very release that introduces `ci` - # would be (correctly, if conservatively) rejected here. - LOWEST=$(printf '%s\n%s\n' "$MIN_VERSION" "$INSTALLED_VERSION" | sort -V | head -n1) - if [ "$LOWEST" != "$MIN_VERSION" ]; then - echo "Error: This action requires react-native-harness >= $MIN_VERSION (found $INSTALLED_VERSION). Pin the action ref to the same release as the installed package." + PROTOCOL=$(node -p "require(require.resolve('react-native-harness/package.json',{paths:[process.cwd()]})).harnessActionProtocol || 0" 2>/dev/null) + if [ -z "$PROTOCOL" ]; then + PROTOCOL=0 + fi + if [ "$PROTOCOL" -lt "$REQUIRED_PROTOCOL" ]; then + echo "Error: the installed react-native-harness ($INSTALLED_VERSION) predates this action's CLI-based interface (harness ci)." + echo "Align the action ref with the react-native-harness version installed in this project." exit 1 fi - name: Load React Native Harness configuration diff --git a/docs/github-action.md b/docs/github-action.md index b0dd956b..5ed4e515 100644 --- a/docs/github-action.md +++ b/docs/github-action.md @@ -19,7 +19,9 @@ The action reads your `rn-harness.config.mjs` file, resolves the `runner` you pa ### Version coupling -Starting with this release, the action invokes your project's own installed `react-native-harness` CLI (via `harness ci `) instead of shipping its own bundled scripts. This means action `@vX` requires `react-native-harness >= X` to be installed in the project the workflow runs against. The action verifies this itself as one of its first steps and fails with a clear error (rather than silently misbehaving) when the installed CLI is missing or too old. +Starting with this release, the action invokes your project's own installed `react-native-harness` CLI (via `harness ci `) instead of shipping its own bundled scripts. This means the action requires a `react-native-harness` install that supports that interface. Rather than comparing version numbers, the action checks for an explicit `harnessActionProtocol` capability marker in the installed package's `package.json` -- this avoids drift between "which release added the interface" and a hard-coded version floor, and correctly accepts prereleases of a compatible release. The action verifies this itself as one of its first steps and fails with a clear error (rather than silently misbehaving) when the installed CLI predates the CLI-based interface or can't be resolved at all. + +Keeping the action ref aligned with the `react-native-harness` version in your project's `package.json` (as described above) remains the right practice -- it just isn't what the action's compatibility check itself relies on. ## Inputs diff --git a/packages/cli/src/ci/__tests__/harness-action-protocol.test.ts b/packages/cli/src/ci/__tests__/harness-action-protocol.test.ts new file mode 100644 index 00000000..cc356380 --- /dev/null +++ b/packages/cli/src/ci/__tests__/harness-action-protocol.test.ts @@ -0,0 +1,26 @@ +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +// The 'react-native-harness' package.json declares `harnessActionProtocol` +// as a capability marker: the callstackincubator/react-native-harness +// GitHub Action reads it (see action.yml's "Verify react-native-harness +// supports this action's CLI interface" step) to confirm the installed CLI +// supports `harness ci ` before invoking it, instead of +// comparing version numbers -- a version floor can't be satisfied by the +// very release that introduces the capability it requires. This test exists +// so the marker isn't silently dropped in a future refactor of that +// package.json, which would make the action's guard reject every install. +describe('react-native-harness package.json harnessActionProtocol marker', () => { + it('declares a numeric harnessActionProtocol capability marker', async () => { + const workspaceRoot = path.resolve(import.meta.dirname, '../../../../..'); + const packageJsonPath = path.join( + workspaceRoot, + 'packages/react-native-harness/package.json' + ); + const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8')); + + expect(typeof packageJson.harnessActionProtocol).toBe('number'); + expect(packageJson.harnessActionProtocol).toBeGreaterThanOrEqual(1); + }); +}); diff --git a/packages/react-native-harness/package.json b/packages/react-native-harness/package.json index 89b0739f..3d19ef53 100644 --- a/packages/react-native-harness/package.json +++ b/packages/react-native-harness/package.json @@ -1,6 +1,10 @@ { "name": "react-native-harness", "version": "1.4.1", + "comments": { + "harnessActionProtocol": "Capability marker read by the callstackincubator/react-native-harness GitHub Action (see action.yml's 'Verify react-native-harness supports this action's CLI interface' step) to confirm the installed CLI supports the `harness ci ` interface the action invokes, instead of comparing version numbers. Bump only on a breaking change to that `harness ci` contract." + }, + "harnessActionProtocol": 1, "bin": { "react-native-harness": "./bin.js", "harness": "./bin.js" diff --git a/website/src/docs/guides/ci-cd.md b/website/src/docs/guides/ci-cd.md index 28889aad..f634f4ff 100644 --- a/website/src/docs/guides/ci-cd.md +++ b/website/src/docs/guides/ci-cd.md @@ -19,7 +19,7 @@ React Native Harness provides an official GitHub Action that simplifies running - `callstackincubator/react-native-harness` :::tip Versioning -Pin the action to the **same [release tag](https://github.com/callstackincubator/react-native-harness/releases) as the `react-native-harness` version in your `package.json`** (for example package `1.0.0` → `uses: callstackincubator/react-native-harness@v1.0.0`). The composite action and the npm package are released together; matching them avoids subtle mismatches between CLI behavior and the workflow steps. The action invokes your project's own installed `react-native-harness` CLI rather than shipping bundled scripts, so action `@vX` requires `react-native-harness >= X` to be installed -- the action checks this itself and fails with a clear error on a mismatch. +Pin the action to the **same [release tag](https://github.com/callstackincubator/react-native-harness/releases) as the `react-native-harness` version in your `package.json`** (for example package `1.0.0` → `uses: callstackincubator/react-native-harness@v1.0.0`). The composite action and the npm package are released together; matching them avoids subtle mismatches between CLI behavior and the workflow steps. The action invokes your project's own installed `react-native-harness` CLI rather than shipping bundled scripts, so it requires an install that supports that interface -- it checks this itself via a capability marker in the installed package (not a version comparison) and fails with a clear error when the installed CLI predates it. ::: The action automatically: