@novacraft-engineering/pulsar-cli 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,6 +16,31 @@ npx @novacraft-engineering/pulsar-cli login https://api.usepulsar.dev
16
16
  is the hosted one; point it at your own if you self-host. The CLI talks to the
17
17
  Pulsar API and nothing else, so it has no host compiled into it.
18
18
 
19
+ ## Set up a project
20
+
21
+ Run these from your React Native project root (no sign-in needed):
22
+
23
+ ```bash
24
+ pulsar init --ios-key <deployment key> --android-key <deployment key> # preview
25
+ pulsar init --ios-key <deployment key> --android-key <deployment key> --write # apply
26
+ pulsar doctor # check the setup
27
+ pulsar uninstall --dry-run # preview removal
28
+ ```
29
+
30
+ - **What `init` does:** it adds the deployment key and server URL to Info.plist and strings.xml. It also
31
+ makes release builds load installed updates, but only where AppDelegate (Swift or Objective-C) and
32
+ MainApplication (Kotlin or Java) match the React Native templates.
33
+ - **Markers:** every change sits between `BEGIN PULSAR` / `END PULSAR` markers. A line it replaces is
34
+ kept as a `PULSAR ORIGINAL` comment.
35
+ - **What `init` won't touch:** it doesn't write without `--write`, and refuses files with uncommitted
36
+ changes. It doesn't install packages, run `pod install` or edit JavaScript; it prints those steps.
37
+ Anything that doesn't match a template is listed for you to change by hand.
38
+ - **Expo:** managed Expo apps (no `ios/` and `android/` folders) aren't supported, because prebuild
39
+ would overwrite the changes.
40
+ - **Uninstall:** `pulsar uninstall` removes the marked blocks (restoring replaced lines) and every
41
+ `CodePush…` setting. It lists anything added without markers (including JavaScript) for you to
42
+ remove by hand, and exits 1 when there is some.
43
+
19
44
  ## Commands
20
45
 
21
46
  ```bash
@@ -50,7 +75,11 @@ pulsar changes --app <name> --deployment <dep> --label <vN> # unlock a private
50
75
  - `--rollout N` — serve to a deterministic N% of devices (by `client_unique_id`).
51
76
  - `--devices id1,id2` — serve **only** to those exact device ids (most granular). Empty = all devices.
52
77
  - `--disabled` — upload the bundle but don't serve it (flip on later with `pulsar patch … --enable`).
53
- - `--target <range>` — semver range of native binary versions the release applies to.
78
+ - `--target <range>` — semver range of native binary versions the release applies to. Leave it out
79
+ to use the app's own version: `CFBundleShortVersionString` / `MARKETING_VERSION` on iOS,
80
+ `versionName` in `android/app/build.gradle` on Android. The CLI then checks that devices on that
81
+ version have checked in with Pulsar, and stops if other store builds are live but this one isn't.
82
+ `release-train` always needs `--target`.
54
83
 
55
84
  ## How a release works
56
85
 
@@ -61,6 +90,30 @@ then downloads it in the background and swaps it in on next launch.
61
90
 
62
91
  Auth is read from `PULSAR_API_URL` / `PULSAR_TOKEN` env, or `~/.pulsar/config.json` (written by `pulsar login`). Nothing is committed.
63
92
 
93
+ ## Native change guard
94
+
95
+ An OTA can only change JavaScript and assets. If a release needs native code the store build doesn't
96
+ have, the app can crash on launch. `pulsar release` reads the project's native fingerprint: the
97
+ React Native version, plus every package with native code for the platform (autolinked or Expo
98
+ module) and its version, plus any `patches/` file for those packages. Podfile.lock and Gradle files
99
+ don't count, so it stays the same from build to build.
100
+
101
+ - The first release for a store version records that build's fingerprint on Pulsar.
102
+ - A later release to that version (or to a range that covers it) with a different fingerprint is
103
+ refused before anything is stored, with the packages that changed listed.
104
+ - `--allow-native-change` releases anyway, without moving the record. `--no-native-check` sends no
105
+ fingerprint.
106
+ - Your own native code (AppDelegate, MainApplication, custom modules in `ios/` or `android/`) isn't
107
+ covered.
108
+
109
+ Record the store build explicitly from the script that makes it, so the record never comes from a
110
+ later, already-changed project:
111
+
112
+ ```bash
113
+ pulsar fingerprint --platform ios # print it
114
+ pulsar fingerprint record MyApp --platform ios --target 1.4.0 # record a store build
115
+ ```
116
+
64
117
  ## Code signing
65
118
 
66
119
  ```bash
package/fingerprint.js ADDED
@@ -0,0 +1,80 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import {execFileSync} from 'node:child_process';
5
+
6
+ const sha256 = (text) => crypto.createHash('sha256').update(text).digest('hex');
7
+
8
+ const readJson = (file) => {
9
+ try {
10
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
11
+ } catch {
12
+ return null;
13
+ }
14
+ };
15
+
16
+ const EXPO_PLATFORMS = {ios: ['ios', 'apple'], android: ['android']};
17
+
18
+ export function autolinkedPackages(config, platform) {
19
+ return Object.values(config?.dependencies || {})
20
+ .filter((dependency) => dependency?.platforms?.[platform])
21
+ .map((dependency) => ({name: dependency.name, root: dependency.root}));
22
+ }
23
+
24
+ export function expoModules(root, platform) {
25
+ const manifest = readJson(path.join(root, 'package.json')) || {};
26
+ const names = Object.keys({...manifest.dependencies, ...manifest.optionalDependencies});
27
+ return names
28
+ .map((name) => ({name, root: path.join(root, 'node_modules', name)}))
29
+ .filter(({root: packageRoot}) => {
30
+ const module = readJson(path.join(packageRoot, 'expo-module.config.json'));
31
+ if (!module) return false;
32
+ return !Array.isArray(module.platforms) || module.platforms.some((entry) => EXPO_PLATFORMS[platform].includes(entry));
33
+ });
34
+ }
35
+
36
+ export function patchDigests(root, names) {
37
+ const dir = path.join(root, 'patches');
38
+ let files;
39
+ try {
40
+ files = fs.readdirSync(dir).filter((file) => file.endsWith('.patch')).sort();
41
+ } catch {
42
+ return {};
43
+ }
44
+ const digests = {};
45
+ for (const name of names) {
46
+ const prefix = `${name.replace('/', '+')}+`;
47
+ const matching = files.filter((file) => file.startsWith(prefix));
48
+ if (matching.length) digests[name] = sha256(matching.map((file) => fs.readFileSync(path.join(dir, file), 'utf8')).join('\n')).slice(0, 12);
49
+ }
50
+ return digests;
51
+ }
52
+
53
+ export function fingerprintOf(packages) {
54
+ const deps = Object.fromEntries(Object.entries(packages).sort(([left], [right]) => left.localeCompare(right)));
55
+ return {v: 1, hash: sha256(JSON.stringify(['pulsar-native-v1', deps])), deps};
56
+ }
57
+
58
+ export function nativeFingerprint(platform, root, {readConfig = defaultReadConfig} = {}) {
59
+ const reactNative = readJson(path.join(root, 'node_modules', 'react-native', 'package.json'));
60
+ if (!reactNative?.version) return {error: 'react-native is not installed in this project'};
61
+ let config;
62
+ try {
63
+ config = readConfig(root);
64
+ } catch (err) {
65
+ return {error: `react-native config failed (${String(err.message || err).split('\n')[0]})`};
66
+ }
67
+ const found = [...autolinkedPackages(config, platform), ...expoModules(root, platform)];
68
+ const versions = {'react-native': reactNative.version};
69
+ for (const {name, root: packageRoot} of found) {
70
+ versions[name] = readJson(path.join(packageRoot || path.join(root, 'node_modules', name), 'package.json'))?.version || 'unknown';
71
+ }
72
+ const patches = patchDigests(root, Object.keys(versions));
73
+ for (const [name, digest] of Object.entries(patches)) versions[name] = `${versions[name]}+patch.${digest}`;
74
+ return {fingerprint: fingerprintOf(versions)};
75
+ }
76
+
77
+ function defaultReadConfig(root) {
78
+ const output = execFileSync('npx', ['--no-install', 'react-native', 'config'], {cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000, maxBuffer: 64 * 1024 * 1024});
79
+ return JSON.parse(output.slice(output.indexOf('{')));
80
+ }
package/hermes.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import fs from 'node:fs';
2
- import os from 'node:os';
3
2
  import path from 'node:path';
