@novacraft-engineering/pulsar-cli 1.0.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -0
  3. package/hash.js +39 -0
  4. package/package.json +19 -0
  5. package/pulsar.js +234 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Novacraft Engineering
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @novacraft-engineering/pulsar-cli
2
+
3
+ Release CLI for [Pulsar](https://pulsar.novacraft.africa) — bundle your React Native JavaScript, hash it exactly the way the client does, and ship it over-the-air.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i -g @novacraft-engineering/pulsar-cli
9
+ # or run without installing:
10
+ npx @novacraft-engineering/pulsar-cli login https://api.pulsar.novacraft.africa
11
+ ```
12
+
13
+ ## Commands
14
+
15
+ ```bash
16
+ pulsar login <apiUrl> # authenticate, saved to ~/.pulsar/config.json
17
+ pulsar apps # list your apps and deployment keys
18
+
19
+ pulsar release <app> <deployment> --platform ios|android --target <ver> \
20
+ [--rollout 25] [--mandatory] [--disabled] [--devices id1,id2,...] [--description "fix crash"]
21
+
22
+ pulsar promote <app> <from> <to> [--rollout 100]
23
+ pulsar rollback <app> <deployment>
24
+
25
+ pulsar deployment ls <app> # list deployments + keys
26
+ pulsar deployment add <app> <name> # create a new deployment (e.g. QA)
27
+ pulsar history <app> <deployment> # release history
28
+ pulsar patch <app> <deployment> <label> [--rollout N] [--mandatory] [--disable] [--enable] [--devices id1,id2,...]
29
+ ```
30
+
31
+ ### Targeting a release's reach
32
+
33
+ - `--rollout N` — serve to a deterministic N% of devices (by `client_unique_id`).
34
+ - `--devices id1,id2` — serve **only** to those exact device ids (most granular). Empty = all devices.
35
+ - `--disabled` — upload the bundle but don't serve it (flip on later with `pulsar patch … --enable`).
36
+ - `--target <range>` — semver range of native binary versions the release applies to.
37
+
38
+ ```bash
39
+ ```
40
+
41
+ ## How a release works
42
+
43
+ `release` runs the React Native bundler, computes the **CodePush package hash** (the exact
44
+ `path:sha256` manifest algorithm the on-device client uses — so a device that already has the
45
+ bundle correctly reports "up to date"), zips the output, and uploads it to Pulsar. The client
46
+ then downloads it in the background and swaps it in on next launch.
47
+
48
+ Auth is read from `PULSAR_API_URL` / `PULSAR_TOKEN` env, or `~/.pulsar/config.json` (written by `pulsar login`). Nothing is committed.
49
+
50
+ ## License
51
+
52
+ MIT © Novacraft Engineering
package/hash.js ADDED
@@ -0,0 +1,39 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex');
6
+
7
+ function isIgnored(relativePath) {
8
+ const name = relativePath.split('/').pop();
9
+ return (
10
+ name === '.DS_Store' ||
11
+ name === '.codepushrelease' ||
12
+ relativePath.split('/').includes('__MACOSX')
13
+ );
14
+ }
15
+
16
+ function walk(dir) {
17
+ const files = [];
18
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
19
+ const full = path.join(dir, entry.name);
20
+ if (entry.isDirectory()) files.push(...walk(full));
21
+ else if (entry.isFile()) files.push(full);
22
+ }
23
+ return files;
24
+ }
25
+
26
+ // Matches @revopush/react-native-code-push CodePushUpdateUtils.computeFinalHashFromManifest:
27
+ // build "relPath:sha256(file)" entries, sort, JSON.stringify the array, sha256 that string.
28
+ export function computePackageHash(contentsDir) {
29
+ const entries = walk(contentsDir)
30
+ .map((file) => {
31
+ const relativePath = path.relative(contentsDir, file).split(path.sep).join('/');
32
+ return {relativePath, hash: sha256(fs.readFileSync(file))};
33
+ })
34
+ .filter((entry) => !isIgnored(entry.relativePath))
35
+ .map((entry) => `${entry.relativePath}:${entry.hash}`)
36
+ .sort();
37
+
38
+ return sha256(JSON.stringify(entries));
39
+ }
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@novacraft-engineering/pulsar-cli",
3
+ "version": "1.0.0",
4
+ "description": "Pulsar OTA release CLI — bundle, hash, and ship React Native updates over-the-air.",
5
+ "type": "module",
6
+ "bin": {"pulsar": "./pulsar.js"},
7
+ "files": ["pulsar.js", "hash.js", "README.md", "LICENSE"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Novacraft-Africa/pulsar-cli.git"
11
+ },
12
+ "homepage": "https://pulsar.novacraft.africa",
13
+ "license": "MIT",
14
+ "author": "Novacraft Engineering",
15
+ "publishConfig": {"access": "public"},
16
+ "engines": {"node": ">=18"},
17
+ "scripts": {"test": "node test/hash.test.js"},
18
+ "keywords": ["react-native", "ota", "code-push", "pulsar", "cli", "release", "hot-update"]
19
+ }
package/pulsar.js ADDED
@@ -0,0 +1,234 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import readline from 'node:readline';
6
+ import {execFileSync} from 'node:child_process';
7
+ import {computePackageHash} from './hash.js';
8
+
9
+ const CONFIG_DIR = path.join(os.homedir(), '.pulsar');
10
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
11
+
12
+ function loadConfig() {
13
+ const fromFile = fs.existsSync(CONFIG_FILE) ? JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')) : {};
14
+ return {
15
+ apiUrl: process.env.PULSAR_API_URL || fromFile.apiUrl,
16
+ token: process.env.PULSAR_TOKEN || fromFile.token,
17
+ };
18
+ }
19
+
20
+ function saveConfig(config) {
21
+ fs.mkdirSync(CONFIG_DIR, {recursive: true});
22
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
23
+ }
24
+
25
+ async function api(pathname, {method = 'GET', body, headers = {}, raw} = {}) {
26
+ const {apiUrl, token} = loadConfig();
27
+ if (!apiUrl) die('No API url. Run: pulsar login <apiUrl>');
28
+ const response = await fetch(apiUrl.replace(/\/$/, '') + pathname, {
29
+ method,
30
+ headers: {
31
+ ...(token ? {authorization: `Bearer ${token}`} : {}),
32
+ ...(raw ? {} : body ? {'content-type': 'application/json'} : {}),
33
+ ...headers,
34
+ },
35
+ body: raw ? body : body ? JSON.stringify(body) : undefined,
36
+ });
37
+ const text = await response.text();
38
+ const data = text ? JSON.parse(text) : {};
39
+ if (!response.ok) die(`${response.status}: ${data.error || text}`);
40
+ return data;
41
+ }
42
+
43
+ function die(message) {
44
+ console.error(`✗ ${message}`);
45
+ process.exit(1);
46
+ }
47
+
48
+ function prompt(question, hidden = false) {
49
+ return new Promise((resolve) => {
50
+ const rl = readline.createInterface({input: process.stdin, output: process.stdout});
51
+ if (hidden) {
52
+ rl.query = question;
53
+ rl._writeToOutput = (text) => rl.output.write(text === rl.query ? text : '');
54
+ }
55
+ rl.question(question, (answer) => {
56
+ rl.close();
57
+ if (hidden) process.stdout.write('\n');
58
+ resolve(answer.trim());
59
+ });
60
+ });
61
+ }
62
+
63
+ async function resolveApp(nameOrId) {
64
+ const apps = await api('/apps');
65
+ const match = apps.find((app) => app.id === nameOrId || app.name === nameOrId);
66
+ if (!match) die(`App not found: ${nameOrId}. Known: ${apps.map((app) => app.name).join(', ') || '(none)'}`);
67
+ return match;
68
+ }
69
+
70
+ function bundle(platform, contentsDir) {
71
+ const bundleName = platform === 'ios' ? 'main.jsbundle' : 'index.android.bundle';
72
+ fs.mkdirSync(contentsDir, {recursive: true});
73
+ console.log(`• bundling ${platform}…`);
74
+ execFileSync(
75
+ 'npx',
76
+ [
77
+ 'react-native',
78
+ 'bundle',
79
+ '--platform', platform,
80
+ '--dev', 'false',
81
+ '--entry-file', 'index.js',
82
+ '--bundle-output', path.join(contentsDir, bundleName),
83
+ '--assets-dest', contentsDir,
84
+ ],
85
+ {stdio: 'inherit'},
86
+ );
87
+ }
88
+
89
+ function zipContents(contentsDir) {
90
+ const zipPath = path.join(os.tmpdir(), `pulsar-${Date.now()}.zip`);
91
+ execFileSync('zip', ['-qq', '-r', '-X', zipPath, '.'], {cwd: contentsDir});
92
+ return zipPath;
93
+ }
94
+
95
+ function getFlag(args, name, fallback) {
96
+ const index = args.indexOf(`--${name}`);
97
+ return index >= 0 ? args[index + 1] : fallback;
98
+ }
99
+
100
+ async function cmdLogin(args) {
101
+ const apiUrl = args[0] || (await prompt('API url: '));
102
+ const email = await prompt('Email: ');
103
+ const password = await prompt('Password: ', true);
104
+ saveConfig({apiUrl, token: undefined});
105
+ const {token, user} = await api('/auth/login', {method: 'POST', body: {email, password}});
106
+ saveConfig({apiUrl, token});
107
+ console.log(`✓ logged in as ${user.email} (${user.platformRole})`);
108
+ }
109
+
110
+ async function cmdApps() {
111
+ const apps = await api('/apps');
112
+ if (!apps.length) return console.log('(no apps)');
113
+ for (const app of apps) {
114
+ console.log(`\n${app.name} [${app.os}] ${app.id}`);
115
+ for (const [name, deployment] of Object.entries(app.deployments)) {
116
+ console.log(` ${name.padEnd(11)} key: ${deployment.key}`);
117
+ }
118
+ }
119
+ }
120
+
121
+ async function cmdRelease(args) {
122
+ const [nameOrId, deployment = 'Staging'] = args;
123
+ if (!nameOrId) die('Usage: pulsar release <app> <Staging|Production> --platform ios|android --target <ver> [--mandatory] [--disabled] [--rollout N] [--devices id1,id2,...] [--description "..."]');
124
+ const platform = getFlag(args, 'platform', 'ios');
125
+ const target = getFlag(args, 'target');
126
+ if (!target) die('--target <binary version> is required (e.g. --target 1.0.0)');
127
+
128
+ const app = await resolveApp(nameOrId);
129
+ const contentsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulsar-build-'));
130
+ bundle(platform, contentsDir);
131
+
132
+ const packageHash = computePackageHash(contentsDir);
133
+ const zipPath = zipContents(contentsDir);
134
+ const zip = fs.readFileSync(zipPath);
135
+ console.log(`• hash ${packageHash.slice(0, 12)}… size ${(zip.length / 1e6).toFixed(2)} MB`);
136
+
137
+ const release = await api(`/apps/${app.id}/deployments/${deployment}/release`, {
138
+ method: 'POST',
139
+ raw: true,
140
+ body: zip,
141
+ headers: {
142
+ 'content-type': 'application/zip',
143
+ 'x-app-version': target,
144
+ 'x-package-hash': packageHash,
145
+ 'x-is-mandatory': String(args.includes('--mandatory')),
146
+ 'x-disabled': String(args.includes('--disabled')),
147
+ 'x-rollout': String(getFlag(args, 'rollout', '100')),
148
+ 'x-client-ids': getFlag(args, 'devices', ''),
149
+ 'x-description': getFlag(args, 'description', ''),
150
+ },
151
+ });
152
+ const reach = release.clientIds?.length
153
+ ? `${release.clientIds.length} device(s)`
154
+ : `${release.rollout}% of devices`;
155
+ console.log(`✓ released ${release.label} to ${app.name}/${deployment} — ${release.isDisabled ? 'DISABLED' : reach}`);
156
+ }
157
+
158
+ async function cmdPromote(args) {
159
+ const [nameOrId, from = 'Staging', to = 'Production'] = args;
160
+ const app = await resolveApp(nameOrId);
161
+ const release = await api(`/apps/${app.id}/deployments/${from}/promote`, {
162
+ method: 'POST',
163
+ body: {to, rollout: Number(getFlag(args, 'rollout', '100'))},
164
+ });
165
+ console.log(`✓ promoted ${from} → ${to} as ${release.label}`);
166
+ }
167
+
168
+ async function cmdRollback(args) {
169
+ const [nameOrId, deployment = 'Production'] = args;
170
+ const app = await resolveApp(nameOrId);
171
+ const release = await api(`/apps/${app.id}/deployments/${deployment}/rollback`, {method: 'POST'});
172
+ console.log(`✓ rolled back ${app.name}/${deployment} → ${release.label}`);
173
+ }
174
+
175
+ async function cmdDeployment(args) {
176
+ const [sub, nameOrId, depName] = args;
177
+ const app = await resolveApp(nameOrId);
178
+ if (sub === 'add') {
179
+ if (!depName) die('Usage: pulsar deployment add <app> <name>');
180
+ const created = await api(`/apps/${app.id}/deployments`, {method: 'POST', body: {name: depName}});
181
+ console.log(`✓ added ${created.name}\n key: ${created.key}`);
182
+ } else if (sub === 'ls' || sub === 'list') {
183
+ const full = await api(`/apps/${app.id}`);
184
+ for (const [name, deployment] of Object.entries(full.deployments)) {
185
+ console.log(` ${name.padEnd(12)} ${deployment.key}`);
186
+ }
187
+ } else {
188
+ die('Usage: pulsar deployment <add|ls> <app> [name]');
189
+ }
190
+ }
191
+
192
+ async function cmdHistory(args) {
193
+ const [nameOrId, deployment = 'Staging'] = args;
194
+ const app = await resolveApp(nameOrId);
195
+ const releases = await api(`/apps/${app.id}/deployments/${deployment}/releases`);
196
+ if (!releases.length) return console.log('(no releases)');
197
+ for (const release of [...releases].reverse()) {
198
+ const flags = `${release.isMandatory ? ' [mandatory]' : ''}${release.isDisabled ? ' [disabled]' : ''}`;
199
+ console.log(` ${release.label.padEnd(5)} target ${String(release.appVersion).padEnd(10)} rollout ${String(release.rollout).padStart(3)}%${flags} ${release.description || ''}`);
200
+ }
201
+ }
202
+
203
+ async function cmdPatch(args) {
204
+ const [nameOrId, deployment, label] = args;
205
+ if (!label) die('Usage: pulsar patch <app> <deployment> <label> [--rollout N] [--mandatory] [--disable] [--enable] [--devices id1,id2,...]');
206
+ const app = await resolveApp(nameOrId);
207
+ const body = {};
208
+ const rollout = getFlag(args, 'rollout');
209
+ if (rollout !== undefined) body.rollout = Number(rollout);
210
+ if (args.includes('--mandatory')) body.isMandatory = true;
211
+ if (args.includes('--disable')) body.isDisabled = true;
212
+ if (args.includes('--enable')) body.isDisabled = false;
213
+ const devices = getFlag(args, 'devices');
214
+ if (devices !== undefined) body.clientIds = devices.split(',').map((id) => id.trim()).filter(Boolean);
215
+ const release = await api(`/apps/${app.id}/deployments/${deployment}/releases/${label}`, {method: 'PATCH', body});
216
+ console.log(`✓ patched ${label}: rollout ${release.rollout}%${release.isMandatory ? ' mandatory' : ''}${release.isDisabled ? ' disabled' : ''}`);
217
+ }
218
+
219
+ const [command, ...rest] = process.argv.slice(2);
220
+ const commands = {
221
+ login: cmdLogin,
222
+ apps: cmdApps,
223
+ release: cmdRelease,
224
+ promote: cmdPromote,
225
+ rollback: cmdRollback,
226
+ deployment: cmdDeployment,
227
+ history: cmdHistory,
228
+ patch: cmdPatch,
229
+ };
230
+
231
+ (commands[command] || (() => {
232
+ console.log('pulsar <login|apps|release|promote|rollback|deployment|history|patch>');
233
+ process.exit(command ? 1 : 0);
234
+ }))(rest);