diff --git a/.changeset/install-without-peer-autoinstall.md b/.changeset/install-without-peer-autoinstall.md new file mode 100644 index 0000000..f3065e5 --- /dev/null +++ b/.changeset/install-without-peer-autoinstall.md @@ -0,0 +1,11 @@ +--- +'@reactivapp/cli': minor +--- + +One `npm install` for the whole project, and no more peers arriving uninvited. + +The app template now lists `app/` as an npm workspace of the project root, so `reactiv app init` and `reactiv app upgrade` run a single `npm install` at the root that installs the library's dependencies and the shell's platform into one `node_modules`. Adding a package is one command at the root; `app/package.json` pins the platform and declares nothing else, and the sync check reports a library package that still appears there instead of asking you to mirror it. The installed-version, nested-copy, podspec and lockfile checks read the root tree and the root `package-lock.json`. + +Every install also runs with `--legacy-peer-deps`, and the managed block the CLI writes into the project's `.npmrc` files sets `legacy-peer-deps=true` so your own `npm install` behaves the same way: npm no longer pulls in packages that a transitive dependency names as a peer. A fresh scaffold was failing with ERESOLVE when such a peer's newest release conflicted with the platform's `react-native`, even though nothing in the project used it. + +Projects scaffolded before this release do not list the workspace; the CLI says so and asks for a fresh `reactiv app init`, into which `src/` moves unchanged. This release needs an app template that carries the workspace; an older template is refused at `init` with the same hint. diff --git a/docs/commands.md b/docs/commands.md index 38153a3..2e6ba28 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -50,7 +50,7 @@ reactiv app init [--path ] [--bundle-id ] [--app-uuid ] [--skip-i | `--app-uuid` | Optional. The app UUID; defaults to the app your login is provisioned for (`reactiv whoami` shows it) and is refused when it differs. | | `--path` | Parent directory to scaffold into. Default: the current directory. | | `--bundle-id` | iOS bundle identifier. Default: `com.reactiv.`. | -| `--skip-install` | Skip `npm install` in the root and in `app/`. | +| `--skip-install` | Skip the `npm install` at the project root. | | `--package-manager` | Only `npm` is supported today. | What happens: @@ -58,7 +58,7 @@ What happens: 1. Your login decides the project identity, and nothing is asked: the merchant slug Reactiv provisioned for your key (lowercase letters, digits and dashes) becomes the folder name, the root package name, the app name in `reactiv.conf.js` and the shell, and the default bundle identifier; the app UUID comes from the same login. 2. The current platform version and its pinned `react` and `react-native` versions are read from the registry, and the template is downloaded with npm so the transcript shows where it came from. 3. The template is expanded into `/`, which must not exist or must be empty. A `git init` follows, and the CLI refuses to continue if the scaffold's `.gitignore` does not ignore `.npmrc`. -4. Dependencies are installed in the root and in `app/` with install scripts turned off. The CLI tells you which packages declared one so you can run `npm rebuild` in `app/` if the native build needs it. +4. Dependencies are installed once at the project root (`app/` is an npm workspace of it) with install scripts turned off, development dependencies included whatever `NODE_ENV` says, and without npm's automatic peer installation (`--legacy-peer-deps`), so a peer a transitive package asks for never enters the project uninvited. The CLI tells you which packages declared an install script so you can run `npm rebuild` at the project root if the native build needs it. 5. An initial commit is created. If anything fails, what this run created is removed so you can fix the cause and run again. ### `reactiv app run ios` @@ -74,7 +74,7 @@ reactiv app run ios [--skip-pods] [--simulator ] | `--skip-pods` | Skip `pod install`. | | `--simulator` | Simulator name to target, for example `"iPhone 16"`. Default: the booted iOS simulator when one is found; otherwise React Native's own choice. | -Before building, the CLI checks that `app/package.json` mirrors the library's dependencies, runs `pod install` in `app/ios`, checks that port 8081 is free, starts Metro in the background (log: `.reactiv-metro.log` in the project root) and runs `react-native run-ios` from `app/`. If the build fails, the Metro it started is stopped. This command does not refresh the registry token. +Before building, the CLI checks that `app/package.json` declares only the platform, runs `pod install` in `app/ios`, checks that port 8081 is free, starts Metro in the background (log: `.reactiv-metro.log` in the project root) and runs `react-native run-ios` from `app/`. If the build fails, the Metro it started is stopped. This command does not refresh the registry token. ### `reactiv app upgrade` @@ -91,7 +91,7 @@ reactiv app upgrade [--to ] What happens: 1. The target version and its pinned `react` and `react-native` are resolved from the registry. Without `--to`, a target older than the project's current version is refused. -2. `package.json` (`peerDependencies`) and `app/package.json` (`dependencies`) are updated to the new trio and both are reinstalled with install scripts off. +2. `package.json` (`peerDependencies`) and `app/package.json` (`dependencies`) are updated to the new trio and the project is reinstalled once at the root with install scripts off and `--legacy-peer-deps`. 3. The current template's toolchain files (`app/metro.config.js`, `app/babel.config.js`, `app/react-native.config.js`, `tsconfig.json`, `app/ios/Podfile`) are compared with yours. Differences are printed for you to apply by hand; the CLI does not overwrite them. 4. `npm run typecheck` runs at the project root. @@ -126,7 +126,7 @@ The checks are listed in [Project layout](project-layout.md#what-reactiv-app-sub | --- | --- | | `~/.config/reactiv/credentials.json` | Your API key and the merchant it belongs to. Mode `0600`. Removed by `reactiv logout`. | | `~/.cache/reactiv/token-cache.json` | The current registry token and its expiry. Mode `0600`. | -| `/.npmrc` and `/app/.npmrc` | A managed block between `# >>> reactiv` and `# <<< reactiv` markers holding the registry URLs and the token, so plain `npm install` works for the token's lifetime. The CLI refuses to write it into a file git does not ignore (where git can tell), into a symlink, or into a file readable by others (it makes the file `0600` first). Your own lines outside the block are kept, except `@reactivapp` and `@reactiv-submissions` registry lines and token lines for the registry host shape, which the block replaces. | +| `/.npmrc` and `/app/.npmrc` | A managed block between `# >>> reactiv` and `# <<< reactiv` markers holding the registry URLs, the token and `legacy-peer-deps=true`, so plain `npm install` works for the token's lifetime and resolves the same tree the CLI does. The CLI refuses to write it into a file git does not ignore (where git can tell), into a symlink, or into a file readable by others (it makes the file `0600` first). Your own lines outside the block are kept, except `@reactivapp` and `@reactiv-submissions` registry lines and token lines for the registry host shape, which the block replaces. | | `/.reactiv-metro.log` | Metro's output from `reactiv app run`. | Registry tokens are short-lived (up to 12 hours). `reactiv login` and `reactiv whoami` run inside a project, and `app init`, `app upgrade` and `app submit`, refresh the token when it is missing or about to expire; `app run` and a login that only validates `REACTIV_API_KEY` do not. The CLI only accepts registry URLs from Reactiv's token service that are https and match the expected registry host shape; anything else is refused and nothing is written. diff --git a/docs/getting-started.md b/docs/getting-started.md index 892d1c3..3d737fd 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -80,17 +80,18 @@ This installs pods, starts Metro, and launches the app on the booted simulator ( ## 5. Adding packages -Install at the root **and** in `app/`, always with an exact version: +Install at the project root, always with an exact version: ```bash npm install --save-exact date-fns@4.1.0 -cd app && npm install --save-exact date-fns@4.1.0 && cd .. ``` +`app/` is an npm workspace of the root, so the one install serves the library and the shell. + `reactiv app submit` checks that: - every package `src/` imports is declared in the root `package.json`, with an exact version (no `^`, `~`, tags, URLs or git links); -- `app/package.json` mirrors the library's dependencies, so what you ran is what you submit; +- `app/package.json` declares nothing but the platform; your packages live in the root `package.json`, so what you ran is what you submit; - nothing the platform already provides is listed: `react`, `react-native` and the Reactiv packages are supplied for you and stay in `peerDependencies`; - no dependency needs changes to the native iOS project, as far as the CLI can tell from a list of known libraries and your direct dependencies' CocoaPods podspecs. Pure JavaScript and TypeScript libraries are fine; a library with its own native setup cannot ship inside a customization, so ask Reactiv if you need one. @@ -121,7 +122,7 @@ reactiv app upgrade # move to the current platform release reactiv app upgrade --to 2610.9.3 # or pick a version ``` -The CLI updates the platform version in both `package.json` files, reinstalls, and runs your typecheck. Then run `cd app/ios && pod install`. If the project no longer checks clean, the change stays in place and the output ends with the exact command to roll back. +The CLI updates the platform version in both `package.json` files, reinstalls once at the root, and runs your typecheck. Then run `cd app/ios && pod install`. If the project no longer checks clean, the change stays in place and the output ends with the exact command to roll back. Some toolchain files (Metro, Babel, tsconfig, Podfile) are yours after the first install. When the current template differs, the CLI prints the new content and leaves the edit to you. diff --git a/docs/project-layout.md b/docs/project-layout.md index d17a291..cf11d79 100644 --- a/docs/project-layout.md +++ b/docs/project-layout.md @@ -5,14 +5,15 @@ ``` / ├── reactiv.conf.js app identity: appName and appUuid -├── package.json the library: what you submit +├── package.json the library: what you submit; lists app/ as an npm workspace +├── package-lock.json one lockfile for the library and the shell +├── node_modules/ one shared install ├── src/ │ └── index.ts must export CustomCompositions and registerCustomComponents ├── tsconfig.json ├── .npmrc generated, git-ignored, never committed └── app/ the runnable shell, never submitted - ├── package.json mirrors the library's dependencies and pins the platform - ├── package-lock.json + ├── package.json pins the platform; declares nothing else ├── ios/ ├── metro.config.js ├── babel.config.js @@ -28,12 +29,13 @@ The root `package.json` and `src/` are the submission. Its `name` is the merchan - `files`: `["src"]`. - `dependencies`: packages your code imports, each with an exact version. - `peerDependencies`: `@reactivapp/mobile`, `react` and `react-native` at the exact versions the app shell runs, plus any package the platform supplies that your code imports. +- `workspaces`: `["app"]`, so one `npm install` at the root installs the library's dependencies and the shell's platform into one `node_modules`. The CLI installs with `--legacy-peer-deps` and writes `legacy-peer-deps=true` into the project's managed `.npmrc` block, so npm never adds peers on its own, from the CLI or from your own `npm install`: a package your code needs is declared, never inherited. `src/index.ts` must export `CustomCompositions` and `registerCustomComponents` as named values. Type-only and default exports do not count. Everything your code imports by relative path must live under `src/`. ## The app shell (`app/`) -`app/` wraps the library in a real React Native app so you can run it. It depends on `@reactivapp/mobile`, the Reactiv platform package, at a pinned version, and delegates its Metro, Babel and React Native configuration to the platform's toolchain. It is never submitted. Its `package.json` must list the same dependencies as the library at the same versions, because native modules autolink from there. +`app/` wraps the library in a real React Native app so you can run it. It is an npm workspace of the root: its `package.json` depends on `@reactivapp/mobile`, the Reactiv platform package, at a pinned version, and on nothing else; the root install hoists the platform and your library's dependencies into one `node_modules`, and the shell delegates its Metro, Babel and React Native configuration to the platform's toolchain. It is never submitted. After the first install, the toolchain files are yours. `reactiv app upgrade` tells you when the current template's versions differ. @@ -42,9 +44,9 @@ After the first install, the toolchain files are yours. `reactiv app upgrade` te The checks run in this order. Steps 1 to 8 finish before the CLI contacts Reactiv; it then obtains a registry token (at which point the signed-in key must belong to this app's UUID and slug) and the next draft version, and steps 9 and 10 run on the staged copy before the publish. 1. **Project identity.** `reactiv.conf.js` exports `appUuid` and `appName`, and the name produces a usable slug. -2. **Layout.** `app/package.json` exists and the root manifest has a `files: ["src"]` entry and an entry point inside `src/`. -3. **Dependencies in sync.** The library's `dependencies` appear in `app/package.json` at the same versions; packages the platform provides are not in the library's `dependencies`; the platform trio is pinned identically in both; `app/node_modules` holds what the manifests declare, without duplicate copies. -4. **Submittable dependencies.** Every dependency is an exact registry version (no ranges, tags, URLs, git links or local paths); nothing in the `@reactivapp` or `@reactiv-submissions` scopes; no `overrides` in `app/package.json`; `app/package-lock.json` exists and records the installed platform version. +2. **Layout.** The root manifest lists `app` in `workspaces` and has a `files: ["src"]` entry and an entry point inside `src/`; `app/package.json` exists. +3. **Dependencies in sync.** `app/package.json` declares only the platform trio, never a library dependency; packages the platform provides are not in the library's `dependencies`; the platform trio is pinned identically in both; `node_modules` holds what the manifests declare, without duplicate copies. +4. **Submittable dependencies.** Every dependency is an exact registry version (no ranges, tags, URLs, git links or local paths); nothing in the `@reactivapp` or `@reactiv-submissions` scopes; no `overrides` in either manifest; `package-lock.json` exists and records the installed platform version. 5. **Native integration.** No dependency needs changes to the native project: a short list of known libraries with app-level setup is refused, and the CocoaPods podspecs of your direct dependencies are checked for build hooks. Gradle changes, Info.plist usage descriptions and entitlements are not detected here and are rejected at Reactiv's review instead. 6. **Forbidden content.** No `node_modules`, `build`, `dist`, `Pods`, `.git` or `DerivedData` under `src/`, and `src/` is not a symlink. 7. **Imports.** Every bare import in `src/` names a declared dependency or a platform package by its public entry, and every relative import stays inside `src/`. Node built-ins, package.json `imports` aliases, absolute paths and computed import specifiers are refused. Whether a relative import's target exists is not checked here; a missing file fails your typecheck and Reactiv's build. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index dafbbd1..4f21424 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -32,23 +32,23 @@ Add `.npmrc` (no leading slash) to `.gitignore` so both the root and `app/` copi ## `package.json dependencies must be exact versions` -Reinstall the package with `--save-exact`, at the root and in `app/`. +Reinstall the package with `--save-exact` at the project root. ## `src/ imports packages that package.json does not declare` -Install the named package at the root and in `app/`. The message shows the exact command. +Install the named package at the project root. The message shows the exact command. ## `package.json dependencies include packages the platform provides` Remove the named package from `dependencies`; it is supplied by the platform. The message tells you where it belongs. -## `app/package.json dependencies are out of sync with the library's package.json` +## `app/package.json declares packages that belong to the library's package.json` -Make both manifests declare the same packages at the same versions, then run `npm install` in `app/`. The message lists each difference. +Declare your packages in the root `package.json` only (`npm install --save-exact @` at the project root) and remove them from `app/package.json`; the shell pins nothing but the platform. The message names each one. -## `app/node_modules does not hold the declared versions` +## `node_modules does not hold the declared versions` -Run `npm install` in `app/`. +Run `npm install` at the project root. ## `entry point must export CustomCompositions and registerCustomComponents` diff --git a/packages/cli/src/commands/app/init.ts b/packages/cli/src/commands/app/init.ts index 49d61f0..57c976a 100644 --- a/packages/cli/src/commands/app/init.ts +++ b/packages/cli/src/commands/app/init.ts @@ -122,6 +122,12 @@ export class AppInit extends Command { reactNativeVersion, }) + const libraryManifest = fs.existsSync(path.join(targetDir, 'package.json')) ? readManifest(path.join(targetDir, 'package.json')) : {} + if (!Array.isArray(libraryManifest.workspaces) || !libraryManifest.workspaces.includes(APP_DIR)) { + throw new Error( + `the downloaded @reactivapp/app-template does not list ${APP_DIR}/ as an npm workspace — it predates the single-install layout this CLI expects; ask Reactiv to publish the current template`, + ) + } if (!fs.existsSync(path.join(targetDir, APP_DIR, 'package.json')) || !fs.existsSync(path.join(targetDir, 'src'))) { throw new Error( `the downloaded @reactivapp/app-template has no ${APP_DIR}/ shell or src/ library — it predates the library layout this CLI expects; ask Reactiv to publish the current template`, @@ -144,16 +150,14 @@ export class AppInit extends Command { assertSameRegistries(registry, await ensureRegistryAuth(ctx, targetDir)) if (!flags['skip-install']) { - this.log('Installing library dependencies (npm, root)…') + this.log(`Installing dependencies (npm, one install for the library and ${APP_DIR}/)…`) await installWithRegistryAuth(ctx, registry, targetDir, targetDir) if (!fs.existsSync(path.join(targetDir, 'node_modules', '@reactivapp', 'mobile', 'package.json'))) { - this.warn('the root install did not add the @reactivapp/mobile peer (is legacy-peer-deps set in your npm config?) — editor types and `npm run typecheck` need it; the app still runs') + throw new Error(`the install did not place @reactivapp/mobile@${platformVersion} in node_modules — ${APP_DIR}/package.json must depend on it and the root package.json must list ${APP_DIR} in workspaces`) } - this.log(`Installing app shell dependencies (npm, ${APP_DIR}/)…`) - await installWithRegistryAuth(ctx, registry, targetDir, path.join(targetDir, APP_DIR)) - const skipped = skippedInstallScripts(path.join(targetDir, APP_DIR)) + const skipped = skippedInstallScripts(targetDir) if (skipped.length > 0) { - this.warn(`install scripts were not run in ${APP_DIR}/ for: ${skipped.join(', ')} — run \`npm rebuild\` in ${APP_DIR}/ if the app fails to build`) + this.warn(`install scripts were not run for: ${skipped.join(', ')} — run \`npm rebuild\` at the project root if the app fails to build`) } } diff --git a/packages/cli/src/commands/app/upgrade.ts b/packages/cli/src/commands/app/upgrade.ts index 12cd113..78a2957 100644 --- a/packages/cli/src/commands/app/upgrade.ts +++ b/packages/cli/src/commands/app/upgrade.ts @@ -7,7 +7,7 @@ import {createAuthContext, reportAuthError} from '../../lib/auth/context' import {writeFileAtomic} from '../../lib/auth/files' import {ensureRegistryAuth, type RegistryAuth} from '../../lib/auth/token' import {BootstrapRegistry, installWithRegistryAuth, type RegistryOperation, skippedInstallScripts} from '../../lib/bootstrap-registry' -import {APP_DIR, assertDependenciesInSync, assertNpmrcFilesIgnored, readManifest, resolveLayout, type ProjectLayout} from '../../lib/layout' +import {APP_DIR, assertDependenciesInSync, assertNpmrcFilesIgnored, assertWorkspaceLayout, readManifest, resolveLayout, type ProjectLayout} from '../../lib/layout' import {npmEnv, runTee} from '../../lib/npm' import {loadProjectIdentity, PROJECT_CONFIG, type ProjectIdentity} from '../../lib/project' import {defaultBundleIdentifier} from '../../lib/scaffold' @@ -16,6 +16,7 @@ import { findDelegationSteps, formatDelegationSteps, isExactVersion, + type ManifestSection, type PlatformTrio, setPlatformVersions, } from '../../lib/upgrade' @@ -60,6 +61,7 @@ export class AppUpgrade extends Command { throw new Error(`${APP_DIR}/package.json does not depend on @reactivapp/mobile — this is not a scaffolded Reactiv Plus project`) } previous = installed + assertWorkspaceLayout(readManifest(libraryPath)) assertNpmrcFilesIgnored(projectRoot) } catch (error) { this.error(error instanceof Error ? error.message : String(error)) @@ -72,7 +74,7 @@ export class AppUpgrade extends Command { } const rollback = isExactVersion(previous) ? `reactiv app upgrade --to ${previous}` - : `restore package.json, ${APP_DIR}/package.json and both package-lock.json files from git (the previous @reactivapp/mobile "${previous}" was not an exact version), then run npm install in both` + : `restore package.json, ${APP_DIR}/package.json and package-lock.json from git (the previous @reactivapp/mobile "${previous}" was not an exact version), then run npm install at the project root` const ctx = createAuthContext(this) let auth: RegistryAuth @@ -126,7 +128,7 @@ export class AppUpgrade extends Command { this.log('Downloading @reactivapp/app-template…') const templateDir = await registry.fetchTemplate() - const edits: Array<[string, 'dependencies' | 'peerDependencies']> = [ + const edits: Array<[string, ManifestSection]> = [ [libraryPath, 'peerDependencies'], [appPath, 'dependencies'], ] @@ -148,14 +150,12 @@ export class AppUpgrade extends Command { } if (!changed) this.log(`package.json and ${APP_DIR}/package.json already declare @reactivapp/mobile@${target} and its peers — reinstalling to match`) - this.log('Installing library dependencies (npm, root)…') + this.log(`Installing dependencies (npm, one install for the library and ${APP_DIR}/)…`) started = true await installWithRegistryAuth(ctx, registry, projectRoot, projectRoot, UPGRADE_OPERATION) - this.log(`Installing app shell dependencies (npm, ${APP_DIR}/)…`) - await installWithRegistryAuth(ctx, registry, projectRoot, layout.appDir, UPGRADE_OPERATION) - const skipped = skippedInstallScripts(layout.appDir) + const skipped = skippedInstallScripts(projectRoot) if (skipped.length > 0) { - this.warn(`install scripts were not run in ${APP_DIR}/ for: ${skipped.join(', ')} — run \`npm rebuild\` in ${APP_DIR}/ if the app fails to build`) + this.warn(`install scripts were not run for: ${skipped.join(', ')} — run \`npm rebuild\` at the project root if the app fails to build`) } try { assertDependenciesInSync(layout) diff --git a/packages/cli/src/lib/auth/npmrc.ts b/packages/cli/src/lib/auth/npmrc.ts index 54c60bd..cd1c8b8 100644 --- a/packages/cli/src/lib/auth/npmrc.ts +++ b/packages/cli/src/lib/auth/npmrc.ts @@ -77,6 +77,7 @@ export const renderBlock = (block: RegistryBlock): string => { `${SUBMISSIONS_SCOPE}:registry=${submissions}`, `${authKey(tools)}=${token}`, `${authKey(submissions)}=${token}`, + 'legacy-peer-deps=true', BLOCK_END, ].join('\n') } diff --git a/packages/cli/src/lib/bootstrap-registry.ts b/packages/cli/src/lib/bootstrap-registry.ts index 8a3e5d8..025622d 100644 --- a/packages/cli/src/lib/bootstrap-registry.ts +++ b/packages/cli/src/lib/bootstrap-registry.ts @@ -136,7 +136,7 @@ export const installWithRegistryAuth = async ( cwd: string, operation: RegistryOperation = INIT_OPERATION, ): Promise => { - const installArgs = ['install', '--no-audit', '--no-fund', '--ignore-scripts', '--loglevel', NPM_LOGLEVEL] + const installArgs = ['install', '--no-audit', '--no-fund', '--ignore-scripts', '--legacy-peer-deps', '--include=dev', '--loglevel', NPM_LOGLEVEL] let result = await runTee('npm', installArgs, {cwd, env: npmEnv()}) if (result.status !== 0 && isRegistryAuthError(result.stderr) && takeRegistryRetry(ctx)) { assertSameRegistries(registry, await refreshAfterRegistryAuthError(ctx, projectRoot), operation) @@ -148,9 +148,12 @@ export const installWithRegistryAuth = async ( if (result.status !== 0) throw new Error(`npm install in ${path.relative(projectRoot, cwd) || '.'} exited with ${result.status}`) } -export const skippedInstallScripts = (appDir: string): string[] => { - const appScripts = (readManifest(path.join(appDir, 'package.json')).scripts ?? {}) as Record - const lockPath = path.join(appDir, 'package-lock.json') +export const skippedInstallScripts = (projectRoot: string): string[] => { + const scriptsOf = (manifestPath: string): Record => + fs.existsSync(manifestPath) ? ((readManifest(manifestPath).scripts ?? {}) as Record) : {} + const rootScripts = scriptsOf(path.join(projectRoot, 'package.json')) + const appScripts = scriptsOf(path.join(projectRoot, APP_DIR, 'package.json')) + const lockPath = path.join(projectRoot, 'package-lock.json') let lockPackages: Record = {} try { if (fs.existsSync(lockPath)) lockPackages = (readManifest(lockPath).packages ?? {}) as Record @@ -158,6 +161,7 @@ export const skippedInstallScripts = (appDir: string): string[] => { lockPackages = {} } return [ + ...['preinstall', 'install', 'postinstall', 'prepare'].filter(name => Object.hasOwn(rootScripts, name)).map(name => `package.json ${name}`), ...['preinstall', 'install', 'postinstall', 'prepare'].filter(name => Object.hasOwn(appScripts, name)).map(name => `${APP_DIR}/package.json ${name}`), ...Object.entries(lockPackages).filter(([, entry]) => entry.hasInstallScript).map(([key]) => key.replace(/^.*node_modules\//, '')), ] diff --git a/packages/cli/src/lib/imports.ts b/packages/cli/src/lib/imports.ts index 5f85e5c..0a1153d 100644 --- a/packages/cli/src/lib/imports.ts +++ b/packages/cli/src/lib/imports.ts @@ -3,7 +3,7 @@ import {builtinModules} from 'node:module' import * as path from 'node:path' import ts from 'typescript' -import {APP_DIR, LIBRARY_SOURCE_DIR, type ProjectLayout, readLibraryDependencies, readPlatformSupplied} from './layout.js' +import {LIBRARY_SOURCE_DIR, type ProjectLayout, readLibraryDependencies, readPlatformSupplied} from './layout.js' export const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'] @@ -120,7 +120,7 @@ const listSourceFiles = (dir: string): string[] => return entry.isFile() && SOURCE_EXTENSIONS.some(extension => entry.name.endsWith(extension)) ? [full] : [] }) -const installFix = (name: string): string => `run \`npm install --save-exact ${name}@\` at the project root and in ${APP_DIR}/` +const installFix = (name: string): string => `run \`npm install --save-exact ${name}@\` at the project root` export interface ImportCrossCheck { errors: string[] @@ -224,7 +224,7 @@ export const crossCheckImports = ( const warnings = Object.keys(declared) .filter(name => !imported.has(name)) .sort() - .map(name => `package.json declares ${name} but nothing in ${LIBRARY_SOURCE_DIR}/ imports it — if nothing needs it, remove it from package.json and ${APP_DIR}/package.json (it ships with the submission)`) + .map(name => `package.json declares ${name} but nothing in ${LIBRARY_SOURCE_DIR}/ imports it — if nothing needs it, remove it from package.json (it ships with the submission)`) return {errors, warnings} } diff --git a/packages/cli/src/lib/layout.ts b/packages/cli/src/lib/layout.ts index 8d0ff3a..ed2648e 100644 --- a/packages/cli/src/lib/layout.ts +++ b/packages/cli/src/lib/layout.ts @@ -106,12 +106,12 @@ export const findDependencyDrift = ( const libraryDeps = dependenciesOf(library, 'package.json') const appDeps = dependenciesOf(app, `${APP_DIR}/package.json`) const drift: DependencyDrift[] = [] - for (const [name, spec] of Object.entries(libraryDeps)) { - if (PLATFORM_PACKAGES.includes(name)) continue - if (appDeps[name] !== spec || !has(appDeps, name)) drift.push({name, library: spec, app: has(appDeps, name) ? appDeps[name] : undefined}) - } for (const [name, spec] of Object.entries(appDeps)) { - if (PLATFORM_PACKAGES.includes(name) || has(libraryDeps, name)) continue + if (PLATFORM_PACKAGES.includes(name)) continue + if (has(libraryDeps, name)) { + drift.push({name, library: libraryDeps[name], app: spec}) + continue + } if (platform.peers.has(name) && !platform.shipped.has(name)) { if (!has(libraryPeers, name)) drift.push({name, app: spec, platformPeer: true}) continue @@ -124,23 +124,20 @@ export const findDependencyDrift = ( export const formatDependencyDrift = (drift: DependencyDrift[]): string => { const lines = drift.map(({name, library, app, platformShipped, platformPeer, installed}) => { if (platformPeer) { - return ` ${name}: the platform expects the app to provide it — run \`npm install\` in ${APP_DIR}/, keep it in ${APP_DIR}/package.json and add its installed exact version ("${installed ?? app}" now) to package.json peerDependencies` + return ` ${name}: the platform expects the app to provide it — keep it in ${APP_DIR}/package.json and add its installed exact version ("${installed ?? app}" now) to package.json peerDependencies` } if (platformShipped) { return ` ${name}: the platform already ships it — remove it from ${APP_DIR}/package.json (declare it in package.json peerDependencies if src/ imports it)` } if (library === undefined) { - return ` ${name}: in ${APP_DIR}/package.json only — add "${name}": "${app}" to the root package.json dependencies (it ships with the submission), or remove it from ${APP_DIR}/package.json` - } - if (app === undefined) { - return ` ${name}: missing from ${APP_DIR}/package.json — add "${name}": "${library}" to its dependencies` + return ` ${name}: in ${APP_DIR}/package.json only — run \`npm install --save-exact ${name}@${app}\` at the project root so it ships with the submission, and remove it from ${APP_DIR}/package.json` } - return ` ${name}: "${library}" in package.json but "${app}" in ${APP_DIR}/package.json — set ${APP_DIR}/package.json to "${library}"` + return ` ${name}: already declared in package.json ("${library}") — remove it from ${APP_DIR}/package.json; the workspace installs it once from the root` }) return [ - `${APP_DIR}/package.json dependencies are out of sync with the library's package.json:`, + `${APP_DIR}/package.json declares packages that belong to the library's package.json (the shell pins only the platform):`, ...lines, - `then run \`npm install\` in ${APP_DIR}/ (native modules only autolink from ${APP_DIR}/package.json)`, + 'then run `npm install` at the project root', ].join('\n') } @@ -171,37 +168,37 @@ export const formatPeerDrift = (drift: PeerDrift[]): string => ].join('\n') const readPlatformManifest = (layout: ProjectLayout): Manifest => { - const manifestPath = path.join(layout.appDir, 'node_modules', '@reactivapp', 'mobile', 'package.json') + const manifestPath = path.join(layout.root, 'node_modules', '@reactivapp', 'mobile', 'package.json') if (!fs.existsSync(manifestPath)) { - throw new Error(`@reactivapp/mobile is not installed in ${APP_DIR}/ — run \`npm install\` in ${APP_DIR}/`) + throw new Error(`@reactivapp/mobile is not installed — run \`npm install\` at the project root`) } return readManifest(manifestPath) } const readPlatformAliases = (layout: ProjectLayout): string[] => { - const file = path.join(layout.appDir, 'node_modules', '@reactivapp', 'mobile', 'toolchain', 'aliases.json') + const file = path.join(layout.root, 'node_modules', '@reactivapp', 'mobile', 'toolchain', 'aliases.json') let raw: string try { raw = fs.readFileSync(file, 'utf8') } catch (error) { const code = (error as NodeJS.ErrnoException).code if (code === 'ENOENT') return [] - throw new Error(`${file} could not be read (${code ?? 'unknown error'}) — reinstall @reactivapp/mobile in ${APP_DIR}/`) + throw new Error(`${file} could not be read (${code ?? 'unknown error'}) — reinstall with \`npm install\` at the project root`) } let parsed: unknown try { parsed = JSON.parse(raw) } catch { - throw new Error(`${file} is not valid JSON — reinstall @reactivapp/mobile in ${APP_DIR}/`) + throw new Error(`${file} is not valid JSON — reinstall with \`npm install\` at the project root`) } const aliases = (parsed as {libAliases?: unknown} | null)?.libAliases if (typeof aliases !== 'object' || aliases === null || Array.isArray(aliases)) { - throw new Error(`${file} has no "libAliases" object — reinstall @reactivapp/mobile in ${APP_DIR}/`) + throw new Error(`${file} has no "libAliases" object — reinstall with \`npm install\` at the project root`) } const names = Object.keys(aliases) const malformed = names.filter(name => !/^@[a-z0-9-]+$/.test(name)) if (malformed.length > 0) { - throw new Error(`${file} lists alias names that are not scope-shaped (${malformed.join(', ')}) — reinstall @reactivapp/mobile in ${APP_DIR}/`) + throw new Error(`${file} lists alias names that are not scope-shaped (${malformed.join(', ')}) — reinstall with \`npm install\` at the project root`) } return names } @@ -228,16 +225,26 @@ const installedVersion = (manifestPath: string): string | undefined => { if (!fs.existsSync(manifestPath)) return undefined const {version} = readManifest(manifestPath) if (typeof version !== 'string' || version === '') { - throw new Error(`${manifestPath} has no version — the install is damaged; run \`npm install\` in ${APP_DIR}/`) + throw new Error(`${manifestPath} has no version — the install is damaged; run \`npm install\` at the project root`) } return version } const nestedPlatformCopy = (layout: ProjectLayout, name: string): string => - path.join(layout.appDir, 'node_modules', '@reactivapp', 'mobile', 'node_modules', name, 'package.json') + path.join(layout.root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', name, 'package.json') + +export const assertWorkspaceLayout = (library: Manifest): void => { + const workspaces = library.workspaces + if (!Array.isArray(workspaces) || !workspaces.includes(APP_DIR)) { + throw new Error( + `package.json does not list "${APP_DIR}" in workspaces — this project was scaffolded before the single-install layout; run \`reactiv app init\` again and move src/ into the new project`, + ) + } +} export const assertDependenciesInSync = (layout: ProjectLayout): void => { const library = readManifest(path.join(layout.root, 'package.json')) + assertWorkspaceLayout(library) const app = readManifest(path.join(layout.appDir, 'package.json')) const libraryDeps = dependenciesOf(library, 'package.json') const platform = readPlatformManifest(layout) @@ -264,7 +271,7 @@ export const assertDependenciesInSync = (layout: ProjectLayout): void => { ) } const drift = findDependencyDrift(library, app, {shipped: shippedByPlatform, peers: supplied}).map(entry => - entry.platformPeer ? {...entry, installed: installedVersion(path.join(layout.appDir, 'node_modules', entry.name, 'package.json'))} : entry, + entry.platformPeer ? {...entry, installed: installedVersion(path.join(layout.root, 'node_modules', entry.name, 'package.json'))} : entry, ) if (drift.length > 0) throw new Error(formatDependencyDrift(drift)) const unlistedPeers = Object.entries(peersOf(library)).filter( @@ -275,7 +282,7 @@ export const assertDependenciesInSync = (layout: ProjectLayout): void => { [ `${APP_DIR}/package.json must list the peers the app provides (native modules only autolink from there):`, ...unlistedPeers.map(([name, spec]) => ` ${name}: add "${name}": "${spec}" to ${APP_DIR}/package.json dependencies`), - `then run \`npm install\` in ${APP_DIR}/`, + `then run \`npm install\` at the project root`, ].join('\n'), ) } @@ -284,29 +291,29 @@ export const assertDependenciesInSync = (layout: ProjectLayout): void => { const nestedFixes = Object.entries(libraryDeps).flatMap(([name, spec]) => { const nested = installedVersion(nestedPlatformCopy(layout, name)) if (nested === undefined) return [] - const hoisted = installedVersion(path.join(layout.appDir, 'node_modules', name, 'package.json')) - if (hoisted === nested) return [`${name}: both copies are ${nested} — run \`npm dedupe\` in ${APP_DIR}/ so one copy remains`] - if (nested === spec) return [`${name}: run \`npm install\` and then \`npm dedupe\` in ${APP_DIR}/ so one ${nested} copy remains`] - return [`${name}: the platform uses ${nested} — pin package.json and ${APP_DIR}/package.json to "${nested}" (now "${spec}"), then run \`npm install\` and \`npm dedupe\` in ${APP_DIR}/`] + const hoisted = installedVersion(path.join(layout.root, 'node_modules', name, 'package.json')) + if (hoisted === nested) return [`${name}: both copies are ${nested} — run \`npm dedupe\` at the project root so one copy remains`] + if (nested === spec) return [`${name}: run \`npm install\` and then \`npm dedupe\` at the project root so one ${nested} copy remains`] + return [`${name}: the platform uses ${nested} — pin package.json to "${nested}" (now "${spec}"), then run \`npm install\` and \`npm dedupe\` at the project root`] }) if (nestedFixes.length > 0) { throw new Error( - `the platform keeps its own copy under ${APP_DIR}/node_modules/@reactivapp/mobile/node_modules, so two copies would be bundled:\n${nestedFixes.map(line => ` ${line}`).join('\n')}`, + `the platform keeps its own copy under node_modules/@reactivapp/mobile/node_modules, so two copies would be bundled:\n${nestedFixes.map(line => ` ${line}`).join('\n')}`, ) } const appDeps = appDepsOfShell const staleTrio = PLATFORM_PACKAGES.filter(name => { - const version = installedVersion(path.join(layout.appDir, 'node_modules', name, 'package.json')) + const version = installedVersion(path.join(layout.root, 'node_modules', name, 'package.json')) return EXACT_VERSION.test(appDeps[name]) && version !== undefined && version !== appDeps[name] }) if (staleTrio.length > 0) { - throw new Error(`${APP_DIR}/node_modules does not hold the ${staleTrio.map(name => `${name}@${appDeps[name]}`).join(', ')} that ${APP_DIR}/package.json declares — run \`npm install\` in ${APP_DIR}/`) + throw new Error(`node_modules does not hold the ${staleTrio.map(name => `${name}@${appDeps[name]}`).join(', ')} that ${APP_DIR}/package.json declares — run \`npm install\` at the project root`) } const notInstalled = [...PLATFORM_PACKAGES.filter(name => name !== '@reactivapp/mobile'), ...Object.keys(libraryDeps)].filter( - name => !fs.existsSync(path.join(layout.appDir, 'node_modules', name, 'package.json')), + name => !fs.existsSync(path.join(layout.root, 'node_modules', name, 'package.json')), ) if (notInstalled.length > 0) { - throw new Error(`${notInstalled.join(', ')} ${plural(notInstalled, 'is', 'are')} declared but not installed in ${APP_DIR}/ — run \`npm install\` in ${APP_DIR}/`) + throw new Error(`${notInstalled.join(', ')} ${plural(notInstalled, 'is', 'are')} declared but not installed — run \`npm install\` at the project root`) } } @@ -330,19 +337,21 @@ export const assertSubmittableDependencies = (layout: ProjectLayout): void => { const unpinned = Object.entries(libraryDeps).filter(([, spec]) => !EXACT_VERSION.test(spec)) if (unpinned.length > 0) { throw new Error( - `package.json dependencies must be exact versions (review approves exactly what installs) — pin ${unpinned.map(([name, spec]) => `${name} (now "${spec}")`).join(', ')} in package.json and ${APP_DIR}/package.json, e.g. \`npm install --save-exact @\` in both`, + `package.json dependencies must be exact versions (review approves exactly what installs) — pin ${unpinned.map(([name, spec]) => `${name} (now "${spec}")`).join(', ')} in package.json, e.g. \`npm install --save-exact @\` at the project root`, ) } const app = readManifest(path.join(layout.appDir, 'package.json')) - if (app.overrides !== undefined) { - throw new Error(`${APP_DIR}/package.json "overrides" cannot be submitted alongside — the merchant build installs the library's declared versions only; remove the overrides and test again`) + for (const [label, manifest] of [['package.json', library], [`${APP_DIR}/package.json`, app]] as const) { + if (manifest.overrides !== undefined) { + throw new Error(`${label} "overrides" cannot be submitted alongside — the merchant build installs the library's declared versions only; remove the overrides and test again`) + } } const stale = Object.entries(libraryDeps).filter(([name, spec]) => { - const manifestPath = path.join(layout.appDir, 'node_modules', name, 'package.json') + const manifestPath = path.join(layout.root, 'node_modules', name, 'package.json') return installedVersion(manifestPath) !== spec || readManifest(manifestPath).name !== name }) if (stale.length > 0) { - throw new Error(`${APP_DIR}/node_modules does not hold the declared versions of ${stale.map(([name, spec]) => `${name}@${spec}`).join(', ')} — run \`npm install\` in ${APP_DIR}/ and test again before submitting`) + throw new Error(`node_modules does not hold the declared versions of ${stale.map(([name, spec]) => `${name}@${spec}`).join(', ')} — run \`npm install\` at the project root and test again before submitting`) } const platform = readPlatformManifest(layout) const supplied = platformSupplied(platform) @@ -356,32 +365,32 @@ export const assertSubmittableDependencies = (layout: ProjectLayout): void => { } const peerFixes = Object.entries(peers).flatMap(([name, spec]) => { if (PLATFORM_PACKAGES.includes(name)) return [] - const hoisted = installedVersion(path.join(layout.appDir, 'node_modules', name, 'package.json')) + const hoisted = installedVersion(path.join(layout.root, 'node_modules', name, 'package.json')) const nested = installedVersion(nestedPlatformCopy(layout, name)) if (hoisted !== undefined && nested !== undefined && hoisted !== nested) { const fix = shippedByPlatform.has(name) - ? `run \`npm ls ${name}\` in ${APP_DIR}/ to find the library dependency that pulls in ${hoisted}; pin a version of it compatible with ${nested} or remove it, then run \`npm dedupe\`` - : `set ${APP_DIR}/package.json to "${nested}" and run \`npm install\` and \`npm dedupe\` in ${APP_DIR}/` - return [`${name}: two copies in ${APP_DIR}/ (${hoisted} for src/, ${nested} for the platform) — ${fix}`] + ? `run \`npm ls ${name}\` at the project root to find the library dependency that pulls in ${hoisted}; pin a version of it compatible with ${nested} or remove it, then run \`npm dedupe\`` + : `set ${APP_DIR}/package.json to "${nested}" and run \`npm install\` and \`npm dedupe\` at the project root` + return [`${name}: two copies in node_modules (${hoisted} for src/, ${nested} for the platform) — ${fix}`] } const version = hoisted ?? nested - if (version === undefined) return [`${name}: not installed in ${APP_DIR}/ — run \`npm install\` in ${APP_DIR}/`] + if (version === undefined) return [`${name}: not installed — run \`npm install\` at the project root`] return spec === version ? [] : [`${name}: "${spec}" — set it to "${version}", the version the platform uses`] }) if (peerFixes.length > 0) { throw new Error(`package.json peerDependencies must name the exact version the platform uses:\n${peerFixes.map(line => ` ${line}`).join('\n')}`) } - const lockfilePath = path.join(layout.appDir, 'package-lock.json') + const lockfilePath = path.join(layout.root, 'package-lock.json') if (!fs.existsSync(lockfilePath)) { - throw new Error(`${APP_DIR}/package-lock.json not found — run \`npm install\` (npm 7 or later) in ${APP_DIR}/ and test again before submitting`) + throw new Error(`package-lock.json not found — run \`npm install\` (npm 7 or later) at the project root and test again before submitting`) } const lockfile = readManifest(lockfilePath) as {packages?: Record} const lockedPlatform = lockfile.packages?.['node_modules/@reactivapp/mobile']?.version if (lockfile.packages === undefined) { - throw new Error(`${APP_DIR}/package-lock.json predates npm 7 — run \`npm install\` with npm 7 or later in ${APP_DIR}/`) + throw new Error(`package-lock.json predates npm 7 — run \`npm install\` with npm 7 or later at the project root`) } if (lockedPlatform === undefined) { - throw new Error(`${APP_DIR}/package-lock.json records no installed @reactivapp/mobile — run \`npm install\` in ${APP_DIR}/`) + throw new Error(`package-lock.json records no installed @reactivapp/mobile — run \`npm install\` at the project root`) } const loosePlatformPeers = PLATFORM_PACKAGES.filter(name => !EXACT_VERSION.test(peers[name] ?? '')) if (loosePlatformPeers.length > 0) { @@ -390,6 +399,6 @@ export const assertSubmittableDependencies = (layout: ProjectLayout): void => { ) } if (platform.version !== lockedPlatform) { - throw new Error(`${APP_DIR}/node_modules holds @reactivapp/mobile@${String(platform.version)} but ${APP_DIR}/package-lock.json records ${lockedPlatform} — run \`npm install\` in ${APP_DIR}/ and test again before submitting`) + throw new Error(`node_modules holds @reactivapp/mobile@${String(platform.version)} but package-lock.json records ${lockedPlatform} — run \`npm install\` at the project root and test again before submitting`) } } diff --git a/packages/cli/src/lib/native-integration.ts b/packages/cli/src/lib/native-integration.ts index cc9e910..e7b29d5 100644 --- a/packages/cli/src/lib/native-integration.ts +++ b/packages/cli/src/lib/native-integration.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs' import * as path from 'node:path' -import {APP_DIR, type ProjectLayout, readLibraryDependencies} from './layout.js' +import {type ProjectLayout, readLibraryDependencies} from './layout.js' export const KNOWN_NATIVE_INTEGRATION_LIBRARIES = [ '@react-native-firebase/app', @@ -81,14 +81,14 @@ export const podspecNativeHook = (content: string, fileName = 'x.podspec'): stri return undefined } -export const findNativeIntegration = (appDir: string, dependencies: Record): string[] => { - const shown = (file: string): string => path.relative(path.dirname(appDir), file).split(path.sep).join('/') +export const findNativeIntegration = (projectRoot: string, dependencies: Record): string[] => { + const shown = (file: string): string => path.relative(projectRoot, file).split(path.sep).join('/') const unreadable = (file: string): string => `${shown(file)} ${UNREADABLE}` return Object.keys(dependencies) .sort() .flatMap(name => { if (KNOWN_NATIVE_INTEGRATION_LIBRARIES.includes(name)) return [` ${name}: needs app-level native setup (AppDelegate, Podfile or Info.plist changes)`] - const packageDir = path.join(appDir, 'node_modules', name) + const packageDir = path.join(projectRoot, 'node_modules', name) if (!fs.existsSync(packageDir) || !fs.statSync(packageDir).isDirectory()) return [] const {podspecs, unreadable: unreadableDirs} = findPodspecs(packageDir) return [ @@ -108,7 +108,7 @@ export const findNativeIntegration = (appDir: string, dependencies: Record { - const findings = findNativeIntegration(layout.appDir, readLibraryDependencies(layout)) + const findings = findNativeIntegration(layout.root, readLibraryDependencies(layout)) if (findings.length === 0) return const unreadable = findings.filter(finding => finding.endsWith(UNREADABLE)) const native = findings.filter(finding => !finding.endsWith(UNREADABLE)) @@ -116,9 +116,9 @@ export const assertNoAppNativeIntegration = (layout: ProjectLayout): void => { [ ...(native.length > 0 ? ['package.json dependencies include libraries that require native project changes a customization cannot ship — contact Reactiv:', ...native] : []), ...(unreadable.length > 0 - ? [`package.json dependencies include files in ${APP_DIR}/node_modules that could not be read — fix their permissions (or reinstall with \`npm install\` in ${APP_DIR}/) and try again:`, ...unreadable] + ? ['package.json dependencies include files in node_modules that could not be read — fix their permissions (or reinstall with `npm install` at the project root) and try again:', ...unreadable] : []), - `This check reads CocoaPods podspecs in ${APP_DIR}/node_modules and a short list of known libraries; a library that needs Gradle changes, Info.plist usage descriptions or entitlements is not detected here and is rejected at Reactiv's review instead.`, + "This check reads CocoaPods podspecs in node_modules and a short list of known libraries; a library that needs Gradle changes, Info.plist usage descriptions or entitlements is not detected here and is rejected at Reactiv's review instead.", ].join('\n'), ) } diff --git a/packages/cli/src/lib/submission.ts b/packages/cli/src/lib/submission.ts index 742e564..a97eabe 100644 --- a/packages/cli/src/lib/submission.ts +++ b/packages/cli/src/lib/submission.ts @@ -10,16 +10,16 @@ import {captureAll, type CaptureAllResult, NPM_LOGLEVEL, npmEnv} from './npm.js' export const DEFAULT_SIZE_CAP_MB = 5 export const readPlatformVersionFromLockfile = (appDir: string): string => { - const lockfilePath = path.join(appDir, 'package-lock.json') + const lockfilePath = path.join(path.dirname(appDir), 'package-lock.json') if (!fs.existsSync(lockfilePath)) { - throw new Error(`${APP_DIR}/package-lock.json not found — run npm install in ${APP_DIR}/ first`) + throw new Error('package-lock.json not found — run npm install at the project root first') } const lockfile = JSON.parse(fs.readFileSync(lockfilePath, 'utf8')) as { packages?: Record } const entry = lockfile.packages?.['node_modules/@reactivapp/mobile'] if (!entry?.version) { - throw new Error(`@reactivapp/mobile not found in ${APP_DIR}/package-lock.json — run npm install in ${APP_DIR}/ first`) + throw new Error('@reactivapp/mobile not found in package-lock.json — run npm install at the project root first') } return entry.version } diff --git a/packages/cli/src/lib/upgrade.ts b/packages/cli/src/lib/upgrade.ts index 572f600..e4a1ecf 100644 --- a/packages/cli/src/lib/upgrade.ts +++ b/packages/cli/src/lib/upgrade.ts @@ -58,7 +58,9 @@ const splitVersion = (version: string): [string[], string | undefined] => { const detectIndent = (text: string): string | number => /^([ \t]+)"/m.exec(text)?.[1] ?? (text.trim().includes('\n') ? 2 : 0) -export const setPlatformVersions = (text: string, section: 'dependencies' | 'peerDependencies', trio: PlatformTrio): string => { +export type ManifestSection = 'dependencies' | 'peerDependencies' | 'devDependencies' + +export const setPlatformVersions = (text: string, section: ManifestSection, trio: PlatformTrio): string => { const manifest = JSON.parse(text) as Record const current = manifest[section] const entries = typeof current === 'object' && current !== null && !Array.isArray(current) ? (current as Record) : {} diff --git a/packages/cli/test/auth/npmrc.test.ts b/packages/cli/test/auth/npmrc.test.ts index 8b4b39c..1ddbebc 100644 --- a/packages/cli/test/auth/npmrc.test.ts +++ b/packages/cli/test/auth/npmrc.test.ts @@ -38,6 +38,7 @@ describe('renderBlock', () => { `@reactiv-submissions:registry=${REGISTRY_URL}`, `//${REGISTRY_HOST}/npm/tools/:_authToken=${TOKEN}`, `//${REGISTRY_HOST}/npm/submissions-acme/:_authToken=${TOKEN}`, + 'legacy-peer-deps=true', BLOCK_END, ]) expect(BLOCK_START).toBe('# >>> reactiv (managed — do not edit; run `reactiv login` to refresh) >>>') diff --git a/packages/cli/test/helpers/npm-shim.ts b/packages/cli/test/helpers/npm-shim.ts index 4207967..cf5267d 100644 --- a/packages/cli/test/helpers/npm-shim.ts +++ b/packages/cli/test/helpers/npm-shim.ts @@ -50,12 +50,21 @@ case "$1" in install) if grep -q 'CODEARTIFACT_AUTH_TOKEN' .npmrc 2>/dev/null; then echo "install saw a placeholder token line" >&2; exit 1; fi if ! grep -q '>>> reactiv' .npmrc 2>/dev/null; then echo "install ran without the managed block" >&2; exit 1; fi - node -e " + LEGACY_PEER_DEPS=0; for arg in "$@"; do [ "$arg" = "--legacy-peer-deps" ] && LEGACY_PEER_DEPS=1; done + SHIM_LEGACY_PEER_DEPS=$LEGACY_PEER_DEPS node -e " const fs = require('fs'); const manifest = JSON.parse(fs.readFileSync('package.json', 'utf8')); const fallback = {'@reactivapp/mobile': '2608.13.1', react: '19.2.3', 'react-native': '0.86.0'}; + const legacyPeerDeps = process.env.SHIM_LEGACY_PEER_DEPS === '1'; + // npm workspaces: the root install also installs each workspace's dependencies into the root tree. + const workspaceDeps = {}; + for (const ws of Array.isArray(manifest.workspaces) ? manifest.workspaces : []) { + try { Object.assign(workspaceDeps, JSON.parse(fs.readFileSync(ws + '/package.json', 'utf8')).dependencies || {}); } catch (error) {} + } for (const [name, version] of Object.entries(fallback)) { - const declared = (manifest.dependencies || {})[name] || (manifest.peerDependencies || {})[name] || version; + const own = (manifest.dependencies || {})[name] || (manifest.devDependencies || {})[name] || workspaceDeps[name]; + if (legacyPeerDeps && !own) continue; + const declared = own || (manifest.peerDependencies || {})[name] || version; fs.mkdirSync('node_modules/' + name, {recursive: true}); const installed = name === '@reactivapp/mobile' ? {name, version: declared, dependencies: {}} : {name, version: declared}; fs.writeFileSync('node_modules/' + name + '/package.json', JSON.stringify(installed)); @@ -149,6 +158,7 @@ export const buildTemplateTarball = ( JSON.stringify({ name: '{{APP_SLUG}}', private: true, + workspaces: ['app'], main: 'src/index.ts', 'react-native': 'src/index.ts', files: ['src'], diff --git a/packages/cli/test/imports.test.ts b/packages/cli/test/imports.test.ts index f53064f..602cd2c 100644 --- a/packages/cli/test/imports.test.ts +++ b/packages/cli/test/imports.test.ts @@ -196,8 +196,8 @@ describe('crossCheckImports', () => { }) expect(errors).toEqual([ 'src/ imports packages that package.json does not declare:', - ' @scope/missing: "@scope/missing/sub" in src/c.ts:1 — run `npm install --save-exact @scope/missing@` at the project root and in app/', - ' lodash: "lodash" in src/a.ts:1, "lodash/fp" in src/b.ts:2 — run `npm install --save-exact lodash@` at the project root and in app/', + ' @scope/missing: "@scope/missing/sub" in src/c.ts:1 — run `npm install --save-exact @scope/missing@` at the project root', + ' lodash: "lodash" in src/a.ts:1, "lodash/fp" in src/b.ts:2 — run `npm install --save-exact lodash@` at the project root', ]) }) @@ -214,8 +214,8 @@ describe('crossCheckImports', () => { expect(check({'src/a.ts': "import {format} from 'date-fns'\n"}, {'date-fns': '4.1.0', 'left-pad': '1.3.0', axios: '1.7.9'})).toEqual({ errors: [], warnings: [ - 'package.json declares axios but nothing in src/ imports it — if nothing needs it, remove it from package.json and app/package.json (it ships with the submission)', - 'package.json declares left-pad but nothing in src/ imports it — if nothing needs it, remove it from package.json and app/package.json (it ships with the submission)', + 'package.json declares axios but nothing in src/ imports it — if nothing needs it, remove it from package.json (it ships with the submission)', + 'package.json declares left-pad but nothing in src/ imports it — if nothing needs it, remove it from package.json (it ships with the submission)', ], }) }) @@ -233,8 +233,8 @@ describe('crossCheckImports', () => { expect(errors).toEqual([ 'src/ imports Node built-in modules, which do not exist in the app runtime (Hermes):', ' "node:fs" in src/a.ts:1 — remove the import', - ' "path" in src/a.ts:2 — remove the import, or if you meant the npm package "path", run `npm install --save-exact path@` at the project root and in app/', - ' "fs/promises" in src/a.ts:3 — remove the import, or if you meant the npm package "fs", run `npm install --save-exact fs@` at the project root and in app/', + ' "path" in src/a.ts:2 — remove the import, or if you meant the npm package "path", run `npm install --save-exact path@` at the project root', + ' "fs/promises" in src/a.ts:3 — remove the import, or if you meant the npm package "fs", run `npm install --save-exact fs@` at the project root', ]) }) @@ -259,7 +259,7 @@ describe('crossCheckImports', () => { it('treats a polyfill listed only as a peer as undeclared', () => { expect(check({'src/a.ts': "import {Buffer} from 'buffer'\n"}).errors).toEqual([ 'src/ imports Node built-in modules, which do not exist in the app runtime (Hermes):', - ' "buffer" in src/a.ts:1 — remove the import, or if you meant the npm package "buffer", run `npm install --save-exact buffer@` at the project root and in app/', + ' "buffer" in src/a.ts:1 — remove the import, or if you meant the npm package "buffer", run `npm install --save-exact buffer@` at the project root', ]) }) @@ -320,7 +320,7 @@ describe('crossCheckImports', () => { it('warns about every declared dependency when src/ has no source files', () => { expect(crossCheckImports([], {'date-fns': '4.1.0'}, platform)).toEqual({ errors: [], - warnings: ['package.json declares date-fns but nothing in src/ imports it — if nothing needs it, remove it from package.json and app/package.json (it ships with the submission)'], + warnings: ['package.json declares date-fns but nothing in src/ imports it — if nothing needs it, remove it from package.json (it ships with the submission)'], }) }) diff --git a/packages/cli/test/init-run.test.ts b/packages/cli/test/init-run.test.ts index c275005..ebf3987 100644 --- a/packages/cli/test/init-run.test.ts +++ b/packages/cli/test/init-run.test.ts @@ -101,17 +101,14 @@ describe('app init and app run on the library layout', () => { expect(readFileSync(npmrc, 'utf8')).toContain(BLOCK_START) expect(readFileSync(npmrc, 'utf8')).not.toContain('CODEARTIFACT_AUTH_TOKEN') } - expect(installs()).toEqual([ - 'install --no-audit --no-fund --ignore-scripts --loglevel notice', - 'install --no-audit --no-fund --ignore-scripts --loglevel notice', - ]) + expect(installs()).toEqual(['install --no-audit --no-fund --ignore-scripts --legacy-peer-deps --include=dev --loglevel notice']) }, 60_000) it('refuses a template that predates the library layout and removes the partial project', async () => { await setup({legacyLayout: true}) const result = await init() expect(result.code).not.toBe(0) - expect(flat(result.errorText)).toContain('predates the library layout') + expect(flat(result.errorText)).toContain('does not list app/ as an npm workspace') expect(existsSync(join(workDir, 'acme'))).toBe(false) expect(installs()).toEqual([]) }, 60_000) @@ -148,7 +145,7 @@ describe('app init and app run on the library layout', () => { writeFileSync(manifestPath, JSON.stringify({...library, dependencies: {'date-fns': '4.1.0'}})) const result = await runCli(['app', 'run', 'ios'], {cwd: project, env}) expect(result.code).not.toBe(0) - expect(flat(result.errorText)).toContain('date-fns: missing from app/package.json — add "date-fns": "4.1.0" to its dependencies') + expect(flat(result.errorText)).toContain('date-fns is declared but not installed — run `npm install` at the project root') expect(readFileSync(podLog, 'utf8')).toBe('') }, 60_000) }) diff --git a/packages/cli/test/layout.test.ts b/packages/cli/test/layout.test.ts index ca77586..04e844b 100644 --- a/packages/cli/test/layout.test.ts +++ b/packages/cli/test/layout.test.ts @@ -16,20 +16,18 @@ import {assertLibraryManifest, buildSubmissionManifest} from '../src/lib/submiss const platform = {'@reactivapp/mobile': '2608.13.1', react: '19.2.3', 'react-native': '0.86.0'} describe('findDependencyDrift', () => { - it('reports nothing when the shell mirrors the library exactly', () => { + it('reports a library dependency the shell still mirrors', () => { expect( findDependencyDrift({dependencies: {'date-fns': '4.1.0'}}, {dependencies: {...platform, 'date-fns': '4.1.0'}}), - ).toEqual([]) + ).toEqual([{name: 'date-fns', library: '4.1.0', app: '4.1.0'}]) }) it('reports nothing for a library without dependencies', () => { expect(findDependencyDrift({}, {dependencies: platform})).toEqual([]) }) - it('reports a library dependency the shell is missing', () => { - expect(findDependencyDrift({dependencies: {'date-fns': '4.1.0'}}, {dependencies: platform})).toEqual([ - {name: 'date-fns', library: '4.1.0', app: undefined}, - ]) + it('reports nothing when the shell declares only the platform', () => { + expect(findDependencyDrift({dependencies: {'date-fns': '4.1.0'}}, {dependencies: platform})).toEqual([]) }) it('reports a spec mismatch, compared as written', () => { @@ -52,9 +50,7 @@ describe('findDependencyDrift', () => { it('ignores inherited object keys', () => { expect(findDependencyDrift({dependencies: {}}, {dependencies: {...platform}})).toEqual([]) - expect(findDependencyDrift({dependencies: {constructor: '1.0.0'}}, {dependencies: platform})).toEqual([ - {name: 'constructor', library: '1.0.0', app: undefined}, - ]) + expect(findDependencyDrift({dependencies: {constructor: '1.0.0'}}, {dependencies: platform})).toEqual([]) }) it('never asks the library to mirror the platform packages the shell depends on', () => { @@ -65,44 +61,43 @@ describe('findDependencyDrift', () => { describe('formatDependencyDrift', () => { it('names the exact edit for each kind of drift and the install to run after', () => { const message = formatDependencyDrift([ - {name: 'a', library: '1.0.0'}, {name: 'b', library: '2.0.0', app: '1.0.0'}, {name: 'c', app: '3.0.0'}, ]) - expect(message).toContain('a: missing from app/package.json — add "a": "1.0.0" to its dependencies') - expect(message).toContain('b: "2.0.0" in package.json but "1.0.0" in app/package.json — set app/package.json to "2.0.0"') - expect(message).toContain('c: in app/package.json only — add "c": "3.0.0" to the root package.json dependencies') - expect(message).toContain('run `npm install` in app/') + expect(message).toContain('b: already declared in package.json ("2.0.0") — remove it from app/package.json') + expect(message).toContain('c: in app/package.json only — run `npm install --save-exact c@3.0.0` at the project root') + expect(message).toContain('run `npm install` at the project root') }) }) const platformManifest = {name: '@reactivapp/mobile', version: '2608.13.1', dependencies: {'@reactivapp/config': '1.0.0', 'react-native-svg': '15.12.0'}} -const installPlatform = (appDir: string): void => { +const installPlatform = (root: string): void => { for (const name of ['react', 'react-native'] as const) { - mkdirSync(join(appDir, 'node_modules', name), {recursive: true}) - writeFileSync(join(appDir, 'node_modules', name, 'package.json'), JSON.stringify({name, version: platform[name]})) + mkdirSync(join(root, 'node_modules', name), {recursive: true}) + writeFileSync(join(root, 'node_modules', name, 'package.json'), JSON.stringify({name, version: platform[name]})) } - writeFileSync(join(appDir, 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.13.1'}}})) + writeFileSync(join(root, 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.13.1'}}})) } const project = (library: object, app: object): string => { const root = mkdtempSync(join(tmpdir(), 'layout-')) - mkdirSync(join(root, 'app', 'node_modules', '@reactivapp', 'mobile'), {recursive: true}) - writeFileSync(join(root, 'package.json'), JSON.stringify(library)) + mkdirSync(join(root, 'app'), {recursive: true}) + mkdirSync(join(root, 'node_modules', '@reactivapp', 'mobile'), {recursive: true}) + writeFileSync(join(root, 'package.json'), JSON.stringify({workspaces: ['app'], ...library})) writeFileSync(join(root, 'app', 'package.json'), JSON.stringify(app)) - writeFileSync(join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'package.json'), JSON.stringify(platformManifest)) - installPlatform(join(root, 'app')) + writeFileSync(join(root, 'node_modules', '@reactivapp', 'mobile', 'package.json'), JSON.stringify(platformManifest)) + installPlatform(root) return root } const install = (root: string, name: string, version = '1.0.0'): void => { - mkdirSync(join(root, 'app', 'node_modules', name), {recursive: true}) - writeFileSync(join(root, 'app', 'node_modules', name, 'package.json'), JSON.stringify({name, version})) + mkdirSync(join(root, 'node_modules', name), {recursive: true}) + writeFileSync(join(root, 'node_modules', name, 'package.json'), JSON.stringify({name, version})) } const inSync = (deps: Record, extra: object = {}): string => { - const root = project({dependencies: deps, peerDependencies: platform, ...extra}, {dependencies: {...platform, ...deps}}) + const root = project({dependencies: deps, peerDependencies: platform, ...extra}, {dependencies: {...platform}}) for (const [name, version] of Object.entries(deps)) install(root, name, version) return root } @@ -118,7 +113,7 @@ describe('assertDependenciesInSync (app run and submit)', () => { it('throws the drift report', () => { const root = project({dependencies: {x: '1.0.0'}, peerDependencies: platform}, {dependencies: platform}) - expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('x: missing from app/package.json') + expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('x is declared but not installed — run `npm install` at the project root') }) it('rejects a package the platform already ships declared as a library dependency', () => { @@ -147,15 +142,15 @@ describe('assertDependenciesInSync (app run and submit)', () => { expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('react: missing from app/package.json — add "react": "19.2.3" to its dependencies') }) - it('requires mirrored dependencies to be installed in app/', () => { + it('refuses a library dependency the shell still mirrors', () => { const root = project({dependencies: {x: '1.0.0'}, peerDependencies: platform}, {dependencies: {...platform, x: '1.0.0'}}) - expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('x is declared but not installed in app/') + expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('x: already declared in package.json ("1.0.0") — remove it from app/package.json') }) it('requires react and react-native to be installed in app/', () => { const root = inSync({}) - rmSync(join(root, 'app', 'node_modules', 'react-native'), {recursive: true}) - expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('react-native is declared but not installed in app/') + rmSync(join(root, 'node_modules', 'react-native'), {recursive: true}) + expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('react-native is declared but not installed — run `npm install` at the project root') }) it('tells the merchant to drop an app-only package the platform already ships', () => { @@ -165,31 +160,31 @@ describe('assertDependenciesInSync (app run and submit)', () => { it('rejects a library dependency the platform keeps its own nested copy of', () => { const root = inSync({'lottie-react-native': '7.0.0'}) - mkdirSync(join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native'), {recursive: true}) - writeFileSync(join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native', 'package.json'), '{"version":"6.1.0"}') + mkdirSync(join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native'), {recursive: true}) + writeFileSync(join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native', 'package.json'), '{"version":"6.1.0"}') expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow( - 'lottie-react-native: the platform uses 6.1.0 — pin package.json and app/package.json to "6.1.0"', + 'lottie-react-native: the platform uses 6.1.0 — pin package.json to "6.1.0"', ) }) it('asks for a dedupe when the nested copy already matches the pin', () => { const root = inSync({'lottie-react-native': '7.0.0'}) - const nested = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native') + const nested = join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native') mkdirSync(nested, {recursive: true}) writeFileSync(join(nested, 'package.json'), '{"version":"7.0.0"}') - expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('lottie-react-native: both copies are 7.0.0 — run `npm dedupe` in app/') + expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('lottie-react-native: both copies are 7.0.0 — run `npm dedupe` at the project root') }) it('treats an installed package without a version as a damaged install', () => { const root = inSync({'lottie-react-native': '7.0.0'}) - const nested = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native') + const nested = join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'lottie-react-native') mkdirSync(nested, {recursive: true}) writeFileSync(join(nested, 'package.json'), '{}') expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('has no version — the install is damaged') }) const withPlatformPeer = (root: string): void => { - const platformPath = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'package.json') + const platformPath = join(root, 'node_modules', '@reactivapp', 'mobile', 'package.json') writeFileSync(platformPath, JSON.stringify({...platformManifest, peerDependencies: {'react-native-reanimated': '>=3'}})) } @@ -221,27 +216,27 @@ describe('assertDependenciesInSync (app run and submit)', () => { const root = project({peerDependencies: platform}, {dependencies: {...platform, 'react-native-reanimated': '3.17.0'}}) withPlatformPeer(root) expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow( - 'react-native-reanimated: the platform expects the app to provide it — run `npm install` in app/, keep it in app/package.json and add its installed exact version ("3.17.0" now) to package.json peerDependencies', + 'react-native-reanimated: the platform expects the app to provide it — keep it in app/package.json and add its installed exact version ("3.17.0" now) to package.json peerDependencies', ) }) it('still rejects a package the platform declares as a peer as a library dependency', () => { const root = project({dependencies: {'react-native-reanimated': '3.17.0'}, peerDependencies: platform}, {dependencies: {...platform, 'react-native-reanimated': '3.17.0'}}) - const platformPath = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'package.json') + const platformPath = join(root, 'node_modules', '@reactivapp', 'mobile', 'package.json') writeFileSync(platformPath, JSON.stringify({...platformManifest, peerDependencies: {'react-native-reanimated': '>=3'}})) expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('react-native-reanimated: the platform expects the app to provide it — move it to peerDependencies and keep it in app/package.json') }) it('requires the installed react and react-native to match app/package.json', () => { const root = inSync({}) - writeFileSync(join(root, 'app', 'node_modules', 'react', 'package.json'), JSON.stringify({name: 'react', version: '19.0.0'})) + writeFileSync(join(root, 'node_modules', 'react', 'package.json'), JSON.stringify({name: 'react', version: '19.0.0'})) expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('does not hold the react@19.2.3 that app/package.json declares') }) it('requires the platform to be installed in app/', () => { const root = inSync({}) - rmSync(join(root, 'app', 'node_modules', '@reactivapp'), {recursive: true}) - expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('@reactivapp/mobile is not installed in app/') + rmSync(join(root, 'node_modules', '@reactivapp'), {recursive: true}) + expect(() => assertDependenciesInSync(resolveLayout(root))).toThrow('@reactivapp/mobile is not installed —') }) it('rejects non-string dependency values', () => { @@ -275,7 +270,7 @@ describe('assertSubmittableDependencies (submit only)', () => { it('requires the installed package to be the declared one, not a substitute', () => { const root = inSync({foo: '1.2.3'}) - writeFileSync(join(root, 'app', 'node_modules', 'foo', 'package.json'), JSON.stringify({name: 'other', version: '1.2.3'})) + writeFileSync(join(root, 'node_modules', 'foo', 'package.json'), JSON.stringify({name: 'other', version: '1.2.3'})) expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('does not hold the declared versions of foo@1.2.3') }) @@ -293,17 +288,17 @@ describe('assertSubmittableDependencies (submit only)', () => { it('refuses two different copies of a supplied peer', () => { const root = inSync({}, {peerDependencies: {...platform, 'react-native-svg': '15.12.0'}}) install(root, 'react-native-svg', '15.0.0') - const nested = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'react-native-svg') + const nested = join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'react-native-svg') mkdirSync(nested, {recursive: true}) writeFileSync(join(nested, 'package.json'), JSON.stringify({name: 'react-native-svg', version: '15.12.0'})) expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow( - 'react-native-svg: two copies in app/ (15.0.0 for src/, 15.12.0 for the platform) — run `npm ls react-native-svg` in app/', + 'react-native-svg: two copies in node_modules (15.0.0 for src/, 15.12.0 for the platform) — run `npm ls react-native-svg` at the project root', ) }) it('accepts a supplied peer that only the platform holds', () => { const root = inSync({}, {peerDependencies: {...platform, 'react-native-svg': '15.12.0'}}) - const nested = join(root, 'app', 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'react-native-svg') + const nested = join(root, 'node_modules', '@reactivapp', 'mobile', 'node_modules', 'react-native-svg') mkdirSync(nested, {recursive: true}) writeFileSync(join(nested, 'package.json'), JSON.stringify({name: 'react-native-svg', version: '15.12.0'})) expect(() => assertSubmittableDependencies(resolveLayout(root))).not.toThrow() @@ -311,27 +306,27 @@ describe('assertSubmittableDependencies (submit only)', () => { it('reports a supplied peer that is not installed at all', () => { const root = inSync({}, {peerDependencies: {...platform, 'react-native-svg': '15.12.0'}}) - expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('react-native-svg: not installed in app/') + expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('react-native-svg: not installed —') }) it('tells a pre-npm-7 lockfile from a stale one', () => { const root = inSync({}) - writeFileSync(join(root, 'app', 'package-lock.json'), JSON.stringify({lockfileVersion: 1, dependencies: {}})) + writeFileSync(join(root, 'package-lock.json'), JSON.stringify({lockfileVersion: 1, dependencies: {}})) expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('predates npm 7') - writeFileSync(join(root, 'app', 'package-lock.json'), JSON.stringify({lockfileVersion: 3, packages: {}})) + writeFileSync(join(root, 'package-lock.json'), JSON.stringify({lockfileVersion: 3, packages: {}})) expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('records no installed @reactivapp/mobile') }) it('explains a missing lockfile', () => { const root = inSync({}) - rmSync(join(root, 'app', 'package-lock.json')) - expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('app/package-lock.json not found — run `npm install` (npm 7 or later)') + rmSync(join(root, 'package-lock.json')) + expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('package-lock.json not found — run `npm install` (npm 7 or later)') }) it('refuses a platform install that disagrees with the lockfile', () => { const root = inSync({}) - writeFileSync(join(root, 'app', 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.14.0'}}})) - expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('holds @reactivapp/mobile@2608.13.1 but app/package-lock.json records 2608.14.0') + writeFileSync(join(root, 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.14.0'}}})) + expect(() => assertSubmittableDependencies(resolveLayout(root))).toThrow('holds @reactivapp/mobile@2608.13.1 but package-lock.json records 2608.14.0') }) it('requires exact platform peers at submit', () => { @@ -461,7 +456,7 @@ describe('buildSubmissionManifest', () => { }) describe('readPlatformSupplied', () => { - const platformDir = (root: string): string => join(root, 'app', 'node_modules', '@reactivapp', 'mobile') + const platformDir = (root: string): string => join(root, 'node_modules', '@reactivapp', 'mobile') const withPlatform = (manifest: object, aliases?: string): string => { const root = mkdtempSync(join(tmpdir(), 'supplied-')) mkdirSync(join(platformDir(root), 'toolchain'), {recursive: true}) diff --git a/packages/cli/test/native-integration.test.ts b/packages/cli/test/native-integration.test.ts index f7f933a..957e5fb 100644 --- a/packages/cli/test/native-integration.test.ts +++ b/packages/cli/test/native-integration.test.ts @@ -62,85 +62,85 @@ describe('findNativeIntegration', () => { const install = (name: string, files: Record): void => { for (const [file, content] of Object.entries(files)) { - mkdirSync(join(appDir, 'node_modules', name, file, '..'), {recursive: true}) - writeFileSync(join(appDir, 'node_modules', name, file), content) + mkdirSync(join(root, 'node_modules', name, file, '..'), {recursive: true}) + writeFileSync(join(root, 'node_modules', name, file), content) } } it('rejects a dependency whose podspec carries script_phases, naming the file', () => { install('scripted-native', {'package.json': '{}', 'scripted-native.podspec': "Pod::Spec.new do |s|\n s.script_phases = [{:name => 'gen'}]\nend\n"}) - expect(findNativeIntegration(appDir, {'scripted-native': '1.0.0'})).toEqual([ - ' scripted-native: app/node_modules/scripted-native/scripted-native.podspec sets script_phases', + expect(findNativeIntegration(root, {'scripted-native': '1.0.0'})).toEqual([ + ' scripted-native: node_modules/scripted-native/scripted-native.podspec sets script_phases', ]) }) it('finds a podspec below the package root and a scoped package', () => { install('@acme/prepared', {'package.json': '{}', 'ios/Prepared.podspec': "s.prepare_command = 'make'\n"}) - expect(findNativeIntegration(appDir, {'@acme/prepared': '2.0.0'})).toEqual([ - ' @acme/prepared: app/node_modules/@acme/prepared/ios/Prepared.podspec sets prepare_command', + expect(findNativeIntegration(root, {'@acme/prepared': '2.0.0'})).toEqual([ + ' @acme/prepared: node_modules/@acme/prepared/ios/Prepared.podspec sets prepare_command', ]) }) it('reads a podspec.json found on disk', () => { install('json-scripted', {'package.json': '{}', 'json-scripted.podspec.json': '{"name": "json-scripted", "prepare_command": "sh setup.sh"}'}) - expect(findNativeIntegration(appDir, {'json-scripted': '1.0.0'})).toEqual([ - ' json-scripted: app/node_modules/json-scripted/json-scripted.podspec.json sets prepare_command', + expect(findNativeIntegration(root, {'json-scripted': '1.0.0'})).toEqual([ + ' json-scripted: node_modules/json-scripted/json-scripted.podspec.json sets prepare_command', ]) }) it('reads podspecs whatever the extension case, and podspecs that are symlinks to files', () => { install('upper-native', {'package.json': '{}', 'ios/Upper.PODSPEC': "s.prepare_command = 'make'\n"}) install('linked-native', {'package.json': '{}', 'real/linked.rb': "s.script_phase = {:name => 'x'}\n"}) - symlinkSync(join(appDir, 'node_modules', 'linked-native', 'real', 'linked.rb'), join(appDir, 'node_modules', 'linked-native', 'linked.podspec')) - expect(findNativeIntegration(appDir, {'upper-native': '1.0.0', 'linked-native': '1.0.0'})).toEqual([ - ' linked-native: app/node_modules/linked-native/linked.podspec sets script_phase', - ' upper-native: app/node_modules/upper-native/ios/Upper.PODSPEC sets prepare_command', + symlinkSync(join(root, 'node_modules', 'linked-native', 'real', 'linked.rb'), join(root, 'node_modules', 'linked-native', 'linked.podspec')) + expect(findNativeIntegration(root, {'upper-native': '1.0.0', 'linked-native': '1.0.0'})).toEqual([ + ' linked-native: node_modules/linked-native/linked.podspec sets script_phase', + ' upper-native: node_modules/upper-native/ios/Upper.PODSPEC sets prepare_command', ]) }) it('reports a podspec symlink whose target cannot be read, and skips a dangling one', () => { install('loop-native', {'package.json': '{}'}) install('dangling-native', {'package.json': '{}'}) - const loopDir = join(appDir, 'node_modules', 'loop-native') + const loopDir = join(root, 'node_modules', 'loop-native') symlinkSync(join(loopDir, 'b.podspec'), join(loopDir, 'a.podspec')) symlinkSync(join(loopDir, 'a.podspec'), join(loopDir, 'b.podspec')) - symlinkSync(join(root, 'missing'), join(appDir, 'node_modules', 'dangling-native', 'gone.podspec')) - expect(findNativeIntegration(appDir, {'loop-native': '1.0.0', 'dangling-native': '1.0.0'})).toEqual([ - ' loop-native: app/node_modules/loop-native/a.podspec could not be read, so its build hooks cannot be checked', - ' loop-native: app/node_modules/loop-native/b.podspec could not be read, so its build hooks cannot be checked', + symlinkSync(join(root, 'missing'), join(root, 'node_modules', 'dangling-native', 'gone.podspec')) + expect(findNativeIntegration(root, {'loop-native': '1.0.0', 'dangling-native': '1.0.0'})).toEqual([ + ' loop-native: node_modules/loop-native/a.podspec could not be read, so its build hooks cannot be checked', + ' loop-native: node_modules/loop-native/b.podspec could not be read, so its build hooks cannot be checked', ]) }) it.skipIf(process.getuid?.() === 0)('reports an unreadable podspec or package directory as a finding instead of crashing', () => { install('locked-file', {'package.json': '{}', 'locked.podspec': PLAIN_PODSPEC}) install('locked-dir', {'package.json': '{}', 'ios/x.m': ''}) - chmodSync(join(appDir, 'node_modules', 'locked-file', 'locked.podspec'), 0o000) - chmodSync(join(appDir, 'node_modules', 'locked-dir', 'ios'), 0o000) + chmodSync(join(root, 'node_modules', 'locked-file', 'locked.podspec'), 0o000) + chmodSync(join(root, 'node_modules', 'locked-dir', 'ios'), 0o000) try { - expect(findNativeIntegration(appDir, {'locked-file': '1.0.0', 'locked-dir': '1.0.0'})).toEqual([ - ' locked-dir: app/node_modules/locked-dir/ios could not be read, so its build hooks cannot be checked', - ' locked-file: app/node_modules/locked-file/locked.podspec could not be read, so its build hooks cannot be checked', + expect(findNativeIntegration(root, {'locked-file': '1.0.0', 'locked-dir': '1.0.0'})).toEqual([ + ' locked-dir: node_modules/locked-dir/ios could not be read, so its build hooks cannot be checked', + ' locked-file: node_modules/locked-file/locked.podspec could not be read, so its build hooks cannot be checked', ]) } finally { - chmodSync(join(appDir, 'node_modules', 'locked-file', 'locked.podspec'), 0o644) - chmodSync(join(appDir, 'node_modules', 'locked-dir', 'ios'), 0o755) + chmodSync(join(root, 'node_modules', 'locked-file', 'locked.podspec'), 0o644) + chmodSync(join(root, 'node_modules', 'locked-dir', 'ios'), 0o755) } }) it('accepts a plain podspec and a JS-only package', () => { install('plain-native', {'package.json': '{}', 'plain-native.podspec': PLAIN_PODSPEC}) install('js-only', {'package.json': '{}', 'index.js': 'module.exports = {}\n'}) - expect(findNativeIntegration(appDir, {'plain-native': '1.0.0', 'js-only': '1.0.0'})).toEqual([]) + expect(findNativeIntegration(root, {'plain-native': '1.0.0', 'js-only': '1.0.0'})).toEqual([]) }) it('does not descend into a nested node_modules', () => { install('wrapper', {'package.json': '{}', 'node_modules/inner/inner.podspec': "s.script_phase = {:name => 'x'}\n"}) - expect(findNativeIntegration(appDir, {wrapper: '1.0.0'})).toEqual([]) + expect(findNativeIntegration(root, {wrapper: '1.0.0'})).toEqual([]) }) it('rejects every library on the known list without reading its files', () => { const declared = Object.fromEntries(KNOWN_NATIVE_INTEGRATION_LIBRARIES.map(name => [name, '1.0.0'])) - expect(findNativeIntegration(appDir, declared)).toEqual( + expect(findNativeIntegration(root, declared)).toEqual( [...KNOWN_NATIVE_INTEGRATION_LIBRARIES].sort().map(name => ` ${name}: needs app-level native setup (AppDelegate, Podfile or Info.plist changes)`), ) }) @@ -152,7 +152,7 @@ describe('findNativeIntegration', () => { [ 'package.json dependencies include libraries that require native project changes a customization cannot ship — contact Reactiv:', ' react-native-code-push: needs app-level native setup (AppDelegate, Podfile or Info.plist changes)', - "This check reads CocoaPods podspecs in app/node_modules and a short list of known libraries; a library that needs Gradle changes, Info.plist usage descriptions or entitlements is not detected here and is rejected at Reactiv's review instead.", + "This check reads CocoaPods podspecs in node_modules and a short list of known libraries; a library that needs Gradle changes, Info.plist usage descriptions or entitlements is not detected here and is rejected at Reactiv's review instead.", ].join('\n'), ) }) @@ -160,16 +160,16 @@ describe('findNativeIntegration', () => { it.skipIf(process.getuid?.() === 0)('reports unreadable files under their own heading, not as native changes', () => { writeFileSync(join(root, 'package.json'), JSON.stringify({dependencies: {'locked-file': '1.0.0'}})) install('locked-file', {'package.json': '{}', 'locked.podspec': PLAIN_PODSPEC}) - chmodSync(join(appDir, 'node_modules', 'locked-file', 'locked.podspec'), 0o000) + chmodSync(join(root, 'node_modules', 'locked-file', 'locked.podspec'), 0o000) try { expect(() => assertNoAppNativeIntegration({root, appDir})).toThrow( [ - 'package.json dependencies include files in app/node_modules that could not be read — fix their permissions (or reinstall with `npm install` in app/) and try again:', - ' locked-file: app/node_modules/locked-file/locked.podspec could not be read, so its build hooks cannot be checked', + 'package.json dependencies include files in node_modules that could not be read — fix their permissions (or reinstall with `npm install` at the project root) and try again:', + ' locked-file: node_modules/locked-file/locked.podspec could not be read, so its build hooks cannot be checked', ].join('\n'), ) } finally { - chmodSync(join(appDir, 'node_modules', 'locked-file', 'locked.podspec'), 0o644) + chmodSync(join(root, 'node_modules', 'locked-file', 'locked.podspec'), 0o644) } }) @@ -184,7 +184,7 @@ describe('findNativeIntegration', () => { } expect(message.split('\n').slice(1, 3)).toEqual([ ' react-native-code-push: needs app-level native setup (AppDelegate, Podfile or Info.plist changes)', - ' scripted-native: app/node_modules/scripted-native/scripted-native.podspec sets script_phases', + ' scripted-native: node_modules/scripted-native/scripted-native.podspec sets script_phases', ]) expect(message).toContain('is not detected here') }) diff --git a/packages/cli/test/submission.test.ts b/packages/cli/test/submission.test.ts index dd69397..3703a01 100644 --- a/packages/cli/test/submission.test.ts +++ b/packages/cli/test/submission.test.ts @@ -479,8 +479,9 @@ describe('submit validate entry file kinds', () => { describe('readPlatformVersionFromLockfile', () => { const projectWith = (packages: Record): string => { const dir = mkdtempSync(join(tmpdir(), 'lock-')) + mkdirSync(join(dir, 'app')) writeFileSync(join(dir, 'package-lock.json'), JSON.stringify({lockfileVersion: 3, packages})) - return dir + return join(dir, 'app') } it('reads the installed @reactivapp/mobile version', () => { @@ -488,6 +489,6 @@ describe('readPlatformVersionFromLockfile', () => { }) it('fails when the platform package is not installed', () => { - expect(() => readPlatformVersionFromLockfile(projectWith({}))).toThrow('@reactivapp/mobile not found in app/package-lock.json') + expect(() => readPlatformVersionFromLockfile(projectWith({}))).toThrow('@reactivapp/mobile not found in package-lock.json') }) }) diff --git a/packages/cli/test/submit-dry-run.test.ts b/packages/cli/test/submit-dry-run.test.ts index b038f2c..3620f66 100644 --- a/packages/cli/test/submit-dry-run.test.ts +++ b/packages/cli/test/submit-dry-run.test.ts @@ -1,7 +1,7 @@ import {execFileSync} from 'node:child_process' import {linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync} from 'node:fs' import {tmpdir} from 'node:os' -import {join} from 'node:path' +import {dirname, join} from 'node:path' import {afterEach, beforeEach, describe, expect, it} from 'vitest' import { @@ -23,6 +23,7 @@ import {SECRET_PATTERNS} from '../src/lib/secret-scan.js' const PLATFORM_PEERS = {'@reactivapp/mobile': '2608.13.1', react: '19.2.3', 'react-native': '0.86.0'} const LIBRARY_MANIFEST = { + workspaces: ['app'], name: 'acme', version: '0.0.1', private: true, @@ -36,7 +37,7 @@ const LIBRARY_MANIFEST = { publishConfig: {registry: 'https://registry.npmjs.org/'}, } -const APP_MANIFEST = {name: 'acme-app', private: true, dependencies: {...PLATFORM_PEERS, 'date-fns': '4.1.0'}} +const APP_MANIFEST = {name: 'acme-app', private: true, dependencies: {...PLATFORM_PEERS}} const writeInstalled = (appDir: string, name: string, manifest: object): void => { mkdirSync(join(appDir, 'node_modules', name), {recursive: true}) @@ -58,12 +59,12 @@ const writeFixtureProject = (root: string): void => { const appDir = join(root, 'app') mkdirSync(appDir) writeFileSync(join(appDir, 'package.json'), JSON.stringify(APP_MANIFEST, null, 2)) - writeFileSync(join(appDir, 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.13.1'}}})) + writeFileSync(join(dirname(appDir), 'package-lock.json'), JSON.stringify({packages: {'node_modules/@reactivapp/mobile': {version: '2608.13.1'}}})) writeFileSync(join(appDir, 'index.js'), "import '@reactivapp/mobile/src/index';\n") - writeInstalled(appDir, '@reactivapp/mobile', {version: '2608.13.1', dependencies: {}}) - writeInstalled(appDir, 'react', {version: '19.2.3'}) - writeInstalled(appDir, 'react-native', {version: '0.86.0'}) - writeInstalled(appDir, 'date-fns', {version: '4.1.0'}) + writeInstalled(root, '@reactivapp/mobile', {version: '2608.13.1', dependencies: {}}) + writeInstalled(root, 'react', {version: '19.2.3'}) + writeInstalled(root, 'react-native', {version: '0.86.0'}) + writeInstalled(root, 'date-fns', {version: '4.1.0'}) } describe('app submit against a mock vending API and a fixture registry', () => { @@ -288,19 +289,18 @@ describe('app submit against a mock vending API and a fixture registry', () => { expect((await submit(['0.1.7'])).stdout).toContain('Dry run complete (publish skipped)') }, 30_000) - it('stops before any login or registry work when app/ does not mirror the library', async () => { - writeFileSync(join(projectDir, 'app', 'package.json'), JSON.stringify({...APP_MANIFEST, dependencies: PLATFORM_PEERS})) + it('stops before any login or registry work when app/ declares a library dependency', async () => { + writeFileSync(join(projectDir, 'app', 'package.json'), JSON.stringify({...APP_MANIFEST, dependencies: {...PLATFORM_PEERS, 'date-fns': '4.1.0'}})) const failure = await submit(['0.1.7']) expect(failure.code).not.toBe(0) - expect(flat(failure.stderr)).toContain('date-fns: missing from app/package.json — add "date-fns": "4.1.0" to its dependencies') - expect(flat(failure.stderr)).toContain('run `npm install` in app/') + expect(flat(failure.stderr)).toContain('date-fns: already declared in package.json ("4.1.0") — remove it from app/package.json') + expect(flat(failure.stderr)).toContain('run `npm install` at the project root') expect(mock.requests.filter(request => request.path === '/v1/tokens')).toEqual([]) expect(npmCalls('view')).toEqual([]) }, 30_000) it('stops before any login on a dependency range that review could not pin', async () => { writeFileSync(join(projectDir, 'package.json'), JSON.stringify({...LIBRARY_MANIFEST, dependencies: {'date-fns': '^4.1.0'}})) - writeFileSync(join(projectDir, 'app', 'package.json'), JSON.stringify({...APP_MANIFEST, dependencies: {...PLATFORM_PEERS, 'date-fns': '^4.1.0'}})) const failure = await submit(['0.1.7']) expect(flat(failure.stderr)).toContain('must be exact versions') expect(mock.requests.filter(request => request.path === '/v1/tokens')).toEqual([]) @@ -352,7 +352,7 @@ describe('app submit against a mock vending API and a fixture registry', () => { writeFileSync(join(projectDir, 'src', 'customizations', 'extra.ts'), "import {chunk} from 'lodash/chunk';\nexport const extra = chunk;\n") const failure = await submit(['0.1.7']) expect(failure.code).not.toBe(0) - expect(flat(failure.stderr)).toContain('lodash: "lodash/chunk" in src/customizations/extra.ts:1 — run `npm install --save-exact lodash@` at the project root and in app/') + expect(flat(failure.stderr)).toContain('lodash: "lodash/chunk" in src/customizations/extra.ts:1 — run `npm install --save-exact lodash@` at the project root') noTokenNoRegistry() }, 30_000) @@ -387,12 +387,11 @@ describe('app submit against a mock vending API and a fixture registry', () => { it('stops before any login on a dependency whose podspec runs build scripts', async () => { const dependencies = {'date-fns': '4.1.0', 'scripted-native': '1.0.0'} writeFileSync(join(projectDir, 'package.json'), JSON.stringify({...LIBRARY_MANIFEST, dependencies})) - writeFileSync(join(projectDir, 'app', 'package.json'), JSON.stringify({...APP_MANIFEST, dependencies: {...PLATFORM_PEERS, ...dependencies}})) - writeInstalled(join(projectDir, 'app'), 'scripted-native', {version: '1.0.0'}) - writeFileSync(join(projectDir, 'app', 'node_modules', 'scripted-native', 'scripted-native.podspec'), "Pod::Spec.new do |s|\n s.script_phases = [{:name => 'gen'}]\nend\n") + writeInstalled(projectDir, 'scripted-native', {version: '1.0.0'}) + writeFileSync(join(projectDir, 'node_modules', 'scripted-native', 'scripted-native.podspec'), "Pod::Spec.new do |s|\n s.script_phases = [{:name => 'gen'}]\nend\n") const failure = await submit(['0.1.7']) expect(flat(failure.stderr)).toContain('require native project changes a customization cannot ship — contact Reactiv') - expect(flat(failure.stderr)).toContain('scripted-native: app/node_modules/scripted-native/scripted-native.podspec sets script_phases') + expect(flat(failure.stderr)).toContain('scripted-native: node_modules/scripted-native/scripted-native.podspec sets script_phases') noTokenNoRegistry() }, 30_000) diff --git a/packages/cli/test/upgrade-lib.test.ts b/packages/cli/test/upgrade-lib.test.ts index b4b5812..ec73948 100644 --- a/packages/cli/test/upgrade-lib.test.ts +++ b/packages/cli/test/upgrade-lib.test.ts @@ -146,12 +146,12 @@ describe('findDelegationSteps', () => { }) describe('skippedInstallScripts', () => { - it('treats an unreadable app/package-lock.json as no lockfile', () => { + it('treats an unreadable package-lock.json as no lockfile', () => { const appDir = mkdtempSync(join(tmpdir(), 'skipped-')) try { writeFileSync(join(appDir, 'package.json'), JSON.stringify({scripts: {postinstall: 'x'}})) writeFileSync(join(appDir, 'package-lock.json'), '{"packages": ') - expect(skippedInstallScripts(appDir)).toEqual(['app/package.json postinstall']) + expect(skippedInstallScripts(appDir)).toEqual(['package.json postinstall']) } finally { rmSync(appDir, {recursive: true, force: true}) } diff --git a/packages/cli/test/upgrade.test.ts b/packages/cli/test/upgrade.test.ts index 927512c..bec0aaf 100644 --- a/packages/cli/test/upgrade.test.ts +++ b/packages/cli/test/upgrade.test.ts @@ -101,7 +101,6 @@ describe('app upgrade against a mock vending API and a fixture registry', () => `view @reactivapp/mobile@${B} peerDependencies`, 'pack @reactivapp/app-template', 'install', - 'install', 'run typecheck', ]) for (const lookup of calls.slice(0, 3)) expect(lookup).toMatch(/--@reactivapp:registry=https:\/\//) @@ -112,7 +111,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () => expect(out.indexOf('cd app/ios && pod install')).toBeLessThan(out.indexOf('Running the project typecheck')) expect(out).toContain(`typecheck clean against @reactivapp/mobile@${B}`) expect(out).toContain(`roll back with: reactiv app upgrade --to ${A}`) - expect(readFileSync(join(project, 'app', 'node_modules', 'react-native', 'package.json'), 'utf8')).toContain(PEERS[B]['react-native']) + expect(readFileSync(join(project, 'node_modules', 'react-native', 'package.json'), 'utf8')).toContain(PEERS[B]['react-native']) }, 60_000) it('leaves src/, developer files and toolchain delegations untouched, printing the exact replacement instead', async () => { @@ -126,7 +125,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () => expect(result.code).toBe(0) expect(git(['ls-files', '--others', '--exclude-standard'])).toBe('') const changed = git(['diff', '--name-only', 'HEAD']).split('\n').sort() - expect(changed).toEqual(['app/package-lock.json', 'app/package.json', 'package-lock.json', 'package.json']) + expect(changed).toEqual(['app/package.json', 'package-lock.json', 'package.json']) expect(readFileSync(join(project, 'src', 'index.ts'), 'utf8')).toBe("export const mine = 'developer code';\n") expect(readFileSync(join(project, 'app', 'babel.config.js'), 'utf8')).toBe("module.exports = {presets: ['my-own-preset']};\n") @@ -145,7 +144,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () => expect(again.code).toBe(0) expect(again.stdout).toContain(`already declare @reactivapp/mobile@${B}`) expect([readFileSync(join(project, 'package.json'), 'utf8'), readFileSync(join(project, 'app', 'package.json'), 'utf8')]).toEqual(before) - expect(npmCalls().filter(call => call.startsWith('install ') || call.startsWith('run typecheck'))).toHaveLength(3) + expect(npmCalls().filter(call => call.startsWith('install ') || call.startsWith('run typecheck'))).toHaveLength(2) }, 60_000) it('keeps a failed upgrade applied, reports the typecheck errors and prints the one-command rollback that works', async () => { @@ -174,7 +173,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () => const result = await upgrade([], 'upgrade a project whose app/ does not mirror the library') expect(result.code).not.toBe(0) const error = flat(result.errorText) - expect(error).toContain('date-fns: missing from app/package.json — add "date-fns": "4.1.0" to its dependencies') + expect(error).toContain('date-fns is declared but not installed — run `npm install` at the project root') expect(error).toContain(`roll back with: reactiv app upgrade --to ${A}`) expect(manifest('app/package.json').dependencies['@reactivapp/mobile']).toBe(B) expect(manifest('package.json').dependencies).toEqual({'date-fns': '4.1.0'}) @@ -201,7 +200,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () => const named = await upgrade(['--to', B]) expect(named.code).toBe(0) - expect(flat(named.stdout)).toContain('roll back with: restore package.json, app/package.json and both') + expect(flat(named.stdout)).toContain('roll back with: restore package.json, app/package.json and') expect(trioOf(manifest('app/package.json').dependencies)).toEqual({'@reactivapp/mobile': B, ...PEERS[B]}) }, 60_000) diff --git a/packages/cli/test/walkthrough.test.ts b/packages/cli/test/walkthrough.test.ts index 2c5cafe..caa452a 100644 --- a/packages/cli/test/walkthrough.test.ts +++ b/packages/cli/test/walkthrough.test.ts @@ -108,7 +108,7 @@ describe('scripted walkthrough against a mock vending API: login → app init assertNoSecrets(npmLog) expect(npmLog).toMatch(/^view @reactivapp\/mobile version --@reactivapp:registry=https:\S+\/npm\/tools\/ --loglevel notice$/m) expect(npmLog).toMatch(/^pack @reactivapp\/app-template --pack-destination \S+ --ignore-scripts --@reactivapp:registry=\S+ --loglevel http$/m) - expect(npmLog).toMatch(/^install --no-audit --no-fund --ignore-scripts --loglevel notice$/m) + expect(npmLog).toMatch(/^install --no-audit --no-fund --ignore-scripts --legacy-peer-deps --include=dev --loglevel notice$/m) expect(npmLog).not.toMatch(/aws |codeartifact get-authorization-token|CODEARTIFACT_AUTH_TOKEN/) transcript.push(`# vending calls: ${mock.requests.map(request => `${request.method} ${request.path}`).join(', ')}`, '# npm calls (recorded by the shim):', npmLog.trimEnd())