@ohos-ports/posthog-cli 0.0.0-stage → 0.19.1-beta.1

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/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2020-2026 PostHog Inc.
2
+
3
+ Portions of this software are licensed as follows:
4
+
5
+ * All content that resides under the "ee/" directory of this repository, if that directory exists, is licensed under the license defined in "ee/LICENSE".
6
+ * All third party components incorporated into the PostHog Software are licensed under the original license provided by the owner of the applicable component.
7
+ * Content outside of the above mentioned directories or restrictions above is available under the "MIT Expat" license as defined below.
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,237 @@
1
- # Temporary Holding Version
1
+ # The Posthog CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The command line interface for PostHog. Exposes PostHog's MCP tool catalog through a shell-friendly interface, handles debug symbol uploads for error tracking, and more. For full documentation, see [our CLI docs](https://posthog.com/docs/cli).
4
+
5
+ ## Installation
6
+
7
+ Install the PostHog CLI with our wizard by running this command:
8
+
9
+ ```bash
10
+ npx -y @posthog/wizard@latest cli add
11
+ ```
12
+
13
+ If you'd rather not use our wizard, you can install the CLI by running:
14
+
15
+ ```bash
16
+ npm install -g @posthog/cli@latest
17
+ ```
18
+
19
+ Or with the install script on macOS and Linux:
20
+
21
+ ```bash
22
+ curl -LsSf https://releases.posthog.com/posthog-cli/install.sh | sh
23
+ ```
24
+
25
+ Or with the install script on Windows (PowerShell):
26
+
27
+ ```powershell
28
+ irm https://releases.posthog.com/posthog-cli/install.ps1 | iex
29
+ ```
30
+
31
+ Or with Homebrew:
32
+
33
+ ```bash
34
+ brew install posthog/tap/posthog-cli
35
+ ```
36
+
37
+ Or with Cargo:
38
+
39
+ ```bash
40
+ cargo install posthog-cli
41
+ ```
42
+
43
+ To update, run:
44
+
45
+ ```bash
46
+ posthog-cli update
47
+ ```
48
+
49
+ If you installed with the macOS or Linux script, it updates in place. If you installed with the Windows script, it prints a command to rerun the installer. If you used npm, Homebrew or cargo, it prints the command your package manager expects instead.
50
+
51
+ Note: if you are installing the CLI for use with a coding agent, you should follow our [setup for agents](https://posthog.com/docs/cli#setup-for-agents) instructions.
52
+
53
+ ## Usage
54
+
55
+ ```bash
56
+ > posthog-cli --help
57
+ The command line interface for PostHog 🦔
58
+
59
+ Usage: posthog-cli [OPTIONS] <COMMAND>
60
+
61
+ Commands:
62
+ login Interactively authenticate with PostHog, storing a personal API token locally. You can also use the environment variables `POSTHOG_CLI_API_KEY` and `POSTHOG_CLI_PROJECT_ID`
63
+ exp Experimental commands, not quite ready for prime time
64
+ sourcemap Upload a directory of bundled chunks to PostHog
65
+ dsym Upload Apple dSYM debug symbol files to PostHog
66
+ hermes Upload hermes sourcemaps to PostHog
67
+ proguard Upload proguard mapping files to PostHog
68
+ symbol-sets Upload, download, and manage symbol sets
69
+ release Look up the release a build belongs to
70
+ api Agent-first PostHog API tools
71
+ help Print this message or the help of the given subcommand(s)
72
+
73
+ Options:
74
+ --host <HOST> The PostHog host to connect to
75
+ --no-fail Disable non-zero exit codes on errors. Use with caution
76
+ --skip-ssl-verification Skip SSL certificate verification when talking to the PostHog API. Use only with self-signed certificates
77
+ --rate-limit <RATE_LIMIT> Set the number of requests per minute for the Posthog API Client [env: POSTHOG_CLIENT_RATE_LIMIT=]
78
+ --dotenv-file <PATH> Load PostHog credentials from this dotenv-style file when not present in the process environment. Also settable as `POSTHOG_CLI_DOTENV_FILE`, for callers that control the environment but not the command line (e.g. an Xcode build phase invoking the iOS SDK's upload-symbols.sh) [env: POSTHOG_CLI_DOTENV_FILE=]
79
+ --dry-run[=<DRY_RUN>] Skip artifact processing and upload (sourcemap, dSYM, hermes, proguard, release) without contacting PostHog or requiring credentials. Intended for CI gates that bundle to catch regressions but must not (or cannot) upload. Not for release builds. Pass it before the subcommand (`posthog-cli --dry-run hermes upload ...`) or set `POSTHOG_CLI_DRY_RUN`. This is distinct from the `exp endpoints` `--dry-run`, which previews endpoint changes [env: POSTHOG_CLI_DRY_RUN=] [default: false] [possible values: true, false]
80
+ -h, --help Print help
81
+ -V, --version Print version
82
+ ```
83
+
84
+ ## Env-based Authentication
85
+
86
+ You can authenticate with PostHog interactively for using the CLI locally, but if you'd like to use it in a CI/CD pipeline, we recommend using these environment variables:
87
+
88
+ - `POSTHOG_CLI_HOST`: The PostHog host to connect to [default: https://us.posthog.com]
89
+ - `POSTHOG_CLI_API_KEY`: [A posthog personal API key.](https://posthog.com/docs/api#private-endpoint-authentication) (also accepts `POSTHOG_CLI_TOKEN` for backward compatibility)
90
+ - `POSTHOG_CLI_PROJECT_ID`: The ID number of the project/environment to connect to. E.g. the "2" in `https://us.posthog.com/project/2` (also accepts `POSTHOG_CLI_ENV_ID` for backward compatibility)
91
+
92
+ These variables can also be loaded from a dotenv-style file via `--dotenv-file <PATH>` (e.g. `posthog-cli --dotenv-file .env query ...`) or the `POSTHOG_CLI_DOTENV_FILE` environment variable. The process environment always wins; the file is only consulted if the required variables aren't set. `POSTHOG_CLI_HOST` is only read from the same source that supplied the rest, so a stray host in the file cannot redirect a key supplied by the process env.
93
+
94
+ Full precedence: CLI args → process env → `--dotenv-file` → `~/.posthog/credentials.json` (from `posthog-cli login`).
95
+
96
+ ## Uploading native debug symbols
97
+
98
+ `posthog-cli symbol-sets upload --directory <dir>` scans a directory for native debug symbols and uploads them so PostHog can symbolicate native stack frames.
99
+ A single command handles both desktop/server formats:
100
+
101
+ - **Linux (ELF):** executables, shared libraries, and `objcopy --only-keep-debug` companions that carry a GNU build id. This branch is cross-platform.
102
+ - **macOS (Apple `.dSYM`):** dSYM bundles are packaged through the same path as `posthog-cli dsym upload`. That path shells out to `dwarfdump` (bundled with Xcode), so it only runs on macOS — if `dwarfdump` is missing, the bundle is reported and skipped while any ELF symbols in the same directory still upload.
103
+ - **macOS (Mach-O executables):** binaries that embed their own DWARF upload directly, keyed by their `LC_UUID`; universal (fat) binaries upload one symbol set per architecture slice. This branch is cross-platform. It exists mainly for Go, which never produces a dSYM (`dsymutil` reports "no debug symbols in executable") — but note Go compresses the embedded DWARF by default, which symbolication can't read yet, so build with `-ldflags=-compressdwarf=false`. C/Swift/Rust executables normally carry no embedded DWARF; upload their dSYMs instead.
104
+
105
+ Pass `--include-source` to bundle referenced source files for context around frames.
106
+ For Flutter `.symbols` files, add `--source-root <app-directory>` to include only source files inside your app directory:
107
+
108
+ ```bash
109
+ posthog-cli symbol-sets upload --directory ./build/debug-info --include-source --source-root ./lib
110
+ ```
111
+
112
+ This option limits uploaded source files, not the debug symbols scanned under `--directory`.
113
+ Upload from the build machine while those source files are still available.
114
+
115
+ The standalone `posthog-cli dsym upload` command is unchanged and still recommended for dSYM-only Xcode build phases, where it also reads release and version metadata from each bundle's `Info.plist`.
116
+
117
+ ## Configuring sourcemap upload concurrency
118
+
119
+ Sourcemap uploads run up to 10 file uploads at a time by default. Set a different positive value with `--concurrency` on `sourcemap upload` or `sourcemap process`:
120
+
121
+ ```bash
122
+ posthog-cli sourcemap process --directory ./dist --concurrency 32
123
+ ```
124
+
125
+ For build integrations such as `@posthog/nextjs-config`, set `POSTHOG_CLI_SOURCEMAP_UPLOAD_CONCURRENCY` in the build environment instead:
126
+
127
+ ```bash
128
+ POSTHOG_CLI_SOURCEMAP_UPLOAD_CONCURRENCY=32 npm run build
129
+ ```
130
+
131
+ The CLI flag takes precedence over the environment variable. Both require a value greater than zero. This setting applies only to plain sourcemap uploads; other CLI concurrency remains unchanged.
132
+
133
+ ## Resolving a release
134
+
135
+ `posthog-cli release resolve` prints the id of the release the current build belongs to, creating the release if it doesn't exist yet.
136
+ The upload commands do this for you, so reach for it when something else needs the id: a bundler plugin that injects the release into your chunks itself, or a deploy script that wants to record which release it shipped.
137
+
138
+ ```bash
139
+ posthog-cli release resolve --release-name my-app --release-version 1.4.0
140
+ 01a0002e-93b5-0000-24cf-fc02638acd46
141
+ ```
142
+
143
+ Only the id goes to stdout, so `RELEASE_ID=$(posthog-cli release resolve)` works.
144
+ Pass `--json` to get the whole release, including its hash id and the version that git or CI metadata filled in.
145
+
146
+ Both `--release-name` and `--release-version` are read from git or CI metadata when you leave them out.
147
+ When the release name or version is missing and git or CI metadata cannot supply it, the command prints nothing (or `null` with `--json`) and exits `0`, so a build can carry on without a release.
148
+ Sourcemap processing still uploads symbols in this case, but it cannot associate them with a release.
149
+ Pass both `--release-name` and `--release-version` if the build has no git metadata and you need that association.
150
+ A failed lookup of a complete release exits non-zero instead.
151
+
152
+ Add `--build` to give a build number its own release: it is packed into the version, so `--release-version 1.4.0 --build 42` resolves to a different release than `--release-version 1.4.0` alone.
153
+
154
+ Pass `--info-plist <path>` to read the release name, version, and build from `CFBundleIdentifier`, `CFBundleShortVersionString`, and `CFBundleVersion`.
155
+ The CLI resolves exact Xcode build-setting references such as `$(APP_VERSION)` and `${BUILD_NUMBER}` from the environment.
156
+ Missing, unresolved, or compound values fall back to `PRODUCT_BUNDLE_IDENTIFIER`, `MARKETING_VERSION`, and `CURRENT_PROJECT_VERSION`.
157
+ Explicit `--release-name`, `--release-version`, and `--build` values take precedence.
158
+
159
+ ## Skipping uploads (dry run)
160
+
161
+ Pass `--dry-run` before the subcommand (`posthog-cli --dry-run hermes upload ...`), or set `POSTHOG_CLI_DRY_RUN=true`, to turn the upload commands — `sourcemap`, `dsym`, `hermes`, and `proguard` — into a no-op.
162
+ `release resolve` is skipped too, since resolving a release can create one.
163
+ The CLI logs what it skipped and exits `0` without contacting PostHog or requiring credentials.
164
+ (This top-level flag is separate from the `exp endpoints` `--dry-run`, which previews endpoint changes.)
165
+
166
+ This is meant for CI gates that still want to run the bundling step (to catch Metro/Hermes or sourcemap regressions) but must not — or cannot — upload artifacts, for example pull-request checks that don't have PostHog credentials.
167
+ Do not use it for release builds, since no symbols are uploaded.
168
+
169
+ The env var accepts the usual truthy/falsy values (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`).
170
+
171
+ ### Personal API key scopes
172
+
173
+ Commands require different API scopes. Make sure to set these scopes on your personal API key:
174
+
175
+ | Command | Required Scopes |
176
+ | ----------------------------- | ------------------------------------------ |
177
+ | `query` | `query:read` |
178
+ | `sourcemap` | `error_tracking:write` |
179
+ | `symbol-sets` | `error_tracking:write` |
180
+ | `dsym` | `error_tracking:write` |
181
+ | `release` | `error_tracking:write` |
182
+ | `exp endpoints list/get/pull` | `endpoint:read` |
183
+ | `exp endpoints push` | `endpoint:write`, `insight_variable:write` |
184
+ | `exp endpoints run` | `query:read` |
185
+ | `exp tasks` | `task:read` |
186
+
187
+ ## Agent-first API tools
188
+
189
+ `posthog-cli api` exposes PostHog's MCP tool catalog through a shell-friendly interface for coding agents:
190
+
191
+ ```bash
192
+ posthog-cli api --agent-help
193
+ posthog-cli api search feature-flag
194
+ posthog-cli api info feature-flag-get-all
195
+ posthog-cli api schema query-trends series
196
+ posthog-cli api call --json feature-flag-get-all '{"limit":5}'
197
+ posthog-cli api call --dry-run feature-flags-bulk-delete-create '{"ids":[123]}'
198
+ posthog-cli api skill list
199
+ posthog-cli api skill install audit
200
+ posthog-cli api agents-md install
201
+ ```
202
+
203
+ Destructive tools require `--confirm` when executed. Use `--dry-run` before mutations.
204
+
205
+ ### Concurrent agents and project targeting
206
+
207
+ Give each API call its own target with `--project-id` and optionally `--organization-id`:
208
+
209
+ ```bash
210
+ posthog-cli api call --project-id 123 --json feature-flag-get-all '{"limit":5}'
211
+ posthog-cli api call --project-id 456 --json feature-flag-get-all '{"limit":5}'
212
+ posthog-cli api call --organization-id 00000000-0000-0000-0000-000000000001 --json projects-get '{}'
213
+ ```
214
+
215
+ These calls can run concurrently with the same API key, including against projects in different organizations. The key must already grant access to both targets. A project-only target derives its organization from the project. An organization-only target never falls back to a project in another organization; pass a project ID for project-scoped tools.
216
+
217
+ Explicit target flags replace both inherited target defaults, so an organization override does not inherit the project from your saved login, and a project override does not inherit another organization. Targets apply to one invocation and do not update your saved login or website selection. Repeat the flags on each call, or set `POSTHOG_CLI_PROJECT_ID` and `POSTHOG_CLI_ORGANIZATION_ID` separately in each agent's environment. The API bundle also accepts `POSTHOG_PROJECT_ID` and `POSTHOG_ORGANIZATION_ID`, which take precedence over the `POSTHOG_CLI_*` aliases. Switch tools do not persist a selection across CLI invocations.
218
+
219
+ `posthog-cli api --agent-help` prints the full agent-facing guide — the same exec tool reference the PostHog MCP server serves, rewritten for CLI invocation — so agents can load it into context before interacting with PostHog APIs.
220
+
221
+ ### Agent steering instructions
222
+
223
+ Install the PostHog CLI steering instructions into the agent instructions file for your project:
224
+
225
+ ```bash
226
+ posthog-cli api agents-md install
227
+ ```
228
+
229
+ By default this updates `AGENTS.md` in the current directory. If your agent reads a different instructions file, pass it explicitly:
230
+
231
+ ```bash
232
+ posthog-cli api agents-md install --path path/to/AGENTS.md
233
+ ```
234
+
235
+ The installed instructions come from the shared snippet at [`services/mcp/src/cli/agents-md-snippet.md`](../services/mcp/src/cli/agents-md-snippet.md), so the installer and this README point at the same source of truth.
236
+
237
+ The snippet is written as a `<posthog>...</posthog>` block. Rerunning the install replaces the existing block in place, so upgrading the CLI and reinstalling refreshes stale instructions without duplicating them.
@@ -0,0 +1,429 @@
1
+ const {
2
+ chmodSync,
3
+ copyFileSync,
4
+ createWriteStream,
5
+ existsSync,
6
+ mkdirSync,
7
+ mkdtemp,
8
+ rmSync,
9
+ } = require("fs");
10
+ const { join, sep } = require("path");
11
+ const { spawnSync } = require("child_process");
12
+ const { tmpdir } = require("os");
13
+
14
+ const https = require("node:https");
15
+ const http = require("node:http");
16
+
17
+ const DOWNLOAD_MAX_ATTEMPTS = 4;
18
+ const DOWNLOAD_RETRY_BASE_DELAY_MS = 1000;
19
+
20
+ function isTransientDownloadError(error) {
21
+ const status = Number(/HTTP (\d{3})/.exec(error?.message ?? '')?.[1])
22
+ if (status) {
23
+ return status === 408 || status === 429 || status >= 500
24
+ }
25
+
26
+ return (
27
+ ['ECONNRESET', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT', 'EAI_AGAIN'].includes(error?.code) ||
28
+ /socket hang up|network|timed? ?out/i.test(error?.message ?? '')
29
+ )
30
+ }
31
+
32
+ function sleep(delayMs) {
33
+ return new Promise((resolve) => setTimeout(resolve, delayMs))
34
+ }
35
+
36
+ async function downloadWithRetry(
37
+ operation,
38
+ {
39
+ maxAttempts = DOWNLOAD_MAX_ATTEMPTS,
40
+ baseDelayMs = DOWNLOAD_RETRY_BASE_DELAY_MS,
41
+ sleepFn = sleep,
42
+ onRetry = () => {},
43
+ } = {}
44
+ ) {
45
+ for (let attempt = 1; ; attempt++) {
46
+ try {
47
+ return await operation()
48
+ } catch (error) {
49
+ if (attempt >= maxAttempts || !isTransientDownloadError(error)) {
50
+ throw error
51
+ }
52
+
53
+ const delayMs = baseDelayMs * 2 ** (attempt - 1)
54
+ onRetry(error, attempt, delayMs)
55
+ await sleepFn(delayMs)
56
+ }
57
+ }
58
+ }
59
+
60
+
61
+ const tmpDir = tmpdir();
62
+
63
+ const error = (msg) => {
64
+ console.error(msg);
65
+ process.exit(1);
66
+ };
67
+
68
+ function getProxyForUrl(urlString) {
69
+ const url = new URL(urlString);
70
+ const isHttps = url.protocol === "https:";
71
+
72
+ const noProxy = process.env.NO_PROXY || process.env.no_proxy || "";
73
+ if (noProxy === "*") return null;
74
+ if (noProxy) {
75
+ const hostname = url.hostname.toLowerCase();
76
+ const noProxyList = noProxy.split(",").map((s) => s.trim().toLowerCase());
77
+ for (const entry of noProxyList) {
78
+ if (hostname === entry || hostname.endsWith("." + entry)) {
79
+ return null;
80
+ }
81
+ }
82
+ }
83
+
84
+ const proxyEnv = isHttps
85
+ ? process.env.HTTPS_PROXY || process.env.https_proxy
86
+ : process.env.HTTP_PROXY || process.env.http_proxy;
87
+
88
+ if (!proxyEnv) return null;
89
+
90
+ const proxyUrl = new URL(proxyEnv);
91
+
92
+ let auth = null;
93
+ if (proxyUrl.username || proxyUrl.password) {
94
+ auth = `${proxyUrl.username}:${proxyUrl.password}`;
95
+ }
96
+
97
+ return {
98
+ hostname: proxyUrl.hostname,
99
+ port: proxyUrl.port || (proxyUrl.protocol === "https:" ? 443 : 80),
100
+ auth: auth,
101
+ };
102
+ }
103
+
104
+ function connectThroughProxy(proxy, target) {
105
+ return new Promise((resolve, reject) => {
106
+ const headers = {};
107
+ if (proxy.auth) {
108
+ headers["Proxy-Authorization"] =
109
+ "Basic " + Buffer.from(proxy.auth).toString("base64");
110
+ }
111
+
112
+ const connectReq = http.request({
113
+ hostname: proxy.hostname,
114
+ port: proxy.port,
115
+ method: "CONNECT",
116
+ path: `${target.hostname}:${target.port || 443}`,
117
+ headers,
118
+ });
119
+ connectReq.on("connect", (res, socket) => {
120
+ if (res.statusCode === 200) {
121
+ resolve(socket);
122
+ } else {
123
+ reject(new Error(`Proxy CONNECT failed with status ${res.statusCode}`));
124
+ }
125
+ });
126
+ connectReq.on("error", reject);
127
+ connectReq.end();
128
+ });
129
+ }
130
+
131
+ function download(urlString, maxRedirects) {
132
+ if (maxRedirects === undefined) maxRedirects = 5;
133
+ return new Promise((resolve, reject) => {
134
+ if (maxRedirects < 0) {
135
+ return reject(new Error("Too many redirects"));
136
+ }
137
+
138
+ const parsed = new URL(urlString);
139
+ const isHttps = parsed.protocol === "https:";
140
+ const mod = isHttps ? https : http;
141
+ const proxy = getProxyForUrl(urlString);
142
+
143
+ const doRequest = (extraOptions) => {
144
+ const options = Object.assign(
145
+ {
146
+ hostname: parsed.hostname,
147
+ port: parsed.port || (isHttps ? 443 : 80),
148
+ path: parsed.pathname + parsed.search,
149
+ method: "GET",
150
+ headers: { "User-Agent": "cargo-dist-npm-installer" },
151
+ },
152
+ extraOptions || {},
153
+ );
154
+
155
+ if (proxy && !isHttps) {
156
+ // HTTP through HTTP proxy: request the full URL via the proxy
157
+ options.hostname = proxy.hostname;
158
+ options.port = proxy.port;
159
+ options.path = urlString;
160
+ if (proxy.auth) {
161
+ options.headers["Proxy-Authorization"] =
162
+ "Basic " + Buffer.from(proxy.auth).toString("base64");
163
+ }
164
+ }
165
+
166
+ const req = mod.request(options, (res) => {
167
+ if (
168
+ res.statusCode >= 300 &&
169
+ res.statusCode < 400 &&
170
+ res.headers.location
171
+ ) {
172
+ res.resume();
173
+ const nextUrl = new URL(res.headers.location, urlString).toString();
174
+ return download(nextUrl, maxRedirects - 1).then(resolve, reject);
175
+ }
176
+ if (res.statusCode < 200 || res.statusCode >= 300) {
177
+ res.resume();
178
+ return reject(new Error(`HTTP ${res.statusCode} from ${urlString}`));
179
+ }
180
+ resolve(res);
181
+ });
182
+ req.on("error", reject);
183
+ req.end();
184
+ };
185
+
186
+ if (proxy && isHttps) {
187
+ connectThroughProxy(proxy, parsed).then(
188
+ (socket) => doRequest({ socket, agent: false }),
189
+ reject,
190
+ );
191
+ } else {
192
+ doRequest();
193
+ }
194
+ });
195
+ }
196
+
197
+ class Package {
198
+ constructor(platform, name, url, filename, zipExt, binaries) {
199
+ let errors = [];
200
+ if (typeof url !== "string") {
201
+ errors.push("url must be a string");
202
+ } else {
203
+ try {
204
+ new URL(url);
205
+ } catch (e) {
206
+ errors.push(e);
207
+ }
208
+ }
209
+ if (name && typeof name !== "string") {
210
+ errors.push("package name must be a string");
211
+ }
212
+ if (!name) {
213
+ errors.push("You must specify the name of your package");
214
+ }
215
+ if (binaries && typeof binaries !== "object") {
216
+ errors.push("binaries must be a string => string map");
217
+ }
218
+ if (!binaries) {
219
+ errors.push("You must specify the binaries in the package");
220
+ }
221
+
222
+ if (errors.length > 0) {
223
+ let errorMsg =
224
+ "One or more of the parameters you passed to the Binary constructor are invalid:\n";
225
+ errors.forEach((error) => {
226
+ errorMsg += error;
227
+ });
228
+ errorMsg +=
229
+ '\n\nCorrect usage: new Package("my-binary", "https://example.com/binary/download.tar.gz", {"my-binary": "my-binary"})';
230
+ error(errorMsg);
231
+ }
232
+
233
+ this.platform = platform;
234
+ this.url = url;
235
+ this.name = name;
236
+ this.filename = filename;
237
+ this.zipExt = zipExt;
238
+ this.installDirectory = join(__dirname, "node_modules", ".bin_real");
239
+ this.binaries = binaries;
240
+
241
+ if (!existsSync(this.installDirectory)) {
242
+ mkdirSync(this.installDirectory, { recursive: true });
243
+ }
244
+ }
245
+
246
+ exists() {
247
+ for (const binaryName in this.binaries) {
248
+ const binRelPath = this.binaries[binaryName];
249
+ const binPath = join(this.installDirectory, binRelPath);
250
+ if (!existsSync(binPath)) {
251
+ return false;
252
+ }
253
+ }
254
+ return true;
255
+ }
256
+
257
+ install(suppressLogs = false) {
258
+ // OpenHarmony/HarmonyOS: this package bundles a binary compiled from
259
+ // source for aarch64-unknown-linux-ohos at vendor/openharmony-arm64/.
260
+ // Stage it into the install directory up front so the local copy is
261
+ // found and the upstream download (no openharmony artifact is
262
+ // published at releases.posthog.com) is skipped.
263
+ const vendoredBinary = join(
264
+ __dirname,
265
+ "vendor",
266
+ "openharmony-arm64",
267
+ "posthog-cli",
268
+ );
269
+ if (existsSync(vendoredBinary)) {
270
+ for (const binaryName in this.binaries) {
271
+ const binRelPath = this.binaries[binaryName];
272
+ const binPath = join(this.installDirectory, binRelPath);
273
+ if (!existsSync(binPath)) {
274
+ mkdirSync(this.installDirectory, { recursive: true });
275
+ copyFileSync(vendoredBinary, binPath);
276
+ chmodSync(binPath, 0o755);
277
+ }
278
+ }
279
+ }
280
+
281
+ if (this.exists()) {
282
+ if (!suppressLogs) {
283
+ console.error(
284
+ `${this.name} is already installed, skipping installation.`,
285
+ );
286
+ }
287
+ return Promise.resolve();
288
+ }
289
+
290
+ try {
291
+ rmSync(this.installDirectory, { recursive: true, force: true });
292
+ } catch {
293
+ // ignore - directory may not exist
294
+ }
295
+
296
+ mkdirSync(this.installDirectory, { recursive: true });
297
+
298
+ if (!suppressLogs) {
299
+ console.error(`Downloading release from ${this.url}`);
300
+ }
301
+
302
+ return downloadWithRetry(() => download(this.url), {
303
+ onRetry: (error, attempt, delayMs) => {
304
+ console.error(
305
+ `Download attempt ${attempt} failed (${error.message}); retrying in ${delayMs}ms...`,
306
+ );
307
+ },
308
+ })
309
+ .then((res) => {
310
+ return new Promise((resolve, reject) => {
311
+ mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
312
+ if (err) return reject(err);
313
+ let tempFile = join(directory, this.filename);
314
+ const sink = res.pipe(createWriteStream(tempFile));
315
+ sink.on("error", (err) => reject(err));
316
+ sink.on("close", () => {
317
+ if (/\.tar\.*/.test(this.zipExt)) {
318
+ const result = spawnSync("tar", [
319
+ "xf",
320
+ tempFile,
321
+ // The tarballs are stored with a leading directory
322
+ // component; we strip one component in the
323
+ // shell installers too.
324
+ "--strip-components",
325
+ "1",
326
+ "-C",
327
+ this.installDirectory,
328
+ ]);
329
+ if (result.status == 0) {
330
+ resolve();
331
+ } else if (result.error) {
332
+ reject(result.error);
333
+ } else {
334
+ reject(
335
+ new Error(
336
+ `An error occurred untarring the artifact: stdout: ${result.stdout}; stderr: ${result.stderr}`,
337
+ ),
338
+ );
339
+ }
340
+ } else if (this.zipExt == ".zip") {
341
+ let result;
342
+ if (this.platform.artifactName.includes("windows")) {
343
+ // Windows does not have "unzip" by default on many installations, instead
344
+ // we use Expand-Archive from powershell
345
+ result = spawnSync("powershell.exe", [
346
+ "-NoProfile",
347
+ "-NonInteractive",
348
+ "-Command",
349
+ "$ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $env:POSTHOG_CLI_ZIP -DestinationPath $env:POSTHOG_CLI_DEST -Force",
350
+ ], {
351
+ env: {
352
+ ...process.env,
353
+ POSTHOG_CLI_ZIP: tempFile,
354
+ POSTHOG_CLI_DEST: this.installDirectory,
355
+ },
356
+ });
357
+ } else {
358
+ result = spawnSync("unzip", [
359
+ "-q",
360
+ tempFile,
361
+ "-d",
362
+ this.installDirectory,
363
+ ]);
364
+ }
365
+
366
+ if (result.status == 0) {
367
+ resolve();
368
+ } else if (result.error) {
369
+ reject(result.error);
370
+ } else {
371
+ reject(
372
+ new Error(
373
+ `An error occurred unzipping the artifact: stdout: ${result.stdout}; stderr: ${result.stderr}`,
374
+ ),
375
+ );
376
+ }
377
+ } else {
378
+ reject(
379
+ new Error(`Unrecognized file extension: ${this.zipExt}`),
380
+ );
381
+ }
382
+ });
383
+ });
384
+ });
385
+ })
386
+ .then(() => {
387
+ if (!this.exists()) {
388
+ throw new Error(
389
+ `The archive extracted, but ${this.name} is missing from ${this.installDirectory}`,
390
+ );
391
+ }
392
+ if (!suppressLogs) {
393
+ console.error(`${this.name} has been installed!`);
394
+ }
395
+ })
396
+ .catch((e) => {
397
+ error(`Error fetching release: ${e.message}`);
398
+ });
399
+ }
400
+
401
+ run(binaryName) {
402
+ const promise = !this.exists() ? this.install(true) : Promise.resolve();
403
+
404
+ promise
405
+ .then(() => {
406
+ const [, , ...args] = process.argv;
407
+
408
+ const options = { cwd: process.cwd(), stdio: "inherit" };
409
+
410
+ const binRelPath = this.binaries[binaryName];
411
+ if (!binRelPath) {
412
+ error(`${binaryName} is not a known binary in ${this.name}`);
413
+ }
414
+ const binPath = join(this.installDirectory, binRelPath);
415
+ const result = spawnSync(binPath, args, options);
416
+
417
+ if (result.error) {
418
+ error(result.error);
419
+ }
420
+
421
+ process.exit(result.status);
422
+ })
423
+ .catch((e) => {
424
+ error(e.message);
425
+ });
426
+ }
427
+ }
428
+
429
+ module.exports.Package = Package;