4
3
  import {spawnSync} from 'node:child_process';
5
4
  import {walk} from './hash.js';
5
+ import {exitIfInterrupted, makeTempDir, removeTemp, trackTemp} from './temp.js';
6
6
 
7
7
  const MAGIC = Buffer.from('c61fbc03c103191f', 'hex');
8
8
  const HEADER_LENGTH = 12;
@@ -94,6 +94,7 @@ export function compileBytecode(hermesc, inputPath, outputPath, {sourcemap = fal
94
94
  ['-emit-binary', '-max-diagnostic-width=80', '-O', ...(sourcemap ? ['-output-source-map'] : []), '-out', outputPath, inputPath],
95
95
  {encoding: 'utf8', maxBuffer: 256 * 1024 * 1024},
96
96
  );
97
+ exitIfInterrupted(result.signal);
97
98
  if (result.error) throw new Error(`could not run ${hermesc}: ${result.error.message}`);
98
99
  if (result.status !== 0) throw new Error(`hermesc failed:\n${diagnostics(result.stderr || result.stdout)}`);
99
100
  const bytecodeVersion = fs.existsSync(outputPath) ? fileBytecodeVersion(outputPath) : null;
@@ -104,28 +105,32 @@ export function compileBytecode(hermesc, inputPath, outputPath, {sourcemap = fal
104
105
 
105
106
  export function composeSourcemaps(composeScript, packagerMapPath, compilerMapPath, outputPath) {
106
107
  const result = spawnSync(process.execPath, [composeScript, packagerMapPath, compilerMapPath, '-o', outputPath], {encoding: 'utf8', maxBuffer: 64 * 1024 * 1024});
108
+ exitIfInterrupted(result.signal);
107
109
  if (result.error) throw new Error(result.error.message);
108
110
  if (result.status !== 0 || !fs.existsSync(outputPath)) throw new Error(diagnostics(result.stderr) || `exit code ${result.status}`);
109
111
  }
110
112
 
111
113
  export function buildBytecode({hermesc, composeScript}, javascript, bundleName) {
112
- const compilerDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-hermesc-'));
113
- const compiledPath = path.join(compilerDir, bundleName);
114
- const compiled = compileBytecode(hermesc, path.join(javascript.contentsDir, bundleName), compiledPath, {sourcemap: Boolean(javascript.sourcemapPath)});
115
- const contentsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-bytecode-'));
116
- fs.cpSync(javascript.contentsDir, contentsDir, {recursive: true});
117
- fs.copyFileSync(compiledPath, path.join(contentsDir, bundleName));
118
- let sourcemapPath = null;
119
- let sourcemapError = null;
120
- if (compiled.sourcemapPath) {
121
- try {
122
- if (!composeScript) throw new Error('react-native/scripts/compose-source-maps.js was not found in node_modules');
123
- composeSourcemaps(composeScript, javascript.sourcemapPath, compiled.sourcemapPath, `${contentsDir}.map`);
124
- sourcemapPath = `${contentsDir}.map`;
125
- } catch (err) {
126
- sourcemapError = err.message;
114
+ const compilerDir = makeTempDir('pulsar-hermesc-');
115
+ try {
116
+ const compiledPath = path.join(compilerDir, bundleName);
117
+ const compiled = compileBytecode(hermesc, path.join(javascript.contentsDir, bundleName), compiledPath, {sourcemap: Boolean(javascript.sourcemapPath)});
118
+ const contentsDir = makeTempDir('pulsar-bytecode-');
119
+ fs.cpSync(javascript.contentsDir, contentsDir, {recursive: true});
120
+ fs.copyFileSync(compiledPath, path.join(contentsDir, bundleName));
121
+ let sourcemapPath = null;
122
+ let sourcemapError = null;
123
+ if (compiled.sourcemapPath) {
124
+ try {
125
+ if (!composeScript) throw new Error('react-native/scripts/compose-source-maps.js was not found in node_modules');
126
+ composeSourcemaps(composeScript, javascript.sourcemapPath, compiled.sourcemapPath, trackTemp(`${contentsDir}.map`));
127
+ sourcemapPath = `${contentsDir}.map`;
128
+ } catch (err) {
129
+ sourcemapError = err.message;
130
+ }
127
131
  }
132
+ return {contentsDir, bytecodeVersion: compiled.bytecodeVersion, sourcemapPath, sourcemapError};
133
+ } finally {
134
+ removeTemp(compilerDir);
128
135
  }
129
- fs.rmSync(compilerDir, {recursive: true, force: true});
130
- return {contentsDir, bytecodeVersion: compiled.bytecodeVersion, sourcemapPath, sourcemapError};
131
136
  }
package/migrate.js CHANGED
@@ -1,10 +1,9 @@
1
1
  import fs from 'node:fs';
2
- import os from 'node:os';
3
2
  import path from 'node:path';
4
- import {execFileSync} from 'node:child_process';
5
3
  import {api, die, getFlag, loadConfig, pushBuiltRelease, splitList} from './pulsar.js';
6
4
  import {computePackageHash} from './hash.js';
7
5
  import {bundleBytecodeIn} from './hermes.js';
6
+ import {execFileSyncInterruptible, makeTempDir, removeTemp} from './temp.js';
8
7
 
9
8
  const USAGE = 'Usage: pulsar migrate --from <serverUrl> --access-key <key> [--apps A,B] [--org <name>] [--platform ios|android] [--releases latest|none] [--dry-run]';
10
9
 
@@ -39,7 +38,7 @@ async function migrateRelease({source, pulsarApp, deploymentName, sourcePackage,
39
38
  if (!sourcePackage) return 'no release on source';
40
39
  if (!sourcePackage.appVersion) return `not migrated: ${sourcePackage.label} has no target app version`;
41
40
  if (dryRun) return `would re-release ${sourcePackage.label} (target ${sourcePackage.appVersion})`;
42
- const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-migrate-'));
41
+ const workDir = makeTempDir('pulsar-migrate-');
43
42
  const zipPath = path.join(workDir, 'source.zip');
44
43
  const contentsDir = path.join(workDir, 'contents');
45
44
  try {
@@ -49,7 +48,7 @@ async function migrateRelease({source, pulsarApp, deploymentName, sourcePackage,
49
48
  if (!response.ok) throw new Error(`download failed (${response.status})`);
50
49
  fs.writeFileSync(zipPath, Buffer.from(await response.arrayBuffer()));
51
50
  try {
52
- execFileSync('unzip', ['-qq', '-o', zipPath, '-d', contentsDir], {stdio: 'pipe'});
51
+ execFileSyncInterruptible('unzip', ['-qq', '-o', zipPath, '-d', contentsDir], {stdio: 'pipe'});
53
52
  } catch {
54
53
  throw new Error('downloaded bundle is not a readable zip');
55
54
  }
@@ -78,7 +77,7 @@ async function migrateRelease({source, pulsarApp, deploymentName, sourcePackage,
78
77
  } catch (err) {
79
78
  return `not migrated: ${err.message}`;
80
79
  } finally {
81
- fs.rmSync(workDir, {recursive: true, force: true});
80
+ removeTemp(workDir);
82
81
  }
83
82
  }
84
83
 
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const readText = (file) => {
5
+ try {
6
+ return fs.readFileSync(file, 'utf8');
7
+ } catch {
8
+ return null;
9
+ }
10
+ };
11
+
12
+ const listDir = (dir) => {
13
+ try {
14
+ return fs.readdirSync(dir, {withFileTypes: true});
15
+ } catch {
16
+ return [];
17
+ }
18
+ };
19
+
20
+ const unique = (values) => [...new Set(values)];
21
+
22
+ const plistString = (text, key) => text.match(new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`))?.[1]?.trim();
23
+
24
+ export function appInfoPlists(iosDir) {
25
+ const plists = listDir(iosDir)
26
+ .filter((entry) => entry.isDirectory() && !['Pods', 'build'].includes(entry.name) && !entry.name.endsWith('.xcodeproj') && !entry.name.endsWith('.xcworkspace'))
27
+ .map((entry) => path.join(iosDir, entry.name, 'Info.plist'))
28
+ .map((file) => ({file, text: readText(file)}))
29
+ .filter((plist) => plist.text?.includes('CFBundleShortVersionString') && !plist.text.includes('<key>NSExtension</key>') && !/Tests$/.test(path.basename(path.dirname(plist.file))));
30
+ const withKey = plists.filter((plist) => plist.text.includes('CodePushDeploymentKey'));
31
+ return withKey.length ? withKey : plists;
32
+ }
33
+
34
+ function buildConfigurations(pbxproj) {
35
+ return pbxproj
36
+ .split('isa = XCBuildConfiguration;')
37
+ .slice(1)
38
+ .map((chunk) => ({
39
+ name: chunk.match(/\bname = "?([^";]+)"?;/)?.[1],
40
+ infoPlist: chunk.match(/INFOPLIST_FILE = "?([^";]+)"?;/)?.[1],
41
+ version: chunk.match(/MARKETING_VERSION = "?([^";]+)"?;/)?.[1],
42
+ }));
43
+ }
44
+
45
+ export function iosVersion(root) {
46
+ const iosDir = path.join(root, 'ios');
47
+ const plists = appInfoPlists(iosDir);
48
+ if (!plists.length) return {error: 'no app Info.plist found under ios/'};
49
+ if (plists.length > 1) return {error: `several app targets in ios/ (${plists.map((plist) => path.relative(root, plist.file)).join(', ')})`};
50
+ const [plist] = plists;
51
+ const source = path.relative(root, plist.file);
52
+ const value = plistString(plist.text, 'CFBundleShortVersionString');
53
+ if (value && !value.includes('$')) return {version: value, source: `${source} CFBundleShortVersionString`};
54
+ if (!/^\$[({]MARKETING_VERSION[)}]$/.test(value || '')) return {error: `${source} sets CFBundleShortVersionString to ${value || 'nothing'}, which can't be read before the build`};
55
+ const relativePlist = path.relative(iosDir, plist.file);
56
+ const projects = listDir(iosDir).filter((entry) => entry.name.endsWith('.xcodeproj') && entry.name !== 'Pods.xcodeproj');
57
+ const configs = projects.flatMap((project) => buildConfigurations(readText(path.join(iosDir, project.name, 'project.pbxproj')) || ''));
58
+ const appConfigs = configs.filter((config) => config.version && config.infoPlist && path.normalize(config.infoPlist.replace(/^\$\(SRCROOT\)\//, '')) === relativePlist);
59
+ const release = appConfigs.filter((config) => !/debug/i.test(config.name || ''));
60
+ const versions = unique((release.length ? release : appConfigs).map((config) => config.version));
61
+ if (!versions.length) return {error: `no MARKETING_VERSION found for ${relativePlist} in the Xcode project`};
62
+ if (versions.length > 1) return {error: `the Xcode project's release configurations disagree on MARKETING_VERSION (${versions.join(', ')})`};
63
+ return {version: versions[0], source: `${projects.map((project) => project.name).join(', ')} MARKETING_VERSION`};
64
+ }
65
+
66
+ export function androidVersion(root) {
67
+ for (const name of ['build.gradle', 'build.gradle.kts']) {
68
+ const file = path.join(root, 'android', 'app', name);
69
+ const text = readText(file);
70
+ if (text === null) continue;
71
+ const source = path.relative(root, file);
72
+ const lines = text.split('\n').filter((line) => /^\s*versionName\b/.test(line));
73
+ if (!lines.length) return {error: `${source} has no versionName`};
74
+ const literals = lines.map((line) => line.match(/^\s*versionName\s*=?\s*["']([^"'$]+)["']\s*$/)?.[1]);
75
+ if (literals.includes(undefined)) return {error: `${source} computes versionName, so it can't be read before the build`};
76
+ const versions = unique(literals);
77
+ if (versions.length > 1) return {error: `${source} sets more than one versionName (${versions.join(', ')})`};
78
+ return {version: versions[0], source: `${source} versionName`};
79
+ }
80
+ return {error: 'no android/app/build.gradle here'};
81
+ }
82
+
83
+ export const nativeVersion = (platform, root) => (platform === 'android' ? androidVersion(root) : iosVersion(root));
84
+
85
+ export function chooseTarget(local, binaries) {
86
+ if (!binaries) return {target: local.version, note: "couldn't check which store builds are live"};
87
+ const versions = binaries.versions || [];
88
+ const seen = versions.find((entry) => entry.version === local.version);
89
+ if (seen) return {target: local.version, note: `${seen.activeDevices || 0} active devices on ${local.version} in the last ${binaries.recentDays} days`};
90
+ if (!versions.length) return {target: local.version, note: 'no store build has checked in with Pulsar yet'};
91
+ const live = versions
92
+ .slice(0, 5)
93
+ .map((entry) => `${entry.version} (${entry.activeDevices || 0} active devices)`)
94
+ .join(', ');
95
+ return {error: `no device has checked in on ${local.version} yet. Builds seen: ${live}`};
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@novacraft-engineering/pulsar-cli",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "Pulsar OTA release CLI — bundle, hash, and ship React Native updates over-the-air.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,10 @@
12
12
  "migrate.js",
13
13
  "private.js",
14
14
  "hermes.js",
15
+ "temp.js",
16
+ "nativeVersion.js",
17
+ "fingerprint.js",
18
+ "setup.js",
15
19
  "envelope.js",
16
20
  "releaseCompare.js",
17
21
  "README.md",
@@ -31,7 +35,7 @@
31
35
  "node": ">=18"
32
36
  },
33
37
  "scripts": {
34
- "test": "node test/hash.test.js && node test/security.test.js && node test/signing.test.js && node test/entry.test.js && node test/migrate.test.js && node test/envelope.test.js && node test/private.test.js && node test/hermes.test.js && node test/connection.test.js"
38
+ "test": "node test/hash.test.js && node test/security.test.js && node test/signing.test.js && node test/entry.test.js && node test/migrate.test.js && node test/envelope.test.js && node test/private.test.js && node test/hermes.test.js && node test/connection.test.js && node test/temp.test.js && node test/nativeVersion.test.js && node test/fingerprint.test.js && node test/setup.test.js"
35
39
  },
36
40
  "keywords": [
37
41
  "cli",
package/pulsar.js CHANGED
@@ -11,6 +11,10 @@ import {computePackageHash, fileHashes} from './hash.js';
11
11
  import {migrate} from './migrate.js';
12
12
  import {privateContext, reportReach, sealArtifact, openArtifact, sealedHeaders, cmdBundleKey, cmdChanges} from './private.js';
13
13
  import {bundleFileName, buildBytecode, findComposeScript, findHermesc, hermesChoice} from './hermes.js';
14
+ import {execFileSyncInterruptible, makeTempDir, removeTemp, trackTemp} from './temp.js';
15
+ import {chooseTarget, nativeVersion} from './nativeVersion.js';
16
+ import {nativeFingerprint} from './fingerprint.js';
17
+ import {doctor, installCommand, planInit, planUninstall} from './setup.js';
14
18
 
15
19
  // Code signing: sign the package hash into an RS256 JWT the client verifies against its
16
20
  // CodePushPublicKey (Info.plist). Both native SDKs read it from <update>/CodePush/.codepushrelease
@@ -224,9 +228,10 @@ function bundle(platform, contentsDir, sourcemapPath, {forHermes = false} = {})
224
228
  const bundleName = bundleFileName(platform);
225
229
  fs.mkdirSync(contentsDir, {recursive: true});
226
230
  console.log(forHermes ? `• bundling ${platform} unminified for the Hermes compiler, as React Native's release build does…` : `• bundling ${platform}…`);
227
- execFileSync(
231
+ execFileSyncInterruptible(
228
232
  'npx',
229
233
  [
234
+ '--no-install',
230
235
  'react-native',
231
236
  'bundle',
232
237
  '--platform', platform,
@@ -260,9 +265,12 @@ function growthChecks(previous, {size, jsSize = null, hermes = false}) {
260
265
  }
261
266
 
262
267
  function zipContents(contentsDir) {
263
- const zipPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-zip-')), 'release.zip');
264
- execFileSync('zip', ['-qq', '-r', '-X', zipPath, '.'], {cwd: contentsDir});
265
- return zipPath;
268
+ const zipDir = makeTempDir('pulsar-zip-');
269
+ const zipPath = path.join(zipDir, 'release.zip');
270
+ execFileSyncInterruptible('zip', ['-qq', '-r', '-X', zipPath, '.'], {cwd: contentsDir});
271
+ const zip = fs.readFileSync(zipPath);
272
+ removeTemp(zipDir);
273
+ return zip;
266
274
  }
267
275
 
268
276
  // Build a differential package: only the files that changed vs the base, plus a hotcodepush.json
@@ -270,14 +278,16 @@ function zipContents(contentsDir) {
270
278
  // this diff, then verifies the result against the target hash. Returns the diff dir, or null if the
271
279
  // base couldn't be fetched.
272
280
  async function buildDiffPackage(baseZip, newDir) {
273
- const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-base-'));
274
- const basePath = path.join(os.tmpdir(), `pulsar-base-${Date.now()}.zip`);
281
+ const baseWorkDir = makeTempDir('pulsar-base-');
282
+ const basePath = path.join(baseWorkDir, 'base.zip');
283
+ const baseDir = path.join(baseWorkDir, 'contents');
275
284
  fs.writeFileSync(basePath, baseZip);
276
- execFileSync('unzip', ['-qq', '-o', basePath, '-d', baseDir]);
285
+ execFileSyncInterruptible('unzip', ['-qq', '-o', basePath, '-d', baseDir]);
277
286
 
278
287
  const baseHashes = fileHashes(baseDir);
288
+ removeTemp(baseWorkDir);
279
289
  const newHashes = fileHashes(newDir);
280
- const diffDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-diff-'));
290
+ const diffDir = makeTempDir('pulsar-diff-');
281
291
 
282
292
  for (const [relativePath, hash] of Object.entries(newHashes)) {
283
293
  if (baseHashes[relativePath] === hash) continue;
@@ -438,7 +448,7 @@ function diffBases(app, previous, packageHash) {
438
448
  const bases = [{
439
449
  label: previous.label,
440
450
  packageHash: previous.packageHash,
441
- file: previous.encrypted && previous.blobKey ? blobFile(previous.blobKey) : `${previous.packageHash}.zip`,
451
+ file: previous.blobKey ? blobFile(previous.blobKey) : `${previous.packageHash}.zip`,
442
452
  }];
443
453
  if (previous.jsCopy?.packageHash && previous.jsCopy.blobKey) {
444
454
  bases.push({label: `${previous.label} JavaScript copy`, packageHash: previous.jsCopy.packageHash, file: blobFile(previous.jsCopy.blobKey), jsCopy: true});
@@ -448,7 +458,7 @@ function diffBases(app, previous, packageHash) {
448
458
 
449
459
  // Sign and push an already-built bundle to one app's deployment, then generate and upload a
450
460
  // differential patch against whatever that deployment was serving.
451
- async function pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported = false, hermes = null, javascript = null} = {}) {
461
+ async function pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported = false, hermes = null, javascript = null, fingerprint = null} = {}) {
452
462
  if (hermes && !javascript) die('a Hermes bytecode release needs its JavaScript copy. Nothing was uploaded.');
453
463
  const privateBundles = await privateContext(app, args, localKey);
454
464
  const sealing = Boolean(privateBundles) && !privateBundles.plain;
@@ -457,9 +467,9 @@ async function pushBuiltRelease(app, deployment, args, contentsDir, packageHash,
457
467
  await signForApp(app, deployment, contentsDir, packageHash, localKey);
458
468
  if (hermes) await signForApp(app, deployment, javascript.contentsDir, javascript.packageHash, localKey, 'the JavaScript copy');
459
469
  const sealFull = async (hash, bytes) => (sealing ? Buffer.from(await sealArtifact(privateBundles, app, hash, bytes, 'full')) : bytes);
460
- const plainZip = fs.readFileSync(zipContents(contentsDir));
470
+ const plainZip = zipContents(contentsDir);
461
471
  const zip = await sealFull(packageHash, plainZip);
462
- const plainJsZip = hermes ? fs.readFileSync(zipContents(javascript.contentsDir)) : null;
472
+ const plainJsZip = hermes ? zipContents(javascript.contentsDir) : null;
463
473
  const jsZip = hermes ? await sealFull(javascript.packageHash, plainJsZip) : null;
464
474
  let prevLatest = null;
465
475
  try {
@@ -507,6 +517,8 @@ async function pushBuiltRelease(app, deployment, args, contentsDir, packageHash,
507
517
  ...(privateBundles?.plain === 'all' ? {'x-plain': '1'} : {}),
508
518
  ...(privateBundles?.plain === 'older' ? {'x-audience': 'older-builds'} : {}),
509
519
  ...(hermes ? {'x-hermes-bytecode-version': String(hermes.bytecodeVersion)} : {}),
520
+ ...(fingerprint ? {'x-native-fingerprint': encodeURIComponent(JSON.stringify(fingerprint))} : {}),
521
+ ...(args.includes('--allow-native-change') ? {'x-allow-native-change': '1'} : {}),
510
522
  'x-app-version': target,
511
523
  'x-package-hash': packageHash,
512
524
  'x-is-mandatory': String(args.includes('--mandatory')),
@@ -626,7 +638,8 @@ async function pushBuiltRelease(app, deployment, args, contentsDir, packageHash,
626
638
  baseZip = await openArtifact(privateBundles.keys, baseZip, {appId: app.id, packageHash: base.packageHash, kind: 'full'});
627
639
  }
628
640
  const diffDir = await buildDiffPackage(baseZip, contentsDir);
629
- const plainDiff = fs.readFileSync(zipContents(diffDir));
641
+ const plainDiff = zipContents(diffDir);
642
+ removeTemp(diffDir);
630
643
  const diffZip = sealing
631
644
  ? Buffer.from(await sealArtifact(privateBundles, app, packageHash, plainDiff, 'diff', {baseHash: base.packageHash}))
632
645
  : plainDiff;
@@ -679,14 +692,14 @@ function hermesCompiler(args, projectRoot = process.cwd()) {
679
692
  function buildOnce(args, compiler = null) {
680
693
  const platform = getFlag(args, 'platform', 'ios');
681
694
  const localKey = localSigningKey(args);
682
- const contentsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-build-'));
683
- const sourcemapPath = args.includes('--no-sourcemap') ? null : `${contentsDir}.map`;
695
+ const contentsDir = makeTempDir('pulsar-build-');
696
+ const sourcemapPath = args.includes('--no-sourcemap') ? null : trackTemp(`${contentsDir}.map`);
684
697
  bundle(platform, contentsDir, sourcemapPath);
685
698
  const packageHash = computePackageHash(contentsDir);
686
699
  console.log(`• hash ${packageHash.slice(0, 12)}…`);
687
700
  if (!compiler) return {contentsDir, packageHash, localKey, sourcemapPath};
688
- const sourceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-hermes-source-'));
689
- const sourceMapPath = sourcemapPath ? `${sourceDir}.map` : null;
701
+ const sourceDir = makeTempDir('pulsar-hermes-source-');
702
+ const sourceMapPath = sourcemapPath ? trackTemp(`${sourceDir}.map`) : null;
690
703
  bundle(platform, sourceDir, sourceMapPath, {forHermes: true});
691
704
  console.log(`• compiling Hermes bytecode with ${path.relative(process.cwd(), compiler.hermesc) || compiler.hermesc}…`);
692
705
  let bytecode;
@@ -696,8 +709,8 @@ function buildOnce(args, compiler = null) {
696
709
  } catch (err) {
697
710
  compileError = err;
698
711
  }
699
- fs.rmSync(sourceDir, {recursive: true, force: true});
700
- if (sourceMapPath) fs.rmSync(sourceMapPath, {force: true});
712
+ removeTemp(sourceDir);
713
+ if (sourceMapPath) removeTemp(sourceMapPath);
701
714
  if (compileError) die(`${compileError.message}\nPass --no-hermes to release JavaScript instead. Nothing was uploaded.`);
702
715
  if (bytecode.sourcemapError) console.log(`⚠ bytecode source map not composed (${bytecode.sourcemapError}): crash stacks from bytecode won't show your source files`);
703
716
  const bytecodeHash = computePackageHash(bytecode.contentsDir);
@@ -712,18 +725,137 @@ function buildOnce(args, compiler = null) {
712
725
  };
713
726
  }
714
727
 
728
+ function releaseFingerprint(args, platform) {
729
+ if (args.includes('--no-native-check')) return null;
730
+ const result = nativeFingerprint(platform, process.cwd());
731
+ if (result.error) {
732
+ console.log(`⚠ native check skipped: ${result.error}`);
733
+ return null;
734
+ }
735
+ console.log(`• native fingerprint ${result.fingerprint.hash.slice(0, 12)} (react-native ${result.fingerprint.deps['react-native']}, ${Object.keys(result.fingerprint.deps).length - 1} native packages)`);
736
+ return result.fingerprint;
737
+ }
738
+
739
+ async function cmdFingerprint(args) {
740
+ const platform = getFlag(args, 'platform', 'ios');
741
+ const result = nativeFingerprint(platform, process.cwd());
742
+ if (result.error) die(result.error);
743
+ const {fingerprint} = result;
744
+ if (args[0] !== 'record') {
745
+ console.log(`${platform} native fingerprint ${fingerprint.hash}`);
746
+ for (const [name, version] of Object.entries(fingerprint.deps)) console.log(` ${name} ${version}`);
747
+ return;
748
+ }
749
+ const nameOrId = args[1];
750
+ const version = getFlag(args, 'target');
751
+ if (!nameOrId || !version || nameOrId.startsWith('--')) die('Usage: pulsar fingerprint record <app> --platform ios|android --target <store version>');
752
+ const app = await resolveApp(nameOrId, platform);
753
+ await api(`/apps/${app.id}/native-baselines`, {method: 'POST', body: {version, fingerprint}});
754
+ console.log(`✓ ${app.name} ${version} store build recorded with native fingerprint ${fingerprint.hash.slice(0, 12)}; releases to ${version} must match it`);
755
+ }
756
+
757
+ const relative = (file) => path.relative(process.cwd(), file) || file;
758
+
759
+ function refuseDirty(files) {
760
+ if (!files.length) return;
761
+ let dirty = '';
762
+ try {
763
+ dirty = execFileSync('git', ['status', '--porcelain', '--', ...files], {cwd: process.cwd(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore']}).trim();
764
+ } catch {
765
+ return;
766
+ }
767
+ if (dirty) die(`these files have uncommitted changes, so nothing was written. Commit or stash them first:\n${dirty}`);
768
+ }
769
+
770
+ function printDoctor() {
771
+ const checks = doctor(process.cwd());
772
+ for (const check of checks) console.log(`${check.ok ? '✓' : '✗'} ${check.name}`);
773
+ return checks.every((check) => check.ok);
774
+ }
775
+
776
+ async function cmdDoctor() {
777
+ if (!printDoctor()) process.exit(1);
778
+ }
779
+
780
+ async function cmdInit(args) {
781
+ const serverUrl = getFlag(args, 'server') || loadConfig().apiUrl || 'https://api.usepulsar.dev';
782
+ const plan = planInit(process.cwd(), {iosKey: getFlag(args, 'ios-key'), androidKey: getFlag(args, 'android-key'), serverUrl});
783
+ if (plan.error) die(plan.error);
784
+ const write = args.includes('--write');
785
+ for (const step of plan.steps) {
786
+ const where = step.file === 'ios' || step.file === 'android' ? step.file : relative(step.file);
787
+ if (step.status === 'changed') console.log(`• ${where}: ${write ? 'added' : 'will add'} ${step.what}`);
788
+ else if (step.status === 'already') console.log(`✓ ${where}: ${step.what} already set up`);
789
+ else if (step.status === 'skipped') console.log(`• ${where}: ${step.what} skipped (${step.reason})`);
790
+ else console.log(`✗ ${where}: ${step.what}: do this by hand (${step.reason}). See https://usepulsar.dev/ai-setup.txt`);
791
+ }
792
+ const changed = plan.steps.filter((step) => step.status === 'changed');
793
+ if (write) {
794
+ refuseDirty(changed.map((step) => step.file));
795
+ for (const step of changed) fs.writeFileSync(step.file, step.text);
796
+ console.log(changed.length ? `\n${changed.length} file(s) changed. Every change is inside BEGIN PULSAR / END PULSAR markers; \`pulsar uninstall\` removes them.\n` : '');
797
+ printDoctor();
798
+ } else if (changed.length) {
799
+ console.log('\nNothing written yet. Run again with --write to make these changes.');
800
+ }
801
+ console.log(`\nStill to do yourself:
802
+ 1. ${installCommand(process.cwd())}${fs.existsSync(path.join(process.cwd(), 'ios')) ? ', then cd ios && pod install' : ''}
803
+ 2. Wrap your root component:
804
+ import codePush from '@novacraft-engineering/pulsar-code-push';
805
+ export default codePush({installMode: codePush.InstallMode.ON_NEXT_RESTART})(App);
806
+ 3. Make a new store or test build: the native code changed, so an OTA alone can't deliver this.
807
+ 4. pulsar doctor (checks all of the above)`);
808
+ }
809
+
810
+ async function cmdUninstall(args) {
811
+ const dryRun = args.includes('--dry-run');
812
+ const {steps, javascript} = planUninstall(process.cwd());
813
+ let manual = javascript.length;
814
+ for (const step of steps) {
815
+ if (step.removed) console.log(`• ${relative(step.file)}: ${dryRun ? 'will remove' : 'removed'} ${step.removed} Pulsar block(s) or setting(s)`);
816
+ for (const leftover of step.leftovers) {
817
+ manual += 1;
818
+ console.log(`✗ ${relative(step.file)}:${leftover.line} remove by hand (added without markers): ${leftover.text}`);
819
+ }
820
+ }
821
+ for (const file of javascript) console.log(`✗ ${relative(file)}: imports or wraps the SDK; restore it by hand`);
822
+ const changed = steps.filter((step) => step.removed);
823
+ if (!dryRun) {
824
+ refuseDirty(changed.map((step) => step.file));
825
+ for (const step of changed) fs.writeFileSync(step.file, step.text);
826
+ }
827
+ if (!changed.length && !manual) console.log('No Pulsar setup found here.');
828
+ console.log(`\n${dryRun ? 'Nothing was changed (--dry-run). ' : ''}Then remove the package (${installCommand(process.cwd()).replace(/ (add|install) /, (match, verb) => (verb === 'add' ? ' remove ' : ' uninstall '))}) and run pod install in ios/.`);
829
+ if (manual) process.exit(1);
830
+ }
831
+
832
+ async function detectTarget(app, platform) {
833
+ const local = nativeVersion(platform, process.cwd());
834
+ if (local.error) die(`--target wasn't given and the store version couldn't be read: ${local.error}. Pass --target <store version>, e.g. --target 1.0.0`);
835
+ let binaries = null;
836
+ try {
837
+ binaries = await api(`/apps/${app.id}/binary-versions`, {optional: true});
838
+ } catch {}
839
+ const choice = chooseTarget(local, binaries);
840
+ if (choice.error) die(`--target wasn't given. ${local.source} says ${local.version}, but ${choice.error}. Pass --target with the store version this release is for. Nothing was uploaded.`);
841
+ console.log(`• --target ${choice.target} (from ${local.source}; ${choice.note})`);
842
+ return choice.target;
843
+ }
844
+
715
845
  async function cmdRelease(args) {
716
846
  const [nameOrId, deployment = 'Staging'] = args;
717
- if (!nameOrId) die('Usage: pulsar release <app> <Staging|Production> --platform ios|android --target <ver> [--mandatory] [--disabled] [--rollout N] [--schedule +6h|ISO] [--ramp 100@48] [--from v6,ota,binary] [--devices id1,id2,...] [--device-models model1;model2] [--users u1,u2] [--private-key key.pem] [--bundle-key key.txt] [--plain-copy-for-old-builds | --plain | --only-older-builds] [--hermes | --no-hermes] [--no-diff] [--no-sourcemap] [--max-growth <percent>] [--description "..."]');
718
- if (!getFlag(args, 'target')) die('--target <binary version> is required (e.g. --target 1.0.0)');
719
- const app = await resolveApp(nameOrId, getFlag(args, 'platform', 'ios'));
720
- if (app.os !== getFlag(args, 'platform', 'ios')) {
721
- console.log(`• note: resolved app "${app.name}" is ${app.os}; bundling ${getFlag(args, 'platform', 'ios')}`);
847
+ if (!nameOrId) die('Usage: pulsar release <app> <Staging|Production> --platform ios|android [--target <store version>, read from ios/ or android/ when left out] [--mandatory] [--disabled] [--rollout N] [--schedule +6h|ISO] [--ramp 100@48] [--from v6,ota,binary] [--devices id1,id2,...] [--device-models model1;model2] [--users u1,u2] [--private-key key.pem] [--bundle-key key.txt] [--plain-copy-for-old-builds | --plain | --only-older-builds] [--hermes | --no-hermes] [--no-diff] [--no-sourcemap] [--max-growth <percent>] [--allow-native-change | --no-native-check] [--description "..."]');
848
+ const platform = getFlag(args, 'platform', 'ios');
849
+ const app = await resolveApp(nameOrId, platform);
850
+ if (app.os !== platform) {
851
+ console.log(`• note: resolved app "${app.name}" is ${app.os}; bundling ${platform}`);
722
852
  }
853
+ if (!getFlag(args, 'target')) args.push('--target', await detectTarget(app, platform));
854
+ const fingerprint = releaseFingerprint(args, platform);
723
855
  await checkPrivateBeforeBuild([app], args);
724
856
  const compiler = hermesCompiler(args);
725
857
  const {contentsDir, packageHash, localKey, sourcemapPath, hermes, javascript} = buildOnce(args, compiler);
726
- await pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported: true, hermes, javascript});
858
+ await pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported: true, hermes, javascript, fingerprint});
727
859
  }
728
860
 
729
861
  // Release the same built bundle to several apps at once (shared-codebase / white-label fleets).
@@ -749,12 +881,13 @@ async function cmdReleaseTrain(args) {
749
881
  if (!apps.length) die(`No ${platform} apps matched.`);
750
882
 
751
883
  await checkPrivateBeforeBuild(apps, args);
884
+ const fingerprint = releaseFingerprint(args, platform);
752
885
  const compiler = hermesCompiler(args);
753
886
  const {contentsDir, packageHash, localKey, sourcemapPath, hermes, javascript} = buildOnce(args, compiler);
754
887
  console.log(`• release train → ${apps.length} app(s): ${apps.map((app) => app.name).join(', ')}`);
755
888
  for (const app of apps) {
756
889
  try {
757
- await pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported: true, hermes, javascript});
890
+ await pushBuiltRelease(app, deployment, args, contentsDir, packageHash, localKey, {sourcemapPath, reachReported: true, hermes, javascript, fingerprint});
758
891
  } catch (err) {
759
892
  console.log(`✗ ${app.name}: ${err.message}`);
760
893
  }
@@ -923,17 +1056,21 @@ if (invokedAsCli()) {
923
1056
  keys: cmdKeys,
924
1057
  'bundle-key': cmdBundleKey,
925
1058
  changes: cmdChanges,
1059
+ fingerprint: cmdFingerprint,
1060
+ init: cmdInit,
1061
+ uninstall: cmdUninstall,
1062
+ doctor: cmdDoctor,
926
1063
  migrate,
927
1064
  };
928
1065
 
929
- const ANONYMOUS_COMMANDS = new Set(['login', 'keygen']);
1066
+ const ANONYMOUS_COMMANDS = new Set(['login', 'keygen', 'fingerprint', 'init', 'uninstall', 'doctor']);
930
1067
 
931
1068
  if (commands[command] && !ANONYMOUS_COMMANDS.has(command) && !loadConfig().token) {
932
1069
  die('Not authenticated. Run: pulsar login <apiUrl>');
933
1070
  }
934
1071
 
935
1072
  (commands[command] || (() => {
936
- console.log('pulsar <login|apps|keys|release|release-train|promote|rollback|deployment|history|patch|keygen|bundle-key|changes|migrate>');
1073
+ console.log('pulsar <login|init|doctor|uninstall|apps|keys|release|release-train|promote|rollback|deployment|history|patch|keygen|bundle-key|changes|fingerprint|migrate>');
937
1074
  process.exit(command ? 1 : 0);
938
1075
  }))(rest);
939
1076
  }
package/setup.js ADDED
@@ -0,0 +1,259 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {appInfoPlists} from './nativeVersion.js';
4
+
5
+ const SDK_PACKAGE = '@novacraft-engineering/pulsar-code-push';
6
+ const ORIGINAL = 'PULSAR ORIGINAL: ';
7
+ const MARKS = {
8
+ slash: {begin: '// BEGIN PULSAR', end: '// END PULSAR', original: (line) => `// ${ORIGINAL}${line}`},
9
+ xml: {begin: '<!-- BEGIN PULSAR -->', end: '<!-- END PULSAR -->', original: (line) => `<!-- ${ORIGINAL}${line} -->`},
10
+ };
11
+
12
+ const marked = (indent, lines, style, original) => [
13
+ `${indent}${MARKS[style].begin}`,
14
+ ...(original === undefined ? [] : [`${indent}${MARKS[style].original(original)}`]),
15
+ ...lines.map((line) => (line ? `${indent}${line}` : line)),
16
+ `${indent}${MARKS[style].end}`,
17
+ ].join('\n');
18
+
19
+ const indentOf = (line) => line.match(/^\s*/)[0];
20
+
21
+ function insertAfterLast(text, pattern, block) {
22
+ const matches = [...text.matchAll(pattern)];
23
+ if (!matches.length) return null;
24
+ const last = matches[matches.length - 1];
25
+ const at = last.index + last[0].length;
26
+ return `${text.slice(0, at)}\n${block}${text.slice(at)}`;
27
+ }
28
+
29
+ function insertBefore(text, pattern, blockFor) {
30
+ const matches = [...text.matchAll(pattern)];
31
+ if (!matches.length) return null;
32
+ const last = matches[matches.length - 1];
33
+ const lineStart = text.lastIndexOf('\n', last.index) + 1;
34
+ return `${text.slice(0, lineStart)}${blockFor(last)}\n${text.slice(lineStart)}`;
35
+ }
36
+
37
+ function replaceLine(text, pattern, replacementFor) {
38
+ const match = text.match(pattern);
39
+ if (!match) return null;
40
+ return text.replace(pattern, replacementFor(match));
41
+ }
42
+
43
+ export function addPlistConfig(text, {deploymentKey, serverUrl}) {
44
+ if (text.includes('CodePushDeploymentKey')) return {text, status: 'already'};
45
+ const keyIndent = text.match(/^([ \t]*)<key>/m)?.[1] ?? '\t';
46
+ const next = insertBefore(text, /^[ \t]*<\/dict>\s*<\/plist>/gm, () => marked(keyIndent, [
47
+ '<key>CodePushDeploymentKey</key>',
48
+ `<string>${deploymentKey}</string>`,
49
+ '<key>CodePushServerURL</key>',
50
+ `<string>${serverUrl}</string>`,
51
+ ], 'xml'));
52
+ return next ? {text: next, status: 'changed'} : {text, status: 'manual', reason: 'no closing </dict></plist>'};
53
+ }
54
+
55
+ export function addStringsConfig(text, {deploymentKey, serverUrl}) {
56
+ if (text.includes('CodePushDeploymentKey')) return {text, status: 'already'};
57
+ const indent = text.match(/^([ \t]*)<string /m)?.[1] ?? ' ';
58
+ const next = insertBefore(text, /^[ \t]*<\/resources>/gm, () => marked(indent, [
59
+ `<string moduleConfig="true" name="CodePushDeploymentKey">${deploymentKey}</string>`,
60
+ `<string moduleConfig="true" name="CodePushServerUrl">${serverUrl}</string>`,
61
+ ], 'xml'));
62
+ return next ? {text: next, status: 'changed'} : {text, status: 'manual', reason: 'no closing </resources>'};
63
+ }
64
+
65
+ const SWIFT_BUNDLE = /^([ \t]*)((?:return\s+)?)(Bundle\.main\.url\(forResource:\s*"main",\s*withExtension:\s*"jsbundle"\))[ \t]*$/m;
66
+ const OBJC_BUNDLE = /^([ \t]*)((?:return\s+)?)(\[\[NSBundle mainBundle\] URLForResource:@"main" withExtension:@"jsbundle"\];)[ \t]*$/m;
67
+
68
+ export function editSwiftAppDelegate(text) {
69
+ if (text.includes('CodePush.bundleURL()')) return {text, status: 'already'};
70
+ let next = replaceLine(text, SWIFT_BUNDLE, ([line, indent, prefix]) => marked(indent, [`${prefix}CodePush.bundleURL()`], 'slash', line.slice(indent.length)));
71
+ if (!next) return {text, status: 'manual', reason: 'no Bundle.main.url(forResource: "main", withExtension: "jsbundle") line to replace'};
72
+ if (!/^import CodePush\s*$/m.test(next)) next = insertAfterLast(next, /^import .+$/gm, marked('', ['import CodePush'], 'slash'));
73
+ return {text: next, status: 'changed'};
74
+ }
75
+
76
+ export function editObjcAppDelegate(text) {
77
+ if (text.includes('[CodePush bundleURL]')) return {text, status: 'already'};
78
+ let next = replaceLine(text, OBJC_BUNDLE, ([line, indent, prefix]) => marked(indent, [`${prefix}[CodePush bundleURL];`], 'slash', line.slice(indent.length)));
79
+ if (!next) return {text, status: 'manual', reason: 'no [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"] line to replace'};
80
+ if (!next.includes('<CodePush/CodePush.h>')) next = insertAfterLast(next, /^#import .+$/gm, marked('', ['#import <CodePush/CodePush.h>'], 'slash'));
81
+ return {text: next, status: 'changed'};
82
+ }
83
+
84
+ const nextIndent = (text, index, fallback) => indentOf(text.slice(index).split('\n')[1] ?? '') || fallback;
85
+
86
+ export function editKotlinMainApplication(text) {
87
+ if (text.includes('CodePush.getJSBundleFile()')) return {text, status: 'already'};
88
+ let next = null;
89
+ const context = text.includes('getDefaultReactHost(') && text.match(/^([ \t]*)context = applicationContext,[ \t]*$/m);
90
+ if (context) {
91
+ const at = context.index + context[0].length;
92
+ next = `${text.slice(0, at)}\n${marked(context[1], ['jsBundleFilePath = CodePush.getJSBundleFile(),'], 'slash')}${text.slice(at)}`;
93
+ } else {
94
+ const host = text.match(/^([ \t]*).*object\s*:\s*DefaultReactNativeHost\(this\)\s*\{[ \t]*$/m);
95
+ if (host) {
96
+ const at = host.index + host[0].length;
97
+ const indent = nextIndent(text, host.index, `${host[1]} `);
98
+ next = `${text.slice(0, at)}\n${marked(indent, ['override fun getJSBundleFile(): String = CodePush.getJSBundleFile()'], 'slash')}${text.slice(at)}`;
99
+ }
100
+ }
101
+ if (!next) return {text, status: 'manual', reason: 'no getDefaultReactHost(context = applicationContext, …) call or DefaultReactNativeHost object'};
102
+ if (!next.includes('import com.microsoft.codepush.react.CodePush')) next = insertAfterLast(next, /^import .+$/gm, marked('', ['import com.microsoft.codepush.react.CodePush'], 'slash'));
103
+ return {text: next, status: 'changed'};
104
+ }
105
+
106
+ export function editJavaMainApplication(text) {
107
+ if (text.includes('CodePush.getJSBundleFile()')) return {text, status: 'already'};
108
+ const host = text.match(/^([ \t]*).*new\s+(?:Default)?ReactNativeHost\(this\)\s*\{[ \t]*$/m);
109
+ if (!host) return {text, status: 'manual', reason: 'no new DefaultReactNativeHost(this) { … } block'};
110
+ const at = host.index + host[0].length;
111
+ const indent = nextIndent(text, host.index, `${host[1]} `);
112
+ let next = `${text.slice(0, at)}\n${marked(indent, ['@Override', 'protected String getJSBundleFile() {', ' return CodePush.getJSBundleFile();', '}'], 'slash')}${text.slice(at)}`;
113
+ if (!next.includes('import com.microsoft.codepush.react.CodePush;')) next = insertAfterLast(next, /^import .+;$/gm, marked('', ['import com.microsoft.codepush.react.CodePush;'], 'slash'));
114
+ return {text: next, status: 'changed'};
115
+ }
116
+
117
+ const CONFIG_LINE = /^[ \t]*(<key>CodePush\w+<\/key>[ \t]*\n[ \t]*<(?:string|integer|true|false)\b[^\n]*|<string[^>]*name="CodePush\w+"[^>]*>[^<]*<\/string>)[ \t]*\n/gm;
118
+ const LEFTOVER = /CodePush\.bundleURL|\[CodePush bundleURL\]|CodePush\.getJSBundleFile|^import CodePush\b|<CodePush\/CodePush\.h>|codepush\.react\.CodePush|pulsar-code-push/m;
119
+
120
+ export function removePulsar(text) {
121
+ const lines = text.split('\n');
122
+ const kept = [];
123
+ let removed = 0;
124
+ for (let index = 0; index < lines.length; index++) {
125
+ const style = Object.values(MARKS).find((mark) => lines[index].trim() === mark.begin);
126
+ if (!style) {
127
+ kept.push(lines[index]);
128
+ continue;
129
+ }
130
+ const end = lines.findIndex((line, position) => position > index && line.trim() === style.end);
131
+ if (end < 0) {
132
+ kept.push(lines[index]);
133
+ continue;
134
+ }
135
+ const indent = indentOf(lines[index]);
136
+ const original = lines.slice(index + 1, end).map((line) => line.trim()).find((line) => line.includes(ORIGINAL));
137
+ if (original) kept.push(`${indent}${original.slice(original.indexOf(ORIGINAL) + ORIGINAL.length).replace(/ -->$/, '')}`);
138
+ removed += 1;
139
+ index = end;
140
+ }
141
+ let next = kept.join('\n');
142
+ const configCount = [...next.matchAll(CONFIG_LINE)].length;
143
+ next = next.replace(CONFIG_LINE, '');
144
+ const leftovers = next.split('\n').map((line, idx) => ({line: idx + 1, text: line.trim()})).filter((entry) => LEFTOVER.test(entry.text));
145
+ return {text: next, removed: removed + configCount, leftovers};
146
+ }
147
+
148
+ const read = (file) => {
149
+ try {
150
+ return fs.readFileSync(file, 'utf8');
151
+ } catch {
152
+ return null;
153
+ }
154
+ };
155
+
156
+ const listFiles = (dir, match, depth = 6) => {
157
+ if (depth < 0) return [];
158
+ let entries;
159
+ try {
160
+ entries = fs.readdirSync(dir, {withFileTypes: true});
161
+ } catch {
162
+ return [];
163
+ }
164
+ return entries.flatMap((entry) => {
165
+ if (entry.name.startsWith('.') || ['node_modules', 'Pods', 'build', 'dist', 'coverage'].includes(entry.name)) return [];
166
+ const full = path.join(dir, entry.name);
167
+ return entry.isDirectory() ? listFiles(full, match, depth - 1) : match(entry.name) ? [full] : [];
168
+ });
169
+ };
170
+
171
+ export function nativeFiles(root) {
172
+ const iosDir = path.join(root, 'ios');
173
+ const androidMain = path.join(root, 'android', 'app', 'src', 'main');
174
+ return {
175
+ ios: fs.existsSync(iosDir)
176
+ ? {
177
+ plists: appInfoPlists(iosDir).map((plist) => plist.file),
178
+ appDelegates: listFiles(iosDir, (name) => /^AppDelegate\.(swift|mm|m)$/.test(name), 2),
179
+ }
180
+ : null,
181
+ android: fs.existsSync(androidMain)
182
+ ? {
183
+ strings: [path.join(androidMain, 'res', 'values', 'strings.xml')].filter((file) => fs.existsSync(file)),
184
+ mainApplications: listFiles(path.join(androidMain, 'java'), (name) => /^MainApplication\.(kt|java)$/.test(name)).concat(listFiles(path.join(androidMain, 'kotlin'), (name) => /^MainApplication\.kt$/.test(name))),
185
+ }
186
+ : null,
187
+ };
188
+ }
189
+
190
+ const appDelegateEdit = (file) => (file.endsWith('.swift') ? editSwiftAppDelegate : editObjcAppDelegate);
191
+ const mainApplicationEdit = (file) => (file.endsWith('.kt') ? editKotlinMainApplication : editJavaMainApplication);
192
+
193
+ export function planInit(root, {iosKey, androidKey, serverUrl}) {
194
+ const files = nativeFiles(root);
195
+ if (!files.ios && !files.android) return {error: 'no ios/ or android/ folder here. A managed Expo app needs `npx expo prebuild` first, and prebuild would overwrite these changes, so Pulsar setup is not supported there yet.'};
196
+ const steps = [];
197
+ const plan = (file, edit, what) => {
198
+ const text = read(file);
199
+ if (text === null) return;
200
+ steps.push({file, what, ...edit(text)});
201
+ };
202
+ if (files.ios) {
203
+ if (iosKey) files.ios.plists.forEach((file) => plan(file, (text) => addPlistConfig(text, {deploymentKey: iosKey, serverUrl}), 'deployment key and server URL'));
204
+ else steps.push({file: 'ios', what: 'deployment key and server URL', status: 'skipped', reason: 'pass --ios-key <deployment key>'});
205
+ if (!files.ios.appDelegates.length) steps.push({file: 'ios', what: 'load installed updates at startup', status: 'manual', reason: 'no AppDelegate found'});
206
+ files.ios.appDelegates.forEach((file) => plan(file, appDelegateEdit(file), 'load installed updates at startup'));
207
+ }
208
+ if (files.android) {
209
+ if (androidKey) files.android.strings.forEach((file) => plan(file, (text) => addStringsConfig(text, {deploymentKey: androidKey, serverUrl}), 'deployment key and server URL'));
210
+ else steps.push({file: 'android', what: 'deployment key and server URL', status: 'skipped', reason: 'pass --android-key <deployment key>'});
211
+ if (!files.android.mainApplications.length) steps.push({file: 'android', what: 'load installed updates at startup', status: 'manual', reason: 'no MainApplication found'});
212
+ files.android.mainApplications.forEach((file) => plan(file, mainApplicationEdit(file), 'load installed updates at startup'));
213
+ }
214
+ return {steps};
215
+ }
216
+
217
+ export function planUninstall(root) {
218
+ const files = nativeFiles(root);
219
+ const candidates = [
220
+ ...(files.ios ? [...files.ios.plists, ...files.ios.appDelegates] : []),
221
+ ...(files.android ? [...files.android.strings, ...files.android.mainApplications] : []),
222
+ ];
223
+ const javascript = listFiles(root, (name) => /\.(js|jsx|ts|tsx)$/.test(name), 4)
224
+ .filter((file) => !file.includes(`${path.sep}android${path.sep}`) && !file.includes(`${path.sep}ios${path.sep}`))
225
+ .filter((file) => /BEGIN PULSAR|pulsar-code-push/.test(read(file) || ''));
226
+ const steps = candidates
227
+ .map((file) => ({file, original: read(file)}))
228
+ .filter(({original}) => original !== null)
229
+ .map(({file, original}) => ({file, original, ...removePulsar(original)}))
230
+ .filter((step) => step.removed || step.leftovers.length);
231
+ return {steps, javascript};
232
+ }
233
+
234
+ export function doctor(root) {
235
+ const files = nativeFiles(root);
236
+ const manifest = JSON.parse(read(path.join(root, 'package.json')) || '{}');
237
+ const checks = [{name: `${SDK_PACKAGE} in package.json`, ok: Boolean({...manifest.dependencies, ...manifest.devDependencies}[SDK_PACKAGE])}];
238
+ const any = (list, pattern) => list.some((file) => pattern.test(read(file) || ''));
239
+ if (files.ios) {
240
+ checks.push({name: 'iOS Info.plist has CodePushDeploymentKey', ok: any(files.ios.plists, /<key>CodePushDeploymentKey<\/key>/)});
241
+ checks.push({name: 'iOS AppDelegate loads installed updates', ok: any(files.ios.appDelegates, /CodePush\.bundleURL\(\)|\[CodePush bundleURL\]/)});
242
+ }
243
+ if (files.android) {
244
+ checks.push({name: 'Android strings.xml has CodePushDeploymentKey', ok: any(files.android.strings, /name="CodePushDeploymentKey"/)});
245
+ checks.push({name: 'Android MainApplication loads installed updates', ok: any(files.android.mainApplications, /CodePush\.getJSBundleFile\(\)/)});
246
+ }
247
+ const javascript = listFiles(root, (name) => /\.(js|jsx|ts|tsx)$/.test(name), 4)
248
+ .filter((file) => !file.includes(`${path.sep}android${path.sep}`) && !file.includes(`${path.sep}ios${path.sep}`));
249
+ checks.push({name: 'JavaScript imports the SDK', ok: javascript.some((file) => (read(file) || '').includes(SDK_PACKAGE))});
250
+ return checks;
251
+ }
252
+
253
+ export function installCommand(root) {
254
+ const has = (file) => fs.existsSync(path.join(root, file));
255
+ if (has('yarn.lock')) return `yarn add ${SDK_PACKAGE}`;
256
+ if (has('pnpm-lock.yaml')) return `pnpm add ${SDK_PACKAGE}`;
257
+ if (has('bun.lockb') || has('bun.lock')) return `bun add ${SDK_PACKAGE}`;
258
+ return `npm install ${SDK_PACKAGE}`;
259
+ }
package/temp.js ADDED
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {execFileSync} from 'node:child_process';
5
+
6
+ const SIGNAL_EXIT_CODES = {SIGINT: 130, SIGTERM: 143, SIGHUP: 129, SIGQUIT: 131, ...(process.platform === 'win32' ? {SIGBREAK: 149} : {})};
7
+ const tempPaths = new Set();
8
+ let cleanupInstalled = false;
9
+
10
+ export function removeTemp(tempPath) {
11
+ fs.rmSync(tempPath, {recursive: true, force: true});
12
+ tempPaths.delete(tempPath);
13
+ }
14
+
15
+ function removeAllTemp() {
16
+ for (const tempPath of tempPaths) {
17
+ try {
18
+ removeTemp(tempPath);
19
+ } catch {}
20
+ }
21
+ }
22
+
23
+ function exitBySignal(signal) {
24
+ removeAllTemp();
25
+ process.removeAllListeners(signal);
26
+ try {
27
+ process.kill(process.pid, signal);
28
+ } catch {}
29
+ process.exit(SIGNAL_EXIT_CODES[signal]);
30
+ }
31
+
32
+ export function exitIfInterrupted(signal) {
33
+ if (signal && Object.hasOwn(SIGNAL_EXIT_CODES, signal)) exitBySignal(signal);
34
+ }
35
+
36
+ export function execFileSyncInterruptible(file, args, options) {
37
+ try {
38
+ return execFileSync(file, args, options);
39
+ } catch (err) {
40
+ exitIfInterrupted(err.signal);
41
+ throw err;
42
+ }
43
+ }
44
+
45
+ function installCleanup() {
46
+ if (cleanupInstalled) return;
47
+ cleanupInstalled = true;
48
+ process.on('exit', removeAllTemp);
49
+ for (const signal of Object.keys(SIGNAL_EXIT_CODES)) process.on(signal, () => exitBySignal(signal));
50
+ }
51
+
52
+ export function trackTemp(tempPath) {
53
+ installCleanup();
54
+ tempPaths.add(tempPath);
55
+ return tempPath;
56
+ }
57
+
58
+ export const makeTempDir = (prefix) => trackTemp(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